Search in sources :

Example 36 with Constant

use of cbit.vcell.math.Constant 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 37 with Constant

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

the class MathDescPanel method refreshEquations.

/**
 * This method was created by a SmartGuide.
 */
private void refreshEquations() throws ExpressionException {
    TreePath selectionPath = getselectionModel1().getSelectionPath();
    if (selectionPath != null) {
        BioModelNode node = (BioModelNode) selectionPath.getLastPathComponent();
        Object[] objectPath = node.getUserObjectPath();
        Object lastPathObject = objectPath[objectPath.length - 1];
        // for non-stochastic
        Expression[] expArray = null;
        // for stochastic
        String[] expString = null;
        getExpressionCanvas1().setStrings(null);
        getExpressionCanvas1().setExpressions(null);
        if (lastPathObject instanceof Function) {
            Function function = (Function) lastPathObject;
            Expression exp = function.getExpression();
            if (getJRadioButtonValue().isSelected()) {
                exp.bindExpression(getMathDescription());
            } else {
                exp.bindExpression(null);
            }
            exp = exp.flatten();
            // stochastic variable initial value must be an int, therefore we must make it here.
            if (getMathDescription().isNonSpatialStoch() && function.getName().startsWith(DiffEquMathMapping.MATH_FUNC_SUFFIX_SPECIES_INIT_CONC_UNIT_PREFIX)) {
                try {
                    double value = exp.evaluateConstant();
                    expString = new String[] { function.getName() + " = " + Math.round(value) };
                    getExpressionCanvas1().setStrings(expString);
                } catch (Exception e) {
                    expArray = new Expression[] { Expression.assign(new Expression(function.getName()), exp) };
                    getExpressionCanvas1().setExpressions(expArray);
                }
            } else {
                expArray = new Expression[] { Expression.assign(new Expression(function.getName()), exp) };
                getExpressionCanvas1().setExpressions(expArray);
            }
        } else if (lastPathObject instanceof Constant) {
            Constant constant = (Constant) lastPathObject;
            Expression exp = constant.getExpression();
            if (getJRadioButtonValue().isSelected()) {
                exp.bindExpression(getMathDescription());
            } else {
                exp.bindExpression(null);
            }
            exp = exp.flatten();
            // stochastic variable initial value must be an int, therefore we must make it here.
            if (getMathDescription().isNonSpatialStoch() && constant.getName().startsWith(DiffEquMathMapping.MATH_FUNC_SUFFIX_SPECIES_INIT_CONC_UNIT_PREFIX)) {
                try {
                    double value = exp.evaluateConstant();
                    expString = new String[] { constant.getName() + " = " + Math.round(value) };
                    getExpressionCanvas1().setStrings(expString);
                } catch (Exception e) {
                    expArray = new Expression[] { Expression.assign(new Expression(constant.getName()), exp) };
                    getExpressionCanvas1().setExpressions(expArray);
                }
            } else {
                expArray = new Expression[] { Expression.assign(new Expression(constant.getName()), exp) };
                getExpressionCanvas1().setExpressions(expArray);
            }
        } else if (lastPathObject instanceof Equation) {
            Equation equ = (Equation) lastPathObject;
            Enumeration<Expression> enum_equ = equ.getTotalExpressions();
            Vector<Expression> expList = new Vector<Expression>();
            while (enum_equ.hasMoreElements()) {
                Expression exp = new Expression(enum_equ.nextElement());
                if (getJRadioButtonValue().isSelected()) {
                    exp.bindExpression(getMathDescription());
                } else {
                    exp.bindExpression(null);
                }
                expList.addElement(exp.flatten());
            }
            expArray = new Expression[expList.size()];
            expList.copyInto(expArray);
            getExpressionCanvas1().setExpressions(expArray);
        } else if (// added Sept 29, 2006
        lastPathObject instanceof VarIniCondition) {
            VarIniCondition varIni = (VarIniCondition) lastPathObject;
            expString = new String[] { varIni.toString() };
            getExpressionCanvas1().setStrings(expString);
        } else if (// added Sept 29, 2006
        lastPathObject instanceof Action) {
            Action action = (Action) lastPathObject;
            expString = new String[] { action.toString() };
            getExpressionCanvas1().setStrings(expString);
        } else if (// added Sept 29, 2006
        lastPathObject instanceof String) {
            // to check if the string is the probability string
            int index1 = ((String) lastPathObject).indexOf("probability_rate");
            int index2 = ((String) lastPathObject).indexOf("=");
            if (// has probability eqution,but don't calculate prob string, since it is not a constant value.
            (index1 == 0) && ((index2 + 2) < ((String) lastPathObject).length())) {
                expString = new String[] { (String) lastPathObject };
                getExpressionCanvas1().setStrings(expString);
            }
        }
    } else {
        getExpressionCanvas1().setExpressions(null);
        getExpressionCanvas1().setStrings(null);
        getExpressionCanvas1().repaint();
    }
// Variable var = getMathDescription().getVariable(varName);
// SubDomain subDomain = getMathDescription().getSubDomain(subDomainName);
// Equation equ = null;
// if (var != null && subDomain != null){
// equ = subDomain.getEquation(var);
// }
// if (equ == null){
// if (subDomain instanceof MembraneSubDomain && var instanceof VolVariable){
// equ = ((MembraneSubDomain)subDomain).getJumpCondition((VolVariable)var);
// }
// }
// if (equ == null){
// Expression exp = null;
// String title = "hello";
// if (var instanceof Constant || var instanceof Function){
// exp = var.getExpression();
// title = "Expression for "+var.getName();
// }
// if (getJRadioButtonValue().isSelected()){
// exp.bindExpression(getMathDescription());
// }else{
// exp.bindExpression(null);
// }
// getExpressionCanvas1().setExpression(exp.flatten());
// getEquationTitleLabel().setText(title);
// }else{
// Enumeration enum_equ = equ.getTotalExpressions();
// Vector expList = new Vector();
// while (enum_equ.hasMoreElements()){
// Expression exp = new Expression((Expression)enum_equ.nextElement());
// if (getJRadioButtonValue().isSelected()){
// exp.bindExpression(getMathDescription());
// }else{
// exp.bindExpression(null);
// }
// expList.addElement(exp.flatten());
// }
// Expression expArray[] = new Expression[expList.size()];
// expList.copyInto(expArray);
// getExpressionCanvas1().setExpressions(expArray);
// getEquationTitleLabel().setText("Equations for "+var.getName()+" within "+subDomain.getName());
// }
// } catch (java.lang.Throwable ivjExc) {
// handleException(ivjExc);
// getEquationTitleLabel().setText("Equations for "+varName+" within "+subDomainName+" *** "+ivjExc.getMessage());
// }
// }
// }else{
// getEquationTitleLabel().setText("no variable selected");
// getExpressionCanvas1().setExpression((Expression)null);
// }
}
Also used : VarIniCondition(cbit.vcell.math.VarIniCondition) Action(cbit.vcell.math.Action) Constant(cbit.vcell.math.Constant) Equation(cbit.vcell.math.Equation) BioModelNode(cbit.vcell.desktop.BioModelNode) ExpressionException(cbit.vcell.parser.ExpressionException) Function(cbit.vcell.math.Function) TreePath(javax.swing.tree.TreePath) Expression(cbit.vcell.parser.Expression) Vector(java.util.Vector)

Example 38 with Constant

use of cbit.vcell.math.Constant 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)

Example 39 with Constant

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

the class MathDescriptionTreeModel method createBaseTree.

/**
 * Insert the method's description here.
 * Creation date: (11/28/00 1:06:51 PM)
 * @return cbit.vcell.desktop.BioModelNode
 * @param docManager cbit.vcell.clientdb.DocumentManager
 */
private BioModelNode createBaseTree() {
    if (getMathDescription() == null) {
        return new BioModelNode(" ", false);
    }
    // 
    // make root node
    // 
    BioModelNode rootNode = new BioModelNode("math description", true);
    // 
    // create subTree of Constants
    // 
    BioModelNode constantRootNode = new BioModelNode("constants", true);
    Enumeration<Constant> enum1 = getMathDescription().getConstants();
    while (enum1.hasMoreElements()) {
        Constant constant = enum1.nextElement();
        BioModelNode constantNode = new BioModelNode(constant, false);
        constantRootNode.add(constantNode);
    }
    if (constantRootNode.getChildCount() > 0) {
        rootNode.add(constantRootNode);
    }
    // 
    // create subTree of Functions
    // 
    BioModelNode functionRootNode = new BioModelNode("functions", true);
    Enumeration<Function> enum2 = getMathDescription().getFunctions();
    while (enum2.hasMoreElements()) {
        Function function = enum2.nextElement();
        BioModelNode functionNode = new BioModelNode(function, false);
        functionRootNode.add(functionNode);
    }
    if (functionRootNode.getChildCount() > 0) {
        rootNode.add(functionRootNode);
    }
    // 
    // create subTree of VolumeSubDomains and MembraneSubDomains
    // 
    BioModelNode volumeRootNode = new BioModelNode("volume domains", true);
    BioModelNode membraneRootNode = new BioModelNode("membrane domains", true);
    Enumeration<SubDomain> enum3 = getMathDescription().getSubDomains();
    while (enum3.hasMoreElements()) {
        SubDomain subDomain = enum3.nextElement();
        if (subDomain instanceof cbit.vcell.math.CompartmentSubDomain) {
            CompartmentSubDomain volumeSubDomain = (CompartmentSubDomain) subDomain;
            BioModelNode volumeSubDomainNode = new BioModelNode(volumeSubDomain, true);
            if (// stochastic subtree
            getMathDescription().isNonSpatialStoch()) {
                // add stoch variable initial conditions
                BioModelNode varIniConditionNode = new BioModelNode("variable_initial_conditions", true);
                for (VarIniCondition varIni : volumeSubDomain.getVarIniConditions()) {
                    BioModelNode varIniNode = new BioModelNode(varIni, false);
                    varIniConditionNode.add(varIniNode);
                }
                volumeSubDomainNode.add(varIniConditionNode);
                // add jump processes
                for (JumpProcess jp : volumeSubDomain.getJumpProcesses()) {
                    BioModelNode jpNode = new BioModelNode(jp, true);
                    // add probability rate.
                    String probRate = "P_" + jp.getName();
                    BioModelNode prNode = new BioModelNode("probability_rate = " + probRate, false);
                    jpNode.add(prNode);
                    // add Actions
                    Enumeration<Action> actions = Collections.enumeration(jp.getActions());
                    while (actions.hasMoreElements()) {
                        Action action = actions.nextElement();
                        BioModelNode actionNode = new BioModelNode(action, false);
                        jpNode.add(actionNode);
                    }
                    volumeSubDomainNode.add(jpNode);
                }
            } else // non-stochastic subtree
            {
                // 
                // add equation children
                // 
                Enumeration<Equation> eqnEnum = volumeSubDomain.getEquations();
                while (eqnEnum.hasMoreElements()) {
                    Equation equation = eqnEnum.nextElement();
                    BioModelNode equationNode = new BioModelNode(equation, false);
                    volumeSubDomainNode.add(equationNode);
                }
                // 
                // add fast system
                // 
                FastSystem fastSystem = volumeSubDomain.getFastSystem();
                if (fastSystem != null) {
                    BioModelNode fsNode = new BioModelNode(fastSystem, true);
                    Enumeration<FastInvariant> enumFI = fastSystem.getFastInvariants();
                    while (enumFI.hasMoreElements()) {
                        FastInvariant fi = enumFI.nextElement();
                        fsNode.add(new BioModelNode(fi, false));
                    }
                    Enumeration<FastRate> enumFR = fastSystem.getFastRates();
                    while (enumFR.hasMoreElements()) {
                        FastRate fr = enumFR.nextElement();
                        fsNode.add(new BioModelNode(fr, false));
                    }
                    volumeSubDomainNode.add(fsNode);
                }
            }
            volumeRootNode.add(volumeSubDomainNode);
        } else if (subDomain instanceof MembraneSubDomain) {
            MembraneSubDomain membraneSubDomain = (MembraneSubDomain) subDomain;
            BioModelNode membraneSubDomainNode = new BioModelNode(membraneSubDomain, true);
            // 
            // add equation children
            // 
            Enumeration<Equation> eqnEnum = membraneSubDomain.getEquations();
            while (eqnEnum.hasMoreElements()) {
                Equation equation = eqnEnum.nextElement();
                BioModelNode equationNode = new BioModelNode(equation, false);
                membraneSubDomainNode.add(equationNode);
            }
            // 
            // add jump condition children
            // 
            Enumeration<JumpCondition> jcEnum = membraneSubDomain.getJumpConditions();
            while (jcEnum.hasMoreElements()) {
                JumpCondition jumpCondition = jcEnum.nextElement();
                BioModelNode jcNode = new BioModelNode(jumpCondition, false);
                membraneSubDomainNode.add(jcNode);
            }
            // 
            // add fast system
            // 
            FastSystem fastSystem = membraneSubDomain.getFastSystem();
            if (fastSystem != null) {
                BioModelNode fsNode = new BioModelNode(fastSystem, true);
                Enumeration<FastInvariant> enumFI = fastSystem.getFastInvariants();
                while (enumFI.hasMoreElements()) {
                    FastInvariant fi = enumFI.nextElement();
                    fsNode.add(new BioModelNode(fi, false));
                }
                Enumeration<FastRate> enumFR = fastSystem.getFastRates();
                while (enumFR.hasMoreElements()) {
                    FastRate fr = enumFR.nextElement();
                    fsNode.add(new BioModelNode(fr, false));
                }
                membraneSubDomainNode.add(fsNode);
            }
            membraneRootNode.add(membraneSubDomainNode);
        }
    }
    if (volumeRootNode.getChildCount() > 0) {
        rootNode.add(volumeRootNode);
    }
    if (membraneRootNode.getChildCount() > 0) {
        rootNode.add(membraneRootNode);
    }
    return rootNode;
}
Also used : JumpCondition(cbit.vcell.math.JumpCondition) VarIniCondition(cbit.vcell.math.VarIniCondition) Action(cbit.vcell.math.Action) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) Enumeration(java.util.Enumeration) Constant(cbit.vcell.math.Constant) Equation(cbit.vcell.math.Equation) FastRate(cbit.vcell.math.FastRate) BioModelNode(cbit.vcell.desktop.BioModelNode) FastInvariant(cbit.vcell.math.FastInvariant) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) Function(cbit.vcell.math.Function) FastSystem(cbit.vcell.math.FastSystem) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) JumpProcess(cbit.vcell.math.JumpProcess)

Example 40 with Constant

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

the class MathOverridesPanel method jMenuItemPaste_ActionPerformed.

/**
 * Comment
 */
private void jMenuItemPaste_ActionPerformed(java.awt.event.ActionEvent actionEvent) {
    java.util.Vector<String> pasteDescriptionsV = new java.util.Vector<String>();
    java.util.Vector<Expression> newConstantsV = new java.util.Vector<Expression>();
    java.util.Vector<String> changedParameterNamesV = new java.util.Vector<String>();
    try {
        if (actionEvent.getSource().equals(getJMenuItemPaste()) || actionEvent.getSource().equals(getJMenuItemPasteAll())) {
            int[] rows = null;
            if (actionEvent.getSource() == getJMenuItemPasteAll()) {
                rows = new int[getJTableFixed().getRowCount()];
                for (int i = 0; i < rows.length; i += 1) {
                    rows[i] = i;
                }
            } else {
                rows = getJTableFixed().getSelectedRows();
            }
            Object pasteThis = VCellTransferable.getFromClipboard(VCellTransferable.OBJECT_FLAVOR);
            for (int i = 0; i < rows.length; i += 1) {
                if (pasteThis instanceof VCellTransferable.ResolvedValuesSelection) {
                    VCellTransferable.ResolvedValuesSelection rvs = (VCellTransferable.ResolvedValuesSelection) pasteThis;
                    for (int j = 0; j < rvs.getPrimarySymbolTableEntries().length; j += 1) {
                        Constant pastedConstant = null;
                        if (rvs.getPrimarySymbolTableEntries()[j] instanceof Constant) {
                            pastedConstant = (Constant) rvs.getPrimarySymbolTableEntries()[j];
                        } else if (rvs.getAlternateSymbolTableEntries() != null && rvs.getAlternateSymbolTableEntries()[j] instanceof Constant) {
                            pastedConstant = (Constant) rvs.getAlternateSymbolTableEntries()[j];
                        }
                        // 
                        if (pastedConstant == null && (rvs.getPrimarySymbolTableEntries()[j] instanceof Function) || (rvs.getPrimarySymbolTableEntries()[j] instanceof VolVariable) || (rvs.getPrimarySymbolTableEntries()[j] instanceof VolumeRegionVariable) || (rvs.getPrimarySymbolTableEntries()[j] instanceof MemVariable) || (rvs.getPrimarySymbolTableEntries()[j] instanceof MembraneRegionVariable)) {
                            MathDescription mathDescription = getMathOverrides().getSimulation().getMathDescription();
                            Enumeration<Constant> constants = mathDescription.getConstants();
                            while (constants.hasMoreElements()) {
                                Constant constant = constants.nextElement();
                                if (constant.getName().startsWith(rvs.getPrimarySymbolTableEntries()[j].getName() + DiffEquMathMapping.MATH_FUNC_SUFFIX_SPECIES_INIT_CONC_UNIT_PREFIX)) {
                                    pastedConstant = new Constant(constant.getName(), rvs.getExpressionValues()[j]);
                                }
                            }
                        }
                        // 
                        // find row of math overrides table with the same name as the pastedConstant and propose to change that override to the pasted value
                        // 
                        String rowName = (String) getJTableFixed().getValueAt(rows[i], MathOverridesTableModel.COLUMN_PARAMETER);
                        if (pastedConstant != null && pastedConstant.getName().equals(rowName)) {
                            changedParameterNamesV.add(rowName);
                            newConstantsV.add(rvs.getExpressionValues()[j]);
                            String originalValueDescription = null;
                            if (getMathOverrides().getConstantArraySpec(rowName) != null) {
                                originalValueDescription = getMathOverrides().getConstantArraySpec(rowName).toString();
                            } else if (getMathOverrides().getActualExpression(rowName, 0) != null) {
                                originalValueDescription = getMathOverrides().getActualExpression(rowName, 0).infix();
                            } else {
                                throw new Exception("MathOverridesPanel can't find value for '" + rowName + "'");
                            }
                            pasteDescriptionsV.add(VCellCopyPasteHelper.formatPasteList(rowName, pastedConstant.getName(), originalValueDescription, rvs.getExpressionValues()[j].infix() + ""));
                        }
                    }
                }
            }
        }
    } catch (Throwable e) {
        PopupGenerator.showErrorDialog(this, "Paste failed during pre-check (no changes made).\n" + e.getClass().getName() + " " + e.getMessage(), e);
        return;
    }
    // Do paste
    try {
        if (pasteDescriptionsV.size() > 0) {
            String[] pasteDescriptionArr = new String[pasteDescriptionsV.size()];
            pasteDescriptionsV.copyInto(pasteDescriptionArr);
            String[] changedParameterNamesArr = new String[changedParameterNamesV.size()];
            changedParameterNamesV.copyInto(changedParameterNamesArr);
            VCellCopyPasteHelper.chooseApplyPaste(this, pasteDescriptionArr, getMathOverrides(), changedParameterNamesArr, newConstantsV);
        } else {
            PopupGenerator.showInfoDialog(this, "No paste items match the destination (no changes made).");
        }
    } catch (Throwable e) {
        PopupGenerator.showErrorDialog(this, "Paste Error\n" + e.getClass().getName() + " " + e.getMessage(), e);
    }
}
Also used : MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) VolVariable(cbit.vcell.math.VolVariable) MathDescription(cbit.vcell.math.MathDescription) Constant(cbit.vcell.math.Constant) VCellTransferable(cbit.vcell.desktop.VCellTransferable) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) Function(cbit.vcell.math.Function) MemVariable(cbit.vcell.math.MemVariable) ScopedExpression(cbit.gui.ScopedExpression) Expression(cbit.vcell.parser.Expression)

Aggregations

Constant (cbit.vcell.math.Constant)69 Expression (cbit.vcell.parser.Expression)43 Variable (cbit.vcell.math.Variable)31 Function (cbit.vcell.math.Function)24 MathDescription (cbit.vcell.math.MathDescription)22 VolVariable (cbit.vcell.math.VolVariable)21 ExpressionException (cbit.vcell.parser.ExpressionException)21 MathException (cbit.vcell.math.MathException)15 Vector (java.util.Vector)15 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)14 MemVariable (cbit.vcell.math.MemVariable)14 MembraneRegionVariable (cbit.vcell.math.MembraneRegionVariable)13 SubDomain (cbit.vcell.math.SubDomain)13 MacroscopicRateConstant (cbit.vcell.math.MacroscopicRateConstant)12 VolumeRegionVariable (cbit.vcell.math.VolumeRegionVariable)12 ReservedVariable (cbit.vcell.math.ReservedVariable)11 FilamentVariable (cbit.vcell.math.FilamentVariable)10 InsideVariable (cbit.vcell.math.InsideVariable)10 OutsideVariable (cbit.vcell.math.OutsideVariable)10 FilamentRegionVariable (cbit.vcell.math.FilamentRegionVariable)9