Search in sources :

Example 46 with SolverException

use of cbit.vcell.solver.SolverException in project vcell by virtualcell.

the class ComsolSolver method initialize.

@Override
protected void initialize() throws SolverException {
    try {
        this.vccModel = ComsolModelBuilder.getVCCModel(getSimulationJob());
        // write mesh file
        File meshFile = new File(getSaveDirectory(), simTask.getSimulationJob().getSimulationJobID() + SimDataConstants.MESHFILE_EXTENSION);
        try (FileOutputStream fos = new FileOutputStream(meshFile)) {
            simTask.getSimulation().getMathDescription().getGeometry().getGeometrySurfaceDescription().updateAll();
            CartesianMesh mesh = CartesianMesh.createSimpleCartesianMesh(simTask.getSimulation().getMathDescription().getGeometry());
            mesh.write(new PrintStream(new BufferedOutputStream(fos)));
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new SolverException(e.getMessage());
        }
        ComsolServiceFactory factory = ComsolServiceFactory.instance;
        if (factory == null) {
            throw new RuntimeException("no Comsol Service available");
        }
        this.comsolService = factory.newComsolService();
    } catch (ExpressionException e) {
        e.printStackTrace();
        throw new SolverException("failed to generate VCell Comsol Model in ComsolSolver: " + e.getMessage(), e);
    }
}
Also used : PrintStream(java.io.PrintStream) CartesianMesh(cbit.vcell.solvers.CartesianMesh) FileOutputStream(java.io.FileOutputStream) SolverException(cbit.vcell.solver.SolverException) ComsolServiceFactory(org.vcell.solver.comsol.service.ComsolServiceFactory) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) SolverException(cbit.vcell.solver.SolverException) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 47 with SolverException

use of cbit.vcell.solver.SolverException in project vcell by virtualcell.

the class NFSimSolver method initialize.

/**
 * This method takes the place of the old runUnsteady()...
 */
protected void initialize() throws SolverException {
    if (lg.isTraceEnabled())
        lg.trace("NFSimSolver.initialize()");
    fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INIT);
    writeFunctionsFile();
    String inputFilename = getInputFilename();
    if (lg.isTraceEnabled())
        lg.trace("NFSimSolver.initialize() inputFilename = " + getInputFilename());
    setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INPUT_FILE));
    fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INPUT_FILE);
    try (PrintWriter pw = new PrintWriter(inputFilename)) {
        NFSimFileWriter stFileWriter = new NFSimFileWriter(pw, simTask, bMessaging);
        stFileWriter.write();
    } catch (Exception e) {
        setSolverStatus(new SolverStatus(SolverStatus.SOLVER_ABORTED, SimulationMessage.solverAborted("Could not generate input file: " + e.getMessage())));
        e.printStackTrace(System.out);
        throw new SolverException(e.getMessage());
    }
    PrintWriter lg = null;
    String logFilename = getLogFilename();
    String outputFilename = getOutputFilename();
    try {
        lg = new PrintWriter(logFilename);
        String shortOutputFilename = outputFilename.substring(1 + outputFilename.lastIndexOf("\\"));
        lg.println(NFSIM_DATA_IDENTIFIER + " " + shortOutputFilename);
    } catch (Exception e) {
        setSolverStatus(new SolverStatus(SolverStatus.SOLVER_ABORTED, SimulationMessage.solverAborted("Could not generate log file: " + e.getMessage())));
        e.printStackTrace(System.out);
        throw new SolverException(e.getMessage());
    } finally {
        if (lg != null) {
            lg.close();
        }
    }
    setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_START));
    // get executable path+name.
    setMathExecutable(new MathExecutable(getMathExecutableCommand(), getSaveDirectory()));
// setMathExecutable(new
// cbit.vcell.solvers.MathExecutable(executableName + " gibson " +
// getBaseName() + ".stochInput" + " " + getBaseName() + ".stoch"));
}
Also used : SolverException(cbit.vcell.solver.SolverException) MathExecutable(cbit.vcell.solvers.MathExecutable) SolverStatus(cbit.vcell.solver.server.SolverStatus) ExecutableException(org.vcell.util.exe.ExecutableException) SolverException(cbit.vcell.solver.SolverException) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Example 48 with SolverException

use of cbit.vcell.solver.SolverException in project vcell by virtualcell.

the class NFsimXMLWriter method isFunction.

private static boolean isFunction(String candidate, MathDescription mathDesc, SimulationSymbolTable simulationSymbolTable) throws SolverException {
    Element listOfParametersElement = new Element("ListOfFunctions");
    for (Variable var : simulationSymbolTable.getVariables()) {
        Double value = null;
        if (var instanceof Constant || var instanceof Function) {
            Expression valExpression = var.getExpression();
            Expression substitutedValExpr = null;
            try {
                substitutedValExpr = simulationSymbolTable.substituteFunctions(valExpression);
            } catch (Exception e) {
                e.printStackTrace(System.out);
                throw new SolverException("Constant or Function " + var.getName() + " substitution failed : exp = \"" + var.getExpression().infix() + "\": " + e.getMessage());
            }
            try {
                value = substitutedValExpr.evaluateConstant();
            } catch (ExpressionException e) {
                System.out.println("constant or function " + var.getName() + " = " + substitutedValExpr.infix() + " does not have a constant value");
            }
            if (value != null) {
                // parameter, see getListOfParameters() above
                continue;
            } else {
                String current = var.getName();
                if (candidate.equals(current)) {
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : Function(cbit.vcell.math.Function) Variable(cbit.vcell.math.Variable) Expression(cbit.vcell.parser.Expression) MacroscopicRateConstant(cbit.vcell.math.MacroscopicRateConstant) Constant(cbit.vcell.math.Constant) Element(org.jdom.Element) SolverException(cbit.vcell.solver.SolverException) SolverException(cbit.vcell.solver.SolverException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 49 with SolverException

use of cbit.vcell.solver.SolverException in project vcell by virtualcell.

the class NFsimXMLWriter method getListOfComponents1.

private static Element getListOfComponents1(String reactionRuleID, String patternID, String moleculeID, ParticleSpeciesPattern speciesPattern, ParticleMolecularTypePattern particleMolecularTypePattern, ArrayList<ComponentOfMolecularTypeOfReactionParticipant> currentComponentOfParticipant, HashMap<Bond, BondSites> bondSitesMap) throws SolverException {
    // while traversing Components of a MolecularTypePattern, it populates bondSiteMapping
    Element listOfComponentsElement = new Element("ListOfComponents");
    for (int componentId = 0; componentId < particleMolecularTypePattern.getMolecularComponentPatternList().size(); componentId++) {
        ParticleMolecularComponentPattern particleMolecularComponentPattern = particleMolecularTypePattern.getMolecularComponentPatternList().get(componentId);
        Element componentElement = new Element("Component");
        ParticleMolecularComponent particleMolecularComponent = particleMolecularComponentPattern.getMolecularComponent();
        // componentElement.setAttribute("id", particleMolecularComponent.getId());
        String elementID = "C" + (componentId + 1);
        String componentID = reactionRuleID + "_" + patternID + "_" + moleculeID + "_" + elementID;
        componentElement.setAttribute("id", componentID);
        componentElement.setAttribute("name", particleMolecularComponent.getName());
        ParticleComponentStatePattern componentStatePattern = particleMolecularComponentPattern.getComponentStatePattern();
        ParticleComponentStateDefinition pcsd = componentStatePattern.getParticleComponentStateDefinition();
        String state = "";
        boolean ignoreFlagState = false;
        if (componentStatePattern.isAny()) {
            state = "*";
            ignoreFlagState = true;
        } else if (pcsd != null) {
            state = pcsd.getName();
            componentElement.setAttribute("state", state);
        } else {
            throw new RuntimeException("Invalid state for ParticleComponentStatePattern.");
        }
        // ParticleComponentState componentState = particleMolecularComponentPattern.getComponentState();
        // String state = "";
        // if (componentState!=null){
        // state = componentState.getName();
        // if(!state.equals("*")) {
        // componentElement.setAttribute("state", state);
        // }
        // }
        ComponentOfMolecularTypeOfReactionParticipant cper = new ComponentOfMolecularTypeOfReactionParticipant(particleMolecularTypePattern.getMolecularType().getName(), particleMolecularTypePattern.getMatchLabel(), particleMolecularComponent.getName(), componentID, state);
        // number of bonds is 0 or 1 for species (concrete species).  the bonds are listed later in the list of bonds
        ParticleBondType bondType = particleMolecularComponentPattern.getBondType();
        boolean ignoreFlagBond = false;
        switch(bondType) {
            case Exists:
                {
                    componentElement.setAttribute("numberOfBonds", bondType.symbol);
                    break;
                }
            case None:
                {
                    componentElement.setAttribute("numberOfBonds", "0");
                    break;
                }
            case Possible:
                {
                    componentElement.setAttribute("numberOfBonds", bondType.symbol);
                    ignoreFlagBond = true;
                    break;
                }
            case Specified:
                {
                    if (particleMolecularComponentPattern.getBondId() >= 0) {
                        componentElement.setAttribute("numberOfBonds", "1");
                        String bondID = reactionRuleID + "_" + patternID + "_B" + particleMolecularComponentPattern.getBondId();
                        Bond bond = new Bond(bondID, speciesPattern);
                        BondSites bondSites = bondSitesMap.get(bond);
                        if (bondSites == null) {
                            BondSites newBondSite = new BondSites();
                            newBondSite.component1 = componentID;
                            bondSitesMap.put(bond, newBondSite);
                        } else {
                            if (bondSites.component1.equals(componentID) || bondSites.component2.equals(componentID)) {
                                throw new SolverException("this molecularComponentPattern already set in bondSites");
                            }
                            if (bondSites.component2.equals("")) {
                                bondSites.component2 = componentID;
                            } else {
                                throw new SolverException("two other molecularComponentPatterns already set in bondSites");
                            }
                        }
                    } else {
                        componentElement.setAttribute("numberOfBonds", "0");
                    }
                    break;
                }
        }
        if (ignoreFlagState == false || ignoreFlagBond == false) {
            currentComponentOfParticipant.add(cper);
            listOfComponentsElement.addContent(componentElement);
        }
    }
    return listOfComponentsElement;
}
Also used : ParticleComponentStatePattern(cbit.vcell.math.ParticleComponentStatePattern) Element(org.jdom.Element) ParticleBondType(cbit.vcell.math.ParticleMolecularComponentPattern.ParticleBondType) ParticleMolecularComponent(cbit.vcell.math.ParticleMolecularComponent) ParticleMolecularComponentPattern(cbit.vcell.math.ParticleMolecularComponentPattern) ParticleComponentStateDefinition(cbit.vcell.math.ParticleComponentStateDefinition) SolverException(cbit.vcell.solver.SolverException)

Example 50 with SolverException

use of cbit.vcell.solver.SolverException 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)

Aggregations

SolverException (cbit.vcell.solver.SolverException)53 ExpressionException (cbit.vcell.parser.ExpressionException)28 IOException (java.io.IOException)23 MathException (cbit.vcell.math.MathException)20 PrintWriter (java.io.PrintWriter)16 File (java.io.File)15 Element (org.jdom.Element)13 SolverStatus (cbit.vcell.solver.server.SolverStatus)10 DataAccessException (org.vcell.util.DataAccessException)9 GeometrySurfaceDescription (cbit.vcell.geometry.surface.GeometrySurfaceDescription)8 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)8 Variable (cbit.vcell.math.Variable)8 FileNotFoundException (java.io.FileNotFoundException)8 ISize (org.vcell.util.ISize)8 MembraneSubDomain (cbit.vcell.math.MembraneSubDomain)7 ImageException (cbit.image.ImageException)6 GeometryException (cbit.vcell.geometry.GeometryException)6 Expression (cbit.vcell.parser.Expression)5 SubVolume (cbit.vcell.geometry.SubVolume)4 DivideByZeroException (cbit.vcell.parser.DivideByZeroException)4