Search in sources :

Example 1 with OptSolverResultSet

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

the class ParameterEstimationTaskXMLPersistence method getParameterEstimationTask.

/**
 * Insert the method's description here.
 * Creation date: (5/5/2006 4:50:36 PM)
 * @return cbit.vcell.modelopt.ParameterEstimationTask
 * @param element org.jdom.Element
 * @param simContext cbit.vcell.mapping.SimulationContext
 */
public static ParameterEstimationTask getParameterEstimationTask(Element parameterEstimationTaskElement, SimulationContext simContext) throws ExpressionException, MappingException, MathException, java.beans.PropertyVetoException {
    Namespace ns = parameterEstimationTaskElement.getNamespace();
    ParameterEstimationTask parameterEstimationTask = new ParameterEstimationTask(simContext);
    String name = parameterEstimationTaskElement.getAttributeValue(NameAttribute);
    parameterEstimationTask.setName(name);
    Element annotationElement = parameterEstimationTaskElement.getChild(AnnotationTag, ns);
    if (annotationElement != null) {
        String annotationText = annotationElement.getText();
        parameterEstimationTask.setAnnotation(annotationText);
    }
    // 
    // read ParameterMappingSpecs
    // 
    Element parameterMappingSpecListElement = parameterEstimationTaskElement.getChild(ParameterMappingSpecListTag, ns);
    if (parameterMappingSpecListElement != null) {
        List<Element> parameterMappingSpecElementList = parameterMappingSpecListElement.getChildren(ParameterMappingSpecTag, ns);
        for (Element parameterMappingSpecElement : parameterMappingSpecElementList) {
            String parameterName = parameterMappingSpecElement.getAttributeValue(ParameterReferenceAttribute);
            SymbolTableEntry ste = getSymbolTableEntry(simContext, parameterName);
            if (ste instanceof Parameter) {
                Parameter parameter = (Parameter) ste;
                ParameterMappingSpec parameterMappingSpec = parameterEstimationTask.getModelOptimizationSpec().getParameterMappingSpec(parameter);
                if (parameterMappingSpec != null) {
                    String lowLimitString = parameterMappingSpecElement.getAttributeValue(LowLimitAttribute);
                    if (lowLimitString != null) {
                        parameterMappingSpec.setLow(parseDouble(lowLimitString));
                    }
                    String highLimitString = parameterMappingSpecElement.getAttributeValue(HighLimitAttribute);
                    if (highLimitString != null) {
                        parameterMappingSpec.setHigh(parseDouble(highLimitString));
                    }
                    String currentValueString = parameterMappingSpecElement.getAttributeValue(CurrentValueAttribute);
                    if (currentValueString != null) {
                        parameterMappingSpec.setCurrent(Double.parseDouble(currentValueString));
                    }
                    String selectedString = parameterMappingSpecElement.getAttributeValue(SelectedAttribute);
                    if (selectedString != null) {
                        parameterMappingSpec.setSelected(Boolean.valueOf(selectedString).booleanValue());
                    }
                }
            } else {
                System.out.println("couldn't read parameterMappingSpec '" + parameterName + "', ste=" + ste);
            }
        }
    }
    // 
    // read ReferenceData
    // 
    Element referenceDataElement = parameterEstimationTaskElement.getChild(ReferenceDataTag, ns);
    if (referenceDataElement != null) {
        String numRowsText = referenceDataElement.getAttributeValue(NumRowsAttribute);
        String numColsText = referenceDataElement.getAttributeValue(NumColumnsAttribute);
        // int numRows = Integer.parseInt(numRowsText);
        int numCols = Integer.parseInt(numColsText);
        // 
        // read columns
        // 
        String[] columnNames = new String[numCols];
        double[] columnWeights = new double[numCols];
        int columnCounter = 0;
        Element dataColumnListElement = referenceDataElement.getChild(DataColumnListTag, ns);
        List<Element> dataColumnList = dataColumnListElement.getChildren(DataColumnTag, ns);
        for (Element dataColumnElement : dataColumnList) {
            columnNames[columnCounter] = dataColumnElement.getAttributeValue(NameAttribute);
            columnWeights[columnCounter] = Double.parseDouble(dataColumnElement.getAttributeValue(WeightAttribute));
            columnCounter++;
        }
        // 
        // read rows
        // 
        Vector<double[]> rowDataVector = new Vector<double[]>();
        Element dataRowListElement = referenceDataElement.getChild(DataRowListTag, ns);
        List<Element> dataRowList = dataRowListElement.getChildren(DataRowTag, ns);
        for (Element dataRowElement : dataRowList) {
            String rowText = dataRowElement.getText();
            CommentStringTokenizer tokens = new CommentStringTokenizer(rowText);
            double[] rowData = new double[numCols];
            for (int j = 0; j < numCols; j++) {
                if (tokens.hasMoreTokens()) {
                    String token = tokens.nextToken();
                    rowData[j] = Double.parseDouble(token);
                } else {
                    throw new RuntimeException("failed to read row data for ReferenceData");
                }
            }
            rowDataVector.add(rowData);
        }
        ReferenceData referenceData = new SimpleReferenceData(columnNames, columnWeights, rowDataVector);
        parameterEstimationTask.getModelOptimizationSpec().setReferenceData(referenceData);
    }
    // 
    // read ReferenceDataMappingSpecs
    // 
    Element referenceDataMappingSpecListElement = parameterEstimationTaskElement.getChild(ReferenceDataMappingSpecListTag, ns);
    if (referenceDataMappingSpecListElement != null) {
        List<Element> referenceDataMappingSpecList = referenceDataMappingSpecListElement.getChildren(ReferenceDataMappingSpecTag, ns);
        for (Element referenceDataMappingSpecElement : referenceDataMappingSpecList) {
            String referenceDataColumnName = referenceDataMappingSpecElement.getAttributeValue(ReferenceDataColumnNameAttribute);
            String referenceDataModelSymbolName = referenceDataMappingSpecElement.getAttributeValue(ReferenceDataModelSymbolAttribute);
            ReferenceDataMappingSpec referenceDataMappingSpec = parameterEstimationTask.getModelOptimizationSpec().getReferenceDataMappingSpec(referenceDataColumnName);
            SymbolTableEntry modelSymbolTableEntry = null;
            if (referenceDataModelSymbolName != null) {
                modelSymbolTableEntry = getSymbolTableEntry(simContext, referenceDataModelSymbolName);
                if (referenceDataMappingSpec != null && modelSymbolTableEntry != null) {
                    referenceDataMappingSpec.setModelObject(modelSymbolTableEntry);
                }
            }
        }
    }
    // 
    // read OptimizationSolverSpec
    // 
    Element optimizationSolverSpecElement = parameterEstimationTaskElement.getChild(OptimizationSolverSpecTag, ns);
    if (optimizationSolverSpecElement != null) {
        OptimizationSolverSpec optSolverSpec = null;
        String optimizationSolverTypeName = optimizationSolverSpecElement.getAttributeValue(OptimizationSolverTypeAttribute);
        // getting parameters
        Element optimizationSolverParameterList = optimizationSolverSpecElement.getChild(OptimizationListOfParametersTag, ns);
        if (optimizationSolverParameterList != null) {
            List<Element> listOfSolverParams = optimizationSolverParameterList.getChildren(OptimizationParameterTag, ns);
            CopasiOptimizationMethod copasiOptMethod = null;
            if (listOfSolverParams != null && listOfSolverParams.size() > 0) {
                List<CopasiOptimizationParameter> copasiSolverParams = new ArrayList<CopasiOptimizationParameter>();
                for (Element solverParam : listOfSolverParams) {
                    String paramName = solverParam.getAttributeValue(OptimizationParameterNameAttribute);
                    double paramValue = Double.parseDouble(solverParam.getAttributeValue(OptimizationParameterValueAttribute));
                    CopasiOptimizationParameter copasiParam = new CopasiOptimizationParameter(getCopasiOptimizationParameterTypeByName(paramName), paramValue);
                    copasiSolverParams.add(copasiParam);
                }
                copasiOptMethod = new CopasiOptimizationMethod(getCopasiOptimizationMethodTypeByName(optimizationSolverTypeName), copasiSolverParams.toArray(new CopasiOptimizationParameter[copasiSolverParams.size()]));
            } else // no parameters
            {
                copasiOptMethod = new CopasiOptimizationMethod(getCopasiOptimizationMethodTypeByName(optimizationSolverTypeName), new CopasiOptimizationParameter[0]);
            }
            optSolverSpec = new OptimizationSolverSpec(copasiOptMethod);
            // add number of runs attribute
            String numOfRunsStr = optimizationSolverSpecElement.getAttributeValue(OptimizationSolverNumOfRunsAttribute);
            if (numOfRunsStr != null) {
                int numOfRuns = Integer.parseInt(numOfRunsStr);
                optSolverSpec.setNumOfRuns(numOfRuns);
            }
        }
        parameterEstimationTask.setOptimizationSolverSpec(optSolverSpec);
    }
    if (// optimization solver spec is null create a default copasi evolutionary programming
    optimizationSolverSpecElement == null || parameterEstimationTask.getOptimizationSolverSpec() == null) {
        OptimizationSolverSpec optSolverSpec = new OptimizationSolverSpec(new CopasiOptimizationMethod(CopasiOptimizationMethodType.EvolutionaryProgram));
        parameterEstimationTask.setOptimizationSolverSpec(optSolverSpec);
    }
    // read optimization solver result set
    Element optimizationResultSetElement = parameterEstimationTaskElement.getChild(OptXmlTags.OptimizationResultSet_Tag, ns);
    if (optimizationResultSetElement != null) {
        OptimizationResultSet optResultSet = null;
        // read optsolverResultSet
        if (optimizationResultSetElement.getChild(OptXmlTags.bestOptRunResultSet_Tag, ns) != null) {
            Element optSolverResultSetElement = optimizationResultSetElement.getChild(OptXmlTags.bestOptRunResultSet_Tag, ns);
            OptSolverResultSet optSolverResultSet = null;
            // get best parameters, best func value, number of evaluations and construct an optRunResultSet
            Element paramListElement = optSolverResultSetElement.getChild(OptimizationListOfParametersTag, ns);
            OptRunResultSet optRunResultSet = null;
            List<String> paramNames = new ArrayList<String>();
            List<Double> paramValues = new ArrayList<Double>();
            if (paramListElement != null && !paramListElement.getChildren().isEmpty()) {
                List<Element> paramElements = paramListElement.getChildren(OptimizationParameterTag, ns);
                if (paramElements != null) {
                    for (Element paramElement : paramElements) {
                        String paramName = paramElement.getAttributeValue(OptimizationParameterNameAttribute);
                        double paramValue = Double.parseDouble(paramElement.getAttributeValue(OptimizationParameterValueAttribute));
                        paramNames.add(paramName);
                        paramValues.add(paramValue);
                    }
                }
            }
            Element bestFuncValueElement = optSolverResultSetElement.getChild(OptXmlTags.ObjectiveFunction_Tag, ns);
            double bestFuncValue = Double.parseDouble(bestFuncValueElement.getAttributeValue(OptimizationParameterValueAttribute));
            Element numEvaluationsElement = optSolverResultSetElement.getChild(OptXmlTags.OptSolverResultSetFunctionEvaluations_Tag, ns);
            long numEvaluations = Long.parseLong(numEvaluationsElement.getAttributeValue(OptimizationParameterValueAttribute));
            // change List<Double> to double[]
            double[] values = new double[paramValues.size()];
            int index = 0;
            for (Double value : paramValues) {
                values[index++] = value;
            }
            optRunResultSet = new OptRunResultSet(values, bestFuncValue, numEvaluations, null);
            // create optSolverResultSet
            optSolverResultSet = new OptSolverResultSet(paramNames.toArray(new String[paramNames.size()]), optRunResultSet);
            // create optimization result set
            optResultSet = new OptimizationResultSet(optSolverResultSet, null);
        }
        parameterEstimationTask.setOptimizationResultSet(optResultSet);
    }
    return parameterEstimationTask;
}
Also used : OptimizationResultSet(cbit.vcell.opt.OptimizationResultSet) Element(org.jdom.Element) ArrayList(java.util.ArrayList) OptSolverResultSet(cbit.vcell.opt.OptSolverResultSet) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) CopasiOptimizationMethod(cbit.vcell.opt.CopasiOptimizationMethod) CopasiOptimizationParameter(cbit.vcell.opt.CopasiOptimizationParameter) OptimizationSolverSpec(cbit.vcell.opt.OptimizationSolverSpec) Vector(java.util.Vector) Namespace(org.jdom.Namespace) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) ReferenceData(cbit.vcell.opt.ReferenceData) Parameter(cbit.vcell.model.Parameter) CopasiOptimizationParameter(cbit.vcell.opt.CopasiOptimizationParameter) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer) OptRunResultSet(cbit.vcell.opt.OptSolverResultSet.OptRunResultSet)

Example 2 with OptSolverResultSet

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

the class ParameterEstimationTaskXMLPersistence method getXML.

/**
 * Insert the method's description here.
 * Creation date: (5/5/2006 9:02:39 AM)
 * @return java.lang.String
 * @param parameterEstimationTask cbit.vcell.modelopt.ParameterEstimationTask
 */
public static Element getXML(ParameterEstimationTask parameterEstimationTask) {
    Element parameterEstimationTaskElement = new Element(XMLTags.ParameterEstimationTaskTag);
    // name attribute
    parameterEstimationTaskElement.setAttribute(NameAttribute, mangle(parameterEstimationTask.getName()));
    // annotation content (optional)
    String annotation = parameterEstimationTask.getAnnotation();
    if (annotation != null && annotation.length() > 0) {
        org.jdom.Element annotationElement = new org.jdom.Element(AnnotationTag);
        annotationElement.setText(mangle(annotation));
        parameterEstimationTaskElement.addContent(annotationElement);
    }
    // 
    // add ParameterMappingSpecs
    // 
    ParameterMappingSpec[] parameterMappingSpecs = parameterEstimationTask.getModelOptimizationSpec().getParameterMappingSpecs();
    if (parameterMappingSpecs != null && parameterMappingSpecs.length > 0) {
        Element parameterMappingSpecListElement = new Element(ParameterMappingSpecListTag);
        for (int i = 0; i < parameterMappingSpecs.length; i++) {
            Element parameterMappingSpecElement = new Element(ParameterMappingSpecTag);
            Parameter parameter = parameterMappingSpecs[i].getModelParameter();
            parameterMappingSpecElement.setAttribute(ParameterReferenceAttribute, parameter.getNameScope().getAbsoluteScopePrefix() + parameter.getName());
            parameterMappingSpecElement.setAttribute(LowLimitAttribute, Double.toString(parameterMappingSpecs[i].getLow()));
            parameterMappingSpecElement.setAttribute(HighLimitAttribute, Double.toString(parameterMappingSpecs[i].getHigh()));
            parameterMappingSpecElement.setAttribute(CurrentValueAttribute, Double.toString(parameterMappingSpecs[i].getCurrent()));
            parameterMappingSpecElement.setAttribute(SelectedAttribute, String.valueOf(parameterMappingSpecs[i].isSelected()));
            parameterMappingSpecListElement.addContent(parameterMappingSpecElement);
        }
        parameterEstimationTaskElement.addContent(parameterMappingSpecListElement);
    }
    // 
    // add ReferenceData
    // 
    ReferenceData referenceData = parameterEstimationTask.getModelOptimizationSpec().getReferenceData();
    if (referenceData != null && referenceData.getNumDataColumns() > 0) {
        Element referenceDataElement = new Element(ReferenceDataTag);
        referenceDataElement.setAttribute(NumRowsAttribute, Integer.toString(referenceData.getNumDataRows()));
        referenceDataElement.setAttribute(NumColumnsAttribute, Integer.toString(referenceData.getNumDataColumns()));
        Element dataColumnListElement = new Element(DataColumnListTag);
        for (int i = 0; i < referenceData.getColumnNames().length; i++) {
            Element dataColumnElement = new Element(DataColumnTag);
            dataColumnElement.setAttribute(NameAttribute, referenceData.getColumnNames()[i]);
            dataColumnElement.setAttribute(WeightAttribute, Double.toString(referenceData.getColumnWeights()[i]));
            dataColumnListElement.addContent(dataColumnElement);
        }
        referenceDataElement.addContent(dataColumnListElement);
        Element dataRowListElement = new Element(DataRowListTag);
        for (int i = 0; i < referenceData.getNumDataRows(); i++) {
            Element dataRowElement = new Element(DataRowTag);
            String rowText = "";
            for (int j = 0; j < referenceData.getNumDataColumns(); j++) {
                if (j > 0) {
                    rowText += " ";
                }
                rowText += referenceData.getDataByRow(i)[j];
            }
            dataRowElement.addContent(rowText);
            dataRowListElement.addContent(dataRowElement);
        }
        referenceDataElement.addContent(dataRowListElement);
        parameterEstimationTaskElement.addContent(referenceDataElement);
    }
    // 
    // add ReferenceDataMappingSpecs
    // 
    ReferenceDataMappingSpec[] referenceDataMappingSpecs = parameterEstimationTask.getModelOptimizationSpec().getReferenceDataMappingSpecs();
    if (referenceDataMappingSpecs != null && referenceDataMappingSpecs.length > 0) {
        Element referenceDataMappingSpecListElement = new Element(ReferenceDataMappingSpecListTag);
        for (int i = 0; i < referenceDataMappingSpecs.length; i++) {
            SymbolTableEntry modelSymbol = referenceDataMappingSpecs[i].getModelObject();
            Element referenceDataMappingSpecElement = new Element(ReferenceDataMappingSpecTag);
            referenceDataMappingSpecElement.setAttribute(ReferenceDataColumnNameAttribute, referenceDataMappingSpecs[i].getReferenceDataColumnName());
            if (modelSymbol != null) {
                referenceDataMappingSpecElement.setAttribute(ReferenceDataModelSymbolAttribute, modelSymbol.getName());
            }
            referenceDataMappingSpecListElement.addContent(referenceDataMappingSpecElement);
        }
        parameterEstimationTaskElement.addContent(referenceDataMappingSpecListElement);
    }
    // 
    if (parameterEstimationTask.getOptimizationSolverSpec() != null) {
        OptimizationSolverSpec solverSpec = parameterEstimationTask.getOptimizationSolverSpec();
        if (solverSpec.getCopasiOptimizationMethod() != null) {
            CopasiOptimizationMethod copasiOptMethod = solverSpec.getCopasiOptimizationMethod();
            Element optimizationSolverSpecElement = new Element(OptimizationSolverSpecTag);
            optimizationSolverSpecElement.setAttribute(OptimizationSolverTypeAttribute, copasiOptMethod.getType().getName());
            optimizationSolverSpecElement.setAttribute(OptimizationSolverNumOfRunsAttribute, solverSpec.getNumOfRuns() + "");
            // adding solve parameter list to optimization solver spec
            CopasiOptimizationParameter[] solverParams = copasiOptMethod.getParameters();
            if (solverParams != null && solverParams.length > 0) {
                Element listOfSolverParams = new Element(OptimizationListOfParametersTag);
                for (CopasiOptimizationParameter solverParam : solverParams) {
                    Element optSolverParam = new Element(OptimizationParameterTag);
                    optSolverParam.setAttribute(OptimizationParameterNameAttribute, solverParam.getType().getDisplayName());
                    optSolverParam.setAttribute(OptimizationParameterValueAttribute, solverParam.getValue() + "");
                    listOfSolverParams.addContent(optSolverParam);
                }
                optimizationSolverSpecElement.addContent(listOfSolverParams);
            }
            parameterEstimationTaskElement.addContent(optimizationSolverSpecElement);
        }
    }
    // add optimization solver result set
    if (parameterEstimationTask.getOptimizationResultSet() != null) {
        OptimizationResultSet optResultSet = parameterEstimationTask.getOptimizationResultSet();
        Element optimizationResultSetElement = new Element(OptXmlTags.OptimizationResultSet_Tag);
        if (optResultSet.getOptSolverResultSet() != null) {
            OptSolverResultSet optSolverResultSet = optResultSet.getOptSolverResultSet();
            Element optSolverResultSetElement = new Element(OptXmlTags.bestOptRunResultSet_Tag);
            // write best parameters
            String[] paramNames = optSolverResultSet.getParameterNames();
            double[] bestValues = optSolverResultSet.getBestEstimates();
            if (paramNames != null && paramNames.length > 0 && bestValues != null && bestValues.length > 0 && paramNames.length == bestValues.length) {
                Element listOfBestParams = new Element(OptimizationListOfParametersTag);
                for (int i = 0; i < paramNames.length; i++) {
                    Element resultParam = new Element(OptimizationParameterTag);
                    resultParam.setAttribute(OptimizationParameterNameAttribute, paramNames[i]);
                    resultParam.setAttribute(OptimizationParameterValueAttribute, bestValues[i] + "");
                    listOfBestParams.addContent(resultParam);
                }
                optSolverResultSetElement.addContent(listOfBestParams);
            }
            // write objective function value
            double objectiveFuncValue = optSolverResultSet.getLeastObjectiveFunctionValue();
            Element objFuncElement = new Element(OptXmlTags.ObjectiveFunction_Tag);
            objFuncElement.setAttribute(OptimizationParameterValueAttribute, objectiveFuncValue + "");
            optSolverResultSetElement.addContent(objFuncElement);
            // write num function evaluations
            long numFuncEvaluations = optSolverResultSet.getObjFunctionEvaluations();
            Element numFuncEvaluationsElement = new Element(OptXmlTags.OptSolverResultSetFunctionEvaluations_Tag);
            numFuncEvaluationsElement.setAttribute(OptimizationParameterValueAttribute, numFuncEvaluations + "");
            optSolverResultSetElement.addContent(numFuncEvaluationsElement);
            optimizationResultSetElement.addContent(optSolverResultSetElement);
        }
        parameterEstimationTaskElement.addContent(optimizationResultSetElement);
    }
    return parameterEstimationTaskElement;
}
Also used : OptimizationResultSet(cbit.vcell.opt.OptimizationResultSet) Element(org.jdom.Element) OptSolverResultSet(cbit.vcell.opt.OptSolverResultSet) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) ReferenceData(cbit.vcell.opt.ReferenceData) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) CopasiOptimizationMethod(cbit.vcell.opt.CopasiOptimizationMethod) CopasiOptimizationParameter(cbit.vcell.opt.CopasiOptimizationParameter) Parameter(cbit.vcell.model.Parameter) CopasiOptimizationParameter(cbit.vcell.opt.CopasiOptimizationParameter) OptimizationSolverSpec(cbit.vcell.opt.OptimizationSolverSpec) Element(org.jdom.Element)

Example 3 with OptSolverResultSet

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

the class FRAPOptimizationUtils method estimate.

// estimate best parameters and return the least error
public static double estimate(FRAPOptData argOptData, Parameter[] inParams, String[] outParaNames, double[] outParaVals, boolean[] eoi) throws Exception {
    /*PowellSolver  solver = new PowellSolver();
		LookupTableObjectiveFunction func = new LookupTableObjectiveFunction(argOptData);
		
		//best point found. we have only one dimension here.
		double[] p = new double[1];
		p[0] = iniDiffGuess;
		//current direction set
		double[][] xi = new double[1][1];
		for (int i=0;i<1;i++)
		{
		   for (int j=0;j<1;j++)
		   {
		       xi[i][j]=(i == j ? 1.0 : 0.0);
		   }
		}
		//run powell with initial guess, initial direction set and objective function
		double minError = solver.powell(1, p, xi, FTOL, func);
		parameters[FRAPOptData.idxOptDiffRate] = p[0];
		parameters[FRAPOptData.idxMinError] = minError;*/
    // long startTime =System.currentTimeMillis();
    // create optimization solver
    PowellOptimizationSolver optSolver = new PowellOptimizationSolver();
    // create optimization spec
    OptimizationSpec optSpec = new OptimizationSpec();
    // add opt function
    DefaultScalarFunction scalarFunc = new LookupTableObjectiveFunction(argOptData, eoi);
    optSpec.setObjectiveFunction(new ImplicitObjectiveFunction(scalarFunc));
    // create solver spec
    OptimizationSolverSpec optSolverSpec = new OptimizationSolverSpec(OptimizationSolverSpec.SOLVERTYPE_POWELL, FRAPOptimizationUtils.FTOL);
    // create solver call back
    OptSolverCallbacks optSolverCallbacks = new DefaultOptSolverCallbacks();
    // create optimization result set
    OptimizationResultSet optResultSet = null;
    for (int i = 0; i < inParams.length; i++) {
        // add parameters
        optSpec.addParameter(inParams[i]);
    }
    optResultSet = optSolver.solve(optSpec, optSolverSpec, optSolverCallbacks);
    OptSolverResultSet optSolverResultSet = optResultSet.getOptSolverResultSet();
    // if the parameters are 5, we have to go over again to see if we get the best answer.
    if (// 5 parameters
    inParams.length == 5) {
        OptimizationSpec optSpec2 = new OptimizationSpec();
        optSpec2.setObjectiveFunction(new ImplicitObjectiveFunction(scalarFunc));
        Parameter[] inParamsFromResult = generateInParamSet(inParams, optSolverResultSet.getBestEstimates());
        for (int i = 0; i < inParamsFromResult.length; i++) {
            // add parameters
            optSpec2.addParameter(inParamsFromResult[i]);
        }
        OptimizationResultSet tempOptResultSet = optSolver.solve(optSpec2, optSolverSpec, optSolverCallbacks);
        OptSolverResultSet tempOptSolverResultSet = tempOptResultSet.getOptSolverResultSet();
        if (optSolverResultSet.getLeastObjectiveFunctionValue() > tempOptSolverResultSet.getLeastObjectiveFunctionValue()) {
            optSolverResultSet = tempOptSolverResultSet;
        }
    }
    // System.out.println("obj function value:"+optResultSet.getObjectiveFunctionValue());
    // System.out.println("");
    // copy results to output parameters
    String[] names = optSolverResultSet.getParameterNames();
    double[] values = optSolverResultSet.getBestEstimates();
    for (int i = 0; i < names.length; i++) {
        outParaNames[i] = names[i];
        outParaVals[i] = values[i];
    }
    // System.out.println("total: " + ( endTime - startTime) );
    return optSolverResultSet.getLeastObjectiveFunctionValue();
}
Also used : PowellOptimizationSolver(cbit.vcell.opt.solvers.PowellOptimizationSolver) DefaultOptSolverCallbacks(org.vcell.optimization.DefaultOptSolverCallbacks) OptSolverCallbacks(org.vcell.optimization.OptSolverCallbacks) OptimizationResultSet(cbit.vcell.opt.OptimizationResultSet) OptSolverResultSet(cbit.vcell.opt.OptSolverResultSet) DefaultScalarFunction(cbit.function.DefaultScalarFunction) DefaultOptSolverCallbacks(org.vcell.optimization.DefaultOptSolverCallbacks) ImplicitObjectiveFunction(cbit.vcell.opt.ImplicitObjectiveFunction) Parameter(cbit.vcell.opt.Parameter) OptimizationSolverSpec(cbit.vcell.opt.OptimizationSolverSpec) OptimizationSpec(cbit.vcell.opt.OptimizationSpec)

Example 4 with OptSolverResultSet

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

the class CurveFitting method fitRecovery_reacKoffRateOnly.

/*
	 * @para: time, time points since the first post bleach.
	 * @para: normalized_data, first dimension index 0:average intensities under cell region, first dimension index 1: average intensities under bleached region
	 * @para: inputparam, index 0:cellROIAvg at time 0(first post bleach). index 1:bleachedROIAvg at time 0(first post bleach).
	 * @para: outputParam, results for 2 or 3 parameters, depending on if there is any fixed parameter. 
	 */
public static double fitRecovery_reacKoffRateOnly(double[] time, double[][] normalized_data, double[] inputparam, double[] outputParam, Parameter fixedParameter, Weights weights) throws ExpressionException, OptimizationException, IOException {
    if (normalized_data != null && normalized_data.length > 0) {
        for (int i = 0; i < normalized_data.length; i++) {
            if (normalized_data[i] != null && time.length != normalized_data[i].length) {
                throw new RuntimeException("Fluorecence and time arrays must be the same length");
            }
        }
    }
    // normaliztion for time by subtracting the starting time: time[0]
    double[] normalized_time = new double[time.length];
    for (int i = 0; i < time.length; i++) {
        normalized_time[i] = time[i] - time[0];
    }
    // initiate variables
    OptimizationResultSet optResultSet = null;
    Expression bwmRateExp = new Expression(FRAPOptFunctions.FUNC_CELL_INTENSITY);
    Expression koffRateExp = new Expression(FRAPOptFunctions.FUNC_RECOVERY_BLEACH_REACTION_DOMINANT);
    // get parameters to be estimated(use all of the 3 if there is no fixed parameter. Or 2 out of the 3 if there is a fixed parameter)
    Parameter bwmParam = new Parameter(FRAPOptFunctions.SYMBOL_BWM_RATE, FRAPModel.REF_BLEACH_WHILE_MONITOR_PARAM.getLowerBound(), FRAPModel.REF_BLEACH_WHILE_MONITOR_PARAM.getUpperBound(), FRAPModel.REF_BLEACH_WHILE_MONITOR_PARAM.getScale(), FRAPModel.REF_BLEACH_WHILE_MONITOR_PARAM.getInitialGuess());
    Parameter koffParam = new Parameter(FRAPOptFunctions.SYMBOL_KOFF, FRAPModel.REF_REACTION_OFF_RATE.getLowerBound(), FRAPModel.REF_REACTION_OFF_RATE.getUpperBound(), FRAPModel.REF_REACTION_OFF_RATE.getScale(), FRAPModel.REF_REACTION_OFF_RATE.getInitialGuess());
    Parameter fittingParamA = new Parameter(FRAPOptFunctions.SYMBOL_A, /*binding site concentration is reused to store fitting parameter A, but the name can not be reused*/
    FRAPModel.REF_BS_CONCENTRATION_OR_A.getLowerBound(), FRAPModel.REF_BS_CONCENTRATION_OR_A.getUpperBound(), FRAPModel.REF_BS_CONCENTRATION_OR_A.getScale(), FRAPModel.REF_BS_CONCENTRATION_OR_A.getInitialGuess());
    // get column names for reference data to be constructed
    String[] columnNames = new String[] { ReservedVariable.TIME.getName(), "cellIntensityAvg", "bleachIntensityAvg" };
    if (fixedParameter == null) {
        // get fitting parameter array
        Parameter[] parameters = new Parameter[] { bwmParam, fittingParamA, koffParam };
        // get expression pairs
        bwmRateExp = bwmRateExp.getSubstitutedExpression(new Expression(FRAPOptFunctions.SYMBOL_I_inicell), new Expression(inputparam[0]));
        bindExpressionToParametersAndTime(bwmRateExp, parameters);
        ExplicitFitObjectiveFunction.ExpressionDataPair bwmRateExpDataPair = new ExplicitFitObjectiveFunction.ExpressionDataPair(bwmRateExp, 1);
        koffRateExp = koffRateExp.getSubstitutedExpression(new Expression(FRAPOptFunctions.SYMBOL_I_inibleached), new Expression(inputparam[1]));
        bindExpressionToParametersAndTime(koffRateExp, parameters);
        ExplicitFitObjectiveFunction.ExpressionDataPair koffRateExpDataPair = new ExplicitFitObjectiveFunction.ExpressionDataPair(koffRateExp, 2);
        ExplicitFitObjectiveFunction.ExpressionDataPair[] expDataPairs = new ExplicitFitObjectiveFunction.ExpressionDataPair[] { bwmRateExpDataPair, koffRateExpDataPair };
        // solve
        optResultSet = solve(expDataPairs, parameters, normalized_time, normalized_data, columnNames, weights);
    } else {
        if (fixedParameter != null && fixedParameter.getName().equals(FRAPModel.MODEL_PARAMETER_NAMES[FRAPModel.INDEX_BLEACH_MONITOR_RATE])) {
            // get fitting parameter array
            Parameter[] parameters = new Parameter[] { fittingParamA, koffParam };
            // get expression pairs
            bwmRateExp = bwmRateExp.getSubstitutedExpression(new Expression(FRAPOptFunctions.SYMBOL_I_inicell), new Expression(inputparam[0]));
            bwmRateExp = bwmRateExp.getSubstitutedExpression(new Expression(FRAPOptFunctions.SYMBOL_BWM_RATE), new Expression(fixedParameter.getInitialGuess()));
            bindExpressionToParametersAndTime(bwmRateExp, parameters);
            ExplicitFitObjectiveFunction.ExpressionDataPair bwmRateExpDataPair = new ExplicitFitObjectiveFunction.ExpressionDataPair(bwmRateExp, 1);
            koffRateExp = koffRateExp.getSubstitutedExpression(new Expression(FRAPOptFunctions.SYMBOL_I_inibleached), new Expression(inputparam[1]));
            koffRateExp = koffRateExp.getSubstitutedExpression(new Expression(FRAPOptFunctions.SYMBOL_BWM_RATE), new Expression(fixedParameter.getInitialGuess()));
            bindExpressionToParametersAndTime(koffRateExp, parameters);
            ExplicitFitObjectiveFunction.ExpressionDataPair koffRateExpDataPair = new ExplicitFitObjectiveFunction.ExpressionDataPair(koffRateExp, 2);
            ExplicitFitObjectiveFunction.ExpressionDataPair[] expDataPairs = new ExplicitFitObjectiveFunction.ExpressionDataPair[] { bwmRateExpDataPair, koffRateExpDataPair };
            // solve
            optResultSet = solve(expDataPairs, parameters, normalized_time, normalized_data, columnNames, weights);
        } else if (fixedParameter != null && fixedParameter.getName().equals(FRAPModel.MODEL_PARAMETER_NAMES[FRAPModel.INDEX_OFF_RATE])) {
            // get fitting parameter array
            Parameter[] parameters = new Parameter[] { bwmParam, fittingParamA };
            // get expression pairs
            bwmRateExp = bwmRateExp.getSubstitutedExpression(new Expression(FRAPOptFunctions.SYMBOL_I_inicell), new Expression(inputparam[0]));
            bindExpressionToParametersAndTime(bwmRateExp, parameters);
            ExplicitFitObjectiveFunction.ExpressionDataPair bwmRateExpDataPair = new ExplicitFitObjectiveFunction.ExpressionDataPair(bwmRateExp, 1);
            koffRateExp = koffRateExp.getSubstitutedExpression(new Expression(FRAPOptFunctions.SYMBOL_I_inibleached), new Expression(inputparam[1]));
            koffRateExp = koffRateExp.getSubstitutedExpression(new Expression(FRAPOptFunctions.SYMBOL_KOFF), new Expression(fixedParameter.getInitialGuess()));
            bindExpressionToParametersAndTime(koffRateExp, parameters);
            ExplicitFitObjectiveFunction.ExpressionDataPair koffRateExpDataPair = new ExplicitFitObjectiveFunction.ExpressionDataPair(koffRateExp, 2);
            ExplicitFitObjectiveFunction.ExpressionDataPair[] expDataPairs = new ExplicitFitObjectiveFunction.ExpressionDataPair[] { bwmRateExpDataPair, koffRateExpDataPair };
            // solve
            optResultSet = solve(expDataPairs, parameters, normalized_time, normalized_data, columnNames, weights);
        }
    }
    // get output parameter values
    OptSolverResultSet optSolverResultSet = optResultSet.getOptSolverResultSet();
    String[] paramNames = optSolverResultSet.getParameterNames();
    double[] paramValues = optSolverResultSet.getBestEstimates();
    // copy into "output" buffer from parameter values.
    for (int i = 0; i < paramValues.length; i++) {
        outputParam[i] = paramValues[i];
    }
    // for debug purpose
    for (int i = 0; i < paramNames.length; i++) {
        System.out.println("finally:   " + paramNames[i] + " = " + paramValues[i]);
    }
    // investigate the return information
    processReturnCode(OptimizationSolverSpec.SOLVERTYPE_POWELL, optSolverResultSet);
    // return objective function value
    return optSolverResultSet.getLeastObjectiveFunctionValue();
}
Also used : OptimizationResultSet(cbit.vcell.opt.OptimizationResultSet) ExplicitFitObjectiveFunction(cbit.vcell.opt.ExplicitFitObjectiveFunction) OptSolverResultSet(cbit.vcell.opt.OptSolverResultSet) Expression(cbit.vcell.parser.Expression) Parameter(cbit.vcell.opt.Parameter)

Example 5 with OptSolverResultSet

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

the class CurveFitting method solveSpatial.

public static OptimizationResultSet solveSpatial(Simulation sim, Parameter[] parameters, SpatialReferenceData refData, File dataDir, FieldDataIdentifierSpec[] fieldDataIDSs) throws ExpressionException, OptimizationException, IOException {
    // choose optimization solver, currently we have Powell
    PowellOptimizationSolver optService = new PowellOptimizationSolver();
    OptimizationSpec optSpec = new OptimizationSpec();
    // send to optimization service
    optSpec.setObjectiveFunction(new PdeObjectiveFunction(sim.getMathDescription(), refData, dataDir, fieldDataIDSs));
    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] + ";\tLB = " + parameters[i].getLowerBound() + ";\tUB = " + parameters[i].getUpperBound());
    }
    // get the initial guess to send it to the f() function. ....
    for (int i = 0; i < parameters.length; i++) {
        optSpec.addParameter(parameters[i]);
    }
    // Parameters in OptimizationSolverSpec are solver type and objective function change tolerance.
    OptimizationSolverSpec optSolverSpec = new OptimizationSolverSpec(OptimizationSolverSpec.SOLVERTYPE_POWELL, 0.000001);
    OptSolverCallbacks optSolverCallbacks = new DefaultOptSolverCallbacks();
    OptimizationResultSet optResultSet = null;
    optResultSet = optService.solve(optSpec, optSolverSpec, optSolverCallbacks);
    OptSolverResultSet optSolverResultSet = optResultSet.getOptSolverResultSet();
    String[] paramNames = optSolverResultSet.getParameterNames();
    double[] paramValues = optSolverResultSet.getBestEstimates();
    for (int i = 0; i < paramNames.length; i++) {
        System.out.println("finally:   " + paramNames[i] + " = " + paramValues[i]);
    }
    return optResultSet;
}
Also used : PowellOptimizationSolver(cbit.vcell.opt.solvers.PowellOptimizationSolver) DefaultOptSolverCallbacks(org.vcell.optimization.DefaultOptSolverCallbacks) OptSolverCallbacks(org.vcell.optimization.OptSolverCallbacks) OptimizationResultSet(cbit.vcell.opt.OptimizationResultSet) PdeObjectiveFunction(cbit.vcell.opt.PdeObjectiveFunction) DefaultOptSolverCallbacks(org.vcell.optimization.DefaultOptSolverCallbacks) OptimizationSolverSpec(cbit.vcell.opt.OptimizationSolverSpec) OptimizationSpec(cbit.vcell.opt.OptimizationSpec) OptSolverResultSet(cbit.vcell.opt.OptSolverResultSet)

Aggregations

OptSolverResultSet (cbit.vcell.opt.OptSolverResultSet)14 OptimizationResultSet (cbit.vcell.opt.OptimizationResultSet)13 OptRunResultSet (cbit.vcell.opt.OptSolverResultSet.OptRunResultSet)6 OptimizationSolverSpec (cbit.vcell.opt.OptimizationSolverSpec)6 Parameter (cbit.vcell.opt.Parameter)5 OptimizationException (cbit.vcell.opt.OptimizationException)4 OptimizationSpec (cbit.vcell.opt.OptimizationSpec)4 OptimizationStatus (cbit.vcell.opt.OptimizationStatus)4 PowellOptimizationSolver (cbit.vcell.opt.solvers.PowellOptimizationSolver)4 DefaultOptSolverCallbacks (org.vcell.optimization.DefaultOptSolverCallbacks)4 OptSolverCallbacks (org.vcell.optimization.OptSolverCallbacks)4 RowColumnResultSet (cbit.vcell.math.RowColumnResultSet)3 Expression (cbit.vcell.parser.Expression)3 Element (org.jdom.Element)3 OptParameterValue (org.vcell.optimization.thrift.OptParameterValue)3 OptProblem (org.vcell.optimization.thrift.OptProblem)3 OptResultSet (org.vcell.optimization.thrift.OptResultSet)3 OptRun (org.vcell.optimization.thrift.OptRun)3 DefaultScalarFunction (cbit.function.DefaultScalarFunction)2 MathException (cbit.vcell.math.MathException)2