Search in sources :

Example 71 with MathException

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

the class SundialsSolver method createFunctionList.

public Vector<AnnotatedFunction> createFunctionList() {
    // 
    // add appropriate Function columns to result set
    // 
    Vector<AnnotatedFunction> funcList = super.createFunctionList();
    SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
    if (getSensitivityParameter() != null) {
        try {
            AnnotatedFunction saf = new AnnotatedFunction(getSensitivityParameter().getName(), new Expression(getSensitivityParameter().getConstantValue()), getSensitivityParameter().getDomain(), "", VariableType.NONSPATIAL, FunctionCategory.PREDEFINED);
            if (!funcList.contains(saf)) {
                funcList.add(saf);
            }
            Variable[] variables = simSymbolTable.getVariables();
            StateVariable[] stateVars = createStateVariables();
            for (int i = 0; i < variables.length; i++) {
                if (variables[i] instanceof Function && SimulationSymbolTable.isFunctionSaved((Function) variables[i])) {
                    Function depSensFunction = (Function) variables[i];
                    Expression depSensFnExpr = new Expression(depSensFunction.getExpression());
                    depSensFnExpr = simSymbolTable.substituteFunctions(depSensFnExpr);
                    depSensFnExpr = getFunctionSensitivity(depSensFnExpr, getSensitivityParameter(), stateVars);
                    // depSensFnExpr = depSensFnExpr.flatten(); 	// already bound and flattened in getFunctionSensitivity, no need here.....
                    String depSensFnName = new String("sens_" + depSensFunction.getName() + "_wrt_" + getSensitivityParameter().getName());
                    if (depSensFunction != null) {
                        AnnotatedFunction af = new AnnotatedFunction(depSensFnName, depSensFnExpr.flatten(), variables[i].getDomain(), "", VariableType.NONSPATIAL, FunctionCategory.PREDEFINED);
                        funcList.add(af);
                    }
                }
            }
        } catch (MathException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding function to resultSet: " + e.getMessage());
        } catch (ExpressionException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding function to resultSet: " + e.getMessage());
        }
    }
    return funcList;
}
Also used : Variable(cbit.vcell.math.Variable) VolVariable(cbit.vcell.math.VolVariable) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) ExpressionException(cbit.vcell.parser.ExpressionException) Function(cbit.vcell.math.Function) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction)

Example 72 with MathException

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

the class RungeKuttaFehlbergSolver method integrate.

protected void integrate() throws cbit.vcell.solver.SolverException, UserStopException, IOException {
    try {
        // Get machine epsilon
        final double DBL_EPSILON = 1.0E-12;
        final double epsilon = DBL_EPSILON;
        final double twentySixEpsilon = 26 * epsilon;
        // 
        SolverTaskDescription taskDescription = simTask.getSimulation().getSolverTaskDescription();
        double startingTime = taskDescription.getTimeBounds().getStartingTime();
        double endingTime = taskDescription.getTimeBounds().getEndingTime();
        double relativeErrorTolerance = taskDescription.getErrorTolerance().getRelativeErrorTolerance();
        double absoluteErrorTolerance = taskDescription.getErrorTolerance().getAbsoluteErrorTolerance();
        fieldCurrentTime = taskDescription.getTimeBounds().getStartingTime();
        // 
        double[] oldValues = getValueVector(0);
        double[] newValues = getValueVector(1);
        // The minimumRelativeError is the minimum acceptable value of
        // relativeError.  Attempts to obtain higher accuracy with this
        // subroutine are usually very expensive and often unsuccessful.
        final double minimumRelativeError = 1e-12;
        // Check input parameters...
        if (relativeErrorTolerance < 0.0 || absoluteErrorTolerance < 0.0 || startingTime >= endingTime) {
            throw new SolverException("Invalid parameters");
        }
        // difficulties arising from impossible accuracy requests
        if (relativeErrorTolerance < 2 * epsilon + minimumRelativeError) {
            // Or just set relativeError = 2 * epsilon + minimumRelativeError???
            throw new SolverException("Relative error too small");
        }
        // before computation begins, settle fast equilibrium
        if (getFastAlgebraicSystem() != null) {
            fieldValueVectors.copyValues(0, 1);
            getFastAlgebraicSystem().initVars(getValueVector(0), getValueVector(1));
            getFastAlgebraicSystem().solveSystem(getValueVector(0), getValueVector(1));
            fieldValueVectors.copyValues(1, 0);
        }
        // check for failure
        check(getValueVector(0));
        // 
        double timeRemaining = endingTime - fieldCurrentTime;
        double tolerance = 0.0;
        double maximumTolerance = 0.0;
        final double maximumTimeStep = taskDescription.getTimeStep().getMaximumTimeStep();
        double h = Math.min(Math.abs(timeRemaining), taskDescription.getTimeStep().getMaximumTimeStep());
        for (int i = 0; i < getStateVariableCount(); i++) {
            int I = getVariableIndex(i);
            tolerance = relativeErrorTolerance * Math.abs(oldValues[I]) + absoluteErrorTolerance;
            if (tolerance > 0.0) {
                double yp = Math.abs(evaluate(oldValues, i));
                if (yp * Math.pow(h, 5.0) > tolerance) {
                    h = Math.pow(tolerance / yp, 0.2);
                }
            }
            maximumTolerance = Math.max(maximumTolerance, tolerance);
        }
        if (maximumTolerance <= 0.0)
            h = 0.0;
        h = Math.max(h, twentySixEpsilon * Math.max(timeRemaining, Math.abs(fieldCurrentTime)));
        // To avoid premature underflow in the error
        // tolerance function,  scale the tolerances...
        final double scale = 2.0 / relativeErrorTolerance;
        final double scaledAbsoluteError = scale * absoluteErrorTolerance;
        boolean previousStepFailed = false;
        // Check for failure...
        check(getValueVector(0));
        updateResultSet();
        // Integrate...
        int iteration = 0;
        while (fieldCurrentTime < endingTime) {
            checkForUserStop();
            // Set smallest allowable stepsize...
            final double minimumTimeStep = Math.max(twentySixEpsilon * Math.abs(fieldCurrentTime), taskDescription.getTimeStep().getMinimumTimeStep());
            h = Math.min(h, taskDescription.getTimeStep().getMaximumTimeStep());
            // Adjust stepsize if necessary to hit the output point.
            // Look ahead two steps to avoid drastic changes in the stepsize and
            // thus lessen the impact of output points on the code.
            timeRemaining = endingTime - fieldCurrentTime;
            if (timeRemaining < 2 * h) {
                if (timeRemaining <= h) {
                    h = timeRemaining;
                } else {
                    h = 0.5 * timeRemaining;
                }
            }
            // If too close to output point, extrapolate and return
            if (timeRemaining <= twentySixEpsilon * Math.abs(fieldCurrentTime)) {
                for (int i = 0; i < getStateVariableCount(); i++) {
                    int I = getVariableIndex(i);
                    newValues[I] = oldValues[I] + timeRemaining * evaluate(oldValues, i);
                }
                // update (old = new)
                fieldValueVectors.copyValuesDown();
                // compute fast system
                if (getFastAlgebraicSystem() != null) {
                    fieldValueVectors.copyValues(0, 1);
                    getFastAlgebraicSystem().initVars(getValueVector(0), getValueVector(1));
                    getFastAlgebraicSystem().solveSystem(getValueVector(0), getValueVector(1));
                    fieldValueVectors.copyValues(1, 0);
                }
                // check for failure
                check(getValueVector(0));
                fieldCurrentTime = endingTime;
                return;
            } else {
                // Advance an approximate solution over one step of length h
                // RungeKuttaStep(Model,y,t,h,ss);
                step(fieldCurrentTime, h);
                // compute fast system
                if (getFastAlgebraicSystem() != null) {
                    fieldValueVectors.copyValues(1, 2);
                    getFastAlgebraicSystem().initVars(getValueVector(1), getValueVector(2));
                    getFastAlgebraicSystem().solveSystem(getValueVector(1), getValueVector(2));
                    fieldValueVectors.copyValues(2, 1);
                }
                // check for failure
                check(getValueVector(1));
                // Compute and test allowable tolerances versus local error estimates
                // and remove scaling of tolerances. Note that relative error is
                // measured with respect to the average of the magnitudes of the
                // solution at the beginning and end of the step.
                double estimatedErrorOverErrorTolerance = 0.0;
                for (int i = 0; i < getStateVariableCount(); i++) {
                    int I = getVariableIndex(i);
                    double errorTolerance = Math.abs(oldValues[I]) + Math.abs(newValues[I]) + scaledAbsoluteError;
                    // Inappropriate error tolerance
                    if (errorTolerance <= 0.0) {
                        throw new SolverException("Error tolerance too small");
                    }
                    double estimatedError = Math.abs(calculateErrorTerm(i));
                    estimatedErrorOverErrorTolerance = Math.max(estimatedErrorOverErrorTolerance, estimatedError / errorTolerance);
                }
                double estimatedTolerance = h * estimatedErrorOverErrorTolerance * scale;
                if (estimatedTolerance > 1.0) {
                    // Unsuccessful step.  Reduce the stepsize and try again.
                    // The decrease is limited to a factor of 1/10...
                    previousStepFailed = true;
                    double s = 0.1;
                    if (estimatedTolerance < 59049.0) {
                        // s = 0.1  @  estimatedTolerance = 59049
                        s = 0.9 / Math.pow(estimatedTolerance, 0.2);
                    }
                    h *= s;
                    if (h < minimumTimeStep) {
                        throw new SolverException("Requested error unattainable at smallest allowable stepsize");
                    }
                } else {
                    // Successful step.  Store solution at t+h and evaluate derivatives there.
                    fieldValueVectors.copyValuesDown();
                    fieldCurrentTime += h;
                    iteration++;
                    if (taskDescription.getOutputTimeSpec().isDefault()) {
                        int keepEvery = ((DefaultOutputTimeSpec) taskDescription.getOutputTimeSpec()).getKeepEvery();
                        if ((iteration % keepEvery) == 0)
                            updateResultSet();
                    }
                    // 
                    // Choose next stepsize.  The increase is limited to a factor of 5. If
                    // step failure has just occurred, next stepsize is not allowed to increase.
                    // 
                    double s = 5;
                    if (estimatedTolerance > 0.0001889568) {
                        // s = 5  @  estimatedTolerance = 0.0001889568
                        s = 0.9 / Math.pow(estimatedTolerance, 0.2);
                    }
                    if (previousStepFailed) {
                        s = Math.min(1.0, s);
                    }
                    h = Math.min(Math.max(minimumTimeStep, s * h), maximumTimeStep);
                    previousStepFailed = false;
                }
            }
        }
        // store last time point
        if (taskDescription.getOutputTimeSpec().isDefault()) {
            int keepEvery = ((DefaultOutputTimeSpec) taskDescription.getOutputTimeSpec()).getKeepEvery();
            if ((iteration % keepEvery) != 0)
                updateResultSet();
        }
    } catch (ExpressionException expressionException) {
        expressionException.printStackTrace(System.out);
        throw new SolverException(expressionException.getMessage());
    } catch (MathException mathException) {
        mathException.printStackTrace(System.out);
        throw new SolverException(mathException.getMessage());
    }
}
Also used : MathException(cbit.vcell.math.MathException) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) SolverException(cbit.vcell.solver.SolverException) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 73 with MathException

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

the class ModelOptimizationMapping method computeOptimizationSpec.

/**
 * Insert the method's description here.
 * Creation date: (8/22/2005 9:26:52 AM)
 * @return cbit.vcell.opt.OptimizationSpec
 * @param modelOptimizationSpec cbit.vcell.modelopt.ModelOptimizationSpec
 */
MathSymbolMapping computeOptimizationSpec() throws MathException, MappingException {
    if (getModelOptimizationSpec().getReferenceData() == null) {
        System.out.println("no referenced data defined");
        return null;
    }
    OptimizationSpec optSpec = new OptimizationSpec();
    optSpec.setComputeProfileDistributions(modelOptimizationSpec.isComputeProfileDistributions());
    parameterMappings = null;
    // 
    // get original MathDescription (later to be substituted for local/global parameters).
    // 
    SimulationContext simContext = modelOptimizationSpec.getSimulationContext();
    MathMapping mathMapping = simContext.createNewMathMapping();
    MathDescription origMathDesc = null;
    mathSymbolMapping = null;
    try {
        origMathDesc = mathMapping.getMathDescription();
        mathSymbolMapping = mathMapping.getMathSymbolMapping();
    } catch (MatrixException e) {
        e.printStackTrace(System.out);
        throw new MappingException(e.getMessage());
    } catch (ModelException e) {
        e.printStackTrace(System.out);
        throw new MappingException(e.getMessage());
    } catch (ExpressionException e) {
        e.printStackTrace(System.out);
        throw new MathException(e.getMessage());
    }
    // 
    // create objective function (mathDesc and data)
    // 
    ReferenceData referenceData = getRemappedReferenceData(mathMapping);
    if (referenceData == null) {
        throw new RuntimeException("no referenced data defined");
    }
    // 
    // get parameter mappings
    // 
    ParameterMappingSpec[] parameterMappingSpecs = modelOptimizationSpec.getParameterMappingSpecs();
    Vector<ParameterMapping> parameterMappingList = new Vector<ParameterMapping>();
    Variable[] allVars = (Variable[]) BeanUtils.getArray(origMathDesc.getVariables(), Variable.class);
    for (int i = 0; i < parameterMappingSpecs.length; i++) {
        cbit.vcell.model.Parameter modelParameter = parameterMappingSpecs[i].getModelParameter();
        String mathSymbol = null;
        Variable mathVariable = null;
        if (mathSymbolMapping != null) {
            Variable variable = mathSymbolMapping.getVariable(modelParameter);
            if (variable != null) {
                mathSymbol = variable.getName();
            }
            if (mathSymbol != null) {
                mathVariable = origMathDesc.getVariable(mathSymbol);
            }
        }
        if (mathVariable != null) {
            if (parameterMappingSpecs[i].isSelected()) {
                if (parameterMappingSpecs[i].getHigh() < parameterMappingSpecs[i].getLow()) {
                    throw new MathException("The lower bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is greater than its upper bound.");
                }
                if (parameterMappingSpecs[i].getCurrent() < parameterMappingSpecs[i].getLow()) {
                    throw new MathException("The initial guess of '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is smaller than its lower bound.");
                }
                if (parameterMappingSpecs[i].getCurrent() > parameterMappingSpecs[i].getHigh()) {
                    throw new MathException("The initial guess of '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is greater than its upper bound.");
                }
                if (parameterMappingSpecs[i].getLow() < 0) {
                    throw new MathException("The lower bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is negative. All lower bounds must not be negative.");
                }
                if (Double.isInfinite(parameterMappingSpecs[i].getLow())) {
                    throw new MathException("The lower bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is infinity. Lower bounds must not be infinity.");
                }
                if (parameterMappingSpecs[i].getHigh() <= 0) {
                    throw new MathException("The upper bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is negative. All upper bounds must be positive.");
                }
                if (Double.isInfinite(parameterMappingSpecs[i].getHigh())) {
                    throw new MathException("The upper bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is infinity. Upper bounds must not be infinity.");
                }
            }
            double low = parameterMappingSpecs[i].isSelected() && parameterMappingSpecs[i].getLow() == 0 ? 1e-8 : parameterMappingSpecs[i].getLow();
            double high = parameterMappingSpecs[i].getHigh();
            double scale = Math.abs(parameterMappingSpecs[i].getCurrent()) < 1.0E-10 ? 1.0 : Math.abs(parameterMappingSpecs[i].getCurrent());
            double current = parameterMappingSpecs[i].getCurrent();
            low = Math.min(low, current);
            high = Math.max(high, current);
            Parameter optParameter = new Parameter(mathSymbol, low, high, scale, current);
            ParameterMapping parameterMapping = new ParameterMapping(modelParameter, optParameter, mathVariable);
            // 
            if (mathVariable instanceof Constant) {
                Constant origConstant = (Constant) mathVariable;
                for (int j = 0; j < allVars.length; j++) {
                    if (allVars[j].equals(origConstant)) {
                        if (parameterMappingSpecs[i].isSelected()) {
                            allVars[j] = new ParameterVariable(origConstant.getName());
                        } else {
                            allVars[j] = new Constant(origConstant.getName(), new Expression(optParameter.getInitialGuess()));
                        }
                        break;
                    }
                }
            }
            // 
            if (parameterMappingSpecs[i].isSelected()) {
                parameterMappingList.add(parameterMapping);
            }
        }
    }
    parameterMappings = (ParameterMapping[]) BeanUtils.getArray(parameterMappingList, ParameterMapping.class);
    try {
        origMathDesc.setAllVariables(allVars);
    } catch (ExpressionBindingException e) {
        e.printStackTrace(System.out);
        throw new MathException(e.getMessage());
    }
    // 
    for (int i = 0; i < parameterMappings.length; i++) {
        optSpec.addParameter(parameterMappings[i].getOptParameter());
    }
    Vector<Issue> issueList = new Vector<Issue>();
    IssueContext issueContext = new IssueContext();
    optSpec.gatherIssues(issueContext, issueList);
    for (int i = 0; i < issueList.size(); i++) {
        Issue issue = issueList.elementAt(i);
        if (issue.getSeverity() == Issue.SEVERITY_ERROR) {
            throw new RuntimeException(issue.getMessage());
        }
    }
    // 
    // 
    // 
    optimizationSpec = optSpec;
    return mathSymbolMapping;
}
Also used : ParameterVariable(cbit.vcell.math.ParameterVariable) Variable(cbit.vcell.math.Variable) Issue(org.vcell.util.Issue) MathDescription(cbit.vcell.math.MathDescription) Constant(cbit.vcell.math.Constant) ParameterVariable(cbit.vcell.math.ParameterVariable) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MatrixException(cbit.vcell.matrix.MatrixException) IssueContext(org.vcell.util.IssueContext) OptimizationSpec(cbit.vcell.opt.OptimizationSpec) Vector(java.util.Vector) ModelException(cbit.vcell.model.ModelException) SimulationContext(cbit.vcell.mapping.SimulationContext) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) ReferenceData(cbit.vcell.opt.ReferenceData) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) MathMapping(cbit.vcell.mapping.MathMapping) Parameter(cbit.vcell.opt.Parameter)

Example 74 with MathException

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

the class SmoldynFileWriter method writeRuntimeCommands.

// uncomment for debug
/*private void writeGraphicsLegend() throws MathException{
	try {
		java.awt.image.BufferedImage cmapImage = new java.awt.image.BufferedImage(200, particleVariableList.size()*30,java.awt.image.BufferedImage.TYPE_INT_RGB);
		Graphics g = cmapImage.getGraphics();
		for (int i = 0; i < particleVariableList.size(); i ++) {
			Color c = colors[i];
			System.out.println("color for legend: " + "red--"+ c.getRed() + "  green--" + c.getGreen() + "  blue--" + c.getBlue());
			String variableName = getVariableName(particleVariableList.get(i),null);
			g.setColor(c);
			g.drawString(variableName, 5, 30*i + 20);
			g.fillRect(105, 30*i + 10, 20, 10);
		}
		g.dispose();
		File tmpFile = File.createTempFile("legend", ".jpg");

		FileOutputStream fios = null;
		try {
			printWriter.println("# legend file: " + tmpFile.getAbsolutePath());
			fios = new FileOutputStream(tmpFile);
			ImageIO.write(cmapImage,"jpg",fios);
		}  finally {
			if(fios != null) {fios.close();}
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw new MathException(e.getMessage());
	}
}*/
private void writeRuntimeCommands() throws SolverException, DivideByZeroException, DataAccessException, IOException, MathException, ExpressionException {
    printWriter.println("# " + SmoldynVCellMapper.SmoldynKeyword.killmolincmpt + " runtime command to kill molecules misplaced during initial condtions");
    for (ParticleVariable pv : particleVariableList) {
        CompartmentSubDomain varDomain = mathDesc.getCompartmentSubDomain(pv.getDomain().getName());
        if (varDomain == null) {
            continue;
        }
        boolean bkillMol = false;
        ArrayList<ParticleInitialCondition> iniConditionList = varDomain.getParticleProperties(pv).getParticleInitialConditions();
        for (ParticleInitialCondition iniCon : iniConditionList) {
            if (iniCon instanceof ParticleInitialConditionConcentration) {
                try {
                    subsituteFlattenToConstant(((ParticleInitialConditionConcentration) iniCon).getDistribution());
                } catch (// can not be evaluated to a constant
                Exception e) {
                    bkillMol = true;
                    break;
                }
            }
        }
        if (bkillMol) {
            Enumeration<SubDomain> subDomainEnumeration = mathDesc.getSubDomains();
            while (subDomainEnumeration.hasMoreElements()) {
                SubDomain subDomain = subDomainEnumeration.nextElement();
                if (subDomain instanceof CompartmentSubDomain && varDomain != subDomain) {
                    printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.B + " " + SmoldynVCellMapper.SmoldynKeyword.killmolincmpt + " " + pv.getName() + "(" + SmoldynVCellMapper.SmoldynKeyword.all + ") " + subDomain.getName());
                }
            }
        }
    }
    printWriter.println();
    // write command to kill molecules on membrane for adsortption to nothing
    printWriter.println("# kill membrane molecues that are absorbed (to nothing)");
    for (String killMolCmd : killMolCommands) {
        printWriter.println(killMolCmd);
    }
    printWriter.println();
    printWriter.println("# runtime command");
    printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.E + " " + VCellSmoldynKeyword.vcellPrintProgress);
    if (outputFile != null && cartesianMesh != null) {
        OutputTimeSpec ots = simulation.getSolverTaskDescription().getOutputTimeSpec();
        if (ots.isUniform()) {
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.output_files + " " + outputFile.getName());
            ISize sampleSize = simulation.getMeshSpecification().getSamplingSize();
            TimeStep timeStep = simulation.getSolverTaskDescription().getTimeStep();
            int n = (int) Math.round(((UniformOutputTimeSpec) ots).getOutputTimeStep() / timeStep.getDefaultTimeStep());
            if (simulation.getSolverTaskDescription().getSmoldynSimulationOptions().isSaveParticleLocations()) {
                printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + SmoldynVCellMapper.SmoldynKeyword.incrementfile + " " + outputFile.getName());
                printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + SmoldynVCellMapper.SmoldynKeyword.listmols + " " + outputFile.getName());
            }
            // DON'T CHANGE THE ORDER HERE.
            // DataProcess must be before vcellWriteOutput
            writeDataProcessor();
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " begin");
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " " + VCellSmoldynKeyword.dimension + " " + dimension);
            printWriter.print(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " " + VCellSmoldynKeyword.sampleSize + " " + sampleSize.getX());
            if (dimension > 1) {
                printWriter.print(" " + sampleSize.getY());
                if (dimension > 2) {
                    printWriter.print(" " + sampleSize.getZ());
                }
            }
            printWriter.println();
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " " + VCellSmoldynKeyword.numMembraneElements + " " + cartesianMesh.getNumMembraneElements());
            for (ParticleVariable pv : particleVariableList) {
                String type = pv instanceof MembraneParticleVariable ? VCellSmoldynKeyword.membrane.name() : VCellSmoldynKeyword.volume.name();
                printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " " + VCellSmoldynKeyword.variable + " " + pv.getName() + " " + type + " " + pv.getDomain().getName());
            }
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " end");
        } else {
            throw new SolverException(SolverDescription.Smoldyn.getDisplayLabel() + " only supports uniform output.");
        }
    }
    printWriter.println();
}
Also used : ParticleInitialConditionConcentration(cbit.vcell.math.ParticleProperties.ParticleInitialConditionConcentration) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) ISize(org.vcell.util.ISize) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) ImageException(cbit.image.ImageException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) SolverException(cbit.vcell.solver.SolverException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) TimeStep(cbit.vcell.solver.TimeStep) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) ParticleInitialCondition(cbit.vcell.math.ParticleProperties.ParticleInitialCondition) SolverException(cbit.vcell.solver.SolverException)

Example 75 with MathException

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

the class SmoldynFileWriter method write.

@Override
public void write(String[] parameterNames) throws ExpressionException, MathException, SolverException, DataAccessException, IOException, ImageException, PropertyVetoException, GeometryException {
    init();
    setupMolecules();
    if (bUseMessaging) {
        writeJms(simulation);
    }
    writeRandomSeed();
    writeSpecies();
    writeDiffusions();
    writeGraphicsOpenGL();
    if (simulation.getSolverTaskDescription().getSmoldynSimulationOptions().isUseHighResolutionSample()) {
        try {
            writeHighResVolumeSamples();
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
            throw new SolverException(ex.getMessage() + "\n" + "Problem may be solved by disable \'fast mesh sampling\'. It may take much longer time to complete the simulation." + "\n" + "Select \'Edit Simulation\' -> \'Solver\' -> \'Advanced Solver Options\' -> uncheck \'fast mesh sampling\'.");
        }
    }
    writeSurfaces();
    writeCompartments();
    // needs to be after dim=3 in input file (after geometry is written).
    writeDrifts();
    writeReactions();
    writeMolecules();
    writeSimulationTimes();
    writeRuntimeCommands();
    writeSimulationSettings();
    printWriter.println(SmoldynVCellMapper.SmoldynKeyword.end_file);
// SimulationWriter.write(SimulationJobToSmoldyn.convertSimulationJob(simulationJob, outputFile), printWriter, simulationJob);
}
Also used : SolverException(cbit.vcell.solver.SolverException) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) ImageException(cbit.image.ImageException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) SolverException(cbit.vcell.solver.SolverException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException)

Aggregations

MathException (cbit.vcell.math.MathException)78 ExpressionException (cbit.vcell.parser.ExpressionException)46 Expression (cbit.vcell.parser.Expression)38 Variable (cbit.vcell.math.Variable)33 VolVariable (cbit.vcell.math.VolVariable)26 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)18 MemVariable (cbit.vcell.math.MemVariable)18 PropertyVetoException (java.beans.PropertyVetoException)18 DataAccessException (org.vcell.util.DataAccessException)16 MathDescription (cbit.vcell.math.MathDescription)15 Vector (java.util.Vector)15 Element (org.jdom.Element)15 IOException (java.io.IOException)14 Function (cbit.vcell.math.Function)13 SimulationSymbolTable (cbit.vcell.solver.SimulationSymbolTable)13 MembraneParticleVariable (cbit.vcell.math.MembraneParticleVariable)12 ParticleVariable (cbit.vcell.math.ParticleVariable)12 VolumeParticleVariable (cbit.vcell.math.VolumeParticleVariable)12 ArrayList (java.util.ArrayList)12 MappingException (cbit.vcell.mapping.MappingException)11