Search in sources :

Example 61 with Variable

use of cbit.vcell.math.Variable in project vcell by virtualcell.

the class SbmlVcmlConverter method solveSimulation.

/**
 * solves the simulation that is passed in throught the simulation job.
 */
private static void solveSimulation(SimulationJob simJob, String filePathName, SimSpec argSimSpec) /* Hashtable argSpUnitsHash, double argTimeFactor, Model.ReservedSymbol kMoleSymbol*/
{
    ODESolverResultSet odeSolverResultSet = null;
    try {
        /*		// Generate .idaInput string		
		File idaInputFile = new File(filePathName.replace(".vcml", ".idaInput"));
		PrintWriter idaPW = new java.io.PrintWriter(idaInputFile);
		IDAFileWriter idaFileWriter = new IDAFileWriter(idaPW, simJob);
		idaFileWriter.write();
		idaPW.close();

		// use the SundialsStandaloneSolver
		File idaOutputFile = new File(filePathName.replace(".vcml", ".ida"));
		Executable executable = new Executable(new String[]{"SundialsSolverStandalone", idaInputFile.getAbsolutePath(), idaOutputFile.getAbsolutePath()});
		executable.start();
*/
        // Generate .cvodeInput string
        File cvodeInputFile = new File(filePathName.replace(".vcml", ".cvodeInput"));
        PrintWriter cvodePW = new java.io.PrintWriter(cvodeInputFile);
        SimulationTask simTask = new SimulationTask(simJob, 0);
        CVodeFileWriter cvodeFileWriter = new CVodeFileWriter(cvodePW, simTask);
        cvodeFileWriter.write();
        cvodePW.close();
        // use the cvodeStandalone solver
        // use the SundialsStandaloneSolver
        File cvodeOutputFile = new File(filePathName.replace(".vcml", ".ida"));
        /*
		Executable executable = new Executable(new String[]{"d:/workspace/VCell_5.3_VCell/SundialsSolverStandalone_x64", cvodeInputFile.getAbsolutePath(), cvodeOutputFile.getAbsolutePath()});
		executable.start();
		*/
        // use the cvodeStandalone solver
        // use the SundialsStandaloneSolver
        File[] exes = SolverUtilities.getExes(SolverDescription.CombinedSundials);
        assert exes.length == 1 : "one and only one smoldyn solver expected";
        File sundialsExe = exes[0];
        Executable executable = new Executable(new String[] { sundialsExe.getAbsolutePath(), cvodeInputFile.getAbsolutePath(), cvodeOutputFile.getAbsolutePath() });
        executable.start();
        // get the result
        odeSolverResultSet = VCellSBMLSolver.getODESolverResultSet(simJob, cvodeOutputFile.getPath());
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("Error running NativeIDA solver : " + e.getMessage());
    }
    // now write out the results into CSV file
    try {
        if (odeSolverResultSet != null) {
            File csvFile = new File(filePathName.replace(".vcml", ".csv"));
            PrintStream outputStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(csvFile)));
            outputStream.print("time");
            for (int i = 0; i < argSimSpec.getVarsList().length; i++) {
                outputStream.print("," + argSimSpec.getVarsList()[i]);
            }
            outputStream.println();
            // extract data for time and species
            double[][] data = new double[argSimSpec.getVarsList().length + 1][];
            int column = odeSolverResultSet.findColumn("t");
            data[0] = odeSolverResultSet.extractColumn(column);
            int origDataLength = data[0].length;
            for (int i = 0; i < argSimSpec.getVarsList().length; i++) {
                column = odeSolverResultSet.findColumn(argSimSpec.getVarsList()[i]);
                if (column == -1) {
                    Variable var = simJob.getSimulationSymbolTable().getVariable(argSimSpec.getVarsList()[i]);
                    data[i + 1] = new double[data[0].length];
                    if (var instanceof cbit.vcell.math.Constant) {
                        double value = ((cbit.vcell.math.Constant) var).getExpression().evaluateConstant();
                        for (int j = 0; j < data[i + 1].length; j++) {
                            data[i + 1][j] = value;
                        }
                    } else {
                        throw new RuntimeException("Did not find " + argSimSpec.getVarsList()[i] + " in simulation");
                    }
                } else {
                    data[i + 1] = odeSolverResultSet.extractColumn(column);
                }
            }
            double endTime = (simJob.getSimulation().getSolverTaskDescription().getTimeBounds().getEndingTime());
            // for each time, print row
            int index = 0;
            double[] sampleTimes = new double[numTimeSteps + 1];
            for (int i = 0; i <= numTimeSteps; i++) {
                sampleTimes[i] = endTime * i / numTimeSteps;
            }
            for (int i = 0; i < sampleTimes.length; i++) {
                // find largest index whose time is not past sample time
                while (true) {
                    // if already at last time point, then if it equals the sampleTime, we're done if it doesn't then we don't have this time point.
                    if (index == odeSolverResultSet.getRowCount() - 1) {
                        if (data[0][index] == sampleTimes[i]) {
                            break;
                        } else {
                            throw new RuntimeException("sampleTime does not match at last time point");
                        }
                    }
                    // haven't gotten to last time point yet, stop when next time step is past sampleTime.
                    if (data[0][index + 1] > sampleTimes[i]) {
                        break;
                    }
                    // sampleTime must be later in our data list.
                    index++;
                }
                // if (data[0][index] == sampleTimes[i]) {
                if (Math.abs(data[0][index] - sampleTimes[i]) < 1e-12) {
                    // if timeFactor is not 1.0, time is not in seconds (mins or hrs); if timeFactor is 60, divide sampleTime/60; if it is 3600, divide sampleTime/3600.
                    // if (argTimeFactor != 1.0) {
                    // outputStream.print(data[0][index]/argTimeFactor);
                    // } else {
                    outputStream.print(data[0][index]);
                    // }
                    for (int j = 0; j < argSimSpec.getVarsList().length; j++) {
                        // SBMLImporter.SBVCConcentrationUnits spConcUnits = (SBMLImporter.SBVCConcentrationUnits)argSpUnitsHash.get(argSimSpec.getVarsList()[j]);
                        // if (spConcUnits != null) {
                        // VCUnitDefinition sbunits = spConcUnits.getSBConcentrationUnits();
                        // VCUnitDefinition vcunits = spConcUnits.getVCConcentrationUnits();
                        // SBMLUnitParameter unitFactor = SBMLUtils.getConcUnitFactor("spConcParam", vcunits, sbunits, kMoleSymbol);
                        // outputStream.print("," + data[j + 1][index] * unitFactor.getExpression().evaluateConstant()); 		//earlier, hack unitfactor = 0.000001
                        // earlier, hack unitfactor = 0.000001
                        outputStream.print("," + data[j + 1][index]);
                    }
                    // }
                    outputStream.println();
                } else {
                    // if data[0][index] < sampleTime, must interpolate
                    double fraction = (sampleTimes[i] - data[0][index]) / (data[0][index + 1] - data[0][index]);
                    // if argTimeFactor is not 1.0, time is not in seconds (mins or hrs); if argTimeFactor is 60, divide sampleTime/60; if it is 3600, divide sampleTime/3600.
                    // if (argTimeFactor != 1.0) {
                    // outputStream.print(sampleTimes[i]/argTimeFactor);
                    // } else {
                    outputStream.print(sampleTimes[i]);
                    // }
                    for (int j = 0; j < argSimSpec.getVarsList().length; j++) {
                        double interpolatedValue = 0.0;
                        double[] speciesVals = null;
                        double[] times = null;
                        // Currently using 2nd order interpolation
                        if (index == 0) {
                            // can only do 1st order interpolation
                            times = new double[] { data[0][index], data[0][index + 1] };
                            speciesVals = new double[] { data[j + 1][index], data[j + 1][index + 1] };
                            interpolatedValue = MathTestingUtilities.taylorInterpolation(sampleTimes[i], times, speciesVals);
                        } else {
                            if (index >= 1 && index <= origDataLength - 3) {
                                double val_1 = Math.abs(sampleTimes[i] - data[0][index - 1]);
                                double val_2 = Math.abs(sampleTimes[i] - data[0][index + 2]);
                                if (val_1 < val_2) {
                                    times = new double[] { data[0][index - 1], data[0][index], data[0][index + 1] };
                                    speciesVals = new double[] { data[j + 1][index - 1], data[j + 1][index], data[j + 1][index + 1] };
                                } else {
                                    times = new double[] { data[0][index], data[0][index + 1], data[0][index + 2] };
                                    speciesVals = new double[] { data[j + 1][index], data[j + 1][index + 1], data[j + 1][index + 2] };
                                }
                                interpolatedValue = MathTestingUtilities.taylorInterpolation(sampleTimes[i], times, speciesVals);
                            } else {
                                times = new double[] { data[0][index - 1], data[0][index], data[0][index + 1] };
                                speciesVals = new double[] { data[j + 1][index - 1], data[j + 1][index], data[j + 1][index + 1] };
                                interpolatedValue = MathTestingUtilities.taylorInterpolation(sampleTimes[i], times, speciesVals);
                            }
                        }
                        // end if-else - calc of interpolated value
                        // interpolatedValue = interpolatedValue * unitFactor.getExpression().evaluateConstant();
                        outputStream.print("," + interpolatedValue);
                    }
                    // end for - sp values for each time point (row)
                    outputStream.println();
                }
            }
            outputStream.close();
        } else {
            throw new RuntimeException("Result set was null, could not write to CSV file");
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("Errors saving results to CSV file" + e.getMessage());
    }
}
Also used : PrintStream(java.io.PrintStream) SimulationTask(cbit.vcell.messaging.server.SimulationTask) Variable(cbit.vcell.math.Variable) CVodeFileWriter(cbit.vcell.solver.ode.CVodeFileWriter) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) ODESolverResultSet(cbit.vcell.solver.ode.ODESolverResultSet) Executable(org.vcell.util.exe.Executable) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) PrintWriter(java.io.PrintWriter)

Example 62 with Variable

use of cbit.vcell.math.Variable in project vcell by virtualcell.

the class OutputFunctionsPanel method getPossibleGeometryClassesAndVariableTypes.

private ArrayList<Object> getPossibleGeometryClassesAndVariableTypes(Expression expr) throws ExpressionException, InconsistentDomainException {
    SimulationOwner simulationOwner = getSimulationWorkspace().getSimulationOwner();
    MathDescription mathDescription = simulationOwner.getMathDescription();
    boolean bSpatial = simulationOwner.getGeometry().getDimension() > 0;
    if (!bSpatial) {
        return null;
    }
    // making sure that output function is not direct function of constant.
    expr.bindExpression(outputFunctionContext);
    // here use math description as symbol table because we allow
    // new expression itself to be function of constant.
    expr = MathUtilities.substituteFunctions(expr, outputFunctionContext).flatten();
    String[] symbols = expr.getSymbols();
    // using bit operation to determine whether geometry classes for symbols in expression are vol, membrane or both. 01 => vol; 10 => membrane; 11 => both
    int gatherFlag = 0;
    Set<GeometryClass> geomClassSet = new HashSet<GeometryClass>();
    ArrayList<Object> objectsList = new ArrayList<Object>();
    boolean bHasVariable = false;
    VariableType[] varTypes = null;
    if (symbols != null && symbols.length > 0) {
        // making sure that new expression is defined in the same domain
        varTypes = new VariableType[symbols.length];
        for (int i = 0; i < symbols.length; i++) {
            if (ReservedMathSymbolEntries.getReservedVariableEntry(symbols[i]) != null) {
                varTypes[i] = VariableType.VOLUME;
            } else {
                Variable var = mathDescription.getVariable(symbols[i]);
                if (var == null) {
                    var = mathDescription.getPostProcessingBlock().getDataGenerator(symbols[i]);
                }
                varTypes[i] = VariableType.getVariableType(var);
                bHasVariable = true;
                if (var.getDomain() != null) {
                    GeometryClass varGeoClass = simulationOwner.getGeometry().getGeometryClass(var.getDomain().getName());
                    geomClassSet.add(varGeoClass);
                    if (varGeoClass instanceof SubVolume) {
                        gatherFlag |= 1;
                    } else if (varGeoClass instanceof SurfaceClass) {
                        gatherFlag |= 2;
                    }
                }
                if (varTypes[i].equals(VariableType.POSTPROCESSING)) {
                    gatherFlag |= 4;
                }
            }
        }
    }
    if (gatherFlag > 4) {
        throw new RuntimeException("cannot mix post processing variables with membrane or volume variables");
    }
    int numGeomClasses = geomClassSet.size();
    if (numGeomClasses == 0) {
        if (bHasVariable) {
            // if there are no variables (like built in function, vcRegionArea), check with flattened expression to find out the variable type of the new expression
            Function flattenedFunction = new Function(getFunctionNameTextField().getText(), expr, null);
            flattenedFunction.bind(outputFunctionContext);
            VariableType newVarType = SimulationSymbolTable.getFunctionVariableType(flattenedFunction, simulationOwner.getMathDescription(), symbols, varTypes, bSpatial);
            objectsList.add(newVarType);
        } else {
            objectsList.add(VariableType.VOLUME);
            objectsList.add(VariableType.MEMBRANE);
        }
    } else if (numGeomClasses == 1) {
        objectsList.add(geomClassSet.iterator().next());
        if (gatherFlag == 1) {
            objectsList.add(VariableType.MEMBRANE);
        }
    } else if (gatherFlag == 1) {
        // all volumes
        if (numGeomClasses == 2) {
            // all subvolumes, if there are only 2, check for adjacency.
            GeometryClass[] geomClassesArray = geomClassSet.toArray(new GeometryClass[0]);
            SurfaceClass sc = simulationOwner.getGeometry().getGeometrySurfaceDescription().getSurfaceClass((SubVolume) geomClassesArray[0], (SubVolume) geomClassesArray[1]);
            if (sc != null) {
                objectsList.add(sc);
            }
        }
        objectsList.add(VariableType.VOLUME);
    } else if (gatherFlag == 2) {
        // all membranes
        objectsList.add(VariableType.MEMBRANE);
    } else if (gatherFlag == 3) {
        // mixed - both vols and membranes
        // add only membranes?
        objectsList.add(VariableType.MEMBRANE);
    }
    return objectsList;
}
Also used : GeometryClass(cbit.vcell.geometry.GeometryClass) Variable(cbit.vcell.math.Variable) VariableType(cbit.vcell.math.VariableType) MathDescription(cbit.vcell.math.MathDescription) SurfaceClass(cbit.vcell.geometry.SurfaceClass) ArrayList(java.util.ArrayList) SimulationOwner(cbit.vcell.solver.SimulationOwner) Function(cbit.vcell.math.Function) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) SubVolume(cbit.vcell.geometry.SubVolume) HashSet(java.util.HashSet)

Example 63 with Variable

use of cbit.vcell.math.Variable in project vcell by virtualcell.

the class SimulationWorkspace method getExpectedSizeBytes.

/**
 * Insert the method's description here.
 * Creation date: (6/12/2001 10:09:25 AM)
 * @return boolean
 * @param simulation cbit.vcell.solver.Simulation
 */
private static long getExpectedSizeBytes(SimulationSymbolTable simSymbolTable) {
    Simulation simulation = simSymbolTable.getSimulation();
    long numTimepoints;
    if (simulation.getMathDescription().isNonSpatialStoch()) {
        numTimepoints = getEstimatedNumTimePointsForStoch(simSymbolTable);
    } else {
        numTimepoints = getExpectedNumTimePoints(simulation);
    }
    int x, y, z;
    int numVariables = 0;
    if (simulation.isSpatial()) {
        x = simulation.getMeshSpecification().getSamplingSize().getX();
        y = simulation.getMeshSpecification().getSamplingSize().getY();
        z = simulation.getMeshSpecification().getSamplingSize().getZ();
        // 
        // compute number of volume variables only (they are multiplied by x*y*z)
        // 
        numVariables = 0;
        Enumeration<Variable> variables = simulation.getMathDescription().getVariables();
        while (variables.hasMoreElements()) {
            Variable var = variables.nextElement();
            if (var instanceof VolVariable) {
                numVariables++;
            }
        }
    } else {
        x = 1;
        y = 1;
        z = 1;
        numVariables = 0;
        Enumeration<Variable> variables = simulation.getMathDescription().getVariables();
        while (variables.hasMoreElements()) {
            Variable var = variables.nextElement();
            if ((var instanceof VolVariable) || (var instanceof Function)) {
                numVariables++;
            }
        }
    }
    // approximate, don't compute header size since it's negligible whenever we approach quota size anyway...
    // values are actually written as longs
    long expectedSize = numTimepoints * numVariables * x * y * z * 8;
    return expectedSize;
}
Also used : Function(cbit.vcell.math.Function) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Variable(cbit.vcell.math.Variable) VolVariable(cbit.vcell.math.VolVariable) Simulation(cbit.vcell.solver.Simulation) VolVariable(cbit.vcell.math.VolVariable)

Example 64 with Variable

use of cbit.vcell.math.Variable 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");
}
Also used : Variable(cbit.vcell.math.Variable) VolVariable(cbit.vcell.math.VolVariable) MathDescription(cbit.vcell.math.MathDescription) VolVariable(cbit.vcell.math.VolVariable) VariableHash(cbit.vcell.math.VariableHash) Constant(cbit.vcell.math.Constant) ExpressionException(cbit.vcell.parser.ExpressionException) Function(cbit.vcell.math.Function) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) Vector(java.util.Vector)

Example 65 with Variable

use of cbit.vcell.math.Variable in project vcell by virtualcell.

the class MathDescriptionCellRenderer method getTreeCellRendererComponent.

/**
 * Insert the method's description here.
 * Creation date: (7/27/2000 6:41:57 PM)
 * @return java.awt.Component
 */
public java.awt.Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    JLabel component = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
    boolean bLoaded = false;
    // 
    try {
        if (value instanceof BioModelNode) {
            BioModelNode node = (BioModelNode) value;
            if (node.getUserObject() instanceof PdeEquation) {
                PdeEquation pdeEquation = (PdeEquation) node.getUserObject();
                Variable var = pdeEquation.getVariable();
                component.setToolTipText("PDE Equation");
                // \u2207 = nabla ... del operator
                // \u2219 = dot
                String DEL = "\u2207";
                // "\u2202";     //  '\u2202' is partial differentiation    'd' is regular diff
                String PARTIAL_DIFF = "d";
                String Super2 = "\u00b2";
                String DOT = "\u2219";
                // String diffusionTerm = DEL+" "+DOT+" "+"("+pdeEquation.getDiffusionExpression()+" "+DEL+" "+var.getName()+")";
                String diffusionTerm = "";
                if (pdeEquation.getVelocityX() != null || pdeEquation.getVelocityY() != null || pdeEquation.getVelocityZ() != null) {
                    if (pdeEquation.getDiffusionExpression().isZero()) {
                        // reaction/advection
                        diffusionTerm = "- " + DEL + " " + DOT + "( velocity " + var.getName() + " )";
                    } else {
                        // reaction/diffusion/advection
                        diffusionTerm = DEL + " " + DOT + " (" + pdeEquation.getDiffusionExpression().infix() + " " + DEL + "  " + var.getName() + "   -   velocity " + var.getName() + ")";
                    }
                } else {
                    diffusionTerm = "(" + pdeEquation.getDiffusionExpression().infix() + ") " + DEL + Super2 + " " + var.getName();
                }
                String gradTerm = "";
                if (pdeEquation.getGradientX() != null && !pdeEquation.getGradientX().isZero()) {
                    gradTerm += " + " + PARTIAL_DIFF + "[" + pdeEquation.getGradientX().infix() + "]/" + PARTIAL_DIFF + "x";
                }
                if (pdeEquation.getGradientY() != null && !pdeEquation.getGradientY().isZero()) {
                    gradTerm += " + " + PARTIAL_DIFF + "[" + pdeEquation.getGradientY().infix() + "]/" + PARTIAL_DIFF + "y";
                }
                if (pdeEquation.getGradientZ() != null && !pdeEquation.getGradientZ().isZero()) {
                    gradTerm += " + " + PARTIAL_DIFF + "[" + pdeEquation.getGradientZ().infix() + "]/" + PARTIAL_DIFF + "z";
                }
                String sourceTerm = pdeEquation.getRateExpression().infix();
                if (!sourceTerm.equals("0.0")) {
                    component.setText(PARTIAL_DIFF + "[" + var.getName() + "]/" + PARTIAL_DIFF + "t = " + diffusionTerm + gradTerm + " + " + sourceTerm);
                } else {
                    component.setText(PARTIAL_DIFF + "[" + var.getName() + "]/" + PARTIAL_DIFF + "t = " + diffusionTerm + gradTerm);
                }
            } else if (node.getUserObject() instanceof OdeEquation) {
                OdeEquation odeEquation = (OdeEquation) node.getUserObject();
                Variable var = odeEquation.getVariable();
                component.setToolTipText("ODE Equation");
                component.setText("d[" + var.getName() + "]/dt = " + odeEquation.getRateExpression().infix());
            } else if (node.getUserObject() instanceof MembraneRegionEquation) {
                MembraneRegionEquation membraneRegionEquation = (MembraneRegionEquation) node.getUserObject();
                Variable var = membraneRegionEquation.getVariable();
                component.setToolTipText("Membrane Region Equation");
                component.setText("Membrane Region Equation for " + var.getName());
            } else if (node.getUserObject() instanceof JumpCondition) {
                JumpCondition jumpCondition = (JumpCondition) node.getUserObject();
                Variable var = jumpCondition.getVariable();
                component.setToolTipText("Jump Condition");
                component.setText("Flux for " + var.getName());
            } else if (node.getUserObject() instanceof Constant) {
                Constant constant = (Constant) node.getUserObject();
                component.setToolTipText("Constant");
                component.setText(constant.getName() + " = " + constant.getExpression().infix());
            } else if (node.getUserObject() instanceof Function) {
                Function function = (Function) node.getUserObject();
                component.setToolTipText("Function");
                component.setText(function.getName() + " = " + function.getExpression().infix());
            } else if (node.getUserObject() instanceof SubDomain) {
                SubDomain subDomain = (SubDomain) node.getUserObject();
                component.setToolTipText("SubDomain");
                component.setText(subDomain.getName());
            } else if (node.getUserObject() instanceof FastSystem) {
                component.setToolTipText("Fast System");
                component.setText("Fast System");
            } else if (node.getUserObject() instanceof FastInvariant) {
                FastInvariant fi = (FastInvariant) node.getUserObject();
                component.setToolTipText("Fast Invariant");
                component.setText("fast invariant: " + fi.getFunction().infix());
            } else if (node.getUserObject() instanceof FastRate) {
                FastRate fr = (FastRate) node.getUserObject();
                component.setToolTipText("Fast Rate");
                component.setText("fast rate: " + fr.getFunction().infix());
            } else if (node.getUserObject() instanceof Annotation) {
                Annotation annotation = (Annotation) node.getUserObject();
                component.setToolTipText("Annotation");
                component.setText("\"" + annotation + "\"");
            } else {
            }
            if (selectedFont == null && component.getFont() != null) {
                selectedFont = component.getFont().deriveFont(Font.BOLD);
            }
            if (unselectedFont == null && component.getFont() != null) {
                unselectedFont = component.getFont().deriveFont(Font.PLAIN);
            }
            if (bLoaded) {
                component.setFont(selectedFont);
            } else {
                component.setFont(unselectedFont);
            }
        }
    } catch (Throwable e) {
        e.printStackTrace(System.out);
    }
    // 
    return component;
}
Also used : JumpCondition(cbit.vcell.math.JumpCondition) Variable(cbit.vcell.math.Variable) Constant(cbit.vcell.math.Constant) JLabel(javax.swing.JLabel) FastRate(cbit.vcell.math.FastRate) BioModelNode(cbit.vcell.desktop.BioModelNode) FastInvariant(cbit.vcell.math.FastInvariant) Annotation(cbit.vcell.desktop.Annotation) PdeEquation(cbit.vcell.math.PdeEquation) SubDomain(cbit.vcell.math.SubDomain) Function(cbit.vcell.math.Function) OdeEquation(cbit.vcell.math.OdeEquation) FastSystem(cbit.vcell.math.FastSystem) MembraneRegionEquation(cbit.vcell.math.MembraneRegionEquation)

Aggregations

Variable (cbit.vcell.math.Variable)108 Expression (cbit.vcell.parser.Expression)69 VolVariable (cbit.vcell.math.VolVariable)63 MemVariable (cbit.vcell.math.MemVariable)48 ReservedVariable (cbit.vcell.math.ReservedVariable)43 MembraneRegionVariable (cbit.vcell.math.MembraneRegionVariable)38 MathException (cbit.vcell.math.MathException)37 VolumeRegionVariable (cbit.vcell.math.VolumeRegionVariable)36 FilamentVariable (cbit.vcell.math.FilamentVariable)35 InsideVariable (cbit.vcell.math.InsideVariable)34 OutsideVariable (cbit.vcell.math.OutsideVariable)34 ExpressionException (cbit.vcell.parser.ExpressionException)34 Function (cbit.vcell.math.Function)32 MathDescription (cbit.vcell.math.MathDescription)32 Constant (cbit.vcell.math.Constant)31 FilamentRegionVariable (cbit.vcell.math.FilamentRegionVariable)29 VolumeParticleVariable (cbit.vcell.math.VolumeParticleVariable)25 MembraneParticleVariable (cbit.vcell.math.MembraneParticleVariable)24 ParticleVariable (cbit.vcell.math.ParticleVariable)24 Vector (java.util.Vector)23