use of cbit.vcell.opt.OptimizationException in project vcell by virtualcell.
the class ParameterEstimationRunTaskPanel method solve.
private void solve() throws NumberFormatException {
CopasiOptimizationMethod com = optimizationMethodParameterTableModel.copasiOptimizationMethod;
OptimizationSolverSpec optSolverSpec = new OptimizationSolverSpec(com);
// get num runs for stochstic opt mehtods before starting solving...
if (com.getType().isStochasticMethod()) {
int numRuns = Integer.parseInt(((String) numberOfRunComboBox.getSelectedItem()));
optSolverSpec.setNumOfRuns(numRuns);
}
parameterEstimationTask.setOptimizationSolverSpec(optSolverSpec);
parameterEstimationTask.getModelOptimizationSpec().setComputeProfileDistributions(computeProfileDistributionsCheckBox.isSelected());
optSolverCallbacks.reset();
Double endValue = com.getEndValue();
optSolverCallbacks.setEvaluation(0, Double.POSITIVE_INFINITY, 0, endValue, 0);
// (endValue != null);
getRunStatusDialog().showProgressBar(com);
Collection<AsynchClientTask> taskList = ClientRequestManager.updateMath(this, parameterEstimationTask.getSimulationContext(), false, NetworkGenerationRequirements.ComputeFullStandardTimeout);
AsynchClientTask task1 = new AsynchClientTask("checking issues", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
StringBuffer issueText = new StringBuffer();
java.util.Vector<Issue> issueList = new java.util.Vector<Issue>();
IssueContext issueContext = new IssueContext();
parameterEstimationTask.gatherIssues(issueContext, issueList);
boolean bFailed = false;
for (int i = 0; i < issueList.size(); i++) {
Issue issue = (Issue) issueList.elementAt(i);
issueText.append(issue.getMessage() + "\n");
if (issue.getSeverity() == Issue.SEVERITY_ERROR) {
bFailed = true;
break;
}
}
if (bFailed) {
throw new OptimizationException(issueText.toString());
}
parameterEstimationTask.refreshMappings();
}
};
taskList.add(task1);
AsynchClientTask task2 = new AsynchClientTask("solving", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
MathMappingCallback mathMappingCallback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
// OptimizationResultSet optResultSet = CopasiOptimizationSolver.solveLocalPython(new ParameterEstimationTaskSimulatorIDA(),parameterEstimationTask,optSolverCallbacks,mathMappingCallback);
OptimizationResultSet optResultSet = CopasiOptimizationSolver.solveRemoteApi(new ParameterEstimationTaskSimulatorIDA(), parameterEstimationTask, optSolverCallbacks, mathMappingCallback);
hashTable.put(ORS_KEY, optResultSet);
}
};
taskList.add(task2);
AsynchClientTask setResultTask = new AsynchClientTask("set results", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
OptimizationResultSet optResultSet = (OptimizationResultSet) hashTable.get(ORS_KEY);
parameterEstimationTask.setOptimizationResultSet(optResultSet);
}
};
taskList.add(setResultTask);
ClientTaskDispatcher.dispatch(this, new Hashtable<String, Object>(), taskList.toArray(new AsynchClientTask[taskList.size()]), getRunStatusDialog(), true, true, true, null, false);
}
use of cbit.vcell.opt.OptimizationException in project vcell by virtualcell.
the class LocalOptimizationService method solve.
/**
* solve method comment.
*/
public OptimizationResultSet solve(OptimizationSpec optSpec, OptimizationSolverSpec optSolverSpec, OptSolverCallbacks optSolverCallbacks) {
OptimizationSolver optSolver = null;
if (optSolverSpec.getSolverType().equals(OptimizationSolverSpec.SOLVERTYPE_POWELL)) {
optSolver = new PowellOptimizationSolver();
// }else if (optSolverSpec.getSolverType().equals(OptimizationSolverSpec.SOLVERTYPE_CONJUGATE_GRADIENT)){
// optSolver = new ConjugateGradientOptimizationSolver();
} else {
throw new RuntimeException("unsupported solver type '" + optSolverSpec.getSolverType() + "'");
}
OptimizationResultSet optResultSet = null;
try {
optResultSet = optSolver.solve(optSpec, optSolverSpec, optSolverCallbacks);
} catch (IOException e) {
e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
} catch (OptimizationException e) {
e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
}
return optResultSet;
}
use of cbit.vcell.opt.OptimizationException in project vcell by virtualcell.
the class FRAPDataAnalysis method fitRecovery_reacOffRateOnly.
/**
* Method fitRecovery2.
* @param frapData, the original image info.
* @param fixedParameter: the fixed parameter from profile likelihood distribution analysis.
* @param measurementError: the measurementError is used as weights for calculating objectiveFunction errors.
* @return FrapDataAnalysisResults.ReactionOnlyAnalysisRestults
* @throws ExpressionException
*/
public static FrapDataAnalysisResults.ReactionOnlyAnalysisRestults fitRecovery_reacOffRateOnly(FRAPData frapData, Parameter fixedParam, double[][] measurementError, int startIndexForRecovery) throws ExpressionException, OptimizationException, IOException {
// int startIndexForRecovery = getRecoveryIndex(frapData);
//
// get unnormalized average background fluorescence at each time point
//
double[] temp_background = frapData.getAvgBackGroundIntensity();
// the prebleachAvg has backgroud subtracted.
double[] preBleachAvgXYZ = FrapDataUtils.calculatePreBleachAverageXYZ(frapData, startIndexForRecovery);
// tempBeachedAverage and tempCellROIAverage have subtracted background and divided by prebleach average. the following array has data for the full time duration.
double[] tempBeachedAverage = getAverageROIIntensity(frapData, frapData.getRoi(FRAPData.VFRAP_ROI_ENUM.ROI_BLEACHED.name()), preBleachAvgXYZ, temp_background);
double[] tempCellROIAverage = getAverageROIIntensity(frapData, frapData.getRoi(FRAPData.VFRAP_ROI_ENUM.ROI_CELL.name()), preBleachAvgXYZ, temp_background);
double[] temp_time = frapData.getImageDataset().getImageTimeStamps();
// get bleached and cell roi data starting from first post bleach
// The time points start from the first post bleach
double[] bleachedAverage = new double[tempBeachedAverage.length - startIndexForRecovery];
// time points start from the first post bleach
double[] cellROIAverage = new double[tempCellROIAverage.length - startIndexForRecovery];
// Time points stat from the first post bleach
double[] time = new double[temp_time.length - startIndexForRecovery];
System.arraycopy(tempBeachedAverage, startIndexForRecovery, bleachedAverage, 0, bleachedAverage.length);
System.arraycopy(tempCellROIAverage, startIndexForRecovery, cellROIAverage, 0, cellROIAverage.length);
System.arraycopy(temp_time, startIndexForRecovery, time, 0, time.length);
// initialize reaction off rate analysis results
FrapDataAnalysisResults.ReactionOnlyAnalysisRestults offRateAnalysisResults = new FrapDataAnalysisResults.ReactionOnlyAnalysisRestults();
/**
*curve fitting
*/
// index 0: cell ROI intensity average at time 0, I_cell_ini. index 1: bleached intensity average at time 0, I_bleached_ini
double[] inputParamValues = new double[] { cellROIAverage[0], bleachedAverage[0] };
// if fixed parameter is null, then outputs are bwm rate, koff rate, fitting parameter A. Otherwise outputs are two out of three.
double[] outputParamValues = null;
// create data array,first col is cell average, second col is bleached average.
double[][] fitData = new double[2][];
fitData[0] = cellROIAverage;
fitData[1] = bleachedAverage;
// create element weights array, first col is cell data weights, second col is bleached data weights
double[][] weightData = new double[time.length][2];
double[] cellROIMeasurementError = measurementError[FRAPData.VFRAP_ROI_ENUM.ROI_CELL.ordinal()];
double[] bleachedROIMeasurementError = measurementError[FRAPData.VFRAP_ROI_ENUM.ROI_BLEACHED.ordinal()];
for (// elementWeight, first dimension is number of rows(time points), second dimension is number of variables(fitDatasets)
int i = 0; // elementWeight, first dimension is number of rows(time points), second dimension is number of variables(fitDatasets)
i < time.length; // elementWeight, first dimension is number of rows(time points), second dimension is number of variables(fitDatasets)
i++) {
weightData[i][0] = 1 / (cellROIMeasurementError[i] * cellROIMeasurementError[i]);
weightData[i][1] = 1 / (bleachedROIMeasurementError[i] * bleachedROIMeasurementError[i]);
}
ElementWeights eleWeights = new ElementWeights(weightData);
if (fixedParam == null) {
// call curvefitting
// bwmrate, fitting parameter A & reaction off rate
outputParamValues = new double[3];
double error = CurveFitting.fitRecovery_reacKoffRateOnly(time, fitData, inputParamValues, outputParamValues, fixedParam, eleWeights);
// set objective function value
offRateAnalysisResults.setObjectiveFunctionValue(error);
// set reaction off rate analysis results
offRateAnalysisResults.setBleachWhileMonitoringTau(outputParamValues[0]);
offRateAnalysisResults.setFittingParamA(outputParamValues[1]);
offRateAnalysisResults.setOffRate(outputParamValues[2]);
// set cell intensity expression ( only t left in expression)
Expression cellIntensityExp = new Expression(FRAPOptFunctions.FUNC_CELL_INTENSITY);
cellIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_I_inicell), new Expression(cellROIAverage[0]));
// subsitute bwmRate
cellIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_BWM_RATE), new Expression(outputParamValues[0]));
// undo time shift
cellIntensityExp.substituteInPlace(new Expression(ReservedVariable.TIME.getName()), new Expression(ReservedVariable.TIME.getName() + "-" + time[0]));
offRateAnalysisResults.setFitBleachWhileMonitorExpression(cellIntensityExp);
// set bleached region intensity expression ( only t left in expression)
Expression bleachIntensityExp = new Expression(FRAPOptFunctions.FUNC_RECOVERY_BLEACH_REACTION_DOMINANT);
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_I_inibleached), new Expression(bleachedAverage[0]));
// subsitute bwmRate
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_BWM_RATE), new Expression(outputParamValues[0]));
// subsitute parameter A
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_A), new Expression(outputParamValues[1]));
// reaction off rate
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_KOFF), new Expression(outputParamValues[2]));
// undo time shift
bleachIntensityExp.substituteInPlace(new Expression(ReservedVariable.TIME.getName()), new Expression(ReservedVariable.TIME.getName() + "-" + time[0]));
offRateAnalysisResults.setOffRateFitExpression(bleachIntensityExp);
} else {
if (fixedParam != null && fixedParam.getName().equals(FRAPModel.MODEL_PARAMETER_NAMES[FRAPModel.INDEX_BLEACH_MONITOR_RATE])) {
// fitting parameter A & reaction off rate
outputParamValues = new double[2];
double error = CurveFitting.fitRecovery_reacKoffRateOnly(time, fitData, inputParamValues, outputParamValues, fixedParam, eleWeights);
// set objective function value
offRateAnalysisResults.setObjectiveFunctionValue(error);
// set reaction off rate analysis results
offRateAnalysisResults.setBleachWhileMonitoringTau(fixedParam.getInitialGuess());
offRateAnalysisResults.setFittingParamA(outputParamValues[0]);
offRateAnalysisResults.setOffRate(outputParamValues[1]);
// set cell intensity expression ( only t left in expression)
Expression cellIntensityExp = new Expression(FRAPOptFunctions.FUNC_CELL_INTENSITY);
cellIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_I_inicell), new Expression(cellROIAverage[0]));
// subsitute bwmRate
cellIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_BWM_RATE), new Expression(fixedParam.getInitialGuess()));
// undo time shift
cellIntensityExp.substituteInPlace(new Expression(ReservedVariable.TIME.getName()), new Expression(ReservedVariable.TIME.getName() + "-" + time[0]));
offRateAnalysisResults.setFitBleachWhileMonitorExpression(cellIntensityExp);
// set bleached region intensity expression ( only t left in expression)
Expression bleachIntensityExp = new Expression(FRAPOptFunctions.FUNC_RECOVERY_BLEACH_REACTION_DOMINANT);
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_I_inibleached), new Expression(bleachedAverage[0]));
// subsitute bwmRate
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_BWM_RATE), new Expression(fixedParam.getInitialGuess()));
// subsitute parameter A
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_A), new Expression(outputParamValues[0]));
// reaction off rate
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_KOFF), new Expression(outputParamValues[1]));
// undo time shift
bleachIntensityExp.substituteInPlace(new Expression(ReservedVariable.TIME.getName()), new Expression(ReservedVariable.TIME.getName() + "-" + time[0]));
offRateAnalysisResults.setOffRateFitExpression(bleachIntensityExp);
} else if (fixedParam != null && fixedParam.getName().equals(FRAPModel.MODEL_PARAMETER_NAMES[FRAPModel.INDEX_OFF_RATE])) {
// bwmRate & fitting parameter A
outputParamValues = new double[2];
double error = CurveFitting.fitRecovery_reacKoffRateOnly(time, fitData, inputParamValues, outputParamValues, fixedParam, eleWeights);
// set objective function value
offRateAnalysisResults.setObjectiveFunctionValue(error);
// set reaction off rate analysis results
offRateAnalysisResults.setBleachWhileMonitoringTau(outputParamValues[0]);
offRateAnalysisResults.setFittingParamA(outputParamValues[1]);
offRateAnalysisResults.setOffRate(fixedParam.getInitialGuess());
// set cell intensity expression ( only t left in expression)
Expression cellIntensityExp = new Expression(FRAPOptFunctions.FUNC_CELL_INTENSITY);
cellIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_I_inicell), new Expression(cellROIAverage[0]));
// subsitute bwmRate
cellIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_BWM_RATE), new Expression(outputParamValues[0]));
// undo time shift
cellIntensityExp.substituteInPlace(new Expression(ReservedVariable.TIME.getName()), new Expression(ReservedVariable.TIME.getName() + "-" + time[0]));
offRateAnalysisResults.setFitBleachWhileMonitorExpression(cellIntensityExp);
// set bleached region intensity expression ( only t left in expression)
Expression bleachIntensityExp = new Expression(FRAPOptFunctions.FUNC_RECOVERY_BLEACH_REACTION_DOMINANT);
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_I_inibleached), new Expression(bleachedAverage[0]));
// subsitute bwmRate
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_BWM_RATE), new Expression(outputParamValues[0]));
// subsitute parameter A
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_A), new Expression(outputParamValues[1]));
// reaction off rate
bleachIntensityExp.substituteInPlace(new Expression(FRAPOptFunctions.SYMBOL_KOFF), new Expression(fixedParam.getInitialGuess()));
// undo time shift
bleachIntensityExp.substituteInPlace(new Expression(ReservedVariable.TIME.getName()), new Expression(ReservedVariable.TIME.getName() + "-" + time[0]));
offRateAnalysisResults.setOffRateFitExpression(bleachIntensityExp);
} else {
throw new OptimizationException("Unknown fixed parameter:" + fixedParam.getName());
}
}
return offRateAnalysisResults;
}
use of cbit.vcell.opt.OptimizationException in project vcell by virtualcell.
the class OptimizationService method optimize.
public static OptimizationResultSet optimize(ParameterEstimationTask parameterEstimationTask) throws Exception {
// if (OperatingSystemInfo.getInstance().isMac()){
// throw new RuntimeException("parameter estimation not currently available on Mac\n\n try Windows or Linux.\n\n coming soon on Mac.");
// }
copasiOptCallbacks.reset();
updateMath(parameterEstimationTask.getSimulationContext(), NetworkGenerationRequirements.ComputeFullStandardTimeout);
StringBuffer issueText = new StringBuffer();
java.util.Vector<Issue> issueList = new java.util.Vector<Issue>();
IssueContext issueContext = new IssueContext();
parameterEstimationTask.gatherIssues(issueContext, issueList);
boolean bFailed = false;
for (int i = 0; i < issueList.size(); i++) {
Issue issue = (Issue) issueList.elementAt(i);
issueText.append(issue.getMessage() + "\n");
if (issue.getSeverity() == Issue.SEVERITY_ERROR) {
bFailed = true;
break;
}
}
if (bFailed) {
throw new OptimizationException(issueText.toString());
}
parameterEstimationTask.refreshMappings();
OptimizationResultSet optResultSet = CopasiOptimizationSolver.solveLocalPython(new ParameterEstimationTaskSimulatorIDA(), parameterEstimationTask, copasiOptCallbacks, callback);
return optResultSet;
}
use of cbit.vcell.opt.OptimizationException in project vcell by virtualcell.
the class CopasiOptimizationSolver method solveRemoteApi.
public static OptimizationResultSet solveRemoteApi(ParameterEstimationTaskSimulatorIDA parestSimulator, ParameterEstimationTask parameterEstimationTask, CopasiOptSolverCallbacks optSolverCallbacks, MathMappingCallback mathMappingCallback) throws IOException, ExpressionException, OptimizationException {
try {
OptProblem optProblem = CopasiServicePython.makeOptProblem(parameterEstimationTask);
boolean bIgnoreCertProblems = true;
boolean bIgnoreHostMismatch = true;
// e.g. vcell.serverhost=vcellapi.cam.uchc.edu:8080
String serverHost = PropertyLoader.getRequiredProperty(PropertyLoader.vcellServerHost);
String[] parts = serverHost.split(":");
String host = parts[0];
int port = Integer.parseInt(parts[1]);
VCellApiClient apiClient = new VCellApiClient(host, port, bIgnoreCertProblems, bIgnoreHostMismatch);
TSerializer serializer = new TSerializer(new TJSONProtocol.Factory());
String optProblemJson = serializer.toString(optProblem);
String optimizationId = apiClient.submitOptimization(optProblemJson);
// 20 second minute timeout
final long TIMEOUT_MS = 1000 * 20;
long startTime = System.currentTimeMillis();
OptRun optRun = null;
while ((System.currentTimeMillis() - startTime) < TIMEOUT_MS) {
if (optSolverCallbacks.getStopRequested()) {
throw new RuntimeException(STOP_REQUESTED);
}
String optRunJson = apiClient.getOptRunJson(optimizationId);
TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory());
optRun = new OptRun();
deserializer.deserialize(optRun, optRunJson.getBytes());
OptRunStatus status = optRun.status;
if (status == OptRunStatus.Complete) {
System.out.println("job " + optimizationId + ": status " + status + " " + optRun.getOptResultSet().toString());
break;
}
if (status == OptRunStatus.Failed) {
throw new RuntimeException("optimization failed, message=" + optRun.statusMessage);
}
System.out.println("job " + optimizationId + ": status " + status);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
System.out.println("done with optimization");
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 VCellAPI---------------\n" + optResultSet.toString());
return copasiOptimizationResultSet;
} catch (Exception e) {
e.printStackTrace(System.out);
if (e.getMessage() != null && e.getMessage().equals(STOP_REQUESTED)) {
throw UserCancelException.CANCEL_GENERIC;
}
throw new OptimizationException(e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
}
}
Aggregations