This page will look better in a graphical browser that supports web standards, but is accessible to any browser or internet device.

Served by Samwise.

# Connecting JSim and Matlab

This page is for the current JSim version 2.0 and higher. Click here for the earlier JSim 1.6 version.

Matlab is a matrix-based computational system distributed by The MathWorks(Natick, MA) and widely used for scientific computation. This document discusses several ways to use JSim and Matlab in conjunction to solve scientific problems. Both JSim and Matlab offer possibilities for graphic data display, however this document will focus on combining the computational power of the two products.

## Exporting JSim models to Matlab

JSim (version 2.07 and above) allows you to export JSim models to Matlab .m files. In the JSim GUI, select the model "Debug" tab and then select "View Matlab" from the "View" menu. Select "Export text..." from the "File" menu to write the Matlab text to a file, which should have extension ".m". For command-line translation, use the jsbatch -omatlab switch, for example:

```jsbatch -f input.proj -omatlab > output.m
jsbatch -f input.mod -omatlab > output.m
jsbatch -f input.sbml -omatlab > output.m
```

Here is an example of how to use the Matlab model export. Consider the following model:

```// Example for MML to Matlab translation
import nsrunit;
unit conversion on;

math mml2matlab {
realDomain t sec; t.min=0; t.max=1; t.delta=0.01;
real C(t) mM;
real k =1 sec^(-1);
when(t=t.min) C=1;
C:t = -k*C;
}
```
(Java required)

Launch the applet above, or download the model and, using either JSim or jsbatch (version 2.07 and above), follow the instructions above to generate Matlab output in file "mytest.m".

To run the model in Matlab, you must write Matlab code that calls "mytest.m" with parameters for the time span you want the model to run, the name of the ODE solver, and options for the ODE solver. Choices for the ODE solver are ode45, ode23, ode13 for non-stiff problems and ode15s, ode23s, ode23t, and ode23tb for stiff problems. If you wish to plot the results, you must write explicit Matlab commands to do so. See Matlab help for details. For example:

```options = odeset('RelTol',1e-12,'AbsTol',1e-9);
[t x rInfo] = mytest( linspace(0,1,101),@ode23,options);
clf;
plot(t,x,'k')
title('Exponential Decay')
xlabel('Time, sec')
ylabel('Concentration, mM')
```

Limitations: JSim Matlab export is currently implemented by translating JSim model code first to SBML, and then using the sbml2matlab tool to translate SBML to Matlab. There is potential for information loss in both translation stages. Limitations of the JSim to SBML translation process are described here, while limitations of sbml2matlab are described here. At present, JSim Matlab output works best for single-domain ODE models with no events or implicit equations. Note that only the default values of model parameters are exported.

Windows users: If you are receiving errors from JSim concerning libSBML and Matlab code generation, please see Installing JSim under MS Windows: SBML, Antimony, and Matlab.

## Exporting JSim data to Matlab

JSim model numeric data may be exported as Matlab .m format. See details in Data Files and Project Data Sets.

## Programatic interaction between JSim and Matlab

There is no single "best" way to connect two software products, such as JSim and Matlab, that is best in all circumstances. Different approaches have different strengths and weaknesses in terms of simplicity, flexibility, performance and long-term viability. The importance of such tradeoffs will vary depending upon the problem at hand and the resources (time, compute power, personnel) available. This document will examine several approaches to JSim/Matlab connectivity, their strengths and weaknesses, and illustrate each approach with working examples. All the examples here require you have both JSim and Matlab installed on your computer. The examples do not work via JSim WWW applets.

Understanding numeric data file formats is vital to making many JSim/Matlab connections. JSim supports a variety of data formats. It is often simplest to write "columnar data format" (AKA tab-separated text) from Matlab for import into JSim, and write either "columnar data format" or "Matlab (.m) format" from JSim for import into Matlab. See Data Files and Project Data Sets for further information on supported data formats.

For long automated analyses, it is usually best to dispense with the engine's graphic user interface(GUI), which can take a signficant time to initialize. The jsbatch program provides command-line access to the JSim engine. The user should study the various jsbatch switches to understand the available options. The -nosplash and -nodesktop switches provide access to Matlab without starting the GUI. For further details, see the Matlab user documentation.

Computational analyses utilizing JSim and Matlab may be classified based upon who is the master, and who is the slave. The master may be either JSim, Matlab or an external agent (for example, the user). For further information, see the design of interest:

## External master, JSim and Matlab slaves

In this design, the user (or some program acting as his/her agent) launches JSim and Matlab alternately, passing the output files of one program to the input of the other. This design is is very simple and quick to implement, although performance may not be ideal due to the multiple launches of the two engines.

### Example using bash script as master

This example models a cell with two genes (gene1 and gene2) and two chemical species (A and B). Gene1 controls the concentration of B, given the concentration of A. Gene2 control the concentration of A, given the concentration of B. The problem is to find the equilibrium concentration when both genes are active.

The bash script below alternately calls the gene1 and gene2 to models, passing the results back and forth, until the concentrations stabilize.

```#!/bin/sh

A=.5

while (true)
do
echo "==running jsbatch gene1 with A=\$A"
BNEW=`jsbatch -f gene1.mod -i A=\$A -oprec 3 -o B -ofmt pretty |\
awk '{ print\$2 }'`
if [ "\$B" = "\$BNEW" ]
then
exit
fi
B=\$BNEW

echo "==running matlab gene2 with B=\$B"
echo "B=\$B" > temp2.m
cat gene2.m >> temp2.m
matlab -nodesktop -nosplash -r temp2 >> /dev/null
A=`sed 's/ //g' gene2.out`
done

```

Gene1 is a JSim model, calculating B from A.

```math main {
extern real A;
real B = cos(A);
}
```

Gene2 is a Matlab model, calculating A from B.

```A=sin(B)
save 'gene2.out' A -ASCII
exit
```

Notes:

• While gene1 and gene2 are very simple in this case, this same approach would work just as well for arbitrarily complex models.
• The numerical approach used by the bash script is simplistic and may be numerically unstable for some models. Users should use numerical approaches appropriate to the models they are attempting to connect.
• There is significant overhead of launching JSim and Matlab for each iteration. Whether this overhead is "acceptable", depends on the details of the analysis being done.

## JSim master, Matlab slave

In this design, a JSim MML model embeds procedural code to call a Matlab process to solve some model variables. The MML constructs for this embedding are called functions and procedures. For information on writing Matlab-specific functions and procedures see here.

## Matlab Master, JSim slave

In this design, Matlab will control the JSim computational engine be using either the jsbatch program or JSim's external API.

In the jsbatch scenario, Matlab will generate JSim readable model and/or numeric data files and pass them, via switch setting to a jsbatch run. When jsbatch terminates, the Matlab then reads the appropriate jsbatch output files for further processing.

The JSim external API scenario is more complex, but (potentially) more computationally efficient. In this scenario a JSim engine in instantiated via a Matlab Java or C API, and is then called multiple times by subsequent Matlab processing. This approach saves the overhead of loading Java, jsbatch and compiling the model before each model run. The JSim API for doing this is undergoing an overhaul at present, due to the desire to make additional JSim functionality to various external software systems (especially finite-element and CFD modeling). A complete working example of the JSim API scenario will be provided once this overhaul is complete (expected fall 2008).

### Example calling jsbatch from Matlab for Monte Carlo analysis

This example performs a simple Monte Carlo analysis. A Matlab mfile generates a set of sinusoidal data curves containing a small amount of random noise. Each curve is sent to jsbatch, which optimizes a model(monte1.proj) to best fit the data curve by varying the sinusoidal amplitude (parameter amp). After each optimization, Matlab collects the optimized values into an array and performs simple statistical analyses on them (calculating mean and variance).

The Matlab control script is as follows:

```% calculate base data
T=0:.5:10;
T=T';
B=sin(T);
N=21;

% initialize array to store optimization results
CT=5;
AMPS = [(1:CT)];

% loop jsbatch runs
for i=1:CT

% add noise to base data
R=rand(N,1)-.5;
D=B+R*.3;

% write JSim columnar data
fp=fopen('rbase.cdata', 'w');
fprintf(fp, 't u\n');
for j=1:21
fprintf(fp, '%g %g\n', T(j,1), D(j,1));
end
fclose(fp);

% call JSim
CMD='jsbatch -f monte1.proj -rm data_1 -f rbase.cdata -optim -o amp -ofmt pretty';
[stat,txt]=unix(CMD);
[tok,txt]=strtok(txt);
tok=strtok(txt);
JSIM_RESULT=str2double(tok)
AMPS(i)=JSIM_RESULT;
end

% show results, mean/variance
AMPS=AMPS
MEAN=mean(AMPS)
VARIANCE=var(AMPS)
```

The JSim project, containing the model and optimization configuration my be downloaded below.

Notes:

• This example presents only the simplest of possible Monte Carlo techniques. A thorough discussion of Monte Carlo techniques is beyond the scope of this document.
• While the example model is small and fast, optimization of complex models can take a fair amount of time. In such cases, the overhead for reloading JSim for each optimization run may be insignificant.
• The jsbatch command uses the -rm switch to remove the existing data set, before inserting the new noisy data set for optimization.
• The jsbatch command uses the -ofmt switch to select an output data format that is easy for Matlab to parse.
• The example above has been tested only on under Linux.

### Example calling JSim engine API from Matlab

This example will be provided once revisions to the JSim API are complete (expected Fall 2008).

Comments or Questions?

[This page was last modified 10Jul20, 10:24 am.]

Model development and archiving support at physiome.org provided by the following grants: NIH U01HL122199 Analyzing the Cardiac Power Grid, 09/15/2015 - 05/31/2020, NIH/NIBIB BE08407 Software Integration, JSim and SBW 6/1/09-5/31/13; NIH/NHLBI T15 HL88516-01 Modeling for Heart, Lung and Blood: From Cell to Organ, 4/1/07-3/31/11; NSF BES-0506477 Adaptive Multi-Scale Model Simulation, 8/15/05-7/31/08; NIH/NHLBI R01 HL073598 Core 3: 3D Imaging and Computer Modeling of the Respiratory Tract, 9/1/04-8/31/09; as well as prior support from NIH/NCRR P41 RR01243 Simulation Resource in Circulatory Mass Transport and Exchange, 12/1/1980-11/30/01 and NIH/NIBIB R01 EB001973 JSim: A Simulation Analysis Platform, 3/1/02-2/28/07.