Search in sources :

Example 66 with Simulation

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

the class BioModelTreePanel method actionsOnClick.

/**
 * Comment
 */
private void actionsOnClick(MouseEvent mouseEvent) {
    DefaultMutableTreeNode currentTreeSelection = (DefaultMutableTreeNode) getJTree2().getLastSelectedPathComponent();
    Object selectedObject = null;
    if (currentTreeSelection == null) {
        return;
    }
    selectedObject = currentTreeSelection.getUserObject();
    // double click
    if (mouseEvent.getClickCount() == 2) {
        if (selectedObject instanceof SimulationContext) {
            fireActionPerformed(new ActionEvent(this, mouseEvent.getID(), GuiConstants.ACTIONCMD_OPEN_APPLICATION, mouseEvent.getModifiers()));
        } else if (selectedObject instanceof Annotation) {
            editAnnotation();
        } else if (selectedObject instanceof MathDescription) {
            fireActionPerformed(new ActionEvent(this, mouseEvent.getID(), GuiConstants.ACTIONCMD_OPEN_APPLICATION_MATH, mouseEvent.getModifiers()));
        } else if (selectedObject instanceof Geometry) {
            fireActionPerformed(new ActionEvent(this, mouseEvent.getID(), GuiConstants.ACTIONCMD_OPEN_APPLICATION_GEOMETRY, mouseEvent.getModifiers()));
        } else if (selectedObject instanceof Simulation) {
            fireActionPerformed(new ActionEvent(this, mouseEvent.getID(), GuiConstants.ACTIONCMD_OPEN_APPLICATION_SIMULATION, mouseEvent.getModifiers()));
        } else if (selectedObject instanceof MathType) {
            // deterministic or stochastic or rule-bsaed
            fireActionPerformed(new ActionEvent(this, mouseEvent.getID(), GuiConstants.ACTIONCMD_OPEN_APPLICATION_DETSTOCH, mouseEvent.getModifiers()));
        }
        return;
    }
    // right click
    if (mouseEvent.isPopupTrigger()) {
        Point mousePoint = mouseEvent.getPoint();
        if (selectedObject instanceof BioModel) {
            getBioModelPopupMenu().show(getJTree2(), mousePoint.x, mousePoint.y);
        } else if (selectedObject instanceof SimulationContext) {
            getAppPopupMenu().show(getJTree2(), mousePoint.x, mousePoint.y);
        } else if (selectedObject instanceof Simulation) {
            getSimPopupMenu().show(getJTree2(), mousePoint.x, mousePoint.y);
        }
        if (selectedObject instanceof Annotation) {
            getEditAnnotationPopupMenu().show(getJTree2(), mousePoint.x, mousePoint.y);
        }
    }
}
Also used : Geometry(cbit.vcell.geometry.Geometry) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) Simulation(cbit.vcell.solver.Simulation) MathDescription(cbit.vcell.math.MathDescription) ActionEvent(java.awt.event.ActionEvent) BioModel(cbit.vcell.biomodel.BioModel) MathType(org.vcell.util.document.BioModelChildSummary.MathType) Point(java.awt.Point) SimulationContext(cbit.vcell.mapping.SimulationContext)

Example 67 with Simulation

use of cbit.vcell.solver.Simulation 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 68 with Simulation

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

the class RunRefSimulationFastOp method runRefSimulation.

private RowColumnResultSet runRefSimulation(ROI cellROI, ROI[] imageDataROIs, UShortImage psf, FloatImage initRefConc, double experimentalRecoveryTime, LocalWorkspace localWorkspace, ClientTaskStatusSupport progressListener) throws Exception {
    User owner = LocalWorkspace.getDefaultOwner();
    KeyValue simKey = LocalWorkspace.createNewKeyValue();
    // 
    // save first image from normalized time series as the initial concentration field data
    // 
    ExternalDataInfo initialConcentrationExtData = createNewExternalDataInfo(localWorkspace, INITCONC_EXTDATA_NAME);
    Extent extent = initRefConc.getExtent();
    Origin origin = initRefConc.getOrigin();
    ISize isize = new ISize(initRefConc.getNumX(), initRefConc.getNumY(), initRefConc.getNumZ());
    saveExternalData(initRefConc, INITCONC_EXTDATA_VARNAME, initialConcentrationExtData.getExternalDataIdentifier(), localWorkspace);
    FieldFunctionArguments initConditionFFA = new FieldFunctionArguments(INITCONC_EXTDATA_NAME, INITCONC_EXTDATA_VARNAME, new Expression(0.0), VariableType.VOLUME);
    // 
    // save ROIs as a multivariate field data
    // 
    ExternalDataInfo roiExtData = createNewExternalDataInfo(localWorkspace, ROI_EXTDATA_NAME);
    saveROIsAsExternalData(imageDataROIs, localWorkspace, roiExtData.getExternalDataIdentifier());
    ArrayList<FieldFunctionArguments> roiFFAs = new ArrayList<FieldFunctionArguments>();
    for (ROI roi : imageDataROIs) {
        roiFFAs.add(new FieldFunctionArguments(ROI_EXTDATA_NAME, ROI_MASK_NAME_PREFIX + roi.getROIName(), new Expression(0.0), VariableType.VOLUME));
    }
    // 
    // save PSF as a field data
    // 
    ExternalDataInfo psfExtData = createNewExternalDataInfo(localWorkspace, PSF_EXTDATA_NAME);
    savePsfAsExternalData(psf, PSF_EXTDATA_VARNAME, psfExtData.getExternalDataIdentifier(), localWorkspace);
    FieldFunctionArguments psfFFA = new FieldFunctionArguments(PSF_EXTDATA_NAME, PSF_EXTDATA_VARNAME, new Expression(0.0), VariableType.VOLUME);
    TimeBounds timeBounds = getEstimatedRefTimeBound(experimentalRecoveryTime);
    double timeStepVal = REFERENCE_DIFF_DELTAT;
    Expression chirpedDiffusionRate = new Expression(REFERENCE_DIFF_RATE_COEFFICIENT + "*(t+" + REFERENCE_DIFF_DELTAT + ")");
    BioModel bioModel = createRefSimBioModel(simKey, owner, origin, extent, cellROI, timeStepVal, timeBounds, VAR_NAME, new Expression(initConditionFFA.infix()), psfFFA, chirpedDiffusionRate);
    if (progressListener != null) {
        progressListener.setMessage("Running Reference Simulation...");
    }
    // run simulation
    Simulation simulation = bioModel.getSimulation(0);
    ROIDataGenerator roiDataGenerator = getROIDataGenerator(localWorkspace, imageDataROIs);
    simulation.getMathDescription().getPostProcessingBlock().addDataGenerator(roiDataGenerator);
    runFVSolverStandalone(new File(localWorkspace.getDefaultSimDataDirectory()), simulation, initialConcentrationExtData.getExternalDataIdentifier(), roiExtData.getExternalDataIdentifier(), psfExtData.getExternalDataIdentifier(), progressListener, true);
    KeyValue referenceSimKeyValue = simulation.getVersion().getVersionKey();
    VCSimulationIdentifier vcSimID = new VCSimulationIdentifier(referenceSimKeyValue, LocalWorkspace.getDefaultOwner());
    VCSimulationDataIdentifier vcSimDataID = new VCSimulationDataIdentifier(vcSimID, 0);
    File hdf5File = new File(localWorkspace.getDefaultSimDataDirectory(), vcSimDataID.getID() + SimDataConstants.DATA_PROCESSING_OUTPUT_EXTENSION_HDF5);
    // get post processing info (time points, variable sizes)
    DataOperation.DataProcessingOutputInfoOP dataOperationInfo = new DataOperation.DataProcessingOutputInfoOP(null, /*no vcDataIdentifier OK*/
    false, null);
    DataOperationResults.DataProcessingOutputInfo dataProcessingOutputInfo = (DataOperationResults.DataProcessingOutputInfo) DataSetControllerImpl.getDataProcessingOutput(dataOperationInfo, hdf5File);
    // get post processing data
    DataOperation.DataProcessingOutputDataValuesOP dataOperationDataValues = new DataOperation.DataProcessingOutputDataValuesOP(null, /*no vcDataIdentifier OK*/
    ROI_EXTDATA_NAME, TimePointHelper.createAllTimeTimePointHelper(), DataIndexHelper.createSliceDataIndexHelper(0), null, null);
    DataOperationResults.DataProcessingOutputDataValues dataProcessingOutputDataValues = (DataOperationResults.DataProcessingOutputDataValues) DataSetControllerImpl.getDataProcessingOutput(dataOperationDataValues, hdf5File);
    // 
    // delete the simulation files
    // 
    // 
    // remove reference simulation files and field data files
    // 
    File userDir = new File(localWorkspace.getDefaultSimDataDirectory());
    File[] oldSimFilesToDelete = getSimulationFileNames(userDir, referenceSimKeyValue);
    for (int i = 0; oldSimFilesToDelete != null && i < oldSimFilesToDelete.length; i++) {
        oldSimFilesToDelete[i].delete();
    }
    deleteCanonicalExternalData(localWorkspace, initialConcentrationExtData.getExternalDataIdentifier());
    deleteCanonicalExternalData(localWorkspace, roiExtData.getExternalDataIdentifier());
    deleteCanonicalExternalData(localWorkspace, roiExtData.getExternalDataIdentifier());
    // get ref sim time points (distorted by time dilation acceleration)
    double[] rawRefDataTimePoints = dataProcessingOutputInfo.getVariableTimePoints();
    // get shifted time points
    double[] correctedRefDataTimePoints = shiftTimeForBaseDiffRate(rawRefDataTimePoints);
    double[][] refData = dataProcessingOutputDataValues.getDataValues();
    // 
    // for rowColumnResultSet with { "t", "roi1", .... , "roiN" } for reference data
    // 
    int numROIs = imageDataROIs.length;
    String[] columnNames = new String[numROIs + 1];
    columnNames[0] = "t";
    for (int i = 0; i < numROIs; i++) {
        columnNames[i + 1] = imageDataROIs[i].getROIName();
    }
    RowColumnResultSet reducedData = new RowColumnResultSet(columnNames);
    for (int i = 0; i < correctedRefDataTimePoints.length; i++) {
        double[] row = new double[numROIs + 1];
        row[0] = correctedRefDataTimePoints[i];
        double[] roiData = refData[i];
        for (int j = 0; j < numROIs; j++) {
            // roiData[0] is the average over the cell .. postbleach this shouldn't change for pure diffusion
            row[j + 1] = roiData[j + 1];
        }
        reducedData.addRow(row);
    }
    return reducedData;
}
Also used : Origin(org.vcell.util.Origin) VCSimulationIdentifier(cbit.vcell.solver.VCSimulationIdentifier) User(org.vcell.util.document.User) KeyValue(org.vcell.util.document.KeyValue) Extent(org.vcell.util.Extent) ISize(org.vcell.util.ISize) ArrayList(java.util.ArrayList) TimeBounds(cbit.vcell.solver.TimeBounds) RowColumnResultSet(cbit.vcell.math.RowColumnResultSet) DataOperation(cbit.vcell.simdata.DataOperation) ExternalDataInfo(org.vcell.vmicro.workflow.data.ExternalDataInfo) FieldFunctionArguments(cbit.vcell.field.FieldFunctionArguments) ROI(cbit.vcell.VirtualMicroscopy.ROI) VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) ROIDataGenerator(org.vcell.vmicro.workflow.data.ROIDataGenerator) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) DataOperationResults(cbit.vcell.simdata.DataOperationResults) File(java.io.File)

Example 69 with Simulation

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

the class KenworthyParticleTest method generateFakeData.

private static ImageTimeSeries<UShortImage> generateFakeData(LocalWorkspace localWorkspace, ClientTaskStatusSupport progressListener) throws Exception {
    // 
    // technical simulation parameters
    // 
    double deltaX = 0.3;
    double outputTimeStep = 0.3;
    // 
    // circular 2D cell geometry
    // 
    double cellRadius = 50.0;
    String extracellularName = "ec";
    String cytosolName = "cytosol";
    // 
    // bleaching experimental protocol
    // 
    double bleachRadius = 1.5;
    double bleachDuration = 0.003;
    double bleachRate = 500.0;
    double postbleachDelay = 0.001;
    double postbleachDuration = 25.0;
    double psfSigma = 0.01;
    // 
    // underlying physiological model
    // 
    double primaryDiffusionRate = 2.0;
    double primaryFraction = 1.0;
    double bleachMonitorRate = 0.0000005;
    double secondaryDiffusionRate = 0.0;
    double secondaryFraction = 0.0;
    // 
    // generate corresponding BioModel with Application and Simulation ready for simulation.
    // 
    Context context = new Context() {

        @Override
        public User getDefaultOwner() {
            return LocalWorkspace.getDefaultOwner();
        }

        @Override
        public KeyValue createNewKeyValue() {
            return LocalWorkspace.createNewKeyValue();
        }
    };
    GeneratedModelResults results = new Generate2DExpModel_GaussianBleachOp().generateModel(deltaX, bleachRadius, cellRadius, bleachDuration, bleachRate, postbleachDelay, postbleachDuration, psfSigma, outputTimeStep, primaryDiffusionRate, primaryFraction, bleachMonitorRate, secondaryDiffusionRate, secondaryFraction, extracellularName, cytosolName, context);
    Simulation simulation = results.simulation_2D;
    double bleachBlackoutStartTime = results.bleachBlackoutBeginTime;
    double bleachBlackoutStopTime = results.bleachBlackoutEndTime;
    // 
    // run simulation to get simulated fluorescence (with noise)
    // 
    boolean hasNoise = true;
    double maxIntensity = 60000.0;
    ImageTimeSeries<UShortImage> simulatedFluorescence = new RunFakeSimOp().runRefSimulation(localWorkspace, simulation, maxIntensity, bleachBlackoutStartTime, bleachBlackoutStopTime, hasNoise, progressListener);
    return simulatedFluorescence;
}
Also used : OptContext(org.vcell.vmicro.workflow.data.OptContext) Context(org.vcell.vmicro.op.Generate2DExpModelOpAbstract.Context) RunFakeSimOp(org.vcell.vmicro.op.RunFakeSimOp) Simulation(cbit.vcell.solver.Simulation) GeneratedModelResults(org.vcell.vmicro.op.Generate2DExpModelOpAbstract.GeneratedModelResults) Generate2DExpModel_GaussianBleachOp(org.vcell.vmicro.op.Generate2DExpModel_GaussianBleachOp) UShortImage(cbit.vcell.VirtualMicroscopy.UShortImage)

Example 70 with Simulation

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

the class NagiosVCellMonitor method checkVCell.

private CheckResults checkVCell(VCELL_CHECK_LEVEL checkLevel, String rmiHostName, int rmiPort, String rmiBootstrapStubName, String vcellNagiosPassword, int criticalTimeout, int monitorPort) throws Exception {
    SimulationStatusPersistent lastSimStatus = null;
    String vcellVersion = null;
    TreeMap<VCELL_CHECK_LEVEL, Long> levelTimesMillisec = new TreeMap<NagiosVCellMonitor.VCELL_CHECK_LEVEL, Long>();
    long startTime = System.currentTimeMillis();
    VCellConnection vcellConnection = null;
    try {
        if (rmiHostName == null || rmiPort == -1) {
            throw new UnexpectedTestStateException("Host name/ip and rmiPort required for testing, rmihostname=" + rmiHostName + " rmiport=" + rmiPort);
        }
        String rmiUrl = "//" + rmiHostName + ":" + rmiPort + "/" + rmiBootstrapStubName;
        VCellBootstrap vcellBootstrap = null;
        try {
            vcellBootstrap = (VCellBootstrap) Naming.lookup(rmiUrl);
        } catch (Exception e) {
            throw new UnexpectedTestStateException("Error during bootstrap lookup, " + e.getClass().getSimpleName() + " " + e.getMessage());
        }
        vcellVersion = vcellBootstrap.getVCellSoftwareVersion();
        levelTimesMillisec.put(VCELL_CHECK_LEVEL.RMI_ONLY_0, System.currentTimeMillis() - startTime);
        if (checkLevel.ordinal() >= VCELL_CHECK_LEVEL.CONNECT_1.ordinal()) {
            if (vcellNagiosPassword == null) {
                throw new UnexpectedTestStateException("vcellNagios Password required for " + VCELL_CHECK_LEVEL.CONNECT_1.toString() + " and above");
            }
            UserLoginInfo userLoginInfo = new UserLoginInfo(VCELL_NAGIOS_USER, new DigestedPassword(vcellNagiosPassword));
            vcellConnection = vcellBootstrap.getVCellConnection(userLoginInfo);
            levelTimesMillisec.put(VCELL_CHECK_LEVEL.CONNECT_1, System.currentTimeMillis() - startTime - levelTimesMillisec.get(VCELL_CHECK_LEVEL.RMI_ONLY_0));
            if (checkLevel.ordinal() >= VCELL_CHECK_LEVEL.INFOS_2.ordinal()) {
                VCInfoContainer vcInfoContainer = vcellConnection.getUserMetaDbServer().getVCInfoContainer();
                levelTimesMillisec.put(VCELL_CHECK_LEVEL.INFOS_2, System.currentTimeMillis() - startTime - levelTimesMillisec.get(VCELL_CHECK_LEVEL.CONNECT_1));
                if (checkLevel.ordinal() >= VCELL_CHECK_LEVEL.LOAD_3.ordinal()) {
                    KeyValue bioModelKey = null;
                    final String testModelName = "Solver Suite 5.1 (BETA only ode)";
                    for (BioModelInfo bioModelInfo : vcInfoContainer.getBioModelInfos()) {
                        if (userLoginInfo.getUserName().equals(bioModelInfo.getVersion().getOwner().getName()) && bioModelInfo.getVersion().getName().equals(testModelName)) {
                            bioModelKey = bioModelInfo.getVersion().getVersionKey();
                            break;
                        }
                    }
                    BigString bioModelXML = vcellConnection.getUserMetaDbServer().getBioModelXML(bioModelKey);
                    BioModel bioModel = XmlHelper.XMLToBioModel(new XMLSource(bioModelXML.toString()));
                    bioModel.refreshDependencies();
                    levelTimesMillisec.put(VCELL_CHECK_LEVEL.LOAD_3, System.currentTimeMillis() - startTime - levelTimesMillisec.get(VCELL_CHECK_LEVEL.INFOS_2));
                    if (checkLevel.ordinal() >= VCELL_CHECK_LEVEL.DATA_4.ordinal()) {
                        final String testSimContextName = "non-spatial ODE";
                        SimulationContext simulationContext = bioModel.getSimulationContext(testSimContextName);
                        final String testSimName = "Copy of combined ida/cvode";
                        Simulation simulation = simulationContext.getSimulation(testSimName);
                        if (simulation == null) {
                            throw new UnexpectedTestStateException("Couldn't find sim '" + testSimName + "' for " + checkLevel.toString());
                        }
                        VCSimulationDataIdentifier vcSimulationDataIdentifier = new VCSimulationDataIdentifier(simulation.getSimulationInfo().getAuthoritativeVCSimulationIdentifier(), 0);
                        ArrayList<AnnotatedFunction> outputFunctionsList = simulationContext.getOutputFunctionContext().getOutputFunctionsList();
                        OutputContext outputContext = new OutputContext(outputFunctionsList.toArray(new AnnotatedFunction[outputFunctionsList.size()]));
                        double[] times = vcellConnection.getDataSetController().getDataSetTimes(vcSimulationDataIdentifier);
                        ODESimData odeSimData = vcellConnection.getDataSetController().getODEData(vcSimulationDataIdentifier);
                        levelTimesMillisec.put(VCELL_CHECK_LEVEL.DATA_4, System.currentTimeMillis() - startTime - levelTimesMillisec.get(VCELL_CHECK_LEVEL.LOAD_3));
                        if (checkLevel.ordinal() >= VCELL_CHECK_LEVEL.RUN_5.ordinal()) {
                            KeyValue copy1Key = null;
                            KeyValue copy2Key = null;
                            VCSimulationIdentifier testRunSimID = null;
                            try {
                                if (simulationContext.getSimulations().length != 1) {
                                    throw new UnexpectedTestStateException("Expecting only 1 sim to be copied for " + checkLevel.toString());
                                }
                                SimulationStatusPersistent simulationStatus = vcellConnection.getUserMetaDbServer().getSimulationStatus(simulation.getVersion().getVersionKey());
                                if (!simulationStatus.isCompleted()) {
                                    throw new UnexpectedTestStateException("Expecting completed sim to copy for " + checkLevel.toString());
                                }
                                String copyModelName = testModelName + "_" + rmiHostName + "_rmi" + rmiPort + "_siteprt" + monitorPort;
                                boolean bForceCleanup = true;
                                while (true) {
                                    boolean bMessy = false;
                                    for (BioModelInfo bioModelInfo : vcInfoContainer.getBioModelInfos()) {
                                        if (userLoginInfo.getUserName().equals(bioModelInfo.getVersion().getOwner().getName()) && bioModelInfo.getVersion().getName().equals(copyModelName)) {
                                            bMessy = true;
                                            if (bForceCleanup) {
                                                try {
                                                    vcellConnection.getUserMetaDbServer().deleteBioModel(bioModelInfo.getVersion().getVersionKey());
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            } else {
                                                throw new MessyTestEnvironmentException("Messy test environment, not expecting " + copyModelName + " and couldn't cleanup");
                                            }
                                        }
                                    }
                                    if (!bMessy) {
                                        break;
                                    }
                                    // get new vcInfoContainer without cleaned-up model
                                    vcInfoContainer = vcellConnection.getUserMetaDbServer().getVCInfoContainer();
                                    bForceCleanup = false;
                                }
                                BigString copyBioModelXMLStr = vcellConnection.getUserMetaDbServer().saveBioModelAs(bioModelXML, copyModelName, null);
                                BioModel copyBioModel = XmlHelper.XMLToBioModel(new XMLSource(copyBioModelXMLStr.toString()));
                                copy1Key = copyBioModel.getVersion().getVersionKey();
                                copyBioModel.refreshDependencies();
                                Simulation copySim = copyBioModel.getSimulationContext(testSimContextName).copySimulation(copyBioModel.getSimulationContext(testSimContextName).getSimulation(testSimName));
                                final String copyTestSimName = "test";
                                copySim.setName(copyTestSimName);
                                copyBioModel.refreshDependencies();
                                copyBioModelXMLStr = new BigString(XmlHelper.bioModelToXML(copyBioModel));
                                copyBioModelXMLStr = vcellConnection.getUserMetaDbServer().saveBioModel(copyBioModelXMLStr, null);
                                copyBioModel = XmlHelper.XMLToBioModel(new XMLSource(copyBioModelXMLStr.toString()));
                                copy2Key = copyBioModel.getVersion().getVersionKey();
                                copyBioModel.refreshDependencies();
                                Simulation newSimulation = copyBioModel.getSimulationContext(testSimContextName).getSimulation(copyTestSimName);
                                simulationStatus = vcellConnection.getUserMetaDbServer().getSimulationStatus(newSimulation.getVersion().getVersionKey());
                                if (simulationStatus != null && !simulationStatus.isNeverRan()) {
                                    throw new UnexpectedTestStateException("Expecting new sim to have 'never ran' status for " + checkLevel.toString());
                                }
                                testRunSimID = new VCSimulationIdentifier(newSimulation.getVersion().getVersionKey(), copyBioModel.getVersion().getOwner());
                                vcellConnection.getSimulationController().startSimulation(testRunSimID, 1);
                                lastSimStatus = simulationStatus;
                                MessageEvent[] messageEvents = null;
                                while (simulationStatus == null || (!simulationStatus.isStopped() && !simulationStatus.isCompleted() && !simulationStatus.isFailed())) {
                                    Thread.sleep(200);
                                    if (((System.currentTimeMillis() - startTime) / 1000) > criticalTimeout) {
                                        vcellConnection.getSimulationController().stopSimulation(testRunSimID);
                                        vcellConnection.getMessageEvents();
                                        break;
                                    }
                                    simulationStatus = vcellConnection.getUserMetaDbServer().getSimulationStatus(newSimulation.getVersion().getVersionKey());
                                    if (simulationStatus != null && !simulationStatus.toString().equals((lastSimStatus == null ? null : lastSimStatus.toString()))) {
                                        lastSimStatus = simulationStatus;
                                    }
                                    if (simulationStatus != null && simulationStatus.isFailed()) {
                                        throw new Exception("time " + ((System.currentTimeMillis() - startTime) / 1000) + ", Sim execution failed key:" + testRunSimID.getSimulationKey() + " sim " + newSimulation.getName() + " model " + copyBioModel.getVersion().getName() + " messg " + simulationStatus.getFailedMessage());
                                    }
                                    messageEvents = vcellConnection.getMessageEvents();
                                }
                            } finally {
                                try {
                                    if (copy1Key != null) {
                                        vcellConnection.getUserMetaDbServer().deleteBioModel(copy1Key);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                try {
                                    if (copy2Key != null) {
                                        vcellConnection.getUserMetaDbServer().deleteBioModel(copy2Key);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (testRunSimID != null) {
                                    deleteSimData(testRunSimID);
                                }
                            }
                            levelTimesMillisec.put(VCELL_CHECK_LEVEL.RUN_5, System.currentTimeMillis() - startTime - levelTimesMillisec.get(VCELL_CHECK_LEVEL.DATA_4));
                        }
                    }
                }
            }
        }
        return new CheckResults(vcellVersion, levelTimesMillisec, lastSimStatus, System.currentTimeMillis() - startTime, null);
    } catch (Exception e) {
        return new CheckResults(vcellVersion, levelTimesMillisec, lastSimStatus, System.currentTimeMillis() - startTime, e);
    } finally {
        vcellConnection = null;
    }
}
Also used : VCSimulationIdentifier(cbit.vcell.solver.VCSimulationIdentifier) KeyValue(org.vcell.util.document.KeyValue) MessageEvent(cbit.rmi.event.MessageEvent) VCellBootstrap(cbit.vcell.server.VCellBootstrap) BigString(org.vcell.util.BigString) ODESimData(cbit.vcell.solver.ode.ODESimData) DigestedPassword(org.vcell.util.document.UserLoginInfo.DigestedPassword) BigString(org.vcell.util.BigString) VCInfoContainer(org.vcell.util.document.VCInfoContainer) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) VCellConnection(cbit.vcell.server.VCellConnection) BioModelInfo(org.vcell.util.document.BioModelInfo) SimulationStatusPersistent(cbit.vcell.server.SimulationStatusPersistent) TreeMap(java.util.TreeMap) SimulationContext(cbit.vcell.mapping.SimulationContext) VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) IOException(java.io.IOException) OutputContext(cbit.vcell.simdata.OutputContext) Simulation(cbit.vcell.solver.Simulation) BioModel(cbit.vcell.biomodel.BioModel) UserLoginInfo(org.vcell.util.document.UserLoginInfo) XMLSource(cbit.vcell.xml.XMLSource)

Aggregations

Simulation (cbit.vcell.solver.Simulation)195 SimulationContext (cbit.vcell.mapping.SimulationContext)57 BioModel (cbit.vcell.biomodel.BioModel)53 MathDescription (cbit.vcell.math.MathDescription)48 KeyValue (org.vcell.util.document.KeyValue)33 Geometry (cbit.vcell.geometry.Geometry)29 MathModel (cbit.vcell.mathmodel.MathModel)27 Expression (cbit.vcell.parser.Expression)26 DataAccessException (org.vcell.util.DataAccessException)26 File (java.io.File)25 ExpressionException (cbit.vcell.parser.ExpressionException)24 IOException (java.io.IOException)24 SimulationJob (cbit.vcell.solver.SimulationJob)23 ArrayList (java.util.ArrayList)23 PropertyVetoException (java.beans.PropertyVetoException)20 UniformOutputTimeSpec (cbit.vcell.solver.UniformOutputTimeSpec)18 XMLSource (cbit.vcell.xml.XMLSource)18 SimulationTask (cbit.vcell.messaging.server.SimulationTask)17 TimeBounds (cbit.vcell.solver.TimeBounds)16 BigString (org.vcell.util.BigString)16