Search in sources :

Example 16 with MathMappingCallback

use of cbit.vcell.mapping.SimulationContext.MathMappingCallback in project vcell by virtualcell.

the class ClientTaskManager method copyApplication.

public static AsynchClientTask[] copyApplication(final JComponent requester, final BioModel bioModel, final SimulationContext simulationContext, final boolean bSpatial, final SimulationContext.Application appType) {
    // get valid application name
    String newApplicationName = null;
    String baseName = "Copy of " + simulationContext.getName();
    int count = 0;
    while (true) {
        if (count == 0) {
            newApplicationName = baseName;
        } else {
            newApplicationName = baseName + " " + count;
        }
        if (bioModel.getSimulationContext(newApplicationName) == null) {
            break;
        }
        count++;
    }
    final String newName = newApplicationName;
    AsynchClientTask task1 = new AsynchClientTask("preparing to copy", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            SimulationContext newSimulationContext = SimulationContext.copySimulationContext(simulationContext, newName, bSpatial, appType);
            newSimulationContext.getGeometry().precomputeAll(new GeometryThumbnailImageFactoryAWT());
            if (newSimulationContext.isSameTypeAs(simulationContext)) {
                MathMappingCallback callback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
                String oldHash = simulationContext.getMd5hash();
                BNGOutputSpec oldSpec = simulationContext.getMostRecentlyCreatedOutputSpec();
                if (oldHash != null && oldSpec != null) {
                    // Warning: the results from "Edit / Test Constraints" are never cached because we want to repeatedly run it
                    // even if nothing changed
                    newSimulationContext.setMd5hash(oldHash);
                    newSimulationContext.setMostRecentlyCreatedOutputSpec(oldSpec);
                    newSimulationContext.setInsufficientIterations(simulationContext.isInsufficientIterations());
                    newSimulationContext.setInsufficientMaxMolecules(simulationContext.isInsufficientMaxMolecules());
                }
                newSimulationContext.refreshMathDescription(callback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
            }
            hashTable.put("newSimulationContext", newSimulationContext);
        }
    };
    AsynchClientTask task2 = new AsynchClientTask("copying application and simulations", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            SimulationContext newSimulationContext = (SimulationContext) hashTable.get("newSimulationContext");
            bioModel.addSimulationContext(newSimulationContext);
            if (newSimulationContext.isSameTypeAs(simulationContext)) {
                // copy simulations to new simContext
                for (Simulation sim : simulationContext.getSimulations()) {
                    Simulation clonedSimulation = new Simulation(sim, false);
                    clonedSimulation.setMathDescription(newSimulationContext.getMathDescription());
                    String newName = sim.getName() + "_";
                    boolean bFound = false;
                    do {
                        bFound = false;
                        newName = TokenMangler.getNextEnumeratedToken(newName);
                        Simulation[] origSimulations = simulationContext.getBioModel().getSimulations();
                        for (int i = 0; i < origSimulations.length; i++) {
                            if (origSimulations[i].getName().equals(newName)) {
                                bFound = true;
                                break;
                            }
                        }
                    } while (bFound);
                    clonedSimulation.setName(newName);
                    newSimulationContext.addSimulation(clonedSimulation);
                }
                // copy output functions to new simContext
                ArrayList<AnnotatedFunction> outputFunctions = simulationContext.getOutputFunctionContext().getOutputFunctionsList();
                ArrayList<AnnotatedFunction> newOutputFunctions = new ArrayList<AnnotatedFunction>();
                for (AnnotatedFunction afn : outputFunctions) {
                    newOutputFunctions.add(new AnnotatedFunction(afn));
                }
                newSimulationContext.getOutputFunctionContext().setOutputFunctions(newOutputFunctions);
            } else {
                if (simulationContext.getSimulations().length > 0) {
                    DialogUtils.showWarningDialog(requester, "Simulations are not copied because new application is of different type.");
                }
            }
        }
    };
    return new AsynchClientTask[] { task1, task2 };
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) SimulationContext(cbit.vcell.mapping.SimulationContext) BNGOutputSpec(cbit.vcell.bionetgen.BNGOutputSpec) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) Simulation(cbit.vcell.solver.Simulation) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction)

Example 17 with MathMappingCallback

use of cbit.vcell.mapping.SimulationContext.MathMappingCallback in project vcell by virtualcell.

the class ClientRequestManager method updateMath.

public static Collection<AsynchClientTask> updateMath(final Component requester, final SimulationContext simulationContext, final boolean bShowWarning, final NetworkGenerationRequirements networkGenerationRequirements) {
    ArrayList<AsynchClientTask> rval = new ArrayList<>();
    AsynchClientTask task1 = new AsynchClientTask("generating math", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            Geometry geometry = simulationContext.getGeometry();
            if (geometry.getDimension() > 0 && geometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
                geometry.getGeometrySurfaceDescription().updateAll();
            }
            // Use differnt mathmapping for different applications (stoch or non-stoch)
            simulationContext.checkValidity();
            MathMappingCallback callback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
            MathMapping mathMapping = simulationContext.createNewMathMapping(callback, networkGenerationRequirements);
            MathDescription mathDesc = mathMapping.getMathDescription(callback);
            callback.setProgressFraction(1.0f / 3.0f * 2.0f);
            hashTable.put("mathMapping", mathMapping);
            hashTable.put("mathDesc", mathDesc);
        }
    };
    rval.add(task1);
    AsynchClientTask task2 = new AsynchClientTask("formating math", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            MathDescription mathDesc = (MathDescription) hashTable.get("mathDesc");
            if (mathDesc != null) {
                simulationContext.setMathDescription(mathDesc);
            }
        }
    };
    rval.add(task2);
    if (bShowWarning) {
        AsynchClientTask task3 = new AsynchClientTask("showing issues", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

            @Override
            public void run(Hashtable<String, Object> hashTable) throws Exception {
                MathMapping mathMapping = (MathMapping) hashTable.get("mathMapping");
                MathDescription mathDesc = (MathDescription) hashTable.get("mathDesc");
                if (mathDesc != null) {
                    // 
                    // inform user if any issues
                    // 
                    Issue[] issues = mathMapping.getIssues();
                    if (issues != null && issues.length > 0) {
                        StringBuffer messageBuffer = new StringBuffer("Issues encountered during Math Generation:\n");
                        int issueCount = 0;
                        for (int i = 0; i < issues.length; i++) {
                            if (issues[i].getSeverity() == Issue.SEVERITY_ERROR || issues[i].getSeverity() == Issue.SEVERITY_WARNING) {
                                messageBuffer.append(issues[i].getCategory() + " " + issues[i].getSeverityName() + " : " + issues[i].getMessage() + "\n");
                                issueCount++;
                            }
                        }
                        if (issueCount > 0) {
                            PopupGenerator.showWarningDialog(requester, messageBuffer.toString(), new String[] { "OK" }, "OK");
                        }
                    }
                }
            }
        };
        rval.add(task3);
    }
    return rval;
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) Issue(org.vcell.util.Issue) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) SetMathDescription(cbit.vcell.client.task.SetMathDescription) MathDescription(cbit.vcell.math.MathDescription) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Geometry(cbit.vcell.geometry.Geometry) MathMapping(cbit.vcell.mapping.MathMapping)

Example 18 with MathMappingCallback

use of cbit.vcell.mapping.SimulationContext.MathMappingCallback in project vcell by virtualcell.

the class OutputFunctionsPanel method addOutputFunction.

private void addOutputFunction() {
    if (simulationWorkspace == null) {
        return;
    }
    AsynchClientTask task1 = new AsynchClientTask("refresh math description", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            MathMappingCallback mathMappingCallback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
            if (simulationWorkspace.getSimulationOwner() instanceof SimulationContext) {
                SimulationContext simulationContext = (SimulationContext) simulationWorkspace.getSimulationOwner();
                simulationContext.refreshMathDescription(mathMappingCallback, NetworkGenerationRequirements.AllowTruncatedStandardTimeout);
            }
        // else, for mathModels, nothing to refresh.
        }
    };
    AsynchClientTask task2 = new AsynchClientTask("show dialog", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            ArrayList<AnnotatedFunction> outputFunctionList = outputFunctionContext.getOutputFunctionsList();
            String defaultName = null;
            int count = 0;
            while (true) {
                boolean nameUsed = false;
                count++;
                defaultName = "func" + count;
                for (AnnotatedFunction function : outputFunctionList) {
                    if (function.getName().equals(defaultName)) {
                        nameUsed = true;
                    }
                }
                if (!nameUsed) {
                    break;
                }
            }
            final boolean bSpatial = simulationWorkspace.getSimulationOwner().getGeometry().getDimension() > 0;
            // for non-spatial application, set 'Next' to 'Finish'.
            if (!bSpatial) {
                getNextButton().setText("Finish");
            } else {
                getNextButton().setText("Next >>");
            }
            getFunctionNameTextField().setText(defaultName);
            getFunctionExpressionTextField().setText("0.0");
            Set<String> autoCompList = new HashSet<String>();
            Map<String, SymbolTableEntry> entryMap = new HashMap<String, SymbolTableEntry>();
            outputFunctionContext.getEntries(entryMap);
            autoCompList = entryMap.keySet();
            getFunctionExpressionTextField().setAutoCompletionWords(autoCompList);
            getFunctionExpressionTextField().setSymbolTable(outputFunctionContext);
            // 
            // Show the editor with a default name and default expression for the function
            // If the OK option is chosen, get the new name and expression for the function and create a new
            // function, add it to the list of output functions in simulationOwner
            // Else, pop-up an error dialog indicating that function cannot be added.
            // 
            cardLayout.show(getAddFunctionPanel(), funcNameAndExprPanel.getName());
            DialogUtils.showModalJDialogOnTop(getAddFunctionDialog(), OutputFunctionsPanel.this);
        }
    };
    ClientTaskDispatcher.dispatch(OutputFunctionsPanel.this, new Hashtable<String, Object>(), new AsynchClientTask[] { task1, task2 });
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) HashMap(java.util.HashMap) Hashtable(java.util.Hashtable) SimulationContext(cbit.vcell.mapping.SimulationContext) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) HashSet(java.util.HashSet)

Example 19 with MathMappingCallback

use of cbit.vcell.mapping.SimulationContext.MathMappingCallback in project vcell by virtualcell.

the class ParameterEstimationRunTaskPanel method saveSolutionAsNewSimulation.

private void saveSolutionAsNewSimulation() {
    try {
        OptimizationSpec optSpec = parameterEstimationTask.getModelOptimizationMapping().getOptimizationSpec();
        if (optSpec == null) {
            throw new RuntimeException("optimization not yet performed");
        }
        // 
        // add new simulation to the Application (other bookkeeping required?)
        // 
        String newSimName = DialogUtils.showInputDialog0(this, "Enter name for new simulation", "Fitted");
        newSimName = (newSimName == null ? null : newSimName.trim());
        if (newSimName == null || newSimName.length() == 0) {
            throw new Exception("New Simulation name cannot be 0 characters");
        }
        SimulationContext simContext = parameterEstimationTask.getModelOptimizationSpec().getSimulationContext();
        MathMappingCallback dummyCallback = new MathMappingCallback() {

            @Override
            public void setProgressFraction(float fractionDone) {
            }

            @Override
            public void setMessage(String message) {
            }

            @Override
            public boolean isInterrupted() {
                return false;
            }
        };
        Simulation newSim = simContext.addNewSimulation(newSimName, dummyCallback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
        parameterEstimationTask.getModelOptimizationMapping().applySolutionToMathOverrides(newSim, parameterEstimationTask.getOptimizationResultSet());
        DialogUtils.showInfoDialog(this, "created simulation \"" + newSim.getName() + "\"");
    } catch (UtilCancelException e) {
    // ignore, user cancelled operation
    } catch (Exception e) {
        e.printStackTrace(System.out);
        DialogUtils.showErrorDialog(this, e.getMessage(), e);
    }
}
Also used : UtilCancelException(org.vcell.util.UtilCancelException) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) Simulation(cbit.vcell.solver.Simulation) ModelOptimizationSpec(cbit.vcell.modelopt.ModelOptimizationSpec) OptimizationSpec(cbit.vcell.opt.OptimizationSpec) SimulationContext(cbit.vcell.mapping.SimulationContext) OptimizationException(cbit.vcell.opt.OptimizationException) UtilCancelException(org.vcell.util.UtilCancelException) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 20 with MathMappingCallback

use of cbit.vcell.mapping.SimulationContext.MathMappingCallback in project vcell by virtualcell.

the class CopasiServicePython method makeOptProblem.

public static OptProblem makeOptProblem(ParameterEstimationTask parameterEstimationTask) throws IOException, ExpressionException, SBMLException, XMLStreamException {
    OptimizationSpec optimizationSpec = parameterEstimationTask.getModelOptimizationMapping().getOptimizationSpec();
    SimulationContext simulationContext = parameterEstimationTask.getSimulationContext();
    MathMappingCallback callback = new MathMappingCallback() {

        @Override
        public void setProgressFraction(float fractionDone) {
            Thread.dumpStack();
            System.out.println("---> stdout mathMapping: progress = " + (fractionDone * 100.0) + "% done");
        }

        @Override
        public void setMessage(String message) {
            Thread.dumpStack();
            System.out.println("---> stdout mathMapping: message = " + message);
        }

        @Override
        public boolean isInterrupted() {
            return false;
        }
    };
    simulationContext.refreshMathDescription(callback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
    MathModel vcellMathModel = new MathModel(null);
    vcellMathModel.setMathDescription(simulationContext.getMathDescription());
    // get math model string
    String sbmlString = MathModel_SBMLExporter.getSBMLString(vcellMathModel, 2, 4);
    OptProblem optProblem = new OptProblem();
    optProblem.setMathModelSbmlContents(sbmlString);
    optProblem.setNumberOfOptimizationRuns(parameterEstimationTask.getOptimizationSolverSpec().getNumOfRuns());
    for (Parameter p : optimizationSpec.getParameters()) {
        ParameterDescription pdesc = new ParameterDescription(p.getName(), p.getScale(), p.getLowerBound(), p.getUpperBound(), p.getInitialGuess());
        optProblem.addToParameterDescriptionList(pdesc);
    }
    SimpleReferenceData refData = (SimpleReferenceData) parameterEstimationTask.getModelOptimizationSpec().getReferenceData();
    // check if t is at the first column
    int timeIndex = refData.findColumn(ReservedVariable.TIME.getName());
    if (timeIndex != 0) {
        throw new RuntimeException("t must be the first column");
    }
    DataSet dataset = new DataSet();
    for (int rowIndex = 0; rowIndex < refData.getNumDataRows(); rowIndex++) {
        DataRow dataRow = new DataRow();
        double[] array = refData.getDataByRow(rowIndex);
        for (double d : array) {
            dataRow.addToData(d);
        }
        dataset.addToRows(dataRow);
    }
    optProblem.setExperimentalDataSet(dataset);
    optProblem.addToReferenceVariableList(new ReferenceVariable(ReservedVariable.TIME.getName(), ReferenceVariableType.independent));
    // add all other dependent variables, recall that the dependent variables start from 2nd column onward in reference data
    for (int i = 1; i < refData.getNumDataColumns(); i++) {
        ReferenceDataMappingSpec rdms = parameterEstimationTask.getModelOptimizationSpec().getReferenceDataMappingSpec(refData.getColumnNames()[i]);
        optProblem.addToReferenceVariableList(new ReferenceVariable(rdms.getModelObject().getName(), ReferenceVariableType.dependent));
    }
    cbit.vcell.opt.CopasiOptimizationMethod vcellCopasiOptimizationMethod = parameterEstimationTask.getOptimizationSolverSpec().getCopasiOptimizationMethod();
    OptimizationMethodType optMethodType = OptimizationMethodType.valueOf(vcellCopasiOptimizationMethod.getType().name());
    CopasiOptimizationMethod thriftOptMethod = new CopasiOptimizationMethod();
    thriftOptMethod.setOptimizationMethodType(optMethodType);
    for (cbit.vcell.opt.CopasiOptimizationParameter optParam : vcellCopasiOptimizationMethod.getParameters()) {
        org.vcell.optimization.thrift.CopasiOptimizationParameter p = new org.vcell.optimization.thrift.CopasiOptimizationParameter();
        p.setValue(optParam.getValue());
        org.vcell.optimization.thrift.OptimizationParameterType optParmType = null;
        org.vcell.optimization.thrift.OptimizationParameterDataType optDataType = null;
        switch(optParam.getType()) {
            case Cooling_Factor:
                optParmType = OptimizationParameterType.Cooling_Factor;
                optDataType = OptimizationParameterDataType.DOUBLE;
                break;
            case IterationLimit:
                optParmType = OptimizationParameterType.IterationLimit;
                optDataType = OptimizationParameterDataType.INT;
                break;
            case Number_of_Generations:
                optParmType = OptimizationParameterType.Number_of_Generations;
                optDataType = OptimizationParameterDataType.INT;
                break;
            case Number_of_Iterations:
                optParmType = OptimizationParameterType.Number_of_Iterations;
                optDataType = OptimizationParameterDataType.INT;
                break;
            case Pf:
                optParmType = OptimizationParameterType.Pf;
                optDataType = OptimizationParameterDataType.DOUBLE;
                break;
            case Population_Size:
                optParmType = OptimizationParameterType.Population_Size;
                optDataType = OptimizationParameterDataType.INT;
                break;
            case Random_Number_Generator:
                optParmType = OptimizationParameterType.Random_Number_Generator;
                optDataType = OptimizationParameterDataType.INT;
                break;
            case Rho:
                optParmType = OptimizationParameterType.Rho;
                optDataType = OptimizationParameterDataType.DOUBLE;
                break;
            case Scale:
                optParmType = OptimizationParameterType.Scale;
                optDataType = OptimizationParameterDataType.DOUBLE;
                break;
            case Seed:
                optParmType = OptimizationParameterType.Seed;
                optDataType = OptimizationParameterDataType.INT;
                break;
            case Start_Temperature:
                optParmType = OptimizationParameterType.Start_Temperature;
                optDataType = OptimizationParameterDataType.DOUBLE;
                break;
            case Std_Deviation:
                optParmType = OptimizationParameterType.Std_Deviation;
                optDataType = OptimizationParameterDataType.DOUBLE;
                break;
            case Swarm_Size:
                optParmType = OptimizationParameterType.Swarm_Size;
                optDataType = OptimizationParameterDataType.INT;
                break;
            case Tolerance:
                optParmType = OptimizationParameterType.Tolerance;
                optDataType = OptimizationParameterDataType.DOUBLE;
                break;
            default:
                throw new RuntimeException("unsupported parameter type :" + optParam.getType().name() + " in COPASI optimization solver");
        }
        p.setParamType(optParmType);
        p.setDataType(optDataType);
        thriftOptMethod.addToOptimizationParameterList(p);
    }
    optProblem.setOptimizationMethod(thriftOptMethod);
    return optProblem;
}
Also used : MathModel(cbit.vcell.mathmodel.MathModel) DataSet(org.vcell.optimization.thrift.DataSet) ReferenceDataMappingSpec(cbit.vcell.modelopt.ReferenceDataMappingSpec) DataRow(org.vcell.optimization.thrift.DataRow) CopasiOptimizationMethod(org.vcell.optimization.thrift.CopasiOptimizationMethod) OptimizationParameterType(org.vcell.optimization.thrift.OptimizationParameterType) OptimizationParameterDataType(org.vcell.optimization.thrift.OptimizationParameterDataType) OptimizationSpec(cbit.vcell.opt.OptimizationSpec) ReferenceVariable(org.vcell.optimization.thrift.ReferenceVariable) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) OptProblem(org.vcell.optimization.thrift.OptProblem) SimulationContext(cbit.vcell.mapping.SimulationContext) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) OptimizationMethodType(org.vcell.optimization.thrift.OptimizationMethodType) Parameter(cbit.vcell.opt.Parameter) ParameterDescription(org.vcell.optimization.thrift.ParameterDescription)

Aggregations

MathMappingCallback (cbit.vcell.mapping.SimulationContext.MathMappingCallback)22 SimulationContext (cbit.vcell.mapping.SimulationContext)17 BioModel (cbit.vcell.biomodel.BioModel)11 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)11 MathMappingCallbackTaskAdapter (cbit.vcell.mapping.MathMappingCallbackTaskAdapter)11 Hashtable (java.util.Hashtable)11 Simulation (cbit.vcell.solver.Simulation)9 ArrayList (java.util.ArrayList)9 MathMapping (cbit.vcell.mapping.MathMapping)6 MathModel (cbit.vcell.mathmodel.MathModel)6 ExpressionException (cbit.vcell.parser.ExpressionException)6 IOException (java.io.IOException)6 File (java.io.File)5 CSGObject (cbit.vcell.geometry.CSGObject)4 MathDescription (cbit.vcell.math.MathDescription)4 XMLSource (cbit.vcell.xml.XMLSource)4 MappingException (cbit.vcell.mapping.MappingException)3 Application (cbit.vcell.mapping.SimulationContext.Application)3 SpeciesContextSpec (cbit.vcell.mapping.SpeciesContextSpec)3 SimulationTask (cbit.vcell.messaging.server.SimulationTask)3