Search in sources :

Example 6 with OptimizationException

use of cbit.vcell.opt.OptimizationException in project vcell by virtualcell.

the class CopasiOptimizationSolver method solveLocalPython.

public static OptimizationResultSet solveLocalPython(ParameterEstimationTaskSimulatorIDA parestSimulator, ParameterEstimationTask parameterEstimationTask, CopasiOptSolverCallbacks optSolverCallbacks, MathMappingCallback mathMappingCallback) throws IOException, ExpressionException, OptimizationException {
    File dir = Files.createTempDirectory("parest", new FileAttribute<?>[] {}).toFile();
    try {
        String prefix = "testing_" + Math.abs(new Random().nextInt(10000));
        File optProblemThriftFile = new File(dir, prefix + ".optprob.bin");
        File optRunFile = new File(dir, prefix + ".optrun.bin");
        // 
        // Setup Python COPASI opt problem and write to disk
        // 
        OptProblem optProblem = CopasiServicePython.makeOptProblem(parameterEstimationTask);
        CopasiServicePython.writeOptProblem(optProblemThriftFile, optProblem);
        // 
        // run Python COPASI opt problem
        // 
        CopasiServicePython.runCopasiPython(optProblemThriftFile, optRunFile);
        if (!optRunFile.exists()) {
            throw new RuntimeException("COPASI optimization output file not found:\n" + optRunFile.getAbsolutePath());
        }
        OptRun optRun = CopasiServicePython.readOptRun(optRunFile);
        OptResultSet optResultSet = optRun.getOptResultSet();
        int numFittedParameters = optResultSet.getOptParameterValues().size();
        String[] paramNames = new String[numFittedParameters];
        double[] paramValues = new double[numFittedParameters];
        for (int pIndex = 0; pIndex < numFittedParameters; pIndex++) {
            OptParameterValue optParamValue = optResultSet.getOptParameterValues().get(pIndex);
            paramNames[pIndex] = optParamValue.parameterName;
            paramValues[pIndex] = optParamValue.bestValue;
        }
        OptimizationStatus status = new OptimizationStatus(OptimizationStatus.NORMAL_TERMINATION, optRun.statusMessage);
        OptRunResultSet optRunResultSet = new OptRunResultSet(paramValues, optResultSet.objectiveFunction, optResultSet.numFunctionEvaluations, status);
        OptSolverResultSet copasiOptSolverResultSet = new OptSolverResultSet(paramNames, optRunResultSet);
        RowColumnResultSet copasiRcResultSet = parestSimulator.getRowColumnRestultSetByBestEstimations(parameterEstimationTask, paramNames, paramValues);
        OptimizationResultSet copasiOptimizationResultSet = new OptimizationResultSet(copasiOptSolverResultSet, copasiRcResultSet);
        System.out.println("-----------SOLUTION FROM PYTHON---------------\n" + optResultSet.toString());
        return copasiOptimizationResultSet;
    } catch (Throwable e) {
        e.printStackTrace(System.out);
        throw new OptimizationException(e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
    } finally {
        if (dir != null && dir.exists()) {
            FileUtils.deleteDirectory(dir);
        }
    }
}
Also used : OptimizationException(cbit.vcell.opt.OptimizationException) OptProblem(org.vcell.optimization.thrift.OptProblem) OptimizationResultSet(cbit.vcell.opt.OptimizationResultSet) OptParameterValue(org.vcell.optimization.thrift.OptParameterValue) OptSolverResultSet(cbit.vcell.opt.OptSolverResultSet) Random(java.util.Random) OptRun(org.vcell.optimization.thrift.OptRun) OptResultSet(org.vcell.optimization.thrift.OptResultSet) OptimizationStatus(cbit.vcell.opt.OptimizationStatus) OptRunResultSet(cbit.vcell.opt.OptSolverResultSet.OptRunResultSet) File(java.io.File) FileAttribute(java.nio.file.attribute.FileAttribute) RowColumnResultSet(cbit.vcell.math.RowColumnResultSet)

Example 7 with OptimizationException

use of cbit.vcell.opt.OptimizationException in project vcell by virtualcell.

the class OptXmlWriter method getModelXML.

public static Element getModelXML(PdeObjectiveFunction pdeObjectiveFunction, String[] parameterNames) {
    Element modelElement = new Element(OptXmlTags.Model_Tag);
    try {
        SpatialReferenceData refData = pdeObjectiveFunction.getReferenceData();
        double refDataEndTime = refData.getDataByRow(refData.getNumDataRows() - 1)[0];
        // 
        // post the problem either as an IDA or CVODE model
        // 
        org.vcell.util.document.SimulationVersion simVersion = new org.vcell.util.document.SimulationVersion(new KeyValue("12345"), "name", new org.vcell.util.document.User("user", new KeyValue("123")), new org.vcell.util.document.GroupAccessNone(), // versionBranchPointRef
        null, // branchID
        new java.math.BigDecimal(1.0), new java.util.Date(), org.vcell.util.document.VersionFlag.Archived, "", null);
        Simulation simulation = new Simulation(simVersion, pdeObjectiveFunction.getMathDescription());
        simulation.getMeshSpecification().setSamplingSize(refData.getDataISize());
        double[] times = refData.getDataByColumn(0);
        double minDt = Double.POSITIVE_INFINITY;
        for (int i = 1; i < times.length; i++) {
            minDt = Math.min(minDt, times[i] - times[i - 1]);
        }
        simulation.getSolverTaskDescription().setTimeBounds(new cbit.vcell.solver.TimeBounds(0.0, refDataEndTime));
        simulation.getSolverTaskDescription().setSolverDescription(SolverDescription.FiniteVolume);
        simulation.getSolverTaskDescription().setTimeStep(new TimeStep(minDt / 5, minDt / 5, minDt / 5));
        // clone and resample geometry
        Geometry resampledGeometry = null;
        try {
            resampledGeometry = (Geometry) BeanUtils.cloneSerializable(simulation.getMathDescription().getGeometry());
            GeometrySurfaceDescription geoSurfaceDesc = resampledGeometry.getGeometrySurfaceDescription();
            ISize newSize = simulation.getMeshSpecification().getSamplingSize();
            geoSurfaceDesc.setVolumeSampleSize(newSize);
            geoSurfaceDesc.updateAll();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SolverException(e.getMessage());
        }
        SimulationTask simTask = new SimulationTask(new SimulationJob(simulation, 0, pdeObjectiveFunction.getFieldDataIDSs()), 0);
        StringWriter simulationInputStringWriter = new StringWriter();
        FiniteVolumeFileWriter fvFileWriter = new FiniteVolumeFileWriter(new PrintWriter(simulationInputStringWriter, true), simTask, resampledGeometry, pdeObjectiveFunction.getWorkingDirectory());
        fvFileWriter.write(parameterNames);
        simulationInputStringWriter.close();
        modelElement.setAttribute(OptXmlTags.ModelType_Attr, OptXmlTags.ModelType_Attr_FVSOLVER);
        CDATA simulationInputText = new CDATA(simulationInputStringWriter.getBuffer().toString());
        modelElement.addContent(simulationInputText);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new OptimizationException("failed to create fv input file: " + e.getMessage());
    }
    return modelElement;
}
Also used : OptimizationException(cbit.vcell.opt.OptimizationException) KeyValue(org.vcell.util.document.KeyValue) SimulationTask(cbit.vcell.messaging.server.SimulationTask) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) ISize(org.vcell.util.ISize) Element(org.jdom.Element) FiniteVolumeFileWriter(cbit.vcell.solvers.FiniteVolumeFileWriter) TimeStep(cbit.vcell.solver.TimeStep) StringWriter(java.io.StringWriter) SpatialReferenceData(cbit.vcell.opt.SpatialReferenceData) SimulationJob(cbit.vcell.solver.SimulationJob) PrintWriter(java.io.PrintWriter) Constraint(cbit.vcell.opt.Constraint) OptimizationException(cbit.vcell.opt.OptimizationException) XMLStreamException(javax.xml.stream.XMLStreamException) SBMLException(org.sbml.jsbml.SBMLException) XmlParseException(cbit.vcell.xml.XmlParseException) SolverException(cbit.vcell.solver.SolverException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) SolverException(cbit.vcell.solver.SolverException) CDATA(org.jdom.CDATA)

Example 8 with OptimizationException

use of cbit.vcell.opt.OptimizationException in project vcell by virtualcell.

the class OptXmlWriter method getObjectiveFunctionXML.

public static Element getObjectiveFunctionXML(OptimizationSpec optimizationSpec) {
    Element objectiveFunctionElement = new Element(OptXmlTags.ObjectiveFunction_Tag);
    ObjectiveFunction objectiveFunction = optimizationSpec.getObjectiveFunction();
    if (objectiveFunction instanceof ExplicitObjectiveFunction) {
        ExplicitObjectiveFunction explicitObjectiveFunction = (ExplicitObjectiveFunction) objectiveFunction;
        objectiveFunctionElement.setAttribute(OptXmlTags.ObjectiveFunctionType_Attr, OptXmlTags.ObjectiveFunctionType_Attr_Explicit);
        Element expressionElement = new Element(OptXmlTags.Expression_Tag);
        expressionElement.addContent(explicitObjectiveFunction.getExpression().infix());
        objectiveFunctionElement.addContent(expressionElement);
    } else if (objectiveFunction instanceof ExplicitFitObjectiveFunction) {
        ExplicitFitObjectiveFunction explicitFitObjectiveFunction = (ExplicitFitObjectiveFunction) objectiveFunction;
        objectiveFunctionElement.setAttribute(OptXmlTags.ObjectiveFunctionType_Attr, OptXmlTags.ObjectiveFunctionType_Attr_ExplicitFit);
        // add expression list
        Element expressionListElement = new Element(OptXmlTags.ExpressionList_Tag);
        objectiveFunctionElement.addContent(expressionListElement);
        ExplicitFitObjectiveFunction.ExpressionDataPair[] expDataPairs = explicitFitObjectiveFunction.getExpressionDataPairs();
        for (int i = 0; i < expDataPairs.length; i++) {
            Element expressionElement = new Element(OptXmlTags.Expression_Tag);
            expressionElement.setAttribute(OptXmlTags.ExpRefDataColumnIndex_Attr, expDataPairs[i].getReferenceDataIndex() + "");
            expressionElement.addContent(expDataPairs[i].getFitFunction().infix());
            expressionListElement.addContent(expressionElement);
        }
        if (explicitFitObjectiveFunction.getReferenceData() instanceof SimpleReferenceData) {
            Element dataElement = getDataXML(explicitFitObjectiveFunction.getReferenceData());
            objectiveFunctionElement.addContent(dataElement);
        } else {
            throw new OptimizationException("Optimization XML Writer exports SimpleReferenceData only.");
        }
    } else if (objectiveFunction instanceof PdeObjectiveFunction) {
        PdeObjectiveFunction pdeObjectiveFunction = (PdeObjectiveFunction) objectiveFunction;
        objectiveFunctionElement.setAttribute(OptXmlTags.ObjectiveFunctionType_Attr, OptXmlTags.ObjectiveFunctionType_Attr_PDE);
        SpatialReferenceData refData = pdeObjectiveFunction.getReferenceData();
        Element dataElement = getDataXML(refData);
        objectiveFunctionElement.addContent(dataElement);
        Element modelElement = getModelXML(pdeObjectiveFunction, optimizationSpec.getParameterNames());
        objectiveFunctionElement.addContent(modelElement);
        Simulation tempSim = new Simulation(pdeObjectiveFunction.getMathDescription());
        SimulationSymbolTable simSymbolTable = new SimulationSymbolTable(tempSim, 0);
        // 
        for (int i = 1; i < refData.getNumVariables(); i++) {
            Element modelMappingElement = new Element(OptXmlTags.ModelMapping_Tag);
            modelMappingElement.setAttribute(OptXmlTags.ModelMappingDataColumn_Attr, refData.getVariableNames()[i]);
            modelMappingElement.setAttribute(OptXmlTags.ModelMappingWeight_Attr, String.valueOf(refData.getVariableWeights()[i]));
            Expression mappingExpression = null;
            try {
                Variable var = pdeObjectiveFunction.getMathDescription().getVariable(refData.getVariableNames()[i]);
                if (var instanceof Function) {
                    Expression exp = new Expression(var.getExpression());
                    exp.bindExpression(simSymbolTable);
                    exp = MathUtilities.substituteFunctions(exp, simSymbolTable);
                    mappingExpression = exp.flatten();
                } else {
                    mappingExpression = new Expression(var.getName());
                }
            } catch (ExpressionException e) {
                e.printStackTrace();
                throw new OptimizationException(e.getMessage());
            }
            modelMappingElement.addContent(mappingExpression.infix());
            objectiveFunctionElement.addContent(modelMappingElement);
        }
    }
    return objectiveFunctionElement;
}
Also used : OptimizationException(cbit.vcell.opt.OptimizationException) ReservedVariable(cbit.vcell.math.ReservedVariable) Variable(cbit.vcell.math.Variable) Element(org.jdom.Element) PdeObjectiveFunction(cbit.vcell.opt.PdeObjectiveFunction) ExplicitFitObjectiveFunction(cbit.vcell.opt.ExplicitFitObjectiveFunction) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) ExplicitFitObjectiveFunction(cbit.vcell.opt.ExplicitFitObjectiveFunction) ExplicitObjectiveFunction(cbit.vcell.opt.ExplicitObjectiveFunction) ObjectiveFunction(cbit.vcell.opt.ObjectiveFunction) PdeObjectiveFunction(cbit.vcell.opt.PdeObjectiveFunction) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) Constraint(cbit.vcell.opt.Constraint) ExpressionException(cbit.vcell.parser.ExpressionException) ExplicitFitObjectiveFunction(cbit.vcell.opt.ExplicitFitObjectiveFunction) Function(cbit.vcell.math.Function) ExplicitObjectiveFunction(cbit.vcell.opt.ExplicitObjectiveFunction) ObjectiveFunction(cbit.vcell.opt.ObjectiveFunction) PdeObjectiveFunction(cbit.vcell.opt.PdeObjectiveFunction) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) ExplicitObjectiveFunction(cbit.vcell.opt.ExplicitObjectiveFunction) SpatialReferenceData(cbit.vcell.opt.SpatialReferenceData)

Example 9 with OptimizationException

use of cbit.vcell.opt.OptimizationException in project vcell by virtualcell.

the class PowellOptimizationSolver method solve.

/**
 * Insert the method's description here.
 * Creation date: (3/5/00 11:15:15 PM)
 * @return double[]
 * @param optSpec cbit.vcell.opt.OptimizationSpec
 * @exception java.io.IOException The exception description.
 * @exception cbit.vcell.parser.ExpressionException The exception description.
 * @exception cbit.vcell.opt.OptimizationException The exception description.
 */
public OptimizationResultSet solve(OptimizationSpec os, OptimizationSolverSpec optSolverSpec, OptSolverCallbacks optSolverCallbacks) throws java.io.IOException, cbit.vcell.parser.ExpressionException, OptimizationException {
    final double power = 2.0;
    final double MU_START = 0.1;
    final double MU_END = 100000.0;
    final double MU_STEP = 10.0;
    AugmentedObjectiveFunction augmentedObjFunc = OptUtils.getAugmentedObjectiveFunction(os, power, MU_START, optSolverCallbacks);
    // 
    // initialize starting guess
    // 
    Parameter[] parameters = os.getParameters();
    double[] parameterValues = new double[parameters.length];
    for (int i = 0; i < parameters.length; i++) {
        parameterValues[i] = parameters[i].getInitialGuess();
        System.out.println("initial " + parameters[i].getName() + " = " + parameterValues[i]);
    }
    // 
    // get initial direction set
    // 
    double[][] xi = new double[parameterValues.length][parameterValues.length];
    for (int i = 0; i < parameterValues.length; i++) {
        for (int j = 0; j < parameterValues.length; j++) {
            xi[i][j] = (i == j ? 1.0 : 0.0);
        }
    }
    final double ftol = 1e-6;
    double fret = augmentedObjFunc.f(parameterValues);
    PowellSolver powellSolver = new PowellSolver();
    for (double mu = MU_START; mu <= MU_END; mu *= MU_STEP) {
        try {
            if (optSolverCallbacks.getStopRequested()) {
                break;
            }
            augmentedObjFunc.setMu(mu);
            fret = powellSolver.powell(parameterValues.length, parameterValues, xi, ftol, augmentedObjFunc);
            System.out.println("mu=" + mu + ", function value=" + fret);
            if (augmentedObjFunc.getPenalty(parameterValues) == 0.0) {
                break;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            break;
        }
    }
    OptimizationStatus optStatus = new OptimizationStatus(OptimizationStatus.NORMAL_TERMINATION, "Normal Termination");
    ODESolverResultSet odeSolverResultSet = null;
    if (optSolverCallbacks.getStopRequested()) {
        optStatus = new OptimizationStatus(OptimizationStatus.STOPPED_BY_USER, "Stopped by user");
    }
    parameterValues = optSolverCallbacks.getBestEvaluation().getParameterValues();
    fret = optSolverCallbacks.getBestEvaluation().getObjectiveFunctionValue();
    odeSolverResultSet = optSolverCallbacks.getBestResultSet();
    for (int i = 0; i < parameters.length; i++) {
        System.out.println("final " + parameters[i].getName() + " = " + parameterValues[i]);
    }
    OptRunResultSet bestResult = new OptRunResultSet(parameterValues, new Double(fret), optSolverCallbacks.getEvaluationCount(), optStatus);
    return new OptimizationResultSet(new OptSolverResultSet(os.getParameterNames(), bestResult), odeSolverResultSet);
}
Also used : OptimizationResultSet(cbit.vcell.opt.OptimizationResultSet) OptimizationException(cbit.vcell.opt.OptimizationException) OptSolverResultSet(cbit.vcell.opt.OptSolverResultSet) Parameter(cbit.vcell.opt.Parameter) OptimizationStatus(cbit.vcell.opt.OptimizationStatus) ODESolverResultSet(cbit.vcell.solver.ode.ODESolverResultSet) OptRunResultSet(cbit.vcell.opt.OptSolverResultSet.OptRunResultSet)

Aggregations

OptimizationException (cbit.vcell.opt.OptimizationException)9 OptimizationResultSet (cbit.vcell.opt.OptimizationResultSet)6 ExpressionException (cbit.vcell.parser.ExpressionException)4 OptSolverResultSet (cbit.vcell.opt.OptSolverResultSet)3 OptRunResultSet (cbit.vcell.opt.OptSolverResultSet.OptRunResultSet)3 OptimizationStatus (cbit.vcell.opt.OptimizationStatus)3 IOException (java.io.IOException)3 RowColumnResultSet (cbit.vcell.math.RowColumnResultSet)2 Constraint (cbit.vcell.opt.Constraint)2 SpatialReferenceData (cbit.vcell.opt.SpatialReferenceData)2 Expression (cbit.vcell.parser.Expression)2 Simulation (cbit.vcell.solver.Simulation)2 Element (org.jdom.Element)2 ParameterEstimationTaskSimulatorIDA (org.vcell.optimization.ParameterEstimationTaskSimulatorIDA)2 OptParameterValue (org.vcell.optimization.thrift.OptParameterValue)2 OptProblem (org.vcell.optimization.thrift.OptProblem)2 OptResultSet (org.vcell.optimization.thrift.OptResultSet)2 OptRun (org.vcell.optimization.thrift.OptRun)2 Issue (org.vcell.util.Issue)2 IssueContext (org.vcell.util.IssueContext)2