Search in sources :

Example 26 with MathException

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

the class StochFileWriter method initialize.

/**
 * Get infomation for stochasic input file.
 * Validate the information. If it is valid, a true value will be return.
 * The function will be called by writeStochInputFile().
 * Creation date: (6/23/2006 3:59:34 PM)
 * @return boolean
 */
public void initialize() throws Exception {
    Simulation simulation = simTask.getSimulation();
    // check variables
    if (!simulation.getMathDescription().getVariables().hasMoreElements()) {
        throw new MathException("Stochastic model has no variable.");
    }
    // check subDomain
    SubDomain subDomain = null;
    Enumeration<SubDomain> e = simulation.getMathDescription().getSubDomains();
    if (e.hasMoreElements()) {
        subDomain = e.nextElement();
    } else
        throw new MathException("There is no sub domain.");
    // check jump processes
    if (subDomain.getJumpProcesses().size() < 1) {
        throw new MathException("Stochastic model has no jump process.");
    }
}
Also used : SubDomain(cbit.vcell.math.SubDomain) Simulation(cbit.vcell.solver.Simulation) MathException(cbit.vcell.math.MathException)

Example 27 with MathException

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

the class NetCDFWriter method initialize.

/**
 * Extract infomation from simulation to write hybrid input file.
 * Validate the information. If it is valid, a true value will be return.
 * The function will be called by writeHybridInputFile().
 * Creation date: (5/22/2007 3:59:34 PM)
 * @return boolean
 */
public boolean initialize() throws Exception {
    Simulation simulation = simTask.getSimulation();
    // check variables
    if (!simulation.getMathDescription().getVariables().hasMoreElements()) {
        throw new MathException("Stochastic model has no variable.");
    }
    // check subDomain
    SubDomain subDomain = null;
    Enumeration<SubDomain> e = simulation.getMathDescription().getSubDomains();
    if (e.hasMoreElements()) {
        subDomain = e.nextElement();
    } else
        throw new MathException("There is no sub domain.");
    // check jump processes
    if (subDomain.getJumpProcesses().size() < 1) {
        throw new MathException("Stochastic model has no jump process.");
    }
    return true;
}
Also used : SubDomain(cbit.vcell.math.SubDomain) Simulation(cbit.vcell.solver.Simulation) MathException(cbit.vcell.math.MathException)

Example 28 with MathException

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

the class NetCDFWriter method getReactionRateLaws.

/**
 * @param reacs
 * @return ReactionRateLaw[]
 */
private ReactionRateLaw[] getReactionRateLaws(Expression[] probs) throws ExpressionException, MathException {
    SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
    ReactionRateLaw[] results = new ReactionRateLaw[probs.length];
    varInProbOrderHash = new Hashtable[probs.length];
    for (int i = 0; i < probs.length; i++) {
        varInProbOrderHash[i] = new Hashtable<String, Integer>();
        results[i] = new ReactionRateLaw();
        Expression prob = probs[i];
        String[] symbols = prob.getSymbols();
        // get stoch variables involved in the reaction
        String[] varSymbols = getVariableSymbols(symbols);
        // max allowed order for each variable(species)
        int maxOrder = 5;
        // order of the reaction
        int totalOrder = 0;
        // the expression of the rate constant
        Expression coefExp = null;
        if (symbols != null) {
            if ((varSymbols != null && !Compare.isEqual(symbols, varSymbols)) || varSymbols == null) {
                throw new MathException("Unrecognized symbols in propensity function " + prob + ". Propensity function should contain stochastic variable symbols only.");
            }
            if (symbols != null && varSymbols != null) {
                PropensitySolver.PropensityFunction pf = PropensitySolver.solvePropensity(prob, varSymbols, maxOrder);
                // get total order and save each var's order according to each reaction.
                for (int j = 0; j < pf.getSpeciesOrders().length; j++) {
                    varInProbOrderHash[i].put(pf.getSpeceisNames()[j], pf.getSpeciesOrders()[j]);
                    totalOrder = totalOrder + pf.getSpeciesOrders()[j];
                }
                // get rate constant
                coefExp = new Expression(pf.getRateExpression());
            }
        } else {
            coefExp = new Expression(prob);
        }
        if (totalOrder == 0) {
            results[i].setLawType(ReactionRateLaw.order_0);
            coefExp = new Expression(coefExp.flatten().infix() + "/6.02214179e23");
            try {
                coefExp.bindExpression(simSymbolTable);
                coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
                double val = coefExp.evaluateConstant();
                results[i].setRateConstant(val);
            } catch (Exception e) {
                e.printStackTrace(System.err);
                throw new ExpressionException(e.getMessage());
            }
        } else if (totalOrder == 1) {
            results[i].setLawType(ReactionRateLaw.order_1);
            coefExp = coefExp.flatten();
            try {
                coefExp.bindExpression(simSymbolTable);
                coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
                double val = coefExp.evaluateConstant();
                results[i].setRateConstant(val);
            } catch (Exception e) {
                e.printStackTrace(System.err);
                throw new ExpressionException(e.getMessage());
            }
        } else if (totalOrder == 2) {
            if (// second order, two same molecules
            varSymbols.length == 1) {
                // k= c*6.02214179e23/2, since in VCell, "/2" is already incorporated into c, so we don'y need to take care of this item from the conversion.
                coefExp = new Expression(coefExp.flatten().infix() + "*6.02214179e23");
                results[i].setLawType(ReactionRateLaw.order_2_1substrate);
                try {
                    coefExp.bindExpression(simSymbolTable);
                    coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
                    double val = coefExp.evaluateConstant();
                    results[i].setRateConstant(val);
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                    throw new ExpressionException(e.getMessage());
                }
            } else if (// second order, two different molecules
            varSymbols.length == 2) {
                coefExp = new Expression(coefExp.flatten().infix() + "*6.02214179e23");
                results[i].setLawType(ReactionRateLaw.order_2_2substrate);
                try {
                    coefExp.bindExpression(simSymbolTable);
                    coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
                    double val = coefExp.evaluateConstant();
                    results[i].setRateConstant(val);
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                    throw new ExpressionException(e.getMessage());
                }
            }
        } else if (totalOrder == 3) {
            if (// third order, three same molecules
            varSymbols.length == 1) {
                results[i].setLawType(ReactionRateLaw.order_3_1substrate);
                // use c directly.  "/3!" is already incorporated into c, so we compensate this item from the conversion.
                coefExp = new Expression(coefExp.flatten().infix() + "*6");
            } else if (// third order, three different molecules
            varSymbols.length == 3) {
                results[i].setLawType(ReactionRateLaw.order_3_3substrate);
            } else if (// third order, two different molecules
            varSymbols.length == 2) {
                results[i].setLawType(ReactionRateLaw.order_3_2substrate);
                // use c directly.  "/(2!*1!)" is already incorporated into c, so we compensate this item from the conversion.
                coefExp = new Expression(coefExp.flatten().infix() + "*2");
            }
            coefExp = coefExp.flatten();
            try {
                coefExp.bindExpression(simSymbolTable);
                coefExp = simSymbolTable.substituteFunctions(coefExp).flatten();
                double val = coefExp.evaluateConstant();
                results[i].setRateConstant(val);
            } catch (Exception e) {
                e.printStackTrace(System.err);
                throw new ExpressionException(e.getMessage());
            }
        } else // order more than 3, throw exception
        {
            throw new RuntimeException("Reaction order is more than 3, we couldn't solve it by Hybrid simulation.");
        }
    }
    return results;
}
Also used : SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) InvalidRangeException(ucar.ma2.InvalidRangeException) MathException(cbit.vcell.math.MathException) ExpressionException(cbit.vcell.parser.ExpressionException) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException)

Example 29 with MathException

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

the class OdeFileWriter method createStateVariables.

private void createStateVariables() throws Exception {
    Simulation simulation = simTask.getSimulation();
    MathDescription mathDescription = simulation.getMathDescription();
    SolverTaskDescription solverTaskDescription = simulation.getSolverTaskDescription();
    // get Ode's from MathDescription and create ODEStateVariables
    Enumeration<Equation> enum1 = mathDescription.getSubDomains().nextElement().getEquations();
    SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
    while (enum1.hasMoreElements()) {
        Equation equation = enum1.nextElement();
        if (equation instanceof OdeEquation) {
            fieldStateVariables.addElement(new ODEStateVariable((OdeEquation) equation, simSymbolTable));
        } else {
            throw new MathException("encountered non-ode equation, unsupported");
        }
    }
    // Get sensitivity variables
    Variable[] variables = simSymbolTable.getVariables();
    Vector<SensVariable> sensVariables = new Vector<SensVariable>();
    Constant sensitivityParameter = solverTaskDescription.getSensitivityParameter();
    if (sensitivityParameter != null) {
        Constant origSensParam = sensitivityParameter;
        Constant overriddenSensParam = (Constant) simSymbolTable.getVariable(origSensParam.getName());
        for (int i = 0; i < variables.length; i++) {
            if (variables[i] instanceof VolVariable) {
                VolVariable volVariable = (VolVariable) variables[i];
                SensVariable sv = new SensVariable(volVariable, overriddenSensParam);
                sensVariables.addElement(sv);
            }
        }
    }
    if (rateSensitivity == null) {
        rateSensitivity = new RateSensitivity(mathDescription, mathDescription.getSubDomains().nextElement());
    }
    if (jacobian == null) {
        jacobian = new Jacobian(mathDescription, mathDescription.getSubDomains().nextElement());
    }
    // get Jacobian and RateSensitivities from MathDescription and create SensStateVariables
    for (int v = 0; v < sensVariables.size(); v++) {
        fieldStateVariables.addElement(new SensStateVariable(sensVariables.elementAt(v), rateSensitivity, jacobian, sensVariables, simSymbolTable));
    }
}
Also used : ReservedVariable(cbit.vcell.math.ReservedVariable) ParameterVariable(cbit.vcell.math.ParameterVariable) Variable(cbit.vcell.math.Variable) VolVariable(cbit.vcell.math.VolVariable) MathDescription(cbit.vcell.math.MathDescription) VolVariable(cbit.vcell.math.VolVariable) Constant(cbit.vcell.math.Constant) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) OdeEquation(cbit.vcell.math.OdeEquation) Equation(cbit.vcell.math.Equation) Simulation(cbit.vcell.solver.Simulation) OdeEquation(cbit.vcell.math.OdeEquation) MathException(cbit.vcell.math.MathException) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) Vector(java.util.Vector)

Example 30 with MathException

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

the class ClientDocumentManager method substituteFieldFuncNames.

public void substituteFieldFuncNames(VCDocument vcDocument, VersionableTypeVersion originalOwner) throws DataAccessException, MathException, ExpressionException {
    Vector<ExternalDataIdentifier> errorCleanupExtDataIDV = new Vector<ExternalDataIdentifier>();
    try {
        if (originalOwner == null || originalOwner.getVersion().getOwner().compareEqual(getUser())) {
            // Substitution for FieldFunc not needed for new doc or if we own doc
            return;
        }
        // Get Objects from Document that might need to have FieldFuncs replaced
        Vector<Object> fieldFunctionContainer_mathDesc_or_simContextV = new Vector<Object>();
        if (vcDocument instanceof MathModel) {
            fieldFunctionContainer_mathDesc_or_simContextV.add(((MathModel) vcDocument).getMathDescription());
        } else if (vcDocument instanceof BioModel) {
            SimulationContext[] simContextArr = ((BioModel) vcDocument).getSimulationContexts();
            for (int i = 0; i < simContextArr.length; i += 1) {
                fieldFunctionContainer_mathDesc_or_simContextV.add(simContextArr[i]);
            }
        }
        // Get original Field names
        Vector<String> origFieldFuncNamesV = new Vector<String>();
        for (int i = 0; i < fieldFunctionContainer_mathDesc_or_simContextV.size(); i += 1) {
            Object fieldFunctionContainer = fieldFunctionContainer_mathDesc_or_simContextV.elementAt(i);
            FieldFunctionArguments[] fieldFuncArgsArr = null;
            if (fieldFunctionContainer instanceof MathDescription) {
                fieldFuncArgsArr = FieldUtilities.getFieldFunctionArguments((MathDescription) fieldFunctionContainer);
            } else if (fieldFunctionContainer instanceof SimulationContext) {
                fieldFuncArgsArr = ((SimulationContext) fieldFunctionContainer).getFieldFunctionArguments();
            }
            for (int j = 0; j < fieldFuncArgsArr.length; j += 1) {
                if (!origFieldFuncNamesV.contains(fieldFuncArgsArr[j].getFieldName())) {
                    origFieldFuncNamesV.add(fieldFuncArgsArr[j].getFieldName());
                }
            }
        }
        if (origFieldFuncNamesV.size() == 0) {
            // No FieldFunctions to substitute
            return;
        }
        FieldDataDBOperationResults copyNamesFieldDataOpResults = fieldDataDBOperation(FieldDataDBOperationSpec.createCopyNoConflictExtDataIDsSpec(getUser(), origFieldFuncNamesV.toArray(new String[0]), originalOwner));
        errorCleanupExtDataIDV.addAll(copyNamesFieldDataOpResults.oldNameNewIDHash.values());
        // Copy Field Data on Data Server FileSystem
        for (String fieldname : origFieldFuncNamesV) {
            KeyValue sourceSimDataKey = copyNamesFieldDataOpResults.oldNameOldExtDataIDKeyHash.get(fieldname);
            if (sourceSimDataKey == null) {
                throw new DataAccessException("Couldn't find original data key for FieldFunc " + fieldname);
            }
            ExternalDataIdentifier newExtDataID = copyNamesFieldDataOpResults.oldNameNewIDHash.get(fieldname);
            getSessionManager().fieldDataFileOperation(FieldDataFileOperationSpec.createCopySimFieldDataFileOperationSpec(newExtDataID, sourceSimDataKey, originalOwner.getVersion().getOwner(), FieldDataFileOperationSpec.JOBINDEX_DEFAULT, getUser()));
        }
        // Finally substitute new Field names
        for (int i = 0; i < fieldFunctionContainer_mathDesc_or_simContextV.size(); i += 1) {
            Object fieldFunctionContainer = fieldFunctionContainer_mathDesc_or_simContextV.elementAt(i);
            if (fieldFunctionContainer instanceof MathDescription) {
                MathDescription mathDesc = (MathDescription) fieldFunctionContainer;
                FieldUtilities.substituteFieldFuncNames(mathDesc, copyNamesFieldDataOpResults.oldNameNewIDHash);
            } else if (fieldFunctionContainer instanceof SimulationContext) {
                SimulationContext simContext = (SimulationContext) fieldFunctionContainer;
                simContext.substituteFieldFuncNames(copyNamesFieldDataOpResults.oldNameNewIDHash);
            }
        }
        fireFieldDataDB(new FieldDataDBEvent(this));
    } catch (Exception e) {
        e.printStackTrace();
        // Cleanup
        for (int i = 0; i < errorCleanupExtDataIDV.size(); i += 1) {
            try {
                fieldDataDBOperation(FieldDataDBOperationSpec.createDeleteExtDataIDSpec(errorCleanupExtDataIDV.elementAt(i)));
            } catch (Exception e2) {
            // ignore, we tried to cleanup
            }
            try {
                fieldDataFileOperation(FieldDataFileOperationSpec.createDeleteFieldDataFileOperationSpec(errorCleanupExtDataIDV.elementAt(i)));
            } catch (Exception e1) {
            // ignore, we tried to cleanup
            }
        }
        throw new RuntimeException("Error copying Field Data \n" + e.getMessage());
    }
}
Also used : MathModel(cbit.vcell.mathmodel.MathModel) KeyValue(org.vcell.util.document.KeyValue) FieldFunctionArguments(cbit.vcell.field.FieldFunctionArguments) MathDescription(cbit.vcell.math.MathDescription) BigString(org.vcell.util.BigString) SimulationContext(cbit.vcell.mapping.SimulationContext) ParseException(java.text.ParseException) PermissionException(org.vcell.util.PermissionException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) XmlParseException(cbit.vcell.xml.XmlParseException) RemoteProxyException(cbit.vcell.message.server.bootstrap.client.RemoteProxyVCellConnectionFactory.RemoteProxyException) DataAccessException(org.vcell.util.DataAccessException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) BioModel(cbit.vcell.biomodel.BioModel) ExternalDataIdentifier(org.vcell.util.document.ExternalDataIdentifier) FieldDataDBOperationResults(cbit.vcell.field.FieldDataDBOperationResults) Vector(java.util.Vector) DataAccessException(org.vcell.util.DataAccessException)

Aggregations

MathException (cbit.vcell.math.MathException)81 ExpressionException (cbit.vcell.parser.ExpressionException)49 Expression (cbit.vcell.parser.Expression)41 Variable (cbit.vcell.math.Variable)34 VolVariable (cbit.vcell.math.VolVariable)27 PropertyVetoException (java.beans.PropertyVetoException)20 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)19 MathDescription (cbit.vcell.math.MathDescription)18 MemVariable (cbit.vcell.math.MemVariable)18 DataAccessException (org.vcell.util.DataAccessException)17 Vector (java.util.Vector)16 Element (org.jdom.Element)16 IOException (java.io.IOException)15 Function (cbit.vcell.math.Function)14 ArrayList (java.util.ArrayList)14 MappingException (cbit.vcell.mapping.MappingException)13 SimulationSymbolTable (cbit.vcell.solver.SimulationSymbolTable)13 Constant (cbit.vcell.math.Constant)12 MembraneParticleVariable (cbit.vcell.math.MembraneParticleVariable)12 ParticleVariable (cbit.vcell.math.ParticleVariable)12