Search in sources :

Example 46 with SimulationContext

use of cbit.vcell.mapping.SimulationContext 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 47 with SimulationContext

use of cbit.vcell.mapping.SimulationContext 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)

Example 48 with SimulationContext

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

the class HybridBioModelVisitor method setBioModel.

public void setBioModel(BioModel bioModel, PrintWriter pw) {
    currentModel = bioModel;
    applications.clear();
    SimulationContext[] scs = currentModel.getSimulationContexts();
    for (SimulationContext sc : scs) {
        if (isSpatialStoch(sc.getSimulations())) {
            applications.add(sc);
        }
    }
    assert !applications.isEmpty();
    moreStates = true;
    currentAppIndex = -1;
    incrementApp();
}
Also used : SimulationContext(cbit.vcell.mapping.SimulationContext)

Example 49 with SimulationContext

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

the class BatchTester method batchScanBioModels.

@SuppressWarnings("static-access")
public void batchScanBioModels(VCMultiBioVisitor databaseVisitor, String statusTable, int chunkSize) throws DataAccessException, XmlParseException, SQLException, IOException {
    PrintStream current = System.out;
    // System.setOut(new PrintStream(new NullStream()));
    try {
        String processHostId = ManagementFactory.getRuntimeMXBean().getName();
        String filename = processHostId + ".txt";
        FileOutputStream fos = new FileOutputStream(filename);
        System.setOut(new PrintStream(fos));
        OutputStreamWriter writer = new OutputStreamWriter(fos);
        // autoflush
        PrintWriter printWriter = new PrintWriter(writer, true);
        Connection conn = connFactory.getConnection(null);
        conn.setAutoCommit(true);
        printWriter.println("reserving slots");
        try (Statement statement = conn.createStatement()) {
            String query = "Update " + statusTable + " set scan_process = '" + processHostId + "', log_file = '" + filename + "' where scanned = 0 and scan_process is null and rownum <= " + chunkSize;
            int uCount = statement.executeUpdate(query);
            if (uCount > chunkSize) {
                throw new Error("logic / SQL bad");
            }
            if (uCount == 0) {
                printWriter.println("No models to scan, exiting");
                System.exit(100);
            }
        }
        printWriter.println("finding  ours");
        ArrayList<BioModelIdent> models = new ArrayList<BatchTester.BioModelIdent>();
        try (Statement statement = conn.createStatement()) {
            String query = "Select id, user_id, model_id from " + statusTable + " where scan_process ='" + processHostId + "' and scanned = 0";
            ResultSet rs = statement.executeQuery(query);
            while (rs.next()) {
                BioModelIdent mi = new BioModelIdent(rs);
                models.add(mi);
                printWriter.println("claiming " + mi.statusId);
            }
        }
        try {
            // start visiting models and writing log
            printWriter.println("Start scanning bio-models......");
            printWriter.println("\n");
            PreparedStatement ps = conn.prepareStatement("Update " + statusTable + " set scanned = 1, good = ? , exception_type = ?, exception = ?, scan_process = null where id = ?");
            for (BioModelIdent modelIdent : models) {
                ScanStatus scanStatus = ScanStatus.PASS;
                String exceptionMessage = null;
                String exceptionClass = null;
                try {
                    User user = new User("", convert(modelIdent.userId));
                    KeyValue modelKey = convert(modelIdent.modelId);
                    BigString bioModelXML = null;
                    // seconds
                    long dbSleepTime = 10;
                    while (bioModelXML == null) {
                        try {
                            bioModelXML = dbServerImpl.getBioModelXML(user, modelKey);
                        } catch (DataAccessException dae) {
                            Throwable cause = dae.getCause();
                            if (cause.getClass().getSimpleName().equals("UniversalConnectionPoolException")) {
                                printWriter.println("No db connection for  " + modelIdent.statusId + ", sleeping " + dbSleepTime + " seconds");
                                Thread.currentThread().sleep(dbSleepTime * 1000);
                                // wait a little longer next time
                                dbSleepTime *= 1.5;
                            } else {
                                // other exception, just rethrow
                                throw dae;
                            }
                        }
                    }
                    BioModel storedModel = cbit.vcell.xml.XmlHelper.XMLToBioModel(new XMLSource(bioModelXML.toString()));
                    if (databaseVisitor.filterBioModel(storedModel)) {
                        storedModel.refreshDependencies();
                        boolean goodModel = verifyMathDescriptionsUnchanged(storedModel, printWriter);
                        if (goodModel) {
                            printWriter.println("Model for " + modelIdent.statusId + " good");
                            databaseVisitor.setBioModel(storedModel, printWriter);
                            for (BioModel bioModel : databaseVisitor) {
                                SimulationContext[] simContexts = bioModel.getSimulationContexts();
                                for (SimulationContext sc : simContexts) {
                                    // try {
                                    // long start = System.currentTimeMillis();
                                    sc.createNewMathMapping().getMathDescription();
                                // long end = System.currentTimeMillis();
                                // printWriter.println("mapping took " + (end - start)/1000.0 + " sec ");
                                /*
									} catch (Exception e) {
										//printWriter.println("\t " + bioModel.getName() + " :: " + sc.getName() + " ----> math regeneration failed.s");
										// e.printStackTrace();
									}
											 */
                                }
                            }
                        } else {
                            throw new MathRegenFail();
                        }
                    } else {
                        scanStatus = ScanStatus.FILTERED;
                    }
                } catch (Exception e) {
                    lg.error(e.getMessage(), e);
                    scanStatus = ScanStatus.FAIL;
                    exceptionClass = e.getClass().getName();
                    exceptionMessage = e.getMessage();
                    printWriter.println("failed " + modelIdent.statusId);
                    e.printStackTrace(printWriter);
                }
                ps.setInt(1, scanStatus.code);
                ps.setString(2, exceptionClass);
                ps.setString(3, exceptionMessage);
                ps.setLong(4, modelIdent.statusId);
                boolean estat = ps.execute();
                if (estat) {
                    throw new Error("logic");
                }
                int uc = ps.getUpdateCount();
                if (uc != 1) {
                    throw new Error("logic / sql ");
                }
            }
        } catch (Exception e) {
            e.printStackTrace(printWriter);
        }
        printWriter.close();
    } finally {
        System.setOut(current);
    }
}
Also used : User(org.vcell.util.document.User) KeyValue(org.vcell.util.document.KeyValue) ArrayList(java.util.ArrayList) BigString(org.vcell.util.BigString) BigString(org.vcell.util.BigString) ResultSet(java.sql.ResultSet) DataAccessException(org.vcell.util.DataAccessException) PrintWriter(java.io.PrintWriter) PrintStream(java.io.PrintStream) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) SimulationContext(cbit.vcell.mapping.SimulationContext) SQLException(java.sql.SQLException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) FileOutputStream(java.io.FileOutputStream) BioModel(cbit.vcell.biomodel.BioModel) OutputStreamWriter(java.io.OutputStreamWriter) XMLSource(cbit.vcell.xml.XMLSource)

Example 50 with SimulationContext

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

the class Generate2DExpModelOpAbstract method generateModel.

public final GeneratedModelResults generateModel(double deltaX, double bleachRadius, double cellRadius, double bleachDuration, double bleachRate, double postbleachDelay, double postbleachDuration, double psfSigma, double outputTimeStep, double primaryDiffusionRate, double primaryFraction, double bleachMonitorRate, double secondaryDiffusionRate, double secondaryFraction, String extracellularName, String cytosolName, Context context) throws PropertyVetoException, ExpressionException, GeometryException, ImageException, ModelException, MappingException, MathException, MatrixException {
    double domainSize = 2.2 * cellRadius;
    Extent extent = new Extent(domainSize, domainSize, 1.0);
    Origin origin = new Origin(-extent.getX() / 2.0, -extent.getY() / 2.0, -extent.getZ() / 2.0);
    String EXTRACELLULAR_NAME = extracellularName;
    String CYTOSOL_NAME = cytosolName;
    AnalyticSubVolume cytosolSubVolume = new AnalyticSubVolume(CYTOSOL_NAME, new Expression("pow(x,2)+pow(y,2)<pow(" + cellRadius + ",2)"));
    AnalyticSubVolume extracellularSubVolume = new AnalyticSubVolume(EXTRACELLULAR_NAME, new Expression(1.0));
    Geometry geometry = new Geometry("geometry", 2);
    geometry.getGeometrySpec().setExtent(extent);
    geometry.getGeometrySpec().setOrigin(origin);
    geometry.getGeometrySpec().addSubVolume(extracellularSubVolume);
    geometry.getGeometrySpec().addSubVolume(cytosolSubVolume, true);
    geometry.getGeometrySurfaceDescription().updateAll();
    BioModel bioModel = new BioModel(null);
    bioModel.setName("unnamed");
    Model model = new Model("model");
    bioModel.setModel(model);
    model.addFeature(EXTRACELLULAR_NAME);
    Feature extracellular = (Feature) model.getStructure(EXTRACELLULAR_NAME);
    model.addFeature(CYTOSOL_NAME);
    Feature cytosol = (Feature) model.getStructure(CYTOSOL_NAME);
    SpeciesContext immobileSC = model.createSpeciesContext(cytosol);
    SpeciesContext primarySC = model.createSpeciesContext(cytosol);
    SpeciesContext secondarySC = model.createSpeciesContext(cytosol);
    // 
    // common bleaching rate for all species
    // 
    double bleachStart = 10 * outputTimeStep - bleachDuration - postbleachDelay;
    double bleachEnd = bleachStart + bleachDuration;
    Expression bleachRateExp = createBleachExpression(bleachRadius, bleachRate, bleachMonitorRate, bleachStart, bleachEnd);
    {
        SimpleReaction immobileBWM = model.createSimpleReaction(cytosol);
        GeneralKinetics immobileBWMKinetics = new GeneralKinetics(immobileBWM);
        immobileBWM.setKinetics(immobileBWMKinetics);
        immobileBWM.addReactant(immobileSC, 1);
        immobileBWMKinetics.getReactionRateParameter().setExpression(Expression.mult(bleachRateExp, new Expression(immobileSC.getName())));
    }
    {
        SimpleReaction primaryBWM = model.createSimpleReaction(cytosol);
        GeneralKinetics primaryBWMKinetics = new GeneralKinetics(primaryBWM);
        primaryBWM.setKinetics(primaryBWMKinetics);
        primaryBWM.addReactant(primarySC, 1);
        primaryBWMKinetics.getReactionRateParameter().setExpression(Expression.mult(bleachRateExp, new Expression(primarySC.getName())));
    }
    {
        SimpleReaction secondaryBWM = model.createSimpleReaction(cytosol);
        GeneralKinetics secondaryBWMKinetics = new GeneralKinetics(secondaryBWM);
        secondaryBWM.setKinetics(secondaryBWMKinetics);
        secondaryBWM.addReactant(secondarySC, 1);
        secondaryBWMKinetics.getReactionRateParameter().setExpression(Expression.mult(bleachRateExp, new Expression(secondarySC.getName())));
    }
    // create simulation context
    SimulationContext simContext = bioModel.addNewSimulationContext("simContext", SimulationContext.Application.NETWORK_DETERMINISTIC);
    simContext.setGeometry(geometry);
    FeatureMapping cytosolFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(cytosol);
    FeatureMapping extracellularFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(extracellular);
    SubVolume cytSubVolume = geometry.getGeometrySpec().getSubVolume(CYTOSOL_NAME);
    SubVolume exSubVolume = geometry.getGeometrySpec().getSubVolume(EXTRACELLULAR_NAME);
    // unused? SurfaceClass pmSurfaceClass = geometry.getGeometrySurfaceDescription().getSurfaceClass(exSubVolume, cytSubVolume);
    cytosolFeatureMapping.setGeometryClass(cytSubVolume);
    extracellularFeatureMapping.setGeometryClass(exSubVolume);
    cytosolFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    extracellularFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    double fixedFraction = 1.0 - primaryFraction - secondaryFraction;
    SpeciesContextSpec immobileSCS = simContext.getReactionContext().getSpeciesContextSpec(immobileSC);
    immobileSCS.getInitialConditionParameter().setExpression(new Expression(fixedFraction));
    immobileSCS.getDiffusionParameter().setExpression(new Expression(0.0));
    SpeciesContextSpec primarySCS = simContext.getReactionContext().getSpeciesContextSpec(primarySC);
    primarySCS.getInitialConditionParameter().setExpression(new Expression(primaryFraction));
    primarySCS.getDiffusionParameter().setExpression(new Expression(primaryDiffusionRate));
    SpeciesContextSpec secondarySCS = simContext.getReactionContext().getSpeciesContextSpec(secondarySC);
    secondarySCS.getInitialConditionParameter().setExpression(new Expression(secondaryFraction));
    secondarySCS.getDiffusionParameter().setExpression(new Expression(secondaryDiffusionRate));
    simContext.getMicroscopeMeasurement().addFluorescentSpecies(immobileSC);
    simContext.getMicroscopeMeasurement().addFluorescentSpecies(primarySC);
    simContext.getMicroscopeMeasurement().addFluorescentSpecies(secondarySC);
    simContext.getMicroscopeMeasurement().setConvolutionKernel(new GaussianConvolutionKernel(new Expression(psfSigma), new Expression(psfSigma)));
    MathMapping mathMapping = simContext.createNewMathMapping();
    MathDescription mathDesc = mathMapping.getMathDescription();
    simContext.setMathDescription(mathDesc);
    User owner = context.getDefaultOwner();
    int meshSize = (int) (domainSize / deltaX);
    if (meshSize % 2 == 0) {
        // want an odd-sized mesh in x and y ... so centered at the origin.
        meshSize = meshSize + 1;
    }
    TimeBounds timeBounds = new TimeBounds(0.0, postbleachDuration);
    // 
    // simulation to use for data generation (output time steps as recorded by the microscope)
    // 
    double bleachBlackoutBegin = bleachStart - postbleachDelay;
    double bleachBlackoutEnd = bleachEnd + postbleachDelay;
    // ArrayList<Double> times = new ArrayList<Double>();
    // double time = 0;
    // while (time<=timeBounds.getEndingTime()){
    // if (time<=bleachBlackoutBegin || time>bleachBlackoutEnd){
    // // postbleachDelay is the time it takes to switch the filters.
    // times.add(time);
    // }
    // time += outputTimeStep.getData();
    // }
    // double[] timeArray = new double[times.size()];
    // for (int i=0;i<timeArray.length;i++){
    // timeArray[i] = times.get(i);
    // }
    // OutputTimeSpec fakeDataSimOutputTimeSpec = new ExplicitOutputTimeSpec(timeArray);
    OutputTimeSpec fakeDataSimOutputTimeSpec = new UniformOutputTimeSpec(outputTimeStep);
    KeyValue fakeDataSimKey = context.createNewKeyValue();
    SimulationVersion fakeDataSimVersion = new SimulationVersion(fakeDataSimKey, "fakeDataSim", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
    Simulation fakeDataSim = new Simulation(fakeDataSimVersion, mathDesc);
    simContext.addSimulation(fakeDataSim);
    fakeDataSim.getSolverTaskDescription().setTimeBounds(timeBounds);
    fakeDataSim.getMeshSpecification().setSamplingSize(new ISize(meshSize, meshSize, 1));
    fakeDataSim.getSolverTaskDescription().setSolverDescription(SolverDescription.SundialsPDE);
    fakeDataSim.getSolverTaskDescription().setOutputTimeSpec(fakeDataSimOutputTimeSpec);
    // 
    // simulation to use for viewing the protocol (output time steps to understand the physics)
    // 
    KeyValue fullExperimentSimKey = context.createNewKeyValue();
    SimulationVersion fullExperimentSimVersion = new SimulationVersion(fullExperimentSimKey, "fullExperiment", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
    Simulation fullExperimentSim = new Simulation(fullExperimentSimVersion, mathDesc);
    simContext.addSimulation(fullExperimentSim);
    OutputTimeSpec fullExperimentOutputTimeSpec = new UniformOutputTimeSpec(outputTimeStep / 10.0);
    fullExperimentSim.getSolverTaskDescription().setTimeBounds(timeBounds);
    fullExperimentSim.getMeshSpecification().setSamplingSize(new ISize(meshSize, meshSize, 1));
    fullExperimentSim.getSolverTaskDescription().setSolverDescription(SolverDescription.SundialsPDE);
    fullExperimentSim.getSolverTaskDescription().setOutputTimeSpec(fullExperimentOutputTimeSpec);
    GeneratedModelResults results = new GeneratedModelResults();
    results.bioModel_2D = bioModel;
    results.simulation_2D = fakeDataSim;
    results.bleachBlackoutBeginTime = bleachBlackoutBegin;
    results.bleachBlackoutEndTime = bleachBlackoutEnd;
    return results;
}
Also used : Origin(org.vcell.util.Origin) User(org.vcell.util.document.User) KeyValue(org.vcell.util.document.KeyValue) Extent(org.vcell.util.Extent) MathDescription(cbit.vcell.math.MathDescription) ISize(org.vcell.util.ISize) SpeciesContext(cbit.vcell.model.SpeciesContext) GeneralKinetics(cbit.vcell.model.GeneralKinetics) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) Feature(cbit.vcell.model.Feature) TimeBounds(cbit.vcell.solver.TimeBounds) GroupAccessNone(org.vcell.util.document.GroupAccessNone) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) SimulationVersion(org.vcell.util.document.SimulationVersion) FeatureMapping(cbit.vcell.mapping.FeatureMapping) SubVolume(cbit.vcell.geometry.SubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) SimpleReaction(cbit.vcell.model.SimpleReaction) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) SimulationContext(cbit.vcell.mapping.SimulationContext) GaussianConvolutionKernel(cbit.vcell.mapping.MicroscopeMeasurement.GaussianConvolutionKernel) BigDecimal(java.math.BigDecimal) Date(java.util.Date) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) BioModel(cbit.vcell.biomodel.BioModel) Model(cbit.vcell.model.Model) MathMapping(cbit.vcell.mapping.MathMapping) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume)

Aggregations

SimulationContext (cbit.vcell.mapping.SimulationContext)181 BioModel (cbit.vcell.biomodel.BioModel)73 Simulation (cbit.vcell.solver.Simulation)57 MathDescription (cbit.vcell.math.MathDescription)32 Geometry (cbit.vcell.geometry.Geometry)29 PropertyVetoException (java.beans.PropertyVetoException)28 MathModel (cbit.vcell.mathmodel.MathModel)25 Model (cbit.vcell.model.Model)25 KeyValue (org.vcell.util.document.KeyValue)25 SpeciesContextSpec (cbit.vcell.mapping.SpeciesContextSpec)23 ArrayList (java.util.ArrayList)23 DataAccessException (org.vcell.util.DataAccessException)23 XMLSource (cbit.vcell.xml.XMLSource)22 XmlParseException (cbit.vcell.xml.XmlParseException)22 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)20 Expression (cbit.vcell.parser.Expression)20 ExpressionException (cbit.vcell.parser.ExpressionException)19 SpeciesContext (cbit.vcell.model.SpeciesContext)17 Structure (cbit.vcell.model.Structure)17 IOException (java.io.IOException)17