use of cbit.vcell.math.CompartmentSubDomain in project vcell by virtualcell.
the class IDAFileWriter method writeEquations.
/**
* Insert the method's description here.
* Creation date: (3/8/00 10:31:52 PM)
*/
protected String writeEquations(HashMap<Discontinuity, String> discontinuityNameMap) throws MathException, ExpressionException {
Simulation simulation = simTask.getSimulation();
StringBuffer sb = new StringBuffer();
MathDescription mathDescription = simulation.getMathDescription();
if (mathDescription.hasFastSystems()) {
//
// define vector of original variables
//
SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
CompartmentSubDomain subDomain = (CompartmentSubDomain) mathDescription.getSubDomains().nextElement();
FastSystem fastSystem = subDomain.getFastSystem();
FastSystemAnalyzer fs_Analyzer = new FastSystemAnalyzer(fastSystem, simSymbolTable);
int numIndependent = fs_Analyzer.getNumIndependentVariables();
int systemDim = mathDescription.getStateVariableNames().size();
int numDependent = systemDim - numIndependent;
//
// get all variables from fast system (dependent and independent)
//
HashSet<String> fastSystemVarHash = new HashSet<String>();
Enumeration<Variable> dependentfastSystemVarEnum = fs_Analyzer.getDependentVariables();
while (dependentfastSystemVarEnum.hasMoreElements()) {
fastSystemVarHash.add(dependentfastSystemVarEnum.nextElement().getName());
}
Enumeration<Variable> independentfastSystemVarEnum = fs_Analyzer.getIndependentVariables();
while (independentfastSystemVarEnum.hasMoreElements()) {
fastSystemVarHash.add(independentfastSystemVarEnum.nextElement().getName());
}
//
// get all equations including for variables that are not in the fastSystem (ode equations for "slow system")
//
RationalExpMatrix origInitVector = new RationalExpMatrix(systemDim, 1);
RationalExpMatrix origSlowRateVector = new RationalExpMatrix(systemDim, 1);
RationalExpMatrix origVarColumnVector = new RationalExpMatrix(systemDim, 1);
Enumeration<Equation> enumEquations = subDomain.getEquations();
int varIndex = 0;
while (enumEquations.hasMoreElements()) {
Equation equation = enumEquations.nextElement();
origVarColumnVector.set_elem(varIndex, 0, new RationalExp(equation.getVariable().getName()));
Expression rateExpr = equation.getRateExpression();
rateExpr.bindExpression(varsSymbolTable);
rateExpr = MathUtilities.substituteFunctions(rateExpr, varsSymbolTable);
origSlowRateVector.set_elem(varIndex, 0, new RationalExp("(" + rateExpr.flatten().infix() + ")"));
Expression initExpr = new Expression(equation.getInitialExpression());
initExpr.substituteInPlace(new Expression("t"), new Expression(0.0));
initExpr = MathUtilities.substituteFunctions(initExpr, varsSymbolTable).flatten();
origInitVector.set_elem(varIndex, 0, new RationalExp("(" + initExpr.flatten().infix() + ")"));
varIndex++;
}
//
// make symbolic matrix for fast invariants (from FastSystem's fastInvariants as well as a new fast invariant for each variable not included in the fast system.
//
RationalExpMatrix fastInvarianceMatrix = new RationalExpMatrix(numDependent, systemDim);
int row = 0;
for (int i = 0; i < origVarColumnVector.getNumRows(); i++) {
//
if (!fastSystemVarHash.contains(origVarColumnVector.get(i, 0).infixString())) {
fastInvarianceMatrix.set_elem(row, i, RationalExp.ONE);
row++;
}
}
Enumeration<FastInvariant> enumFastInvariants = fastSystem.getFastInvariants();
while (enumFastInvariants.hasMoreElements()) {
FastInvariant fastInvariant = enumFastInvariants.nextElement();
Expression fastInvariantExpression = fastInvariant.getFunction();
for (int col = 0; col < systemDim; col++) {
Expression coeff = fastInvariantExpression.differentiate(origVarColumnVector.get(col, 0).infixString()).flatten();
coeff = simSymbolTable.substituteFunctions(coeff);
fastInvarianceMatrix.set_elem(row, col, RationalExpUtils.getRationalExp(coeff));
}
row++;
}
for (int i = 0; i < systemDim; i++) {
sb.append("VAR " + origVarColumnVector.get(i, 0).infixString() + " INIT " + origInitVector.get(i, 0).infixString() + ";\n");
}
RationalExpMatrix fullMatrix = null;
RationalExpMatrix inverseFullMatrix = null;
RationalExpMatrix newSlowRateVector = null;
try {
RationalExpMatrix fastMat = ((RationalExpMatrix) fastInvarianceMatrix.transpose().findNullSpace());
fullMatrix = new RationalExpMatrix(systemDim, systemDim);
row = 0;
for (int i = 0; i < fastInvarianceMatrix.getNumRows(); i++) {
for (int col = 0; col < systemDim; col++) {
fullMatrix.set_elem(row, col, fastInvarianceMatrix.get(i, col));
}
row++;
}
for (int i = 0; i < fastMat.getNumRows(); i++) {
for (int col = 0; col < systemDim; col++) {
fullMatrix.set_elem(row, col, fastMat.get(i, col));
}
row++;
}
inverseFullMatrix = new RationalExpMatrix(systemDim, systemDim);
inverseFullMatrix.identity();
RationalExpMatrix copyOfFullMatrix = new RationalExpMatrix(fullMatrix);
copyOfFullMatrix.gaussianElimination(inverseFullMatrix);
newSlowRateVector = new RationalExpMatrix(numDependent, 1);
newSlowRateVector.matmul(fastInvarianceMatrix, origSlowRateVector);
} catch (MatrixException ex) {
ex.printStackTrace();
throw new MathException(ex.getMessage());
}
sb.append("TRANSFORM\n");
for (row = 0; row < systemDim; row++) {
for (int col = 0; col < systemDim; col++) {
sb.append(fullMatrix.get(row, col).getConstant().doubleValue() + " ");
}
sb.append("\n");
}
sb.append("INVERSETRANSFORM\n");
for (row = 0; row < systemDim; row++) {
for (int col = 0; col < systemDim; col++) {
sb.append(inverseFullMatrix.get(row, col).getConstant().doubleValue() + " ");
}
sb.append("\n");
}
int numDifferential = numDependent;
int numAlgebraic = numIndependent;
sb.append("RHS DIFFERENTIAL " + numDifferential + " ALGEBRAIC " + numAlgebraic + "\n");
int equationIndex = 0;
while (equationIndex < numDependent) {
// print row of mass matrix followed by slow rate corresponding to fast invariant
Expression slowRateExp = new Expression(newSlowRateVector.get(equationIndex, 0).infixString()).flatten();
slowRateExp.bindExpression(simSymbolTable);
slowRateExp = MathUtilities.substituteFunctions(slowRateExp, varsSymbolTable).flatten();
Vector<Discontinuity> v = slowRateExp.getDiscontinuities();
for (Discontinuity od : v) {
od = getSubsitutedAndFlattened(od, varsSymbolTable);
String dname = discontinuityNameMap.get(od);
if (dname == null) {
dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
discontinuityNameMap.put(od, dname);
}
slowRateExp.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
}
sb.append(slowRateExp.infix() + ";\n");
equationIndex++;
}
Enumeration<FastRate> enumFastRates = fastSystem.getFastRates();
while (enumFastRates.hasMoreElements()) {
// print the fastRate for this row
Expression fastRateExp = new Expression(enumFastRates.nextElement().getFunction());
fastRateExp = MathUtilities.substituteFunctions(fastRateExp, varsSymbolTable).flatten();
Vector<Discontinuity> v = fastRateExp.getDiscontinuities();
for (Discontinuity od : v) {
od = getSubsitutedAndFlattened(od, varsSymbolTable);
String dname = discontinuityNameMap.get(od);
if (dname == null) {
dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
discontinuityNameMap.put(od, dname);
}
fastRateExp.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
}
sb.append(fastRateExp.flatten().infix() + ";\n");
equationIndex++;
}
} else {
for (int i = 0; i < getStateVariableCount(); i++) {
StateVariable stateVar = getStateVariable(i);
Expression initExpr = new Expression(stateVar.getInitialRateExpression());
initExpr = MathUtilities.substituteFunctions(initExpr, varsSymbolTable);
initExpr.substituteInPlace(new Expression("t"), new Expression(0.0));
sb.append("VAR " + stateVar.getVariable().getName() + " INIT " + initExpr.flatten().infix() + ";\n");
}
sb.append("TRANSFORM\n");
for (int row = 0; row < getStateVariableCount(); row++) {
for (int col = 0; col < getStateVariableCount(); col++) {
sb.append((row == col ? 1 : 0) + " ");
}
sb.append("\n");
}
sb.append("INVERSETRANSFORM\n");
for (int row = 0; row < getStateVariableCount(); row++) {
for (int col = 0; col < getStateVariableCount(); col++) {
sb.append((row == col ? 1 : 0) + " ");
}
sb.append("\n");
}
sb.append("RHS DIFFERENTIAL " + getStateVariableCount() + " ALGEBRAIC 0\n");
for (int i = 0; i < getStateVariableCount(); i++) {
StateVariable stateVar = getStateVariable(i);
Expression rateExpr = new Expression(stateVar.getRateExpression());
rateExpr = MathUtilities.substituteFunctions(rateExpr, varsSymbolTable).flatten();
Vector<Discontinuity> v = rateExpr.getDiscontinuities();
for (Discontinuity od : v) {
od = getSubsitutedAndFlattened(od, varsSymbolTable);
String dname = discontinuityNameMap.get(od);
if (dname == null) {
dname = ROOT_VARIABLE_PREFIX + discontinuityNameMap.size();
discontinuityNameMap.put(od, dname);
}
rateExpr.substituteInPlace(od.getDiscontinuityExp(), new Expression("(" + dname + "==1)"));
}
sb.append(rateExpr.infix() + ";\n");
}
}
return sb.toString();
}
use of cbit.vcell.math.CompartmentSubDomain in project vcell by virtualcell.
the class SubdomainInfo method write.
public static void write(File file, MathDescription mathDesc) throws IOException, MathException {
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileWriter(file));
pw.println("# " + VCML.CompartmentSubDomain + " name, handle");
pw.println("# " + VCML.MembraneSubDomain + " name, inside compartment name, handle, outside compartment name, handle");
Enumeration<SubDomain> subdomains = mathDesc.getSubDomains();
while (subdomains.hasMoreElements()) {
SubDomain sd = subdomains.nextElement();
if (sd instanceof CompartmentSubDomain) {
CompartmentSubDomain csd = (CompartmentSubDomain) sd;
pw.println(VCML.CompartmentSubDomain + ", " + csd.getName() + ", " + mathDesc.getHandle(csd));
} else if (sd instanceof MembraneSubDomain) {
MembraneSubDomain msd = (MembraneSubDomain) sd;
CompartmentSubDomain insideCompartment = msd.getInsideCompartment();
CompartmentSubDomain outsideCompartment = msd.getOutsideCompartment();
pw.println(VCML.MembraneSubDomain + ", " + msd.getName() + ", " + insideCompartment.getName() + ", " + mathDesc.getHandle(insideCompartment) + ", " + outsideCompartment.getName() + ", " + mathDesc.getHandle(outsideCompartment));
}
}
pw.close();
} finally {
if (pw != null) {
pw.close();
}
}
}
use of cbit.vcell.math.CompartmentSubDomain in project vcell by virtualcell.
the class SimulationData method getVarAndFunctionDataIdentifiers.
/**
* This method was created in VisualAge.
* @return java.lang.String[]
*/
public synchronized DataIdentifier[] getVarAndFunctionDataIdentifiers(OutputContext outputContext) throws IOException, DataAccessException {
// Is this zip format?
boolean bIsChombo = false;
try {
bIsChombo = isChombo();
} catch (FileNotFoundException e) {
e.printStackTrace(System.out);
}
File zipFile1 = getZipFile(bIsChombo, null);
File zipFile2 = getZipFile(bIsChombo, 0);
bZipFormat1 = false;
bZipFormat2 = false;
if (zipFile1.exists()) {
bZipFormat1 = true;
} else if (zipFile2.exists()) {
bZipFormat2 = true;
}
refreshLogFile();
if (!isComsol()) {
try {
refreshMeshFile();
} catch (MathException e) {
e.printStackTrace(System.out);
throw new DataAccessException(e.getMessage());
}
}
if (!isRulesData && !getIsODEData() && !isComsol() && dataFilenames != null) {
// read variables only when I have never read the file since variables don't change
if (dataSetIdentifierList.size() == 0) {
File file = getPDEDataFile(0.0);
DataSet dataSet = getPDEDataSet(file, 0.0);
String[] varNames = dataSet.getDataNames();
int[] varTypeInts = dataSet.getVariableTypeIntegers();
if (varNames == null) {
return null;
}
dataSetIdentifierList.clear();
for (int i = 0; i < varNames.length; i++) {
VariableType varType = null;
try {
varType = VariableType.getVariableTypeFromInteger(varTypeInts[i]);
} catch (IllegalArgumentException e) {
if (LG.isEnabledFor(Level.WARN)) {
LG.warn("Exception typing " + varNames[i] + " has unsupported type " + varTypeInts[i] + ": " + e.getMessage());
}
varType = SimulationData.getVariableTypeFromLength(mesh, dataSet.getDataLength(varNames[i]));
}
Domain domain = Variable.getDomainFromCombinedIdentifier(varNames[i]);
String varName = Variable.getNameFromCombinedIdentifier(varNames[i]);
dataSetIdentifierList.addElement(new DataSetIdentifier(varName, varType, domain));
}
refreshDataProcessingOutputInfo(outputContext);
if (dataProcessingOutputInfo != null) {
for (int i = 0; i < dataProcessingOutputInfo.getVariableNames().length; i++) {
if (dataProcessingOutputInfo.getPostProcessDataType(dataProcessingOutputInfo.getVariableNames()[i]).equals(DataProcessingOutputInfo.PostProcessDataType.image)) {
dataSetIdentifierList.addElement(new DataSetIdentifier(dataProcessingOutputInfo.getVariableNames()[i], VariableType.POSTPROCESSING, null));
}
}
}
}
// always read functions file since functions might change
getFunctionDataIdentifiers(outputContext);
}
if ((isRulesData || getIsODEData()) && dataSetIdentifierList.size() == 0) {
ODEDataBlock odeDataBlock = getODEDataBlock();
if (odeDataBlock == null) {
throw new DataAccessException("Results are not availabe yet. Please try again later.");
}
ODESimData odeSimData = odeDataBlock.getODESimData();
int colCount = odeSimData.getColumnDescriptionsCount();
// assume index=0 is time "t"
int DATA_OFFSET = 1;
dataSetIdentifierList.clear();
for (int i = 0; i < (colCount - DATA_OFFSET); i++) {
String varName = odeSimData.getColumnDescriptions(i + DATA_OFFSET).getDisplayName();
// TODO domain
Domain domain = null;
dataSetIdentifierList.addElement(new DataSetIdentifier(varName, VariableType.NONSPATIAL, domain));
}
}
if (isComsol() && dataSetIdentifierList.size() == 0) {
ComsolSimFiles comsolSimFiles = getComsolSimFiles();
if (comsolSimFiles.simTaskXMLFile != null) {
try {
String xmlString = FileUtils.readFileToString(comsolSimFiles.simTaskXMLFile);
SimulationTask simTask = XmlHelper.XMLToSimTask(xmlString);
Enumeration<Variable> variablesEnum = simTask.getSimulation().getMathDescription().getVariables();
while (variablesEnum.hasMoreElements()) {
Variable var = variablesEnum.nextElement();
if (var instanceof VolVariable) {
dataSetIdentifierList.addElement(new DataSetIdentifier(var.getName(), VariableType.VOLUME, var.getDomain()));
} else if (var instanceof MemVariable) {
dataSetIdentifierList.addElement(new DataSetIdentifier(var.getName(), VariableType.MEMBRANE, var.getDomain()));
} else if (var instanceof Function) {
VariableType varType = VariableType.UNKNOWN;
if (var.getDomain() != null && var.getDomain().getName() != null) {
SubDomain subDomain = simTask.getSimulation().getMathDescription().getSubDomain(var.getDomain().getName());
if (subDomain instanceof CompartmentSubDomain) {
varType = VariableType.VOLUME;
} else if (subDomain instanceof MembraneSubDomain) {
varType = VariableType.MEMBRANE;
} else if (subDomain instanceof FilamentSubDomain) {
throw new RuntimeException("filament subdomains not supported");
} else if (subDomain instanceof PointSubDomain) {
varType = VariableType.POINT_VARIABLE;
}
}
dataSetIdentifierList.addElement(new DataSetIdentifier(var.getName(), varType, var.getDomain()));
} else if (var instanceof Constant) {
System.out.println("ignoring Constant " + var.getName());
} else if (var instanceof InsideVariable) {
System.out.println("ignoring InsideVariable " + var.getName());
} else if (var instanceof OutsideVariable) {
System.out.println("ignoring OutsideVariable " + var.getName());
} else {
throw new RuntimeException("unexpected variable " + var.getName() + " of type " + var.getClass().getName());
}
}
} catch (XmlParseException | ExpressionException e) {
e.printStackTrace();
throw new RuntimeException("failed to read sim task file, msg: " + e.getMessage(), e);
}
}
}
DataIdentifier[] dis = new DataIdentifier[dataSetIdentifierList.size()];
for (int i = 0; i < dataSetIdentifierList.size(); i++) {
DataSetIdentifier dsi = (DataSetIdentifier) dataSetIdentifierList.elementAt(i);
String displayName = dsi.getName();
if (dsi.isFunction()) {
AnnotatedFunction f = null;
for (int j = 0; j < annotatedFunctionList.size(); j++) {
AnnotatedFunction function = (AnnotatedFunction) annotatedFunctionList.elementAt(j);
if (function.getName().equals(dsi.getName())) {
f = function;
break;
}
}
if (f != null) {
displayName = f.getDisplayName();
}
}
dis[i] = new DataIdentifier(dsi.getName(), dsi.getVariableType(), dsi.getDomain(), dsi.isFunction(), displayName);
}
return dis;
}
use of cbit.vcell.math.CompartmentSubDomain in project vcell by virtualcell.
the class MathDebuggerPanel method main.
public static void main(java.lang.String[] args) {
try {
javax.swing.JFrame frame = new javax.swing.JFrame();
MathDebuggerPanel aMathDebuggerPanel;
aMathDebuggerPanel = new MathDebuggerPanel();
frame.setContentPane(aMathDebuggerPanel);
frame.setTitle("Math Descriptions Comparator");
frame.setSize(aMathDebuggerPanel.getSize());
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
MathModel mathModel1 = new MathModel(null);
mathModel1.setName("math1");
Geometry geometry1 = new Geometry("geo", 0);
MathDescription mathDesc1 = mathModel1.getMathDescription();
mathDesc1.setGeometry(geometry1);
mathDesc1.addSubDomain(new CompartmentSubDomain("Compartment", CompartmentSubDomain.NON_SPATIAL_PRIORITY));
MathModel mathModel2 = new MathModel(null);
mathModel2.setName("math2");
Geometry geometry2 = new Geometry("geo", 0);
MathDescription mathDesc2 = mathModel2.getMathDescription();
mathDesc2.setGeometry(geometry2);
mathDesc2.addSubDomain(new CompartmentSubDomain("Compartment", CompartmentSubDomain.NON_SPATIAL_PRIORITY));
aMathDebuggerPanel.setMathModel1(mathModel1);
aMathDebuggerPanel.setMathModel2(mathModel2);
frame.setSize(1500, 800);
frame.setVisible(true);
} catch (Throwable exception) {
System.err.println("Exception occurred in main() of javax.swing.JPanel");
exception.printStackTrace(System.out);
}
}
use of cbit.vcell.math.CompartmentSubDomain in project vcell by virtualcell.
the class MatlabOdeFileCoder method write_V6_MFile.
/**
* Insert the method's description here.
* Creation date: (3/8/00 10:31:52 PM)
*/
public void write_V6_MFile(java.io.PrintWriter pw, String functionName) throws MathException, ExpressionException {
MathDescription mathDesc = simulation.getMathDescription();
if (!mathDesc.isValid()) {
throw new MathException("invalid math description\n" + mathDesc.getWarning());
}
if (mathDesc.isSpatial()) {
throw new MathException("spatial math description, cannot create ode file");
}
if (mathDesc.hasFastSystems()) {
throw new MathException("math description contains algebraic constraints, cannot create .m file");
}
//
// print function declaration
//
pw.println("function [T,Y,yinit,param, allNames, allValues] = " + functionName + "(argTimeSpan,argYinit,argParam)");
pw.println("% [T,Y,yinit,param] = " + functionName + "(argTimeSpan,argYinit,argParam)");
pw.println("%");
pw.println("% input:");
pw.println("% argTimeSpan is a vector of start and stop times (e.g. timeSpan = [0 10.0])");
pw.println("% argYinit is a vector of initial conditions for the state variables (optional)");
pw.println("% argParam is a vector of values for the parameters (optional)");
pw.println("%");
pw.println("% output:");
pw.println("% T is the vector of times");
pw.println("% Y is the vector of state variables");
pw.println("% yinit is the initial conditions that were used");
pw.println("% param is the parameter vector that was used");
pw.println("% allNames is the output solution variable names");
pw.println("% allValues is the output solution variable values corresponding to the names");
pw.println("%");
pw.println("% example of running this file: [T,Y,yinit,param,allNames,allValues] = myMatlabFunc; <-(your main function name)");
pw.println("%");
VariableHash varHash = new VariableHash();
for (Variable var : simulationSymbolTable.getVariables()) {
varHash.addVariable(var);
}
Variable[] variables = varHash.getTopologicallyReorderedVariables();
CompartmentSubDomain subDomain = (CompartmentSubDomain) mathDesc.getSubDomains().nextElement();
//
// collect "true" constants (Constants without identifiers)
//
//
// collect "variables" (VolVariables only)
//
//
// collect "functions" (Functions and Constants with identifiers)
//
Vector<Constant> constantList = new Vector<Constant>();
Vector<VolVariable> volVarList = new Vector<VolVariable>();
Vector<Variable> functionList = new Vector<Variable>();
for (int i = 0; i < variables.length; i++) {
if (variables[i] instanceof Constant) {
Constant constant = (Constant) variables[i];
String[] symbols = constant.getExpression().getSymbols();
if (symbols == null || symbols.length == 0) {
constantList.addElement(constant);
} else {
functionList.add(constant);
}
} else if (variables[i] instanceof VolVariable) {
volVarList.addElement((VolVariable) variables[i]);
} else if (variables[i] instanceof Function) {
functionList.addElement(variables[i]);
}
}
Constant[] constants = (Constant[]) BeanUtils.getArray(constantList, Constant.class);
VolVariable[] volVars = (VolVariable[]) BeanUtils.getArray(volVarList, VolVariable.class);
Variable[] functions = (Variable[]) BeanUtils.getArray(functionList, Variable.class);
int numVars = volVarList.size() + functionList.size();
String varNamesForStringArray = "";
String varNamesForValueArray = "";
for (Variable var : volVarList) {
varNamesForStringArray = varNamesForStringArray + "'" + var.getName() + "';";
varNamesForValueArray = varNamesForValueArray + var.getName() + " ";
}
for (Variable func : functionList) {
varNamesForStringArray = varNamesForStringArray + "'" + func.getName() + "';";
varNamesForValueArray = varNamesForValueArray + func.getName() + " ";
}
pw.println("");
pw.println("%");
pw.println("% Default time span");
pw.println("%");
double beginTime = 0.0;
double endTime = simulation.getSolverTaskDescription().getTimeBounds().getEndingTime();
pw.println("timeSpan = [" + beginTime + " " + endTime + "];");
pw.println("");
pw.println("% output variable lengh and names");
pw.println("numVars = " + numVars + ";");
pw.println("allNames = {" + varNamesForStringArray + "};");
pw.println("");
pw.println("if nargin >= 1");
pw.println("\tif length(argTimeSpan) > 0");
pw.println("\t\t%");
pw.println("\t\t% TimeSpan overridden by function arguments");
pw.println("\t\t%");
pw.println("\t\ttimeSpan = argTimeSpan;");
pw.println("\tend");
pw.println("end");
pw.println("%");
pw.println("% Default Initial Conditions");
pw.println("%");
pw.println("yinit = [");
for (int j = 0; j < volVars.length; j++) {
Expression initial = subDomain.getEquation(volVars[j]).getInitialExpression();
double defaultInitialCondition = 0;
try {
initial.bindExpression(mathDesc);
defaultInitialCondition = initial.evaluateConstant();
pw.println("\t" + defaultInitialCondition + ";\t\t% yinit(" + (j + 1) + ") is the initial condition for '" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[j].getName()) + "'");
} catch (ExpressionException e) {
e.printStackTrace(System.out);
pw.println("\t" + initial.infix_Matlab() + ";\t\t% yinit(" + (j + 1) + ") is the initial condition for '" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[j].getName()) + "'");
// throw new RuntimeException("error evaluating initial condition for variable "+volVars[j].getName());
}
}
pw.println("];");
pw.println("if nargin >= 2");
pw.println("\tif length(argYinit) > 0");
pw.println("\t\t%");
pw.println("\t\t% initial conditions overridden by function arguments");
pw.println("\t\t%");
pw.println("\t\tyinit = argYinit;");
pw.println("\tend");
pw.println("end");
pw.println("%");
pw.println("% Default Parameters");
pw.println("% constants are only those \"Constants\" from the Math Description that are just floating point numbers (no identifiers)");
pw.println("% note: constants of the form \"A_init\" are really initial conditions and are treated in \"yinit\"");
pw.println("%");
pw.println("param = [");
int paramIndex = 0;
for (int i = 0; i < constants.length; i++) {
pw.println("\t" + constants[i].getExpression().infix_Matlab() + ";\t\t% param(" + (paramIndex + 1) + ") is '" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(constants[i].getName()) + "'");
paramIndex++;
}
pw.println("];");
pw.println("if nargin >= 3");
pw.println("\tif length(argParam) > 0");
pw.println("\t\t%");
pw.println("\t\t% parameter values overridden by function arguments");
pw.println("\t\t%");
pw.println("\t\tparam = argParam;");
pw.println("\tend");
pw.println("end");
pw.println("%");
pw.println("% invoke the integrator");
pw.println("%");
pw.println("[T,Y] = ode15s(@f,timeSpan,yinit,odeset('OutputFcn',@odeplot),param,yinit);");
pw.println("");
pw.println("% get the solution");
pw.println("all = zeros(size(T), numVars);");
pw.println("for i = 1:size(T)");
pw.println("\tall(i,:) = getRow(T(i), Y(i,:), yinit, param);");
pw.println("end");
pw.println("");
pw.println("allValues = all;");
pw.println("end");
// get row data for solution
pw.println("");
pw.println("% -------------------------------------------------------");
pw.println("% get row data");
pw.println("function rowValue = getRow(t,y,y0,p)");
//
// print volVariables (in order and assign to var vector)
//
pw.println("\t% State Variables");
for (int i = 0; i < volVars.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[i].getName()) + " = y(" + (i + 1) + ");");
}
//
// print constants
//
pw.println("\t% Constants");
paramIndex = 0;
for (int i = 0; i < constants.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(constants[i].getName()) + " = p(" + (paramIndex + 1) + ");");
paramIndex++;
}
//
// print variables
//
pw.println("\t% Functions");
for (int i = 0; i < functions.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(functions[i].getName()) + " = " + functions[i].getExpression().infix_Matlab() + ";");
}
pw.println("");
pw.println("\trowValue = [" + varNamesForValueArray + "];");
pw.println("end");
//
// print ode-rate
//
pw.println("");
pw.println("% -------------------------------------------------------");
pw.println("% ode rate");
pw.println("function dydt = f(t,y,p,y0)");
//
// print volVariables (in order and assign to var vector)
//
pw.println("\t% State Variables");
for (int i = 0; i < volVars.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[i].getName()) + " = y(" + (i + 1) + ");");
}
//
// print constants
//
pw.println("\t% Constants");
paramIndex = 0;
for (int i = 0; i < constants.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(constants[i].getName()) + " = p(" + (paramIndex + 1) + ");");
paramIndex++;
}
//
// print variables
//
pw.println("\t% Functions");
for (int i = 0; i < functions.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(functions[i].getName()) + " = " + functions[i].getExpression().infix_Matlab() + ";");
}
pw.println("\t% Rates");
pw.println("\tdydt = [");
for (int i = 0; i < volVars.length; i++) {
pw.println("\t\t" + subDomain.getEquation(volVars[i]).getRateExpression().infix_Matlab() + "; % rate for " + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[i].getName()));
}
pw.println("\t];");
pw.println("end");
}
Aggregations