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);
}
}
}
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;
}
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;
}
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);
}
Aggregations