Search in sources :

Example 6 with ReferenceData

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

the class NonGUIFRAPTest method dumpSpatialResults.

public static void dumpSpatialResults(SpatialAnalysisResults spatialAnalysisResults, double[] frapDataTimeStamps, File outputFile) throws Exception {
    FileWriter fw = new FileWriter(outputFile);
    // FileOutputStream fos = new FileOutputStream(outputFile);
    // BufferedOutputStream bos = new BufferedOutputStream(fos);
    ReferenceData[] referenceDataArr = spatialAnalysisResults.createReferenceDataForAllDiffusionRates(frapDataTimeStamps);
    ODESolverResultSet[] odeSolverResultSetArr = spatialAnalysisResults.createODESolverResultSetForAllDiffusionRates();
    for (int i = 0; i < spatialAnalysisResults.analysisParameters.length; i++) {
        DataSource expDataSource = new DataSource.DataSourceReferenceData("experiment", referenceDataArr[i]);
        DataSource fitDataSource = new DataSource.DataSourceRowColumnResultSet("fit", odeSolverResultSetArr[i]);
    // MultisourcePlotListModel multisourcePlotListModel =
    // new MultisourcePlotListModel();
    // multisourcePlotListModel.setDataSources(new DataSource[] {expDataSource,fitDataSource});
    // System.out.println("AnalysisParameters = "+spatialAnalysisResults.analysisParameters[i]);
    // for (int j = 0; j < multisourcePlotListModel.getSize(); j++) {
    // DataReference dataReference = (DataReference)multisourcePlotListModel.getElementAt(j);
    // DataSource dataSource = dataReference.getDataSource();
    // for (int k = 0; k < dataSource.getNumRows(); k++) {
    // for (int k2 = 0; k2 < dataSource.getNumColumns(); k2++) {
    // System.out.print(dataSource.getRowData(k)[k2]+" ");
    // fw.write(dataSource.getRowData(k)[k2]+" ");
    // }
    // System.out.println();
    // fw.write("\n");
    // }
    // if(dataReference.getDataSource().getSource() instanceof ReferenceData){
    // ReferenceData refData = (ReferenceData)dataReference.getDataSource().getSource();
    // for (int k = 0; k < refData.getNumRows(); k++) {
    // for (int k2 = 0; k2 < refData.getNumColumns(); k2++) {
    // System.out.print(refData.getRowData(k)[k2]+" ");
    // fw.write(refData.getRowData(k)[k2]+" ");
    // }
    // System.out.println();
    // fw.write("\n");
    // }
    // }else{
    // ODESolverResultSet odeRS = (ODESolverResultSet)dataReference.getDataSource().getSource();
    // for (int k = 0; k < odeRS.getRowCount(); k++) {
    // for (int k2 = 0; k2 < odeRS.getDataColumnCount(); k2++) {
    // System.out.print(odeRS.getRow(k)[k2]+" ");
    // fw.write(odeRS.getRow(k)[k2]+" ");
    // }
    // System.out.println();
    // fw.write("\n");
    // }
    // }
    // }
    }
    fw.close();
}
Also used : ReferenceData(cbit.vcell.opt.ReferenceData) FileWriter(java.io.FileWriter) ODESolverResultSet(cbit.vcell.solver.ode.ODESolverResultSet) DataSource(cbit.vcell.modelopt.DataSource)

Example 7 with ReferenceData

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

the class EstParams_CompareResultsDescriptor method aboutToDisplayPanel.

public void aboutToDisplayPanel() {
    FRAPStudy fStudy = frapWorkspace.getWorkingFrapStudy();
    // create Mean square error for different models under different ROIs
    // if(fStudy.getAnalysisMSESummaryData() == null)
    // {
    fStudy.createAnalysisMSESummaryData();
    // }
    // auto find best model for user if best model is not selected.
    double[][] mseSummaryData = fStudy.getAnalysisMSESummaryData();
    // for(int i =0; i<10; i++)
    // System.out.print(mseSummaryData[0][i]+"  ");
    // find best model with significance and has least error
    int bestModel = FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT;
    if (// best model is saved and there is no model selection change
    fStudy.getBestModelIndex() != null) {
        bestModel = fStudy.getBestModelIndex().intValue();
    } else // need to find the best model
    {
        // check model significance if more than one model
        if (fStudy.getSelectedModels().size() > 1) {
            if (getFrapWorkspace().getWorkingFrapStudy().getFrapOptData() != null || getFrapWorkspace().getWorkingFrapStudy().getFrapOptFunc() != null) {
                ProfileSummaryData[][] allProfileSumData = FRAPOptimizationUtils.getAllProfileSummaryData(fStudy);
                FRAPModel[] frapModels = frapWorkspace.getWorkingFrapStudy().getModels();
                int confidenceIdx = ((EstParams_CompareResultsPanel) this.getPanelComponent()).getSelectedConfidenceIndex();
                boolean[] modelSignificance = new boolean[FRAPModel.NUM_MODEL_TYPES];
                Arrays.fill(modelSignificance, true);
                if (frapModels[FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT] != null && frapModels[FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT].getModelParameters() != null && allProfileSumData != null && allProfileSumData[FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT] != null) {
                    for (int i = 0; i < FRAPModel.NUM_MODEL_PARAMETERS_ONE_DIFF; i++) {
                        ConfidenceInterval[] intervals = allProfileSumData[FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT][i].getConfidenceIntervals();
                        if (intervals[confidenceIdx].getUpperBound() == frapModels[FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT].getModelParameters()[i].getUpperBound() && intervals[confidenceIdx].getLowerBound() == frapModels[FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT].getModelParameters()[i].getLowerBound()) {
                            modelSignificance[FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT] = false;
                            break;
                        }
                    }
                }
                if (frapModels[FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS] != null && frapModels[FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS].getModelParameters() != null && allProfileSumData != null && allProfileSumData[FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS] != null) {
                    for (int i = 0; i < FRAPModel.NUM_MODEL_PARAMETERS_TWO_DIFF; i++) {
                        ConfidenceInterval[] intervals = allProfileSumData[FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS][i].getConfidenceIntervals();
                        if (intervals[confidenceIdx].getUpperBound() == frapModels[FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS].getModelParameters()[i].getUpperBound() && intervals[confidenceIdx].getLowerBound() == frapModels[FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS].getModelParameters()[i].getLowerBound()) {
                            modelSignificance[FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS] = false;
                            break;
                        }
                    }
                }
                if (frapModels[FRAPModel.IDX_MODEL_REACTION_OFF_RATE] != null && frapModels[FRAPModel.IDX_MODEL_REACTION_OFF_RATE].getModelParameters() != null && allProfileSumData != null && allProfileSumData[FRAPModel.IDX_MODEL_REACTION_OFF_RATE] != null) {
                    for (int i = 0; i < FRAPModel.NUM_MODEL_PARAMETERS_REACTION_OFF_RATE; i++) {
                        if (i == FRAPModel.INDEX_BLEACH_MONITOR_RATE) {
                            ConfidenceInterval[] intervals = allProfileSumData[FRAPModel.IDX_MODEL_REACTION_OFF_RATE][FRAPModel.INDEX_BLEACH_MONITOR_RATE].getConfidenceIntervals();
                            if (intervals[confidenceIdx].getUpperBound() == frapModels[FRAPModel.IDX_MODEL_REACTION_OFF_RATE].getModelParameters()[FRAPModel.INDEX_BLEACH_MONITOR_RATE].getUpperBound() && intervals[confidenceIdx].getLowerBound() == frapModels[FRAPModel.IDX_MODEL_REACTION_OFF_RATE].getModelParameters()[FRAPModel.INDEX_BLEACH_MONITOR_RATE].getLowerBound()) {
                                modelSignificance[FRAPModel.IDX_MODEL_REACTION_OFF_RATE] = false;
                                break;
                            }
                        } else if (i == FRAPModel.INDEX_OFF_RATE) {
                            ConfidenceInterval[] intervals = allProfileSumData[FRAPModel.IDX_MODEL_REACTION_OFF_RATE][FRAPModel.INDEX_OFF_RATE].getConfidenceIntervals();
                            if (intervals[confidenceIdx].getUpperBound() == frapModels[FRAPModel.IDX_MODEL_REACTION_OFF_RATE].getModelParameters()[FRAPModel.INDEX_OFF_RATE].getUpperBound() && intervals[confidenceIdx].getLowerBound() == frapModels[FRAPModel.IDX_MODEL_REACTION_OFF_RATE].getModelParameters()[FRAPModel.INDEX_OFF_RATE].getLowerBound()) {
                                modelSignificance[FRAPModel.IDX_MODEL_REACTION_OFF_RATE] = false;
                                break;
                            }
                        }
                    }
                }
                // check least error model with significance
                double minError = 1E8;
                if (mseSummaryData != null) {
                    // exclude cell and bkground ROIs, include sum of error
                    int secDimLen = FRAPData.VFRAP_ROI_ENUM.values().length - 2 + 1;
                    if (modelSignificance[FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT] == modelSignificance[FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS] && modelSignificance[FRAPModel.IDX_MODEL_REACTION_OFF_RATE] == modelSignificance[FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS]) {
                        // if all models' significance are the same, find the least error
                        for (int i = 0; i < FRAPModel.NUM_MODEL_TYPES; i++) {
                            if ((minError > mseSummaryData[i][secDimLen - 1])) {
                                minError = mseSummaryData[i][secDimLen - 1];
                                bestModel = i;
                            }
                        }
                    } else {
                        // if models' significance are different, find the least error with significance
                        for (int i = 0; i < FRAPModel.NUM_MODEL_TYPES; i++) {
                            if (modelSignificance[i] && (minError > mseSummaryData[i][secDimLen - 1])) {
                                minError = mseSummaryData[i][secDimLen - 1];
                                bestModel = i;
                            }
                        }
                    }
                }
            }
        } else // only one model is selected and the selected model should be the best model
        {
            for (int i = 0; i < fStudy.getModels().length; i++) {
                if (fStudy.getModels()[i] != null) {
                    bestModel = i;
                    break;
                }
            }
        }
    }
    ((EstParams_CompareResultsPanel) this.getPanelComponent()).setBestModelRadioButton(bestModel);
    // set data source to multiSourcePlotPane
    // length should be fStudy.getSelectedModels().size()+1, however, reaction binding may not have data
    ArrayList<DataSource> comparableDataSource = new ArrayList<DataSource>();
    // add exp data
    ReferenceData expReferenceData = FRAPOptimizationUtils.doubleArrayToSimpleRefData(fStudy.getDimensionReducedExpData(), fStudy.getFrapData().getImageDataset().getImageTimeStamps(), fStudy.getStartingIndexForRecovery(), fStudy.getSelectedROIsForErrorCalculation());
    final DataSource expDataSource = new DataSource.DataSourceReferenceData("exp", expReferenceData);
    comparableDataSource.add(expDataSource);
    // add opt/sim data
    // using the same loop, disable the radio button if the model is not included
    // adjust radio buttons
    ((EstParams_CompareResultsPanel) this.getPanelComponent()).disableAllRadioButtons();
    ArrayList<Integer> selectedModelIndexes = fStudy.getSelectedModels();
    for (int i = 0; i < selectedModelIndexes.size(); i++) {
        DataSource newDataSource = null;
        double[] timePoints = fStudy.getFrapData().getImageDataset().getImageTimeStamps();
        int startingIndex = fStudy.getStartingIndexForRecovery();
        double[] truncatedTimes = new double[timePoints.length - startingIndex];
        System.arraycopy(timePoints, startingIndex, truncatedTimes, 0, truncatedTimes.length);
        if (selectedModelIndexes.get(i).equals(FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT)) {
            // adjust radio button
            ((EstParams_CompareResultsPanel) this.getPanelComponent()).enableRadioButton(FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT);
            FRAPModel temModel = fStudy.getFrapModel(FRAPModel.IDX_MODEL_DIFF_ONE_COMPONENT);
            ODESolverResultSet temSolverResultSet = FRAPOptimizationUtils.doubleArrayToSolverResultSet(temModel.getData(), truncatedTimes, 0, fStudy.getSelectedROIsForErrorCalculation());
            newDataSource = new DataSource.DataSourceRowColumnResultSet("opt_DF1", temSolverResultSet);
        } else if (selectedModelIndexes.get(i).equals(FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS)) {
            // adjust radio button
            ((EstParams_CompareResultsPanel) this.getPanelComponent()).enableRadioButton(FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS);
            FRAPModel temModel = fStudy.getFrapModel(FRAPModel.IDX_MODEL_DIFF_TWO_COMPONENTS);
            ODESolverResultSet temSolverResultSet = FRAPOptimizationUtils.doubleArrayToSolverResultSet(temModel.getData(), truncatedTimes, 0, fStudy.getSelectedROIsForErrorCalculation());
            newDataSource = new DataSource.DataSourceRowColumnResultSet("opt_DF2", temSolverResultSet);
        } else if (selectedModelIndexes.get(i).equals(FRAPModel.IDX_MODEL_REACTION_OFF_RATE)) {
            // adjust radio button
            ((EstParams_CompareResultsPanel) this.getPanelComponent()).enableRadioButton(FRAPModel.IDX_MODEL_REACTION_OFF_RATE);
            FRAPModel temModel = fStudy.getFrapModel(FRAPModel.IDX_MODEL_REACTION_OFF_RATE);
            if (temModel.getData() != null) {
                ODESolverResultSet temSolverResultSet = FRAPOptimizationUtils.doubleArrayToSolverResultSet(temModel.getData(), truncatedTimes, 0, // for reaction off model, display curve under bleached region only
                FRAPStudy.createSelectedROIsForReactionOffRateModel());
                newDataSource = new DataSource.DataSourceRowColumnResultSet("sim_Koff", temSolverResultSet);
            }
        }
        if (newDataSource != null) {
            comparableDataSource.add(newDataSource);
        }
    }
    // set data to multiSourcePlotPane
    ((EstParams_CompareResultsPanel) this.getPanelComponent()).setPlotData(comparableDataSource.toArray(new DataSource[comparableDataSource.size()]));
}
Also used : ArrayList(java.util.ArrayList) FRAPModel(cbit.vcell.microscopy.FRAPModel) DataSource(cbit.vcell.modelopt.DataSource) ReferenceData(cbit.vcell.opt.ReferenceData) FRAPStudy(cbit.vcell.microscopy.FRAPStudy) ODESolverResultSet(cbit.vcell.solver.ode.ODESolverResultSet) ConfidenceInterval(org.vcell.optimization.ConfidenceInterval)

Example 8 with ReferenceData

use of cbit.vcell.opt.ReferenceData 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 9 with ReferenceData

use of cbit.vcell.opt.ReferenceData 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 10 with ReferenceData

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

the class ModelOptimizationMapping method getRemappedReferenceData.

/**
 * Gets the constraintData property (cbit.vcell.opt.ConstraintData) value.
 * @return The constraintData property value.
 * @see #setConstraintData
 */
private ReferenceData getRemappedReferenceData(MathMapping mathMapping) throws MappingException {
    if (modelOptimizationSpec.getReferenceData() == null) {
        return null;
    }
    // 
    // make sure time is mapped
    // 
    ReferenceData refData = modelOptimizationSpec.getReferenceData();
    ReferenceDataMappingSpec[] refDataMappingSpecs = modelOptimizationSpec.getReferenceDataMappingSpecs();
    RowColumnResultSet rowColResultSet = new RowColumnResultSet();
    Vector<SymbolTableEntry> modelObjectList = new Vector<SymbolTableEntry>();
    Vector<double[]> dataList = new Vector<double[]>();
    // 
    // find bound columns, (time is always mapped to the first column)
    // 
    int mappedColumnCount = 0;
    for (int i = 0; i < refDataMappingSpecs.length; i++) {
        SymbolTableEntry modelObject = refDataMappingSpecs[i].getModelObject();
        if (modelObject != null) {
            int mappedColumnIndex = mappedColumnCount;
            if (modelObject instanceof Model.ReservedSymbol && ((ReservedSymbol) modelObject).isTime()) {
                mappedColumnIndex = 0;
            }
            String origRefDataColumnName = refDataMappingSpecs[i].getReferenceDataColumnName();
            int origRefDataColumnIndex = refData.findColumn(origRefDataColumnName);
            if (origRefDataColumnIndex < 0) {
                throw new RuntimeException("reference data column named '" + origRefDataColumnName + "' not found");
            }
            double[] columnData = refData.getDataByColumn(origRefDataColumnIndex);
            if (modelObjectList.contains(modelObject)) {
                throw new RuntimeException("multiple reference data columns mapped to same model object '" + modelObject.getName() + "'");
            }
            modelObjectList.insertElementAt(modelObject, mappedColumnIndex);
            dataList.insertElementAt(columnData, mappedColumnIndex);
            mappedColumnCount++;
        }
    }
    // 
    if (modelObjectList.size() == 0) {
        throw new RuntimeException("reference data was not associated with model");
    }
    if (modelObjectList.size() == 1) {
        throw new RuntimeException("reference data was not associated with model, must map time and at least one other column");
    }
    boolean bFoundTimeVar = false;
    for (SymbolTableEntry ste : modelObjectList) {
        if (ste instanceof Model.ReservedSymbol && ((ReservedSymbol) ste).isTime()) {
            bFoundTimeVar = true;
            break;
        }
    }
    if (!bFoundTimeVar) {
        throw new RuntimeException("must map time column of reference data to model");
    }
    // 
    for (int i = 0; i < modelObjectList.size(); i++) {
        SymbolTableEntry modelObject = (SymbolTableEntry) modelObjectList.elementAt(i);
        try {
            // Find by name because MathSybolMapping has different 'objects' than refDataMapping 'objects'
            Variable variable = mathMapping.getMathSymbolMapping().findVariableByName(modelObject.getName());
            if (variable != null) {
                String symbol = variable.getName();
                rowColResultSet.addDataColumn(new ODESolverResultSetColumnDescription(symbol));
            } else if (modelObject instanceof Model.ReservedSymbol && ((Model.ReservedSymbol) modelObject).isTime()) {
                Model.ReservedSymbol time = (Model.ReservedSymbol) modelObject;
                String symbol = time.getName();
                rowColResultSet.addDataColumn(new ODESolverResultSetColumnDescription(symbol));
            }
        } catch (MathException | MatrixException | ExpressionException | ModelException e) {
            e.printStackTrace();
            throw new MappingException(e.getMessage(), e);
        }
    }
    // 
    // populate data columns (time and rest)
    // 
    double[] weights = new double[rowColResultSet.getColumnDescriptionsCount()];
    weights[0] = 1.0;
    int numRows = ((double[]) dataList.elementAt(0)).length;
    int numColumns = modelObjectList.size();
    for (int j = 0; j < numRows; j++) {
        double[] row = new double[numColumns];
        for (int i = 0; i < numColumns; i++) {
            row[i] = ((double[]) dataList.elementAt(i))[j];
            if (i > 0) {
                weights[i] += row[i] * row[i];
            }
        }
        rowColResultSet.addRow(row);
    }
    for (int i = 0; i < numColumns; i++) {
        if (weights[i] == 0) {
            weights[i] = 1;
        } else {
            weights[i] = 1 / weights[i];
        }
    }
    SimpleReferenceData remappedRefData = new SimpleReferenceData(rowColResultSet, weights);
    return remappedRefData;
}
Also used : ParameterVariable(cbit.vcell.math.ParameterVariable) Variable(cbit.vcell.math.Variable) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MatrixException(cbit.vcell.matrix.MatrixException) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) ODESolverResultSetColumnDescription(cbit.vcell.math.ODESolverResultSetColumnDescription) Vector(java.util.Vector) RowColumnResultSet(cbit.vcell.math.RowColumnResultSet) ModelException(cbit.vcell.model.ModelException) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) ReferenceData(cbit.vcell.opt.ReferenceData) MathException(cbit.vcell.math.MathException) Model(cbit.vcell.model.Model)

Aggregations

ReferenceData (cbit.vcell.opt.ReferenceData)17 SimpleReferenceData (cbit.vcell.opt.SimpleReferenceData)13 ODESolverResultSet (cbit.vcell.solver.ode.ODESolverResultSet)8 DataSource (cbit.vcell.modelopt.DataSource)6 ExpressionException (cbit.vcell.parser.ExpressionException)5 ODESolverResultSetColumnDescription (cbit.vcell.math.ODESolverResultSetColumnDescription)4 RowColumnResultSet (cbit.vcell.math.RowColumnResultSet)4 Variable (cbit.vcell.math.Variable)3 SymbolTableEntry (cbit.vcell.parser.SymbolTableEntry)3 ParseException (java.text.ParseException)3 Vector (java.util.Vector)3 Element (org.jdom.Element)3 UserCancelException (org.vcell.util.UserCancelException)3 MappingException (cbit.vcell.mapping.MappingException)2 CSV (cbit.vcell.math.CSV)2 Constant (cbit.vcell.math.Constant)2 FunctionColumnDescription (cbit.vcell.math.FunctionColumnDescription)2 MathException (cbit.vcell.math.MathException)2 ParameterVariable (cbit.vcell.math.ParameterVariable)2 MatrixException (cbit.vcell.matrix.MatrixException)2