Search in sources :

Example 6 with FastRate

use of cbit.vcell.math.FastRate 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();
}
Also used : Variable(cbit.vcell.math.Variable) MathDescription(cbit.vcell.math.MathDescription) MatrixException(cbit.vcell.matrix.MatrixException) RationalExpMatrix(cbit.vcell.matrix.RationalExpMatrix) HashSet(java.util.HashSet) Discontinuity(cbit.vcell.parser.Discontinuity) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) Equation(cbit.vcell.math.Equation) FastRate(cbit.vcell.math.FastRate) RationalExp(cbit.vcell.matrix.RationalExp) FastInvariant(cbit.vcell.math.FastInvariant) FastSystemAnalyzer(cbit.vcell.mapping.FastSystemAnalyzer) Simulation(cbit.vcell.solver.Simulation) FastSystem(cbit.vcell.math.FastSystem) Expression(cbit.vcell.parser.Expression) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) MathException(cbit.vcell.math.MathException)

Example 7 with FastRate

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

the class MathTestingUtilities method constructOdesForSensitivity.

// 
// This method is used to solve for sensitivity of variables to a given parameter.
// The mathDescription and the sensitivity parameter are passed as arguments.
// New variables and ODEs are constructed according to the rule listed below and are added to the mathDescription.
// The method returns the modified mathDescription.
// 
public static MathDescription constructOdesForSensitivity(MathDescription mathDesc, Constant sensParam) throws ExpressionException, MathException, MappingException {
    // 
    // For each ODE :
    // 
    // dX/dt = F(X, P)
    // 
    // (where P is the sensitivity parameter)
    // 
    // we create two other ODEs :
    // 
    // dX_1/dt = F(X_1, P_1)    and
    // 
    // dX_2/dt = F(X_2, P_2)
    // 
    // where P_1 = P + epsilon, and
    // P_2 = P - epsilon.
    // 
    // We keep the initial conditions for both the new ODEs to be the same,
    // i.e., X_1_init = X_2_init.
    // 
    // Then, solving for X_1 & X_2, sensitivity of X wrt P can be computed as :
    // 
    // dX = (X_1 - X_2)
    // --	 -----------   .
    // dP	 (P_1 - P_2)
    // 
    // 
    // REMOVE PRINTS AFTER CHECKING !!!
    System.out.println(" \n\n------------  Old Math Description -----------------");
    System.out.println(mathDesc.getVCML_database());
    if (mathDesc.getGeometry().getDimension() > 0) {
        throw new RuntimeException("Suppport for Spatial systems not yet implemented.");
    }
    VariableHash varHash = new VariableHash();
    Enumeration<Variable> enumVar = mathDesc.getVariables();
    while (enumVar.hasMoreElements()) {
        varHash.addVariable(enumVar.nextElement());
    }
    // 
    // Get 2 values of senstivity parameter (P + epsilon) & (P - epsilon)
    // 
    Constant epsilon = new Constant("epsilon", new Expression(sensParam.getConstantValue() * 1e-3));
    Constant sensParam1 = new Constant(sensParam.getName() + "_1", new Expression(sensParam.getConstantValue() + epsilon.getConstantValue()));
    Constant sensParam2 = new Constant(sensParam.getName() + "_2", new Expression(sensParam.getConstantValue() - epsilon.getConstantValue()));
    // 
    // Iterate through each subdomain (only 1 in compartmental case), and each equation in the subdomain
    // 
    Enumeration<SubDomain> subDomainEnum = mathDesc.getSubDomains();
    // 
    // Create a vector of equations to store the 2 equations for each ODE variable in the subdomain.
    // Later, add it to the equations list in the subdomain.
    // 
    Vector<Equation> equnsVector = new Vector<Equation>();
    Vector<Variable> varsVector = new Vector<Variable>();
    Vector<Variable> var1s = new Vector<Variable>();
    Vector<Variable> var2s = new Vector<Variable>();
    while (subDomainEnum.hasMoreElements()) {
        SubDomain subDomain = subDomainEnum.nextElement();
        Enumeration<Equation> equationEnum = subDomain.getEquations();
        Domain domain = new Domain(subDomain);
        while (equationEnum.hasMoreElements()) {
            Equation equation = equationEnum.nextElement();
            if (equation instanceof OdeEquation) {
                OdeEquation odeEquation = (OdeEquation) equation;
                // Similar to substituteWithExactSolutions, to bind and substitute functions in the ODE
                Expression substitutedRateExp = substituteFunctions(odeEquation.getRateExpression(), mathDesc);
                String varName = odeEquation.getVariable().getName();
                VolVariable var = new VolVariable(varName, domain);
                varsVector.addElement(var);
                // 
                // Create the variable var1, and get the initExpr and rateExpr from the original ODE.
                // Substitute the new vars (var1 and param1) in the old initExpr and rateExpr and create a new ODE
                // 
                String varName1 = new String("__" + varName + "_1");
                Expression initExpr1 = odeEquation.getInitialExpression();
                Expression rateExpr1 = new Expression(substitutedRateExp);
                rateExpr1.substituteInPlace(new Expression(varName), new Expression(varName1));
                rateExpr1.substituteInPlace(new Expression(sensParam.getName()), new Expression(sensParam1.getName()));
                VolVariable var1 = new VolVariable(varName1, domain);
                var1s.addElement(var1);
                OdeEquation odeEqun1 = new OdeEquation(var1, initExpr1, rateExpr1);
                equnsVector.addElement(odeEqun1);
                // 
                // Create the variable var2, and get the initExpr and rateExpr from the original ODE.
                // Substitute the new vars (var2 and param2) in the old initExpr and rateExpr and create a new ODE
                // 
                String varName2 = new String("__" + varName + "_2");
                Expression initExpr2 = odeEquation.getInitialExpression();
                Expression rateExpr2 = new Expression(substitutedRateExp);
                rateExpr2.substituteInPlace(new Expression(varName), new Expression(varName2));
                rateExpr2.substituteInPlace(new Expression(sensParam.getName()), new Expression(sensParam2.getName()));
                VolVariable var2 = new VolVariable(varName2, domain);
                var2s.addElement(var2);
                OdeEquation odeEqun2 = new OdeEquation(var2, initExpr2, rateExpr2);
                equnsVector.addElement(odeEqun2);
                // 
                // Create a function for the sensitivity function expression (X1-X2)/(P1-P2), and save in varHash
                // 
                Expression diffVar = Expression.add(new Expression(var1.getName()), Expression.negate(new Expression(var2.getName())));
                Expression diffParam = Expression.add(new Expression(sensParam1.getName()), Expression.negate(new Expression(sensParam2.getName())));
                Expression sensitivityExpr = Expression.mult(diffVar, Expression.invert(diffParam));
                Function sens_Func = new Function("__sens" + varName + "_wrt_" + sensParam.getName(), sensitivityExpr, domain);
                varHash.addVariable(epsilon);
                varHash.addVariable(sensParam1);
                varHash.addVariable(sensParam2);
                varHash.addVariable(var1);
                varHash.addVariable(var2);
                varHash.addVariable(sens_Func);
            } else {
                // sensitivity not implemented for PDEs or other equation types.
                throw new RuntimeException("SolverTest.constructedExactMath(): equation type " + equation.getClass().getName() + " not yet implemented");
            }
        }
        // 
        // Need to substitute the new variables in the new ODEs.
        // i.e., if Rate Expr for ODE_1 for variable X_1 contains variable Y, variable Z, etc.
        // Rate Expr is already substituted with X_1, but it also needs substitute Y with Y_1, Z with Z_1, etc.
        // So get the volume variables, from the vectors for vars, var_1s and var_2s
        // Substitute the rate expressions for the newly added ODEs in equnsVector.
        // 
        Variable[] vars = (Variable[]) BeanUtils.getArray(varsVector, Variable.class);
        Variable[] var_1s = (Variable[]) BeanUtils.getArray(var1s, Variable.class);
        Variable[] var_2s = (Variable[]) BeanUtils.getArray(var2s, Variable.class);
        Vector<Equation> newEqunsVector = new Vector<Equation>();
        for (int i = 0; i < equnsVector.size(); i++) {
            Equation equn = equnsVector.elementAt(i);
            Expression initEx = equn.getInitialExpression();
            Expression rateEx = equn.getRateExpression();
            for (int j = 0; j < vars.length; j++) {
                if (equn.getVariable().getName().endsWith("_1")) {
                    rateEx.substituteInPlace(new Expression(vars[j].getName()), new Expression(var_1s[j].getName()));
                } else if (equn.getVariable().getName().endsWith("_2")) {
                    rateEx.substituteInPlace(new Expression(vars[j].getName()), new Expression(var_2s[j].getName()));
                }
            }
            OdeEquation odeEqun = new OdeEquation(equn.getVariable(), initEx, rateEx);
            newEqunsVector.addElement(odeEqun);
        }
        // 
        for (int i = 0; i < newEqunsVector.size(); i++) {
            mathDesc.getSubDomain(subDomain.getName()).addEquation((Equation) newEqunsVector.elementAt(i));
        }
        // 
        // FAST SYSTEM
        // If the subdomain has a fast system, create a new fast system by substituting the high-low variables/parameters
        // in the expressions for the fastInvariants and fastRates and adding them to the fast system.
        // 
        Vector<FastInvariant> invarsVector = new Vector<FastInvariant>();
        Vector<FastRate> ratesVector = new Vector<FastRate>();
        Enumeration<FastInvariant> fastInvarsEnum = null;
        Enumeration<FastRate> fastRatesEnum = null;
        // Get the fast invariants and fast rates in the system.
        FastSystem fastSystem = subDomain.getFastSystem();
        if (fastSystem != null) {
            fastInvarsEnum = fastSystem.getFastInvariants();
            fastRatesEnum = fastSystem.getFastRates();
            // 
            while (fastInvarsEnum.hasMoreElements()) {
                FastInvariant fastInvar = fastInvarsEnum.nextElement();
                Expression fastInvarExpr = fastInvar.getFunction();
                fastInvarExpr = MathUtilities.substituteFunctions(fastInvarExpr, mathDesc);
                Expression fastInvarExpr1 = new Expression(fastInvarExpr);
                Expression fastInvarExpr2 = new Expression(fastInvarExpr);
                for (int i = 0; i < vars.length; i++) {
                    fastInvarExpr1.substituteInPlace(new Expression(vars[i].getName()), new Expression(var_1s[i].getName()));
                    fastInvarExpr2.substituteInPlace(new Expression(vars[i].getName()), new Expression(var_2s[i].getName()));
                }
                fastInvarExpr1.substituteInPlace(new Expression(sensParam.getName()), new Expression(sensParam1.getName()));
                FastInvariant fastInvar1 = new FastInvariant(fastInvarExpr1);
                invarsVector.addElement(fastInvar1);
                fastInvarExpr2.substituteInPlace(new Expression(sensParam.getName()), new Expression(sensParam2.getName()));
                FastInvariant fastInvar2 = new FastInvariant(fastInvarExpr2);
                invarsVector.addElement(fastInvar2);
            }
            // Add the newly created fast invariants to the existing list of fast invariants in the fast system.
            for (int i = 0; i < invarsVector.size(); i++) {
                FastInvariant inVar = (FastInvariant) invarsVector.elementAt(i);
                fastSystem.addFastInvariant(inVar);
            }
            // 
            while (fastRatesEnum.hasMoreElements()) {
                FastRate fastRate = fastRatesEnum.nextElement();
                Expression fastRateExpr = fastRate.getFunction();
                fastRateExpr = MathUtilities.substituteFunctions(fastRateExpr, mathDesc);
                Expression fastRateExpr1 = new Expression(fastRateExpr);
                Expression fastRateExpr2 = new Expression(fastRateExpr);
                for (int i = 0; i < vars.length; i++) {
                    fastRateExpr1.substituteInPlace(new Expression(vars[i].getName()), new Expression(var_1s[i].getName()));
                    fastRateExpr2.substituteInPlace(new Expression(vars[i].getName()), new Expression(var_2s[i].getName()));
                }
                fastRateExpr1.substituteInPlace(new Expression(sensParam.getName()), new Expression(sensParam1.getName()));
                FastRate fastRate1 = new FastRate(fastRateExpr1);
                ratesVector.addElement(fastRate1);
                fastRateExpr2.substituteInPlace(new Expression(sensParam.getName()), new Expression(sensParam2.getName()));
                FastRate fastRate2 = new FastRate(fastRateExpr2);
                ratesVector.addElement(fastRate2);
            }
            // Add the newly created fast rates to the existing list of fast rates in the fast system.
            for (int i = 0; i < ratesVector.size(); i++) {
                FastRate rate = (FastRate) ratesVector.elementAt(i);
                fastSystem.addFastRate(rate);
            }
        }
    }
    // Reset all variables in mathDesc.
    mathDesc.setAllVariables(varHash.getAlphabeticallyOrderedVariables());
    // REMOVE PRINTS AFTER CHECKING
    System.out.println(" \n\n------------  New Math Description -----------------");
    System.out.println(mathDesc.getVCML_database());
    return mathDesc;
}
Also used : MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) InsideVariable(cbit.vcell.math.InsideVariable) SensVariable(cbit.vcell.solver.ode.SensVariable) FilamentVariable(cbit.vcell.math.FilamentVariable) VolVariable(cbit.vcell.math.VolVariable) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) ReservedVariable(cbit.vcell.math.ReservedVariable) MemVariable(cbit.vcell.math.MemVariable) OutsideVariable(cbit.vcell.math.OutsideVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) Variable(cbit.vcell.math.Variable) VariableHash(cbit.vcell.math.VariableHash) Constant(cbit.vcell.math.Constant) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) Function(cbit.vcell.math.Function) Vector(java.util.Vector) VolVariable(cbit.vcell.math.VolVariable) OdeEquation(cbit.vcell.math.OdeEquation) PdeEquation(cbit.vcell.math.PdeEquation) Equation(cbit.vcell.math.Equation) FastRate(cbit.vcell.math.FastRate) FastInvariant(cbit.vcell.math.FastInvariant) OdeEquation(cbit.vcell.math.OdeEquation) Expression(cbit.vcell.parser.Expression) FastSystem(cbit.vcell.math.FastSystem) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) Domain(cbit.vcell.math.Variable.Domain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain)

Example 8 with FastRate

use of cbit.vcell.math.FastRate 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 9 with FastRate

use of cbit.vcell.math.FastRate 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 10 with FastRate

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

the class FastSystemAnalyzer method refreshSubstitutedRateExps.

/**
 */
private void refreshSubstitutedRateExps() throws MathException, ExpressionException {
    // 
    // refresh PseudoConstants (temp constants involved with fastInvariants)
    // 
    pseudoConstantList.removeAllElements();
    Enumeration<FastInvariant> enum_fi = fastSystem.getFastInvariants();
    while (enum_fi.hasMoreElements()) {
        FastInvariant fi = enum_fi.nextElement();
        fi.getFunction().bindExpression(this);
        PseudoConstant pc = new PseudoConstant(getAvailablePseudoConstantName(), fi.getFunction(), MathMapping_4_8.nullDomain);
        pseudoConstantList.addElement(pc);
    // System.out.println("FastSystem.refreshSubstitutedRateExps() __C"+i+" = "+fi.getFunction());
    }
    // 
    // build expressions for dependent variables in terms of independent vars
    // and pseudoConstants
    // 
    dependencyExpList.removeAllElements();
    for (int row = 0; row < dependentVarList.size(); row++) {
        Expression exp = new Expression("0.0;");
        // 
        for (int col = 0; col < independentVarList.size(); col++) {
            Variable indepVar = (Variable) independentVarList.elementAt(col);
            RationalExp coefExp = dependencyMatrix.get(row, col).simplify();
            if (!coefExp.isZero()) {
                exp = Expression.add(exp, new Expression(coefExp.infixString() + "*" + indepVar.getName()));
            }
        }
        // 
        for (int col = independentVarList.size(); col < dependencyMatrix.getNumCols(); col++) {
            PseudoConstant pc = (PseudoConstant) pseudoConstantList.elementAt(col - independentVarList.size());
            RationalExp coefExp = dependencyMatrix.get(row, col);
            if (!coefExp.isZero()) {
                exp = Expression.add(exp, new Expression(coefExp.infixString() + "*" + pc.getName()));
            }
        }
        exp.bindExpression(null);
        exp = exp.flatten();
        exp.bindExpression(this);
        // System.out.println("FastSystem.refreshSubstitutedRateExps() "+((Variable)dependentVarList.elementAt(row)).getName()+" = "+exp.toString()+";");
        dependencyExpList.addElement(exp);
    }
    // 
    // flatten functions, then substitute expressions for dependent vars into rate expressions
    // 
    fastRateExpList.removeAllElements();
    // VariableSymbolTable combinedSymbolTable = getCombinedSymbolTable();
    Enumeration<FastRate> enum_fr = fastSystem.getFastRates();
    while (enum_fr.hasMoreElements()) {
        FastRate fr = enum_fr.nextElement();
        Expression exp = new Expression(MathUtilities.substituteFunctions(new Expression(fr.getFunction()), this));
        // System.out.println("FastSystem.refreshSubstitutedRateExps() fast rate before substitution = "+exp.toString());
        for (int j = 0; j < dependentVarList.size(); j++) {
            Variable depVar = (Variable) dependentVarList.elementAt(j);
            Expression subExp = new Expression((Expression) dependencyExpList.elementAt(j));
            exp.substituteInPlace(new Expression(depVar.getName()), subExp);
        }
        exp.bindExpression(null);
        exp = exp.flatten();
        // System.out.println("FastSystem.refreshSubstitutedRateExps() fast rate after substitution  = "+exp.toString());
        exp.bindExpression(this);
        fastRateExpList.addElement(exp);
    }
}
Also used : ReservedVariable(cbit.vcell.math.ReservedVariable) Variable(cbit.vcell.math.Variable) VolVariable(cbit.vcell.math.VolVariable) MemVariable(cbit.vcell.math.MemVariable) Expression(cbit.vcell.parser.Expression) PseudoConstant(cbit.vcell.math.PseudoConstant) FastRate(cbit.vcell.math.FastRate) RationalExp(cbit.vcell.matrix.RationalExp) FastInvariant(cbit.vcell.math.FastInvariant)

Aggregations

FastInvariant (cbit.vcell.math.FastInvariant)13 FastRate (cbit.vcell.math.FastRate)13 Variable (cbit.vcell.math.Variable)9 Expression (cbit.vcell.parser.Expression)9 FastSystem (cbit.vcell.math.FastSystem)7 MemVariable (cbit.vcell.math.MemVariable)7 VolVariable (cbit.vcell.math.VolVariable)7 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)5 Constant (cbit.vcell.math.Constant)5 Equation (cbit.vcell.math.Equation)5 MathException (cbit.vcell.math.MathException)5 ReservedVariable (cbit.vcell.math.ReservedVariable)5 SubDomain (cbit.vcell.math.SubDomain)5 Function (cbit.vcell.math.Function)4 JumpCondition (cbit.vcell.math.JumpCondition)4 MembraneSubDomain (cbit.vcell.math.MembraneSubDomain)4 OdeEquation (cbit.vcell.math.OdeEquation)4 PdeEquation (cbit.vcell.math.PdeEquation)4 MathDescription (cbit.vcell.math.MathDescription)3 MembraneRegionEquation (cbit.vcell.math.MembraneRegionEquation)3