Code Monkey home page Code Monkey logo

basico's Introduction

COPASI: biochemical network simulator

COPASI is a software application for simulation and analysis of biochemical networks and their dynamics. COPASI is a stand-alone program that supports models in the SBML standard and can simulate their behavior using ODEs or Gillespie's stochastic simulation algorithm; arbitrary discrete events can be included in such simulations.

COPASI carries out several analyses of the network and its dynamics and has extensive support for parameter estimation and optimization. COPASI provides means to visualize data in customizable plots, histograms and animations of network diagrams. (list of features).

Follow us on Mastodon.

Download COPASI

Precompiled versions of COPASI are available for all operating systems on the COPASI Homepage.

Building COPASI

COPASI's sources are available from our github repository. These sources are written in standard C++ and will compile on Linux, OS X and Windows.

Dependencies

To start compiling COPASI we recommend to use the copasi-dependencies package.The dependency package compiles all the dependencies necessary for COPASI, they include clapack, cppunit, expat, raptor libSEDML, libsbml, SBW as well as the Qt libraries QWT, QWT3D and the Qt MML widget. Instructions for building the dependencies are described here:

Compiling COPASI

Once the dependencies have been built, COPASI is easily compiled using CMake:

git clone https://github.com/copasi/COPASI
mkdir build_copasi
cd build_copasi
cmake -DBUILD_GUI=OFF -DCMAKE_INSTALL_PREFIX=~/copasi -DCOPASI_DEPENDENCY_DIR=../copasi-dependencies/bin ../COPASI
make
make install 

In the above ../copasi-dependencies/bin is the location of the build folder of the compiled copasi-dependencies. The option BUILD_GUI=OFF builds only the command line version of COPASI (aka CopasiSE). To build the graphical frontend (aka CopasiUI), and having Qt 4 or 5 installed, the option would need to be BUILD_GUI=ON. In that case you'd additionally provide an option SELECT_QT=Qt5 (or SELECT_QT=Qt4) for COPASI to look for the Qt libraries. (To help finding the Qt version you selected, you should specify the Qt5_DIR=<dir> variable to point to the lib/cmake/Qt5 directory of the Qt5 installation. Alternatively for Qt4 you can set the QT_DIR=<dir> variable to point to your Qt4 installation.)

The option CMAKE_INSTALL_PREFIX=~/copasi specifies, that COPASI ought to be installed in the current users home directory in a subfolder copasi. The path ../COPASI is the source directory of COPASI that has been created by the git clone command in the first statement.

There are many more compile options available, options for building the language bindings as well as options to enable some experimental features that are not yet available in the stable builds that are released publicly. To view the complete set of options, start the graphical cmake frontend in the continuing from the above command this would be done with:

cmake-gui ../COPASI

The correct version number

The COPASI version number you will see in your application is generated during the build process. For this to work we install git hooks, so it gets updated automatically, by running:

./gitTools/initTools

once from the COPASI source dir (which will set up the paths to astyle, gawk, dos2unix and wget). This helps us keep commits formatted correctly from different operating systems. Once that is set up, a call to:

 ./gitTools/UpdateCopasiVersion

will update the <copasi/CopasiVersion.h> to match that of the selected branch. That

Linking a C++ program against the COPASI API

To link your own program against the COPASI C++ API you would first build COPASI as described above however, with an additional CMake option -DCOPASI_INSTALL_C_API=ON. Thus the full configure / make / install commands from above would be:

git clone https://github.com/copasi/COPASI
mkdir build_copasi
cd build_copasi
cmake -DCOPASI_INSTALL_C_API=ON -DBUILD_GUI=OFF -DCMAKE_INSTALL_PREFIX=~/copasi -DCOPASI_DEPENDENCY_DIR=../copasi-dependencies/bin ../COPASI
make
make install 

Now additionally to the COPASI SE executable being built, also all COPASI header files and the COPASI (static) library will be installed into the CMAKE_INSTALL_PREFIX (thus in the example above header files will end up in ~/copasi/include and libraries in ~/copasi/lib). We also export a CMAKE configuration that you can import for your own CMAKE projects. That way you only need to add a line like:

find_package(libCOPASISE-static CONFIG REQUIRED)

to the CMakeLists.txt file of your project. And later link your project against libCOPASISE-static. This will then automatically link against all the libraries that the COPASISE library was linked against. In order for CMake to find the configuration you would either have to include the lib/cmake folder of your install prefix into your projects CMAKE_PREFIX_PATH variable or specify an option libCOPASISE-static_DIR with the folder of the config file when configuring your project. For the prefix specified above this would be:

-DlibCOPASISE-static_DIR=~/copasi/lib/cmake

The gist of a complete example CMakeList.txt is also available.

Feedback

To submit feedback, or bug reports, please use the COPASI Tracker, or our mailing list.

License

The packages available on this page are provided under the Artistic License 2.0, which is an OSI approved license. This license allows non-commercial and commercial use free of charge.

Git maintenance

Release branches:

  • Naming: Version-$major.$minor

Start release branch

To create a new release branch check out the starting branch which is normally develop:

git checkout develop
git flow release start <name>
git push origin

Finish release branch

To finish a release:

git checkout release/<name>
git flow release finish <name>
git push

Tagging snapshots

In order to tag the latest commit in the current branch as a snapshot execute:

gitTools/UpdateCopasiVersion --registerBuild

The above command will automatically select the next tag of the format: Build-N and push the tag to the upstream repository.

Building API documentation

To build the API documentation doxygen can be used. here the command line for generating the documentation after a git checkout:

PROJECT_NUMBER=4.40.278 doxygen -x COPASI.doxyfile > Doxyfile && doxygen

This will fix the version number of the generated files to the one specified in the environment variable and generate a local Doxygen file with which it runs doxygen. The resulting documentation is placed in ./doc/html.

To update it on the copasi.github.io project you'd run from the copasi.github.io folder:

pushd ./static/API_Documentation/
rm -rf ./*
git commit -a -m " - removed old documentation"
cp -R ../../../COPASI/doc/html/* .
git add . 
git commit -a -m " - add documentation for COPASI 4.40.278"
git push

basico's People

Contributors

fbergmann avatar jonasfoe avatar lilijap avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

basico's Issues

Slow ssa simulation of large-ish model

Hi,
I am trying to simulate a sbml model (attached as a .txt file, as GitHub does not accept .XML files). This is the code:

from basico import *
load_model('../Data/egfr_net.txt');
%time run_time_course(duration=0.0001, method='directMethod');

the simulation time is about 20s, which is very long considering the short time (0.0001). I have tried setting automatic=True, but that does not change the time.

egfr_net.txt

Conditional Stochastic Events

The following code does not trigger an stochastic event once A reaches zero:

new_model(name='Simple Model')
add_reaction('R1', 'A ->')
set_species('A', initial_particle_number=50)
set_reaction_parameters('(R1).k1', value=1)
add_event('E1', 'A == 0', [('A', '50')])

result = run_time_course(duration=20, method='stochastic')
result.plot()
plt.show()

Thank you for your time and reading this report.

installing basico 0.53 on remote ubuntu server via workflow

Dear Frank,
I am implementing basio in other repository and I want to use it for different projects, however, I have an issue with installing copasi-basico on a remote ubuntu/macos server.
Maybe you have some hints what to do to avoid this error?

Here is an error message I keep getting (wheel is installed).

image

JOSS Review: Errros in Working_with_ipyparallel

I had to add !pip install ipyparallel to run this notebook, and then ran into this:

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[5], line 1
----> 1 cluster = ipp.Cluster.from_file()
      2 rc = cluster.connect_client_sync()
      3 # wait to get the engines and print their id

File /srv/conda/envs/notebook/lib/python3.10/site-packages/ipyparallel/cluster/cluster.py:556, in Cluster.from_file(cls, cluster_file, profile, profile_dir, cluster_id, **kwargs)
    554 # ensure from_file preserves cluster_file, even if it moved
    555 kwargs.setdefault("cluster_file", cluster_file)
--> 556 with open(cluster_file) as f:
    557     return cls.from_dict(json.load(f), **kwargs)

FileNotFoundError: [Errno 2] No such file or directory: '/home/jovyan/.ipython/profile_default/security/cluster-.json'

File reading error in Parameter Estimation Task.

Hi,

I am following parameter estimation tutorial (https://basico.readthedocs.io/en/latest/notebooks/Parameter_Estimation_Example.html) and I reached to the step 4 where I run

run_parameter_estimation(method='Statistics')

but I get the following error:

ERROR:root:Error while initializing parameter estimation: >ERROR 2022-04-18T09:47:44<
  CFitting (8): Failure reading file '~/../Tutorials/2017-ICSB/MAPKdata.txt'.

I do not have this directory /Tutorials/2017-ICSB/ on my computer. Do I need to provide the path for this file MAPKdata.txt explicitly in run_paramtere_estimation function? I tried to look at the list of arguments it takes but I could not see the file path can be specified. Please suggest what I am missing here?

Thanks

File path issue with add_experiment()

Hello,

When doing parameter estimation, one loads data with the add_experiment() function which takes a parameter "file_name" to chose a specific storage location for the preprocessed file.

If i want my model and experiment files to be in a subfolder compared to the current directory i am running my script in, i would typically do:

from basico import *
import pandas as pd

model_io.load_model("copasi\\example.cps")
data = pd.read_csv("copasi\\example.txt", header=0, sep='\t')
add_experiment("example", data, file_name="copasi\\exp_example.tsv")

result = run_parameter_estimation()   # raises file not found (from C code ?)

The experiment saving works fine, but when run_parameter_estimation() looks for the file, it looks at a wrong path:

ERROR:root:Error while initializing the simulation: >ERROR 2022-01-14T10:00:09<
  CFitting (8): Failure reading file 'C:/Users/lbecquey/Desktop/minimal_example/copasi/copasi/exp_example.tsv'.

Notice the duplicated name of the subfolder in the path.

Note that using an absolute path everywhere does not change the problem.

Plots of steady-state experiments

Hello @fbergmann ,

I tried to make a few changes in the function def plot_per_dependent_variable to create plots for the steady-state data and
I would like to share the modified function (please see below) with you.

Thanks so much for the new release, this helps me a lot in obtaining the steady-state data in the required format.

def plot_per_dependent_variable_ss(**kwargs):
    """
    This function creates a figure for each dependent variable, with traces for all experiments.

    :param kwargs:

    - | `model`: to specify the data model to be used (if not specified
      | the one from :func:`.get_current_model` will be taken)

    :return: array of tuples (fig, ax) for each figure created
    """
    dm = model_io.get_model_from_dict_or_default(kwargs)

    task = dm.getTask(TASK_PARAMETER_ESTIMATION)
    assert (isinstance(task, COPASI.CFitTask))

    problem = task.getProblem()
    assert (isinstance(problem, COPASI.CFitProblem))

    experiments = problem.getExperimentSet()
    assert (isinstance(experiments, COPASI.CExperimentSet))

    result = []
    num_experiments = experiments.getExperimentCount()
    if num_experiments == 0:
        return result

    data = get_simulation_results(**kwargs)
    exp_data = data[0]  # experimental data
    sim_data = data[1]  # simulation data

    dependent_variables = {}

    for i in range(num_experiments):
        experiment = experiments.getExperiment(i)
        mapping = get_experiment_mapping(experiment)

        # set independent values for that experiment
        independent = mapping[mapping.type == 'independent']
        xname = independent.iloc[0].mapping

        # set dependent values for that experiment
        dependent = mapping[mapping.type == 'dependent']
        num_dependent = dependent.shape[0]
        for j in range(num_dependent):
            name = dependent.iloc[j].mapping
            if name not in dependent_variables:
                dependent_variables[name] = []
            dependent_variables[name].append(i)

    for dependent in dependent_variables:
        fig, ax = plt.subplots()
        cycler = plt.cycler("color", plt.cm.tab20c.colors)()
        ax.set_title(dependent)
        experiment_indices = dependent_variables[dependent]

        for i in experiment_indices:
            experiment = experiments.getExperiment(i)
            exp_name = experiment.getObjectName()
            nextval = next(cycler)['color']
            name = dependent
            if name not in sim_data[i].columns:
                name = name[1:-1]

            sim_data[i][xname] = exp_data[i][xname]
            # print(sim_data[i])

            sim_data[i].reset_index().plot(x=xname, y=name,
                                           label="{0} Fit".format(exp_name), ax=ax, color=nextval)
            exp_data[i].plot.scatter(x=xname, y=dependent, ax=ax, color=nextval,
                                     label='{0} Measured'.format(exp_name))
        # plt.savefig('ss.png')
        result.append((fig, ax))

    return result

filter functions by reaction

when retrieving the function database, it would be nice to filter it to suitable ones for a specific reaction

JOSS Review: No output file defined in stochastic simulation

In Creating_a_simple_model.ipynb on binder:

result = run_time_course(duration=50, method='stochastic')

Error while initializing the simulation: >ERROR 2023-07-06T07:33:31<
  CCopasiTask (5): No output file defined for report of task 'Time-Course'.

problems with get_events(), spurious spaces in trigger expression

I use
mevents = get_events()
then I inspect the trigger on that:
mevents.loc['e1','trigger'] and I get
'Y.Rate < 0 & & [Y] > 1e - 3'
but instead it should be
'Y.Rate < 0 && [Y] > 1e-3'
note the spurious spaces between '& &' and in '1e - 3'
of course if I use this string to set another trigger it won't work as the expression is incorrect.

Am I doing something wrong? Where do these extra spaces come from?

Retrieving "Time-Course" Task information

Hi,
I want to retrieve attributes and values related to "Time-Course" task. For example, from the following task section, how can I read the information about "Method" name?

............ 
<Task key="Task_18" name="Time-Course" type="timeCourse" scheduled="false" updateModel="false">
      <Report reference="Report_12" target="" append="1" confirmOverwrite="1"/>
      <Problem>
        <Parameter name="AutomaticStepSize" type="bool" value="0"/>
        <Parameter name="StepNumber" type="unsignedInteger" value="2000"/>
        <Parameter name="StepSize" type="float" value="0.10000000000000001"/>
        <Parameter name="Duration" type="float" value="200"/>
        <Parameter name="TimeSeriesRequested" type="bool" value="1"/>
        <Parameter name="OutputStartTime" type="float" value="0"/>
        <Parameter name="Output Event" type="bool" value="0"/>
        <Parameter name="Start in Steady State" type="bool" value="0"/>
        <Parameter name="Use Values" type="bool" value="0"/>
        <Parameter name="Values" type="string" value=""/>
      </Problem>
      <Method name="Stochastic (Direct method)" type="Stochastic">
        <Parameter name="Max Internal Steps" type="integer" value="1000000"/>
        <Parameter name="Use Random Seed" type="bool" value="0"/>
        <Parameter name="Random Seed" type="unsignedInteger" value="1"/>
      </Method>
    </Task>
............ 

If no method currently exists to retrieve "Time-Course" task information, can methods similar to "get_scan_items()" and "get_scan_settings()" be added?

problem setting model initial time

I'm trying to set the initial time of a model using this code

set_value('Time', 6.0, True)

but when I check the saved model it does not have this value (it is 0.0)

Is there any other way to set the initial time?

Unexpected "ERROR:root:Error while running the simulation: >EXCEPTION 2022-02-22T11:21:58< CTrajectoryMethod (12): Internal step limit exceeded." when setting large stepsize

Hello,
I have a model which I can simulate without problem using the direct method:

from basico import *
load_model('mymodel.txt');
run_time_course(duration=1000.0, method='directMethod')

Next, I want to set stepsize=1000.0, to ensure that only the final datapoint is saved:

run_time_course(duration=1000.0, stepsize=1000.0, method='directMethod')

however, this gives an error:

ERROR:root:Error while running the simulation: >EXCEPTION 2022-02-22T11:21:58<
  CTrajectoryMethod (12): Internal step limit exceeded.

and an altered output (final timepoint is around t=775), see image:
image

This seems unexpected to me, as I only change when we save the output, I am uncertain why this causes an error.

Thie file is attached (originally had the .XML extension, but changed to .txt so that GitHub would accept it):
mymodel.txt

Retrieving information of <Problem> section in tasks.

Hi,

Following is the description of task (sensitivities) which has been extracted from a copasi model file. I want to retrieve the information enclosed in <problem> section.

<Task key="Task_16" name="Sensitivities" type="sensitivities" scheduled="false" updateModel="false"> <Report reference="Report_3" target="" append="1" confirmOverwrite="0"/> <Problem> <Parameter name="SubtaskType" type="unsignedInteger" value="1"/> <ParameterGroup name="TargetFunctions"> <Parameter name="SingleObject" type="cn" value="CN=Root,Model=MAPK cascade,Vector=Compartments[compartment],Vector=Metabolites[PP-MAPK],Reference=Concentration"/> <Parameter name="ObjectListType" type="unsignedInteger" value="1"/> </ParameterGroup> <ParameterGroup name="ListOfVariables"> <ParameterGroup name="Variables"> <Parameter name="SingleObject" type="cn" value="CN=Root,Model=MAPK cascade,Vector=Reactions[binding of MAPKKK activator],ParameterGroup=Parameters,Parameter=k1,Reference=Value"/> <Parameter name="ObjectListType" type="unsignedInteger" value="1"/> </ParameterGroup> <ParameterGroup name="Variables"> <Parameter name="SingleObject" type="cn" value=""/> <Parameter name="ObjectListType" type="unsignedInteger" value="0"/> </ParameterGroup> </ParameterGroup> </Problem> <Method name="Sensitivities Method" type="SensitivitiesMethod"> <Parameter name="Delta factor" type="unsignedFloat" value="0.001"/> <Parameter name="Delta minimum" type="unsignedFloat" value="9.9999999999999998e-13"/> </Method> </Task>

I used the function get_task_settings('Sensitivities', basic_only=False) with and without setting "basic_only" flag to False, but it gives the same following results:

{'scheduled': False, 'update_model': False, 'problem': {'SubtaskType': 1}, 'method': {'Delta factor': 0.001, 'Delta minimum': 1e-12, 'name': 'Sensitivities Method'}, 'report': {'filename': '', 'report_definition': 'Sensitivities', 'append': True, 'confirm_overwrite': True}}

Here you can see, the above function is returning only the name and value attributes of the sub-section (<Parameter >) within the <Problem> section.

Can you please suggest how can I retrieve all the required information within <Problem> section?

Thanks

Mapping bug for multiple experiments in parameter estimation

Heya Frank, hope you're well!

I found evidence of a possible bug when adding experiments for parameter estimation. I may well be running the code wrong somehow, so would be delighted if you could correct it for me!

The bug arises when I try add multiple experiments to COPASI and when I try map a column in those experiments to a global quantity parameter. Then, when trying to get the experimental mapping it gives me a pandas dataframe error: KeyError: "None of ['column'] are in the columns", resulting from the last line of the get_experiment_mapping function: return pandas.DataFrame(data=rows).set_index('column'). I've attached a notebook, model and experimental data for this in the zip folder.

From some rudimentary digging myself, I think there's something wrong with the experiment object. However, I can't see any difference between when add_experiment does work and when it doesn't.

Interestingly

  • the .txt files are created fine for all experiments
  • it works if you map to a species instead of a parameter/global quantity
  • the first experiment is retrieved fine, but the next ones have a problem

Let me know if you want any more detail!
Thanks,
Theo

PE_Bug.zip

setting a function that requires modifiers, should map them if specified

When changing a function on a reaction, it should automatically add modifiers to the reaction scheme.

  • currently, when a reaction r1 with scheme A -> B is assigned a kinetic using modifiers this fails

In the gui, this is allowed, however, this results in an invalid function, since no mapping is specified at that point. I would rather want to avoid creating invalid states, as it would be hard to track down later.

So i propose to silently add modifiers to the reaction scheme, iff a mapping for modifier to species is defined. that means:

  • set_reaction('r1', function='function with modifier') would still fail, however
  • set_reaction('r1', function='function with modifier', mapping={'formulaTokenUsedAsModifier', 'speciesName' }) would work

@pmendes would that work for you?

Need help with parameter estimation

Hi,

I am working with parameter estimation. Instead of following the procedure of "scheduling" the PE task to "execute" and running the model using CLI, I noticed in the basico documentation that I can directly run the parameter estimation task and obtain the solution using the run_parameter_estimation() method. I ran this method with the copasi method Current Solution Statistics and got the required solution. I now have the following questions:

  1. What is the difference between run_parameter_estimation() and get_parameters_solution() when they both return the same results (in my case as well as in the documentation)?

  2. I have 3 fit parameters in my model, and I get the solution for all 3 of them when I run above basico method. However, when I run get_experiment_data_from_model(), I do not get the data of relevant parameters. Please suggest if I am missing anything. (Currently I am not in a need of experimental data but asking just out of curiosity)

  3. As same as obtaining the solution values of parameters using the above basico method, I am wondering if there is anyway to get the calculated Objective Value also?

  4. Finally, while creating a report, how can I included the "Objective Value" to go in the report?

Thanks!

AttributeError: 'CDataObject' object has no attribute 'setDblValue' when running plot_per_dependent_variable()

Hello basiCO team,

when I'm running the function 'plot_per_dependent_variable()' I get the following error:

'AttributeError: 'CDataObject' object has no attribute 'setDblValue'' with the following traceback:

(Environment: Anaconda 3; Python 3.8.3 (default, Jul 2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)]; IPython 7.16.1)

AttributeError                            Traceback (most recent call last)
<ipython-input-12-0f3cf678761d> in <module>
----> 1 plot_per_dependent_variable();

C:\anaconda3\lib\site-packages\basico\task_parameterestimation.py in plot_per_dependent_variable(**kwargs)
   1176         return result
   1177
-> 1178     exp_data, sim_data = get_simulation_results(**kwargs)
   1179
   1180     dependent_variables = {}

C:\anaconda3\lib\site-packages\basico\task_parameterestimation.py in get_simulation_results(values_only, **kwargs)
   1027             model.updateInitialValues(change_set)
   1028
-> 1029         _update_fit_parameters_from(dm, solution, exp_name)
   1030
   1031         if experiment.getExperimentType() == COPASI.CTaskEnum.Task_steadyState:

C:\anaconda3\lib\site-packages\basico\task_parameterestimation.py in _update_fit_parameters_from(dm, solution, exp_name)
   1078                 obj.getObjectParent().setInitialConcentration(value)
   1079             elif type(obj.getObjectParent()) is COPASI.CCopasiParameter:
-> 1080                 obj.setDblValue(value)
   1081                 model.updateInitialValues(obj)
   1082             else:

C:\anaconda3\lib\site-packages\COPASI\__init__.py in <lambda>(self, name)
   3235     for _s in [CObjectInterface, CUndoObjectInterface]:
   3236         __swig_getmethods__.update(getattr(_s, '__swig_getmethods__', {}))
-> 3237     __getattr__ = lambda self, name: _swig_getattr(self, CDataObject, name)
   3238     __repr__ = _swig_repr
   3239     Container = _COPASI.CDataObject_Container

C:\anaconda3\lib\site-packages\COPASI\__init__.py in _swig_getattr(self, class_type, name)
     83     if method:
     84         return method(self)
---> 85     raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name))
     86
     87

I'm using the example model 'LM' and I'm following the steps of the parameter estimation as listed in the documentation here: https://basico.readthedocs.io/en/latest/notebooks/Parameter_Estimation_Example.html
Input lines 1 - 11 all work without any issue.

Custom selection with parameter does not work

Based on the example in #17 I tried to set a custom selection to include the things I want to see in the results via

tc = run_time_course_with_output(['Time', '[S1]', '[S2]', 'Values[k1]'], 0, 5, 5)

But this results in the following error due to the Values[k1] in the selection.

--- c1 ---
ERROR:root:Error while initializing the simulation: >WARNING 2022-04-05T12:44:44<
  CCopasiTask (7): Problems compiling output.
Empty DataFrame
Columns: [Time, [S1], [S2], Values[k1]]
Index: []

Names appear different in exp_data and sim_data dataframes

Hi @fbergmann ,

Square brackets are missing in the columns names of sim_data returned by the function get_simulation_results for time course data.

e.g.

sim_data>
Index(['ADP', 'fructose 6-phosphate', 'NAD', 'glyceraldehyde 3-phosphate',
       'pyruvate{cytosol}', 'dihydroxyacetone phosphate', '2-phosphoglycerate',
       dtype='object')

exp_data>
Index(['Time', '[d-glucose{"external compartment (blood)"}]_0', '[ATP]',
       '[dihydroxyacetone phosphate]', '[fructose 6-phosphate]',
       dtype='object')

For steady-state data both sim_data and exp_data have brackets for the concentration of species in the column names.

Could you please have a look?

Segfault in basico when simulating BIOMD0000000516 after BIOMD0000000513.

Hello, I've been trying to load and simulate the curated section of biomodels using basico. It seems there is a segfault when trying to simulate model 516 after 513 has already been loaded/simulated. Here's the code:

from basico import *
import os
import glob
import time
try:
    from roadrunner.tests.download_biomodels import download_biomodels
except ImportError:
    raise ImportError("Do a `pip install libroadrunner==2.2.0`")

biomodels_folder = os.path.join(os.path.dirname(__file__), "biomodels")

if not os.path.isdir(biomodels_folder):
    biomodels_folder = download_biomodels(os.path.dirname(__file__))

if not os.path.isdir(biomodels_folder):
    raise NotADirectoryError(biomodels_folder)

biomodels_files = glob.glob(os.path.join(biomodels_folder, "*.xml"))

print(len(biomodels_files))

start = time.time()
for model_file in [biomodels_files[512], biomodels_files[515]]:
    try:
        print(model_file)
        model = load_model(model_file)
        result = run_time_course(duration=100)
    except Exception:
        print(f"Model {model_file} failed")

end = time.time() - start

output:

1036
D:\roadrunner\roadrunner\docs\source\parallel\roadrunner_map\biomodels\BIOMD0000000513.xml
D:\roadrunner\roadrunner\docs\source\parallel\roadrunner_map\biomodels\BIOMD0000000516.xml

Process finished with exit code -1073740791 (0xC0000409)

error exporting sbml with explicit level and version

I try saving sbml to a different level and version (in this case level 3 and version 1). I get:

Traceback (most recent call last):
  File "/home/mendes/Copasi/model_replicator/./sbmodelr", line 668, in <module>
    save_model(filename=newfilename, type='sbml', sbml_level=sbmll, sbml_version=sbmlv, model=newmodel)
  File "/home/mendes/.local/lib/python3.9/site-packages/basico/model_io.py", line 488, in save_model
    if not exporters[file_type](filename):
  File "/home/mendes/.local/lib/python3.9/site-packages/basico/model_io.py", line 470, in <lambda>
    'sbml': lambda filename: model.exportSBML(filename, overwrite, sbmlLevel=sbml_level, sbmlVersion=sbml_version,
  File "/home/mendes/.local/lib/python3.9/site-packages/COPASI/__init__.py", line 18604, in exportSBML
    return _COPASI.CDataModel_exportSBML(self, fileName, overwriteFile, sbmlLevel, sbmlVersion, exportIncomplete, exportCOPASIMIRIAM, pProcessReport)
TypeError: Wrong number or type of arguments for overloaded function 'CDataModel_exportSBML'.
  Possible C/C++ prototypes are:
    CDataModel::exportSBML(std::string const &,bool,int,int,bool,bool,CProcessReport *)
    CDataModel::exportSBML(std::string const &,bool,int,int,bool,bool)
    CDataModel::exportSBML(std::string const &,bool,int,int,bool)
    CDataModel::exportSBML(std::string const &,bool,int,int)
    CDataModel::exportSBML(std::string const &,bool,int)
    CDataModel::exportSBML(std::string const &,bool)
    CDataModel::exportSBML(std::string const &)

JOSS Review: Errors with `pytest`

I installed the software and ran pytest. I get the following two errors:


self = <test_timecourse.TestTimeCourse testMethod=test_general_run>

    def test_general_run(self):
        dm = basico.load_example('bruss')
        plots = []
>       basico.run_task(basico.T.TIME_COURSE, model=dm, plots=plots)
E       AttributeError: module 'basico' has no attribute 'run_task'

tests/test_timecourse.py:49: AttributeError
____________________________________________________________ TestTimeCourse.test_general_run_sedml ____________________________________________________________

self = <test_timecourse.TestTimeCourse testMethod=test_general_run_sedml>

    def test_general_run_sedml(self):
        dm = basico.load_model(os.path.join(THIS_DIR, 'sedml.xml'))
        plots = []
>       basico.run_scheduled_tasks(include_plots=False, include_general_plots=True, plots=plots, model=dm)
E       AttributeError: module 'basico' has no attribute 'run_scheduled_tasks'. Did you mean: 'get_scheduled_tasks'?

tests/test_timecourse.py:56: AttributeError

changing transient values

As @matthiaskoenig noted, it is currently not possible to change transient values. Though of course it could be useful to do so. All task have a flag use_initial_values defaulting to True, that the initial values would be used. But to continue from the current state, it makes sense to be able to change the transient values as well.

Error running parameter estimation task

Hi Frank,

I tried to reproduce experiments in the notebook "Setting up parameter Estimation" [https://github.com/copasi/basico/blob/master/docs/notebooks/Setting_up_Parameter_Estimation.ipynb]. However, if I add parameter set to the model with

add_parameter_set('InitialState')

after loading the model, I encountered this error message

Error while initializing parameter estimation:

and the parameter estimation will not produce any result. Why is this so?
What does this error message try to say?

Thanks!

Running Gillespie simulatons

Hello,
I have gotten this to work, however, I have been unable to run Gillespie type simulations. This is possible in Copasi, but there is no mention of it in the basic documentation?

How to get SBML identifiers in timecourse results? How to get amount/concentrations for species?

Hi all,
great library. I want to have timecourse results with SBML identifiers and be able to access either amount/concentration of species.

Currently there is the function

def __build_result_from_ts(time_series, use_concentrations=True):
    # type: (COPASI.CTimeSeries) -> pandas.DataFrame
    col_count = time_series.getNumVariables()
    row_count = time_series.getRecordedSteps()

    column_names = []
    column_keys = []
    for i in range(col_count):
        column_keys.append(time_series.getKey(i))
        column_names.append(time_series.getTitle(i))
        # FIXME: SBML ids for comparison
        column_names.append(time_series.getSBMLId(i))

    concentrations = np.empty([row_count, col_count])
    for i in range(row_count):
        for j in range(col_count):
            if use_concentrations:
                concentrations[i, j] = time_series.getConcentrationData(i, j)
            else:
                concentrations[i, j] = time_series.getData(i, j)

    df = pd.DataFrame(data=concentrations, columns=column_names)
    df = df.set_index('Time')

    return df

I tried to get the SBML identifiers but need a CDataModel for that in time_serices.getSBMLId(i). How would I do this?
Is there some documention for the python-copasi API? Are there some examples and use cases?

How would I get amounts/concentrations for species?

Best Matthias

should `get_simulation_results` update parameters?

Currently when basico gets simulation / experimental data in get_simulation_results, it also updates the model parameters to the ones found by the fit. The question is, whether this is needed or not.

Species missing from timecourse result

I ran a simple timecourse simulation with copasi-basico==0.16. I have a species S1 in the model which does not appear in the results data frame. Model and code attached.
tellurium_sim.zip

Expected behavior: columns: S1, S2, Values[k1]
Current behavior: columns S2, Values[k1]

from basico import *

basico.load_model("tellurium_sim.sbml")

print("--- c1 ---")
tc = run_time_course(0, 5, 5)
print(tc)

print("--- c2 ---")
set_species(name='S1', initial_concentration=2)
tc = run_time_course(0, 5, 5)
print(tc)

results in

--- c1 ---
       S2  Values[k1]
Time                 
0.0   0.0         0.0
1.0   0.0         0.0
2.0   0.0         0.0
3.0   0.0         0.0
4.0   0.0         0.0
5.0   0.0         0.0
--- c2 ---
       S2  Values[k1]
Time                 
0.0   0.0         1.0
1.0   1.0         1.0
2.0   2.0         1.0
3.0   3.0         1.0
4.0   4.0         1.0
5.0   5.0         1.0

There is a species S1 in the model, but somehow it is missing from the results DataFrame? Perhaps indexing issue or similar thing.

JOSS Review: Error in Working_with_Annotations ipynb

I see the following error when running the annotations notebook on binder:

TypeError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 get_miriam_resources().head()

File /srv/conda/envs/notebook/lib/python3.10/site-packages/basico/model_info.py:3951, in get_miriam_resources()
   3946         res = miriam.getMIRIAMResource(i)
   3947         assert (isinstance(res, COPASI.CMIRIAMResource))
   3948         resources.append({
   3949             'resource': res.getMIRIAMDisplayName(),
   3950             'is_citation': res.getMIRIAMCitation(),
-> 3951             'uri': res.getIdentifiersOrgURL()
   3952         })
   3953 except AttributeError:
   3954     logger.error("Couldn't retrieve list of miriam resources, please update the python-copasi version")

TypeError: CMIRIAMResource.getIdentifiersOrgURL() missing 1 required positional argument: 'compact'

Increase step size to avoid "CTrajectoryMethod (12): Internal step limit exceeded." error

When I attempt to simulate a large model using

from basico import *
load_model('../Data/mymodel.xml');
run_time_course(duration=1000.0, method='deterministic')

(I also seem to get it with method='directMethod'

I get an error:

ERROR:root:Error while running the simulation: >EXCEPTION 2022-02-15T19:38:40<
  CTrajectoryMethod (12): Internal step limit exceeded.

Looking here, I get the impression that I can increase the max step size: http://copasi.org/Support/User_Manual/Methods/Time_Course_Calculation/Hybrid_Simulation/#:~:text=Max%20Internal%20Steps,default%20value%20is%20'1000000'.

However, I am unsure how to do so in basico.

Retrieving Method details.

Hi,

I want to retrieve complete information of methods used in any specific task. For example, copasi model with optimization task has the following method details:

<Method name="Genetic Algorithm" type="GeneticAlgorithm"> <Parameter name="Log Verbosity" type="unsignedInteger" value="0"/> <Parameter name="Number of Generations" type="unsignedInteger" value="200"/> <Parameter name="Population Size" type="unsignedInteger" value="20"/> <Parameter name="Random Number Generator" type="unsignedInteger" value="1"/> <Parameter name="Seed" type="unsignedInteger" value="0"/> <Parameter name="Mutation Variance" type="float" value="0.10000000000000001"/> <Parameter name="Stop after # Stalled Generations" type="unsignedInteger" value="0"/> </Method>

I want to retrieve/set all the information including the "type" of the method. I tried to use get_opt_settings() but i returns on the following information related to method:
'method': {'Number of Generations': 200, 'Population Size': 20, 'name': 'Genetic Algorithm'}

Progress Report

When running parameter estimation in basico, it would be nice to have some sort of progress report.

set_species failing to set initial concentration

I tried this code:

add_species('B');
set_species('B', exact=True,  initial_concentration=0.4, status='fixed');

and the result is that species 'B' ends up with initial concentration of 1 (default value, set by the add_species), not 0.4 as should have been changed by set_species ...

I had to write:

add_species('B', initial_concentration=0.4);
set_species('B', exact=True, status='fixed');

to have 'B' actually get the initial concentration of 0.4.

does basico use threading?

Hello!

I have thinking of running Basico on an HPC, but I was wondering if Basico uses threading to make use of multitasking and more CPU cores. I have run the UI previously on my laptop, but to do massive parameter scans I wanted to understand how could I leverage the performance of the HPC.

Thank you!

Regards,
Z

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.