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

-->

Connecting JSim and Matlab

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.

Prerequisites

Contents

The Basics

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:

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:

Example calling JSim engine API from Matlab

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

[This page was last modified 15Sep08, 11:34 am.]

Model development and archiving support at physiome.org provided by the following grants: 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.