Search in sources :

Example 16 with Simulation

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

the class FRAPStudy method createNewRefBioModel.

public static BioModel createNewRefBioModel(FRAPStudy sourceFrapStudy, String baseDiffusionRate, TimeStep tStep, KeyValue simKey, User owner, FieldDataIdentifierSpec psfFDIS, int startingIndexForRecovery) throws Exception {
    if (owner == null) {
        throw new Exception("Owner is not defined");
    }
    ROI cellROI_2D = sourceFrapStudy.getFrapData().getRoi(FRAPData.VFRAP_ROI_ENUM.ROI_CELL.name());
    Extent extent = sourceFrapStudy.getFrapData().getImageDataset().getExtent();
    TimeBounds timeBounds = FRAPOptData.getEstimatedRefTimeBound(sourceFrapStudy);
    double timeStepVal = FRAPOptData.REFERENCE_DIFF_DELTAT;
    int numX = cellROI_2D.getRoiImages()[0].getNumX();
    int numY = cellROI_2D.getRoiImages()[0].getNumY();
    int numZ = cellROI_2D.getRoiImages().length;
    short[] shortPixels = cellROI_2D.getRoiImages()[0].getPixels();
    byte[] bytePixels = new byte[numX * numY * numZ];
    final byte EXTRACELLULAR_PIXVAL = 0;
    final byte CYTOSOL_PIXVAL = 1;
    for (int i = 0; i < bytePixels.length; i++) {
        if (shortPixels[i] != 0) {
            bytePixels[i] = CYTOSOL_PIXVAL;
        }
    }
    VCImage maskImage;
    try {
        maskImage = new VCImageUncompressed(null, bytePixels, extent, numX, numY, numZ);
    } catch (ImageException e) {
        e.printStackTrace();
        throw new RuntimeException("failed to create mask image for geometry");
    }
    Geometry geometry = new Geometry("geometry", maskImage);
    if (geometry.getGeometrySpec().getNumSubVolumes() != 2) {
        throw new Exception("Cell ROI has no ExtraCellular.");
    }
    int subVolume0PixVal = ((ImageSubVolume) geometry.getGeometrySpec().getSubVolume(0)).getPixelValue();
    geometry.getGeometrySpec().getSubVolume(0).setName((subVolume0PixVal == EXTRACELLULAR_PIXVAL ? EXTRACELLULAR_NAME : CYTOSOL_NAME));
    int subVolume1PixVal = ((ImageSubVolume) geometry.getGeometrySpec().getSubVolume(1)).getPixelValue();
    geometry.getGeometrySpec().getSubVolume(1).setName((subVolume1PixVal == CYTOSOL_PIXVAL ? CYTOSOL_NAME : EXTRACELLULAR_NAME));
    geometry.getGeometrySurfaceDescription().updateAll();
    BioModel bioModel = new BioModel(null);
    bioModel.setName("unnamed");
    Model model = new Model("model");
    bioModel.setModel(model);
    Feature extracellular = model.addFeature(EXTRACELLULAR_NAME);
    Feature cytosol = model.addFeature(CYTOSOL_NAME);
    Membrane plasmaMembrane = model.addMembrane(PLASMAMEMBRANE_NAME);
    String roiDataName = FRAPStudy.ROI_EXTDATA_NAME;
    final int ONE_DIFFUSION_SPECIES_COUNT = 1;
    final int MOBILE_SPECIES_INDEX = 0;
    Expression[] diffusionConstants = new Expression[ONE_DIFFUSION_SPECIES_COUNT];
    Species[] species = new Species[ONE_DIFFUSION_SPECIES_COUNT];
    SpeciesContext[] speciesContexts = new SpeciesContext[ONE_DIFFUSION_SPECIES_COUNT];
    Expression[] initialConditions = new Expression[ONE_DIFFUSION_SPECIES_COUNT];
    // Mobile Species
    diffusionConstants[MOBILE_SPECIES_INDEX] = new Expression(baseDiffusionRate);
    species[MOBILE_SPECIES_INDEX] = new Species(SPECIES_NAME_PREFIX_MOBILE, "Mobile bleachable species");
    speciesContexts[MOBILE_SPECIES_INDEX] = new SpeciesContext(null, species[MOBILE_SPECIES_INDEX].getCommonName(), species[MOBILE_SPECIES_INDEX], cytosol);
    FieldFunctionArguments postBleach_first = new FieldFunctionArguments(roiDataName, "postbleach_first", new Expression(0), VariableType.VOLUME);
    FieldFunctionArguments prebleach_avg = new FieldFunctionArguments(roiDataName, "prebleach_avg", new Expression(0), VariableType.VOLUME);
    Expression expPostBleach_first = new Expression(postBleach_first.infix());
    Expression expPreBleach_avg = new Expression(prebleach_avg.infix());
    initialConditions[MOBILE_SPECIES_INDEX] = Expression.div(expPostBleach_first, expPreBleach_avg);
    SimulationContext simContext = new SimulationContext(bioModel.getModel(), geometry);
    bioModel.addSimulationContext(simContext);
    FeatureMapping cytosolFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(cytosol);
    FeatureMapping extracellularFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(extracellular);
    MembraneMapping plasmaMembraneMapping = (MembraneMapping) simContext.getGeometryContext().getStructureMapping(plasmaMembrane);
    SubVolume cytSubVolume = geometry.getGeometrySpec().getSubVolume(CYTOSOL_NAME);
    SubVolume exSubVolume = geometry.getGeometrySpec().getSubVolume(EXTRACELLULAR_NAME);
    SurfaceClass pmSurfaceClass = geometry.getGeometrySurfaceDescription().getSurfaceClass(exSubVolume, cytSubVolume);
    cytosolFeatureMapping.setGeometryClass(cytSubVolume);
    extracellularFeatureMapping.setGeometryClass(exSubVolume);
    plasmaMembraneMapping.setGeometryClass(pmSurfaceClass);
    cytosolFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    extracellularFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    plasmaMembraneMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    for (int i = 0; i < initialConditions.length; i++) {
        model.addSpecies(species[i]);
        model.addSpeciesContext(speciesContexts[i]);
    }
    for (int i = 0; i < speciesContexts.length; i++) {
        SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(speciesContexts[i]);
        scs.getInitialConditionParameter().setExpression(initialConditions[i]);
        scs.getDiffusionParameter().setExpression(diffusionConstants[i]);
    }
    MathMapping mathMapping = simContext.createNewMathMapping();
    MathDescription mathDesc = mathMapping.getMathDescription();
    // Add PSF function
    mathDesc.addVariable(new Function(Simulation.PSF_FUNCTION_NAME, new Expression(psfFDIS.getFieldFuncArgs().infix()), null));
    simContext.setMathDescription(mathDesc);
    SimulationVersion simVersion = new SimulationVersion(simKey, "sim1", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
    Simulation newSimulation = new Simulation(simVersion, simContext.getMathDescription());
    newSimulation.getSolverTaskDescription().setSolverDescription(SolverDescription.FiniteVolumeStandalone);
    simContext.addSimulation(newSimulation);
    newSimulation.getSolverTaskDescription().setTimeBounds(timeBounds);
    newSimulation.getSolverTaskDescription().setOutputTimeSpec(new UniformOutputTimeSpec(timeStepVal));
    newSimulation.getMeshSpecification().setSamplingSize(cellROI_2D.getISize());
    newSimulation.getSolverTaskDescription().setTimeStep(new TimeStep(timeStepVal, timeStepVal, timeStepVal));
    return bioModel;
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) ImageException(cbit.image.ImageException) KeyValue(org.vcell.util.document.KeyValue) Extent(org.vcell.util.Extent) SurfaceClass(cbit.vcell.geometry.SurfaceClass) MathDescription(cbit.vcell.math.MathDescription) VCImage(cbit.image.VCImage) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) Feature(cbit.vcell.model.Feature) TimeBounds(cbit.vcell.solver.TimeBounds) Function(cbit.vcell.math.Function) GroupAccessNone(org.vcell.util.document.GroupAccessNone) TimeStep(cbit.vcell.solver.TimeStep) SimulationVersion(org.vcell.util.document.SimulationVersion) FeatureMapping(cbit.vcell.mapping.FeatureMapping) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) Membrane(cbit.vcell.model.Membrane) Species(cbit.vcell.model.Species) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) FieldFunctionArguments(cbit.vcell.field.FieldFunctionArguments) VCImageUncompressed(cbit.image.VCImageUncompressed) SimulationContext(cbit.vcell.mapping.SimulationContext) ROI(cbit.vcell.VirtualMicroscopy.ROI) ImageException(cbit.image.ImageException) UserCancelException(org.vcell.util.UserCancelException) 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) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) MathMapping(cbit.vcell.mapping.MathMapping)

Example 17 with Simulation

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

the class MathModel method addNewSimulation.

/**
 * Sets the simulations property (cbit.vcell.solver.Simulation[]) value.
 * @param simulations The new value for the property.
 * @exception java.beans.PropertyVetoException The exception description.
 * @see #getSimulations
 */
public Simulation addNewSimulation(String simNamePrefix) throws java.beans.PropertyVetoException {
    MathDescription math = getMathDescription();
    if (math == null) {
        throw new RuntimeException("Can't create Simulation, math not created");
    }
    // 
    // get free name for new Simulation.
    // 
    Simulation[] sims = getSimulations();
    String newSimName = null;
    for (int i = 0; newSimName == null && i < 100; i++) {
        String proposedName = simNamePrefix + i;
        boolean bFound = false;
        for (int j = 0; sims != null && !bFound && j < sims.length; j++) {
            if (sims[j].getName().equals(proposedName)) {
                bFound = true;
            }
        }
        if (!bFound) {
            newSimName = proposedName;
        }
    }
    if (newSimName == null) {
        throw new RuntimeException("failed to find name for new Simulation");
    }
    // 
    // create new Simulation and add to MathModel.
    // 
    Simulation newSimulation = new Simulation(math);
    newSimulation.setName(newSimName);
    addSimulation(newSimulation);
    return newSimulation;
}
Also used : Simulation(cbit.vcell.solver.Simulation) MathDescription(cbit.vcell.math.MathDescription)

Example 18 with Simulation

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

the class MathModel method createMathModelChildSummary.

public MathModelChildSummary createMathModelChildSummary() {
    MathType modelType = getMathDescription().getMathType();
    String geoName = getMathDescription().getGeometry().getName();
    int geoDim = getMathDescription().getGeometry().getDimension();
    Simulation[] sims = getSimulations();
    String[] simNames = new String[sims.length];
    String[] simAnnots = new String[sims.length];
    for (int i = 0; i < sims.length; i += 1) {
        simNames[i] = sims[i].getName();
        simAnnots[i] = sims[i].getDescription();
    }
    return new MathModelChildSummary(modelType, geoName, geoDim, simNames, simAnnots);
}
Also used : MathModelChildSummary(org.vcell.util.document.MathModelChildSummary) Simulation(cbit.vcell.solver.Simulation) MathType(org.vcell.util.document.BioModelChildSummary.MathType)

Example 19 with Simulation

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

the class ClientRequestManager method stopSimulations.

public void stopSimulations(final ClientSimManager clientSimManager, final Simulation[] simulations) {
    // stop is single step operation, don't bother with tasks, thread inline
    AsynchClientTask task1 = new AsynchClientTask("stopping simulations", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            Hashtable<Simulation, Throwable> failures = new Hashtable<Simulation, Throwable>();
            if (simulations != null && simulations.length > 0) {
                for (int i = 0; i < simulations.length; i++) {
                    try {
                        SimulationInfo simInfo = simulations[i].getSimulationInfo();
                        if (simInfo != null) {
                            // check for running once more... directly from job status
                            SimulationStatus serverSimulationStatus = getServerSimulationStatus(simInfo);
                            if (serverSimulationStatus != null && serverSimulationStatus.numberOfJobsDone() < simulations[i].getScanCount()) {
                                SimulationStatus simStatus = getClientServerManager().getJobManager().stopSimulation(simInfo.getAuthoritativeVCSimulationIdentifier());
                                // updateStatus
                                clientSimManager.updateStatusFromStopRequest(simulations[i], simStatus);
                            }
                        } else {
                            // this should really not happen...
                            throw new RuntimeException(">>>>>>>>>> trying to stop an unsaved simulation...");
                        }
                    } catch (Throwable exc) {
                        exc.printStackTrace(System.out);
                        failures.put(simulations[i], exc);
                    }
                }
                hashTable.put("failures", failures);
            }
        }
    };
    AsynchClientTask task2 = new AsynchClientTask("stopping simulations", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            @SuppressWarnings("unchecked") Hashtable<Simulation, Throwable> failures = (Hashtable<Simulation, Throwable>) hashTable.get("failures");
            if (failures != null && !failures.isEmpty()) {
                Enumeration<Simulation> en = failures.keys();
                while (en.hasMoreElements()) {
                    Simulation sim = (Simulation) en.nextElement();
                    Throwable exc = (Throwable) failures.get(sim);
                    // notify user
                    PopupGenerator.showErrorDialog(clientSimManager.getDocumentWindowManager(), "Failed to dispatch stop request for simulation'" + sim.getName() + "'\n" + exc.getMessage(), exc);
                }
            }
        }
    };
    ClientTaskDispatcher.dispatch(clientSimManager.getDocumentWindowManager().getComponent(), new Hashtable<String, Object>(), new AsynchClientTask[] { task1, task2 });
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Hashtable(java.util.Hashtable) Simulation(cbit.vcell.solver.Simulation) SimulationStatus(cbit.vcell.server.SimulationStatus) CSGObject(cbit.vcell.geometry.CSGObject) SimulationInfo(cbit.vcell.solver.SimulationInfo)

Example 20 with Simulation

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

the class ClientSimManager method runSmoldynParticleView.

public void runSmoldynParticleView(final Simulation originalSimulation) {
    SimulationOwner simulationOwner = simWorkspace.getSimulationOwner();
    Collection<AsynchClientTask> tasks;
    if (simulationOwner instanceof SimulationContext) {
        tasks = ClientRequestManager.updateMath(documentWindowManager.getComponent(), (SimulationContext) simulationOwner, false, NetworkGenerationRequirements.ComputeFullStandardTimeout);
    } else {
        tasks = new ArrayList<>();
    }
    AsynchClientTask pv = new AsynchClientTask("starting particle view", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            File[] exes = SolverUtilities.getExes(SolverDescription.Smoldyn);
            assert exes.length == 1 : "one and only one smoldyn solver expected";
            File smoldynExe = exes[0];
            Simulation simulation = new TempSimulation(originalSimulation, false);
            SimulationTask simTask = new SimulationTask(new SimulationJob(simulation, 0, null), 0);
            File inputFile = new File(ResourceUtil.getLocalSimDir(User.tempUser.getName()), simTask.getSimulationJobID() + SimDataConstants.SMOLDYN_INPUT_FILE_EXTENSION);
            inputFile.deleteOnExit();
            PrintWriter pw = new PrintWriter(inputFile);
            SmoldynFileWriter smf = new SmoldynFileWriter(pw, true, null, simTask, false);
            smf.write();
            pw.close();
            String[] cmd = new String[] { smoldynExe.getAbsolutePath(), inputFile.getAbsolutePath() };
            StringBuilder commandLine = new StringBuilder();
            for (int i = 0; i < cmd.length; i++) {
                if (i > 0) {
                    commandLine.append(" ");
                }
                commandLine.append(TokenMangler.getEscapedPathName(cmd[i]));
            }
            System.out.println(commandLine);
            char[] charArrayOut = new char[10000];
            char[] charArrayErr = new char[10000];
            ProcessBuilder processBuilder = new ProcessBuilder(cmd);
            final Process process = processBuilder.start();
            getClientTaskStatusSupport().addProgressDialogListener(new ProgressDialogListener() {

                public void cancelButton_actionPerformed(EventObject newEvent) {
                    process.destroy();
                }
            });
            InputStream errorStream = process.getErrorStream();
            InputStreamReader errisr = new InputStreamReader(errorStream);
            InputStream outputStream = process.getInputStream();
            InputStreamReader outisr = new InputStreamReader(outputStream);
            StringBuilder sb = new StringBuilder();
            boolean running = true;
            while (running) {
                try {
                    process.exitValue();
                    running = false;
                } catch (IllegalThreadStateException e) {
                // process didn't exit yet, do nothing
                }
                if (outputStream.available() > 0) {
                    outisr.read(charArrayOut, 0, charArrayOut.length);
                }
                if (errorStream.available() > 0) {
                    errisr.read(charArrayErr, 0, charArrayErr.length);
                    sb.append(new String(charArrayErr));
                }
            }
            if (sb.length() > 0) {
                throw new RuntimeException(sb.toString());
            }
        }
    };
    tasks.add(pv);
    ClientTaskDispatcher.dispatchColl(documentWindowManager.getComponent(), new Hashtable<String, Object>(), tasks, false, true, null);
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) SimulationTask(cbit.vcell.messaging.server.SimulationTask) SmoldynFileWriter(org.vcell.solver.smoldyn.SmoldynFileWriter) SimulationOwner(cbit.vcell.solver.SimulationOwner) ProgressDialogListener(org.vcell.util.ProgressDialogListener) SimulationJob(cbit.vcell.solver.SimulationJob) PrintWriter(java.io.PrintWriter) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) InputStream(java.io.InputStream) TempSimulation(cbit.vcell.solver.TempSimulation) SimulationContext(cbit.vcell.mapping.SimulationContext) EventObject(java.util.EventObject) Simulation(cbit.vcell.solver.Simulation) TempSimulation(cbit.vcell.solver.TempSimulation) EventObject(java.util.EventObject) File(java.io.File)

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