Search in sources :

Example 16 with SolverTaskDescription

use of cbit.vcell.solver.SolverTaskDescription in project vcell by virtualcell.

the class XmlHelper method sedmlToBioModel.

public static VCDocument sedmlToBioModel(VCLogger transLogger, ExternalDocInfo externalDocInfo, SedML sedml, AbstractTask selectedTask) throws Exception {
    if (sedml.getModels().isEmpty()) {
        return null;
    }
    VCDocument doc = null;
    try {
        // extract the path only from the sedml file
        String fullPath = FileUtils.getFullPath(externalDocInfo.getFile().getAbsolutePath());
        // Namespace namespace = sedml.getNamespace();
        // iterate through all the elements and show them at the console
        List<org.jlibsedml.Model> mmm = sedml.getModels();
        for (Model mm : mmm) {
            System.out.println(mm.toString());
        }
        List<org.jlibsedml.Simulation> sss = sedml.getSimulations();
        for (org.jlibsedml.Simulation ss : sss) {
            System.out.println(ss.toString());
        }
        List<AbstractTask> ttt = sedml.getTasks();
        for (AbstractTask tt : ttt) {
            System.out.println(tt.toString());
        }
        List<DataGenerator> ddd = sedml.getDataGenerators();
        for (DataGenerator dd : ddd) {
            System.out.println(dd.toString());
        }
        List<Output> ooo = sedml.getOutputs();
        for (Output oo : ooo) {
            System.out.println(oo.toString());
        }
        KisaoTerm sedmlKisao = null;
        // this will become the vCell simulation
        org.jlibsedml.Simulation sedmlSimulation = null;
        // the "original" model referred to by the task
        org.jlibsedml.Model sedmlOriginalModel = null;
        String sedmlOriginalModelName = null;
        if (selectedTask == null) {
            // no task, just pick the Model and find its sbml file
            sedmlOriginalModelName = SEDMLUtil.getName(mmm.get(0));
        } else {
            if (selectedTask instanceof Task) {
                sedmlOriginalModel = sedml.getModelWithId(selectedTask.getModelReference());
                sedmlSimulation = sedml.getSimulation(selectedTask.getSimulationReference());
            } else if (selectedTask instanceof RepeatedTask) {
                RepeatedTask rt = (RepeatedTask) selectedTask;
                assert (rt.getSubTasks().size() == 1);
                // first (and only) subtask
                SubTask st = rt.getSubTasks().entrySet().iterator().next().getValue();
                String taskId = st.getTaskId();
                AbstractTask t = sedml.getTaskWithId(taskId);
                // get model and simulation from subtask
                sedmlOriginalModel = sedml.getModelWithId(t.getModelReference());
                sedmlSimulation = sedml.getSimulation(t.getSimulationReference());
            } else {
                throw new RuntimeException("Unexpected task " + selectedTask);
            }
            sedmlOriginalModelName = sedmlOriginalModel.getId();
            sedmlKisao = KisaoOntology.getInstance().getTermById(sedmlSimulation.getAlgorithm().getKisaoID());
        }
        // UniformTimeCourse [initialTime=0.0, numberOfPoints=1000, outputEndTime=1.0, outputStartTime=0.0,
        // Algorithm [kisaoID=KISAO:0000019], getId()=SimSlow]
        // identify the vCell solvers that would match best the sedml solver kisao id
        List<SolverDescription> solverDescriptions = new ArrayList<>();
        for (SolverDescription sd : SolverDescription.values()) {
            KisaoTerm solverKisaoTerm = KisaoOntology.getInstance().getTermById(sd.getKisao());
            if (solverKisaoTerm == null) {
                break;
            }
            boolean isExactlySame = solverKisaoTerm.equals(sedmlKisao);
            if (isExactlySame && !solverKisaoTerm.isObsolete()) {
                // we make a list with all the solvers that match the kisao
                solverDescriptions.add(sd);
            }
        }
        // from the list of vcell solvers that match the sedml kisao we select the ones that have a matching time step
        SolverDescription solverDescription = null;
        for (SolverDescription sd : solverDescriptions) {
            if (true) {
                solverDescription = sd;
                break;
            }
        }
        // find out everything else we need about the application we're going to use,
        // some of the info will be needed when we parse the sbml file
        boolean bSpatial = false;
        Application appType = Application.NETWORK_DETERMINISTIC;
        Set<SolverDescription.SolverFeature> sfList = solverDescription.getSupportedFeatures();
        for (SolverDescription.SolverFeature sf : sfList) {
            switch(sf) {
                case Feature_Rulebased:
                    appType = Application.RULE_BASED_STOCHASTIC;
                    break;
                case Feature_Stochastic:
                    appType = Application.NETWORK_STOCHASTIC;
                    break;
                case Feature_Deterministic:
                    appType = Application.NETWORK_DETERMINISTIC;
                    break;
                case Feature_Spatial:
                    bSpatial = true;
                    break;
                default:
                    break;
            }
        }
        // -------------------------------------------------------------------------------------------
        // extract bioModel name from sedx (or sedml) file
        String bioModelName = FileUtils.getBaseName(externalDocInfo.getFile().getAbsolutePath());
        // if we have repeated task, we ignore them, we just use the normal resolvers for archive and changes
        // once the application and simulation are built, we iterate through the repeated tasks and
        // add math overrides to the simulation for each repeated task
        ArchiveComponents ac = null;
        if (externalDocInfo.getFile().getPath().toLowerCase().endsWith("sedx") || externalDocInfo.getFile().getPath().toLowerCase().endsWith("omex")) {
            ac = Libsedml.readSEDMLArchive(new FileInputStream(externalDocInfo.getFile().getPath()));
        }
        ModelResolver resolver = new ModelResolver(sedml);
        if (ac != null) {
            resolver.add(new ArchiveModelResolver(ac));
        }
        resolver.add(new FileModelResolver());
        resolver.add(new RelativeFileModelResolver(fullPath));
        String newMdl = resolver.getModelString(sedmlOriginalModel);
        // sbmlSource with all the changes applied
        XMLSource sbmlSource = new XMLSource(newMdl);
        doc = XmlHelper.importSBML(transLogger, sbmlSource, bSpatial);
        BioModel bioModel = (BioModel) doc;
        bioModel.setName(bioModelName);
        // we already have an application loaded from the sbml file, with initial conditions and stuff
        // which may be not be suitable because the sedml kisao may need a different app type
        // so we do a "copy as" to the right type and then delete the original we loaded from the sbml file
        // the new application we're making from the old one
        SimulationContext newSimulationContext = null;
        if (bioModel.getSimulationContexts().length == 1) {
            SimulationContext oldSimulationContext = bioModel.getSimulationContext(0);
            newSimulationContext = SimulationContext.copySimulationContext(oldSimulationContext, sedmlOriginalModelName, bSpatial, appType);
            bioModel.removeSimulationContext(oldSimulationContext);
            bioModel.addSimulationContext(newSimulationContext);
        } else {
            // length == 0
            newSimulationContext = bioModel.addNewSimulationContext(sedmlOriginalModelName, appType);
        }
        // making the new vCell simulation based on the sedml simulation
        newSimulationContext.refreshDependencies();
        MathMappingCallback callback = new MathMappingCallbackTaskAdapter(null);
        newSimulationContext.refreshMathDescription(callback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
        Simulation newSimulation = new Simulation(newSimulationContext.getMathDescription());
        newSimulation.setName(SEDMLUtil.getName(sedmlSimulation));
        // TODO: make sure that everything has proper names
        // we check the repeated tasks, if any, and add to the list of math overrides
        // if(selectedTask instanceof RepeatedTask) {
        // for(Change change : ((RepeatedTask) selectedTask).getChanges()) {
        // if(!(change instanceof SetValue)) {
        // throw new RuntimeException("Only 'SetValue' changes are supported for repeated tasks.");
        // }
        // SetValue setValue = (SetValue)change;
        // // TODO: extract target from XPath
        // // ......
        // //
        // String target = "s0";	// for now we just use a hardcoded thing
        // ConstantArraySpec cas;
        // Range range = ((RepeatedTask) selectedTask).getRange(setValue.getRangeReference());
        // if(range instanceof UniformRange) {
        // cas = ConstantArraySpec.createIntervalSpec(target, ((UniformRange) range).getStart(), ((UniformRange) range).getEnd(),
        // range.getNumElements(), ((UniformRange) range).getType() == UniformRange.UniformType.LOG ? true : false);
        // } else if(range instanceof VectorRange) {
        // //    				List<String> constants = new ArrayList<> ();
        // //    				for(int i=0; i<range.getNumElements(); i++) {
        // //    					constants.add(new Constant(i+"", new Expression(range.getElementAt(i))));
        // //    				}
        // //    				cas = ConstantArraySpec.createListSpec(target, constants);
        // 
        // } else {
        // throw new RuntimeException("Only 'Uniform Range' and 'Vector Range' are supported at this time.");
        // }
        // 
        // }
        // }
        // we identify the type of sedml simulation (uniform time course, etc)
        // and set the vCell simulation parameters accordingly
        SolverTaskDescription simTaskDesc = newSimulation.getSolverTaskDescription();
        TimeBounds timeBounds = new TimeBounds();
        TimeStep timeStep = new TimeStep();
        double outputTimeStep = 0.1;
        if (sedmlSimulation instanceof UniformTimeCourse) {
            // we translate initial time to zero, we provide output for the duration of the simulation
            // because we can't select just an interval the way the SEDML simulation can
            double initialTime = ((UniformTimeCourse) sedmlSimulation).getInitialTime();
            double outputStartTime = ((UniformTimeCourse) sedmlSimulation).getOutputStartTime();
            double outputEndTime = ((UniformTimeCourse) sedmlSimulation).getOutputEndTime();
            double outputNumberOfPoints = ((UniformTimeCourse) sedmlSimulation).getNumberOfPoints();
            outputTimeStep = (outputEndTime - outputStartTime) / outputNumberOfPoints;
            timeBounds = new TimeBounds(0, outputEndTime - initialTime);
        } else if (sedmlSimulation instanceof OneStep) {
        // for anything other than UniformTimeCourse we just ignore
        } else if (sedmlSimulation instanceof SteadyState) {
        } else {
        }
        OutputTimeSpec outputTimeSpec = new UniformOutputTimeSpec(outputTimeStep);
        simTaskDesc.setTimeBounds(timeBounds);
        simTaskDesc.setTimeStep(timeStep);
        simTaskDesc.setOutputTimeSpec(outputTimeSpec);
        newSimulation.setSolverTaskDescription(simTaskDesc);
        bioModel.addSimulation(newSimulation);
        newSimulation.refreshDependencies();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Unable to initialize bioModel for the given selection.");
    }
    return doc;
}
Also used : Task(org.jlibsedml.Task) RepeatedTask(org.jlibsedml.RepeatedTask) SimulationTask(cbit.vcell.messaging.server.SimulationTask) AbstractTask(org.jlibsedml.AbstractTask) SubTask(org.jlibsedml.SubTask) ArrayList(java.util.ArrayList) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) FileModelResolver(org.jlibsedml.execution.FileModelResolver) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) ModelResolver(org.jlibsedml.execution.ModelResolver) SteadyState(org.jlibsedml.SteadyState) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) SubTask(org.jlibsedml.SubTask) VCDocument(org.vcell.util.document.VCDocument) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) FileInputStream(java.io.FileInputStream) KisaoTerm(org.jlibsedml.modelsupport.KisaoTerm) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) DataGenerator(org.jlibsedml.DataGenerator) UniformTimeCourse(org.jlibsedml.UniformTimeCourse) Application(cbit.vcell.mapping.SimulationContext.Application) AbstractTask(org.jlibsedml.AbstractTask) SolverDescription(cbit.vcell.solver.SolverDescription) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) OneStep(org.jlibsedml.OneStep) TimeBounds(cbit.vcell.solver.TimeBounds) TimeStep(cbit.vcell.solver.TimeStep) ArchiveComponents(org.jlibsedml.ArchiveComponents) RepeatedTask(org.jlibsedml.RepeatedTask) Output(org.jlibsedml.Output) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) FileModelResolver(org.jlibsedml.execution.FileModelResolver) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) SBMLException(org.sbml.jsbml.SBMLException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) Simulation(cbit.vcell.solver.Simulation) Model(org.jlibsedml.Model) BioModel(cbit.vcell.biomodel.BioModel) MathModel(cbit.vcell.mathmodel.MathModel) BioModel(cbit.vcell.biomodel.BioModel) Model(org.jlibsedml.Model)

Example 17 with SolverTaskDescription

use of cbit.vcell.solver.SolverTaskDescription in project vcell by virtualcell.

the class HybridSolver method getMathExecutableCommand.

@Override
protected String[] getMathExecutableCommand() {
    String randomNumber = "";
    // if one of the following paras is applied, all the paras in front of it must be set.
    String epsilon = " 100";
    String lambda = " 10";
    String MSR_Tolerance = " 0.01";
    String SDE_Tolerance = " 1e-4";
    String SDE_dt = " 0.1";
    String paraString = "";
    SolverTaskDescription solverTaskDescription = simTask.getSimulation().getSolverTaskDescription();
    NonspatialStochSimOptions stochOpts = solverTaskDescription.getStochOpt();
    NonspatialStochHybridOptions hybridOpts = solverTaskDescription.getStochHybridOpt();
    if (hybridOpts == null) {
        throw new RuntimeException("expecting StochHybridOptions for solver type " + solverTaskDescription.getSolverDescription().getDisplayLabel());
    }
    epsilon = " " + String.valueOf(hybridOpts.getEpsilon());
    lambda = " " + String.valueOf(hybridOpts.getLambda());
    MSR_Tolerance = " " + String.valueOf(hybridOpts.getMSRTolerance());
    if (solverTaskDescription.getSolverDescription().equals(SolverDescription.HybridMilAdaptive))
        SDE_Tolerance = " " + String.valueOf(hybridOpts.getSDETolerance());
    else
        SDE_Tolerance = "";
    SDE_dt = " " + String.valueOf(solverTaskDescription.getTimeStep().getDefaultTimeStep());
    paraString = epsilon + lambda + MSR_Tolerance + SDE_Tolerance + SDE_dt;
    if (stochOpts.isUseCustomSeed())
        randomNumber = " -R " + String.valueOf(stochOpts.getCustomSeed());
    SolverDescription solverDescription = null;
    if (getIntegratorType() == HybridSolver.EMIntegrator) {
        solverDescription = SolverDescription.HybridEuler;
    } else if (getIntegratorType() == HybridSolver.MilsteinIntegrator) {
        solverDescription = SolverDescription.HybridMilstein;
    } else {
        solverDescription = SolverDescription.HybridMilAdaptive;
    }
    String executableName;
    try {
        executableName = SolverUtilities.getExes(SolverDescription.HybridEuler)[0].getAbsolutePath();
    } catch (IOException e) {
        throw new RuntimeException("failed to get executable for solver " + solverDescription.getDisplayLabel() + ": " + e.getMessage(), e);
    }
    ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(executableName);
    commandList.add(getInputFilename());
    String argumentString = paraString.toLowerCase() + randomNumber + " -OV";
    StringTokenizer st = new StringTokenizer(argumentString);
    while (st.hasMoreTokens()) {
        commandList.add(st.nextToken());
    }
    return commandList.toArray(new String[0]);
}
Also used : StringTokenizer(java.util.StringTokenizer) SolverDescription(cbit.vcell.solver.SolverDescription) NonspatialStochSimOptions(cbit.vcell.solver.NonspatialStochSimOptions) ArrayList(java.util.ArrayList) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) NonspatialStochHybridOptions(cbit.vcell.solver.NonspatialStochHybridOptions) IOException(java.io.IOException)

Example 18 with SolverTaskDescription

use of cbit.vcell.solver.SolverTaskDescription in project vcell by virtualcell.

the class SimulationWorkspace method applyChanges.

/**
 * Insert the method's description here.
 * Creation date: (5/11/2004 3:52:25 PM)
 */
private static String applyChanges(Simulation clonedSimulation, Simulation simulation) {
    // we cannot simply replace the simulation with the clone because of two reasons:
    // major - vetoable listeners are transient, thus not preserved during serialization/deserialization
    // minor - proper refreshing the simulation list would require delete/reinsert which would make it non-trivial to avoid reordering
    String errors = "";
    try {
        simulation.setName(clonedSimulation.getName());
    } catch (java.beans.PropertyVetoException exc) {
        errors += "\n" + exc.getMessage();
    }
    try {
        simulation.setDescription(clonedSimulation.getDescription());
    } catch (java.beans.PropertyVetoException exc) {
        errors += "\n" + exc.getMessage();
    }
    simulation.setMathOverrides(new MathOverrides(simulation, clonedSimulation.getMathOverrides()));
    try {
        simulation.setMeshSpecification(clonedSimulation.getMeshSpecification());
    } catch (java.beans.PropertyVetoException exc) {
        errors += "\n" + exc.getMessage();
    }
    try {
        simulation.setSolverTaskDescription(new SolverTaskDescription(simulation, clonedSimulation.getSolverTaskDescription()));
    } catch (java.beans.PropertyVetoException exc) {
        errors += "\n" + exc.getMessage();
    }
    simulation.setDataProcessingInstructions(clonedSimulation.getDataProcessingInstructions());
    simulation.setIsDirty(true);
    return errors;
}
Also used : MathOverrides(cbit.vcell.solver.MathOverrides) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription)

Example 19 with SolverTaskDescription

use of cbit.vcell.solver.SolverTaskDescription in project vcell by virtualcell.

the class SimulationWorkspace method getEstimatedNumTimePointsForStoch.

private static long getEstimatedNumTimePointsForStoch(SimulationSymbolTable simSymbolTable) {
    Simulation sim = simSymbolTable.getSimulation();
    SolverTaskDescription solverTaskDescription = sim.getSolverTaskDescription();
    TimeBounds tb = solverTaskDescription.getTimeBounds();
    double startTime = tb.getStartingTime();
    double endTime = tb.getEndingTime();
    OutputTimeSpec tSpec = solverTaskDescription.getOutputTimeSpec();
    // hybrid G_E and G_M are fixed time step methods using uniform output time spec
    if (tSpec.isUniform()) {
        double outputTimeStep = ((UniformOutputTimeSpec) tSpec).getOutputTimeStep();
        return (long) ((endTime - startTime) / outputTimeStep);
    }
    double maxProbability = 0;
    SubDomain subDomain = sim.getMathDescription().getSubDomains().nextElement();
    List<VarIniCondition> varInis = subDomain.getVarIniConditions();
    // get all the probability expressions
    ArrayList<Expression> probList = new ArrayList<Expression>();
    for (JumpProcess jp : subDomain.getJumpProcesses()) {
        probList.add(jp.getProbabilityRate());
    }
    // loop through probability expressions
    for (int i = 0; i < probList.size(); i++) {
        try {
            Expression pExp = new Expression(probList.get(i));
            pExp.bindExpression(simSymbolTable);
            pExp = simSymbolTable.substituteFunctions(pExp);
            pExp = pExp.flatten();
            String[] symbols = pExp.getSymbols();
            // substitute stoch vars with it's initial condition expressions
            if (symbols != null) {
                for (int j = 0; symbols != null && j < symbols.length; j++) {
                    for (int k = 0; k < varInis.size(); k++) {
                        if (symbols[j].equals(varInis.get(k).getVar().getName())) {
                            pExp.substituteInPlace(new Expression(symbols[j]), new Expression(varInis.get(k).getIniVal()));
                            break;
                        }
                    }
                }
            }
            pExp = simSymbolTable.substituteFunctions(pExp);
            pExp = pExp.flatten();
            double val = pExp.evaluateConstant();
            if (maxProbability < val) {
                maxProbability = val;
            }
        } catch (ExpressionBindingException e) {
            System.out.println("Cannot estimate the total time points for stochastic simulation!! Due to the reason below...");
            e.printStackTrace();
        } catch (ExpressionException ex) {
            System.out.println("Cannot estimate the total time points for stochastic simulation!! Due to the reason below...");
            ex.printStackTrace();
        } catch (MathException e) {
            System.out.println("Cannot estimate the total time points for stochastic simulation!! Due to the reason below...");
            e.printStackTrace();
        }
    }
    int keepEvery = 1;
    if (tSpec.isDefault()) {
        keepEvery = ((DefaultOutputTimeSpec) tSpec).getKeepEvery();
    }
    // points = (endt-startt)/(t*keepEvery) = (endt - startt)/(keepEvery*1/prob)
    long estimatedPoints = Math.round((tb.getEndingTime() - tb.getStartingTime()) * maxProbability / keepEvery) + 1;
    return estimatedPoints;
}
Also used : VarIniCondition(cbit.vcell.math.VarIniCondition) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) ArrayList(java.util.ArrayList) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ExpressionException(cbit.vcell.parser.ExpressionException) SubDomain(cbit.vcell.math.SubDomain) TimeBounds(cbit.vcell.solver.TimeBounds) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) JumpProcess(cbit.vcell.math.JumpProcess) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription)

Example 20 with SolverTaskDescription

use of cbit.vcell.solver.SolverTaskDescription in project vcell by virtualcell.

the class SimulationWorkspace method checkSimulationParameters.

/**
 * Insert the method's description here.
 * Creation date: (5/11/2004 2:57:10 PM)
 * @return boolean
 * @param simulation cbit.vcell.solver.Simulation
 */
private static boolean checkSimulationParameters(Simulation simulation, Component parent) {
    SimulationSymbolTable simSymbolTable = new SimulationSymbolTable(simulation, 0);
    String errorMessage = null;
    long maxTimepoints = Simulation.MAX_LIMIT_NON_SPATIAL_TIMEPOINTS;
    long warningTimepoints = Simulation.WARNING_NON_SPATIAL_TIMEPOINTS;
    boolean bSpatial = simulation.isSpatial();
    if (bSpatial) {
        maxTimepoints = Simulation.MAX_LIMIT_SPATIAL_TIMEPOINTS;
        warningTimepoints = Simulation.WARNING_SPATIAL_TIMEPOINTS;
    }
    long maxSizeBytes = megabytesToBytes(Simulation.MAX_LIMIT_0DE_MEGABYTES);
    long warningSizeBytes = megabytesToBytes(Simulation.WARNING_0DE_MEGABYTES);
    if (bSpatial) {
        maxSizeBytes = megabytesToBytes(Simulation.MAX_LIMIT_PDE_MEGABYTES);
        warningSizeBytes = megabytesToBytes(Simulation.WARNING_PDE_MEGABYTES);
    } else if (simulation.getMathDescription().isNonSpatialStoch()) {
        maxSizeBytes = megabytesToBytes(Simulation.MAX_LIMIT_STOCH_MEGABYTES);
        warningSizeBytes = megabytesToBytes(Simulation.WARNING_STOCH_MEGABYTES);
    }
    long expectedNumTimePoints = getExpectedNumTimePoints(simulation);
    long expectedSizeBytes = getExpectedSizeBytes(simSymbolTable);
    // 
    // check for error conditions (hard limits on resources) ... Note: each user should have it's own limits (and quotas).
    // 
    SolverTaskDescription solverTaskDescription = simulation.getSolverTaskDescription();
    SolverDescription solverDescription = solverTaskDescription.getSolverDescription();
    if (expectedNumTimePoints > maxTimepoints) {
        errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The simulation has too many timepoints (" + expectedNumTimePoints + ") to be saved, which has exceeded our limit.\n\n" + "maximum saving timepoints limits are:\n" + "     " + Simulation.MAX_LIMIT_NON_SPATIAL_TIMEPOINTS + " for compartmental simulations\n" + "     " + Simulation.MAX_LIMIT_SPATIAL_TIMEPOINTS + " for spatial simulations\n" + "suggested saving timepoints limits are:\n" + "     " + Simulation.WARNING_NON_SPATIAL_TIMEPOINTS + " for compartmental simulations\n" + "     " + Simulation.WARNING_SPATIAL_TIMEPOINTS + " for spatial simulations\n" + "Try saving fewer timepoints\n" + "If you need to exceed the quota, please contact us";
        // not used for multiple stochastic run
        if (solverTaskDescription.getStochOpt() != null && solverTaskDescription.getStochOpt().getNumOfTrials() > 1) {
            errorMessage = null;
        }
    } else if (expectedSizeBytes > maxSizeBytes) {
        errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The simulation's result dataset (" + CodeUtil.humanBytePrint(expectedSizeBytes) + ") is too large, which has exceeded our limit.\n\n" + "maximum size limits are:\n" + "     " + Simulation.MAX_LIMIT_0DE_MEGABYTES + " MB for compartmental ODE simulations\n" + "     " + Simulation.MAX_LIMIT_PDE_MEGABYTES + " MB for spatial simulations\n" + "     " + Simulation.MAX_LIMIT_STOCH_MEGABYTES + " MB for compartmental stochastic simulations\n" + "suggested size limits are:\n" + "     " + Simulation.WARNING_0DE_MEGABYTES + " MB for compartmental ODE simulations\n" + "     " + Simulation.WARNING_PDE_MEGABYTES + " MB for spatial simulations\n" + "     " + Simulation.WARNING_STOCH_MEGABYTES + " MB for compartmental stochastic simulations\n" + "Try saving fewer timepoints or using a smaller mesh (if spatial)\n" + "If you need to exceed the quota, please contact us";
        // not used for multiple stochastic run
        if (solverTaskDescription.getStochOpt() != null && solverTaskDescription.getStochOpt().getNumOfTrials() > 1) {
            errorMessage = null;
        }
    } else if (simulation.getScanCount() > Simulation.MAX_LIMIT_SCAN_JOBS) {
        errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The simulation generates too many simulations (" + simulation.getScanCount() + ") required for parameter scan, which has exceeded our limit.\n\n" + "maximum number of parameter sets is: " + Simulation.MAX_LIMIT_SCAN_JOBS + " \n" + "suggested limit for number of parameter sets is: " + Simulation.WARNING_SCAN_JOBS + " \n" + "Try choosing fewer parameters or reducing the size of scan for each parameter.";
        // not used for multiple stochastic run
        if (simulation.getMathDescription().isNonSpatialStoch() && solverTaskDescription.getStochOpt() != null && solverTaskDescription.getStochOpt().getNumOfTrials() > 1) {
            errorMessage = null;
        }
    } else if (solverDescription.equals(SolverDescription.SundialsPDE)) {
        if (solverTaskDescription.getOutputTimeSpec().isDefault()) {
            DefaultOutputTimeSpec dot = (DefaultOutputTimeSpec) solverTaskDescription.getOutputTimeSpec();
            int maxNumberOfSteps = dot.getKeepEvery() * dot.getKeepAtMost();
            double maximumTimeStep = solverTaskDescription.getTimeStep().getMaximumTimeStep();
            double maxSimTime = maxNumberOfSteps * maximumTimeStep;
            double endingTime = solverTaskDescription.getTimeBounds().getEndingTime();
            if (maxSimTime < endingTime) {
                errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "The maximum possible simulation time (keepEvery * maxTimestep * keepAtMost = " + maxSimTime + ") is less than simulation end time (" + endingTime + ").\n\n" + "You have chosen a variable time step solver and specified a maximum number of time steps of " + maxNumberOfSteps + " (keepEvery*keepAtMost).  " + "Actual time steps are often small, but even if all steps were at the maximum time step of " + maximumTimeStep + ", the simulation end time of " + endingTime + " would not be reached. \n\n" + "Either adjust the parameters or choose the \"Output Interval\" option.";
            }
        }
    } else if (simulation.getMathDescription().isNonSpatialStoch() && !(solverDescription.isNonSpatialStochasticSolver())) {
        // to guarantee stochastic model uses stochastic methods and deterministic model uses ODE/PDE methods.
        errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "Stochastic simulation(s) must use stochastic solver(s).\n" + solverDescription.getDisplayLabel() + " is not a stochastic solver!";
    } else if (!simulation.getMathDescription().isNonSpatialStoch() && (solverDescription.isNonSpatialStochasticSolver())) {
        errorMessage = "Errors in Simulation: '" + simulation.getName() + "'!\n" + "ODE/PDE simulation(s) must use ODE/PDE solver(s).\n" + solverDescription.getDisplayLabel() + " is not a ODE/PDE solver!";
    } else if (simulation.getSolverTaskDescription().getSolverDescription().isChomboSolver()) {
        MeshSpecification meshSpecification = simulation.getMeshSpecification();
        boolean bCellCentered = simulation.hasCellCenteredMesh();
        if (meshSpecification != null && !meshSpecification.isAspectRatioOK(1e-4, bCellCentered)) {
            errorMessage = "Non uniform spatial step is detected. This will affect the accuracy of the solution.\n\n" + "\u0394x=" + meshSpecification.getDx(bCellCentered) + "\n" + "\u0394y=" + meshSpecification.getDy(bCellCentered) + (meshSpecification.getGeometry().getDimension() < 3 ? "" : "\n\u0394z=" + meshSpecification.getDz(bCellCentered));
        }
    } else {
        errorMessage = null;
    }
    if (errorMessage != null) {
        DialogUtils.showErrorDialog(parent, errorMessage);
        return false;
    } else if (simulation.getSolverTaskDescription().getSolverDescription().isChomboSolver()) {
        Geometry geometry = simulation.getMathDescription().getGeometry();
        ChomboMeshValidator meshValidator = new ChomboMeshValidator(geometry, simulation.getSolverTaskDescription().getChomboSolverSpec());
        ChomboMeshRecommendation chomboMeshRecommendation = meshValidator.computeMeshSpecs();
        boolean bValid = chomboMeshRecommendation.validate();
        if (!bValid) {
            String option = DialogUtils.showWarningDialog(parent, "Error", chomboMeshRecommendation.getErrorMessage(), chomboMeshRecommendation.getDialogOptions(), ChomboMeshRecommendation.optionClose);
            if (ChomboMeshRecommendation.optionSuggestions.equals(option)) {
                DialogUtils.showInfoDialog(parent, ChomboMeshRecommendation.optionSuggestions, chomboMeshRecommendation.getMeshSuggestions());
            }
        }
        return bValid;
    } else {
        String warningMessage = null;
        // don't check warning message for stochastic multiple trials, let it run.
        if (simulation.getMathDescription().isNonSpatialStoch() && simulation.getSolverTaskDescription().getStochOpt() != null && simulation.getSolverTaskDescription().getStochOpt().getNumOfTrials() > 1) {
            return true;
        }
        // 
        if (expectedNumTimePoints > warningTimepoints) {
            warningMessage = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "The simulation has large number of saving timepoints (" + expectedNumTimePoints + "), suggested saving timepoints limits are:\n" + "     " + Simulation.WARNING_NON_SPATIAL_TIMEPOINTS + " for compartmental simulations\n" + "     " + Simulation.WARNING_SPATIAL_TIMEPOINTS + " for spatial simulations\n" + "Try saving fewer timepoints";
        } else if (expectedSizeBytes > warningSizeBytes) {
            warningMessage = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "The simulation has large result dataset (" + (expectedSizeBytes / 1000000L) + "MB), suggested size limits are:\n" + "     " + Simulation.WARNING_0DE_MEGABYTES + " MB for compartmental ODE simulations\n" + "     " + Simulation.WARNING_PDE_MEGABYTES + " MB for spatial simulations\n" + "     " + Simulation.WARNING_STOCH_MEGABYTES + " MB for compartmental stochastic simulations\n" + "Try saving fewer timepoints or using a coarser mesh if spatial.";
        } else if (simulation.getScanCount() > Simulation.WARNING_SCAN_JOBS) {
            warningMessage = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "The simulation generates a large number of simulations (" + simulation.getScanCount() + ") required for parameter scan.\n" + "maximum number of parameter sets is: " + Simulation.MAX_LIMIT_SCAN_JOBS + " \n" + "suggested limit for the number of parameter sets is: " + Simulation.WARNING_SCAN_JOBS + " \n" + "Try choosing fewer parameters or reducing the size of scan for each parameter.";
        }
        if (solverDescription.equals(SolverDescription.SundialsPDE)) {
            if (solverTaskDescription.getErrorTolerance().getRelativeErrorTolerance() > 1e-4) {
                String msg = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "Warning: it is not reccomended to use a relative tolerance that is greater than \n1e-4 for " + solverDescription.getDisplayLabel() + ".";
                warningMessage = warningMessage == null ? msg : warningMessage + "\n\n" + msg;
            }
        } else if (solverDescription.isSemiImplicitPdeSolver()) {
            if (solverTaskDescription.getErrorTolerance().getRelativeErrorTolerance() > 1e-8) {
                String msg = "Warnings from Simulation: '" + simulation.getName() + "'!\n" + "Warning: it is not reccomended to use a relative tolerance that is greater than \n1e-8 for " + solverDescription.getDisplayLabel() + ".";
                warningMessage = warningMessage == null ? msg : warningMessage + "\n\n" + msg;
            }
        }
        MeshSpecification meshSpecification = simulation.getMeshSpecification();
        boolean bCellCentered = simulation.hasCellCenteredMesh();
        if (meshSpecification != null && !meshSpecification.isAspectRatioOK(bCellCentered)) {
            warningMessage = (warningMessage == null ? "" : warningMessage + "\n\n") + "Non uniform spatial step is detected. This might affect the accuracy of the solution.\n\n" + "\u0394x=" + meshSpecification.getDx(bCellCentered) + "\n" + "\u0394y=" + meshSpecification.getDy(bCellCentered) + (meshSpecification.getGeometry().getDimension() < 3 ? "" : "\n\u0394z=" + meshSpecification.getDz(bCellCentered));
        }
        if (warningMessage != null) {
            String result = DialogUtils.showWarningDialog(parent, warningMessage + "\n\nDo you want to continue anyway?", new String[] { UserMessage.OPTION_OK, UserMessage.OPTION_CANCEL }, UserMessage.OPTION_OK);
            return (result != null && result.equals(UserMessage.OPTION_OK));
        } else {
            return true;
        }
    }
}
Also used : Geometry(cbit.vcell.geometry.Geometry) ChomboMeshRecommendation(org.vcell.chombo.ChomboMeshValidator.ChomboMeshRecommendation) ChomboMeshValidator(org.vcell.chombo.ChomboMeshValidator) SolverDescription(cbit.vcell.solver.SolverDescription) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec) MeshSpecification(cbit.vcell.solver.MeshSpecification)

Aggregations

SolverTaskDescription (cbit.vcell.solver.SolverTaskDescription)39 DefaultOutputTimeSpec (cbit.vcell.solver.DefaultOutputTimeSpec)13 Simulation (cbit.vcell.solver.Simulation)12 UniformOutputTimeSpec (cbit.vcell.solver.UniformOutputTimeSpec)10 ExpressionException (cbit.vcell.parser.ExpressionException)7 OutputTimeSpec (cbit.vcell.solver.OutputTimeSpec)7 SolverDescription (cbit.vcell.solver.SolverDescription)7 TimeBounds (cbit.vcell.solver.TimeBounds)7 ArrayList (java.util.ArrayList)6 MathException (cbit.vcell.math.MathException)5 ExplicitOutputTimeSpec (cbit.vcell.solver.ExplicitOutputTimeSpec)5 Constant (cbit.vcell.math.Constant)4 SubDomain (cbit.vcell.math.SubDomain)4 Expression (cbit.vcell.parser.Expression)4 NonspatialStochSimOptions (cbit.vcell.solver.NonspatialStochSimOptions)4 SimulationSymbolTable (cbit.vcell.solver.SimulationSymbolTable)4 SolverException (cbit.vcell.solver.SolverException)4 IOException (java.io.IOException)4 BioModel (cbit.vcell.biomodel.BioModel)3 Geometry (cbit.vcell.geometry.Geometry)3