Search in sources :

Example 1 with TempSimulation

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

the class SimulationServiceImpl method computeModel.

private SimulationInfo computeModel(BioModel bioModel, SimulationSpec simSpec, ClientTaskStatusSupport statusCallback) {
    try {
        SimulationContext simContext = bioModel.getSimulationContext(0);
        MathMappingCallback callback = new MathMappingCallbackTaskAdapter(statusCallback);
        Simulation newsim = simContext.addNewSimulation(SimulationOwner.DEFAULT_SIM_NAME_PREFIX, callback, NetworkGenerationRequirements.AllowTruncatedStandardTimeout);
        SimulationInfo simulationInfo = new SimulationInfo();
        simulationInfo.setId(Math.abs(new Random().nextInt(1000000)));
        // ----------- run simulation(s)
        final File localSimDataDir = ResourceUtil.getLocalSimDir(User.tempUser.getName());
        Simulation simulation = new TempSimulation(newsim, false);
        final SimulationServiceContext simServiceContext = new SimulationServiceContext();
        simServiceContext.simInfo = simulationInfo;
        simServiceContext.simState = SimulationState.running;
        simServiceContext.simTask = new SimulationTask(new SimulationJob(simulation, 0, null), 0);
        simServiceContext.vcDataIdentifier = simServiceContext.simTask.getSimulationJob().getVCDataIdentifier();
        simServiceContext.solver = createQuickRunSolver(localSimDataDir, simServiceContext.simTask);
        simServiceContext.localSimDataDir = localSimDataDir;
        if (simServiceContext.solver == null) {
            throw new RuntimeException("null solver");
        }
        sims.put(simulationInfo.id, simServiceContext);
        simServiceContext.solver.addSolverListener(new SolverListener() {

            public void solverStopped(SolverEvent event) {
                simServiceContext.simState = SimulationState.failed;
                System.err.println("Simulation stopped");
            }

            public void solverStarting(SolverEvent event) {
                simServiceContext.simState = SimulationState.running;
                updateStatus(event);
            }

            public void solverProgress(SolverEvent event) {
                simServiceContext.simState = SimulationState.running;
                updateStatus(event);
            }

            public void solverPrinted(SolverEvent event) {
                simServiceContext.simState = SimulationState.running;
            }

            public void solverFinished(SolverEvent event) {
                try {
                    getDataSetController(simServiceContext).getDataSetTimes(simServiceContext.vcDataIdentifier);
                    simServiceContext.simState = SimulationState.done;
                } catch (DataAccessException e) {
                    simServiceContext.simState = SimulationState.failed;
                    e.printStackTrace();
                }
                updateStatus(event);
            }

            public void solverAborted(SolverEvent event) {
                simServiceContext.simState = SimulationState.failed;
                System.err.println(event.getSimulationMessage().getDisplayMessage());
            }

            private void updateStatus(SolverEvent event) {
                if (statusCallback == null)
                    return;
                statusCallback.setMessage(event.getSimulationMessage().getDisplayMessage());
                statusCallback.setProgress((int) (event.getProgress() * 100));
            }
        });
        simServiceContext.solver.startSolver();
        return simServiceContext.simInfo;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        // remember the exceptiopn ... fail the status ... save the error message
        return new SimulationInfo().setId(1);
    }
}
Also used : MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) SimulationTask(cbit.vcell.messaging.server.SimulationTask) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) TempSimulation(cbit.vcell.solver.TempSimulation) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLStreamException(javax.xml.stream.XMLStreamException) ThriftDataAccessException(org.vcell.vcellij.api.ThriftDataAccessException) SbmlException(org.vcell.sbml.SbmlException) SBMLException(org.sbml.jsbml.SBMLException) XmlParseException(cbit.vcell.xml.XmlParseException) SolverException(cbit.vcell.solver.SolverException) TException(org.apache.thrift.TException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) SolverEvent(cbit.vcell.solver.server.SolverEvent) Simulation(cbit.vcell.solver.Simulation) TempSimulation(cbit.vcell.solver.TempSimulation) Random(java.util.Random) SolverListener(cbit.vcell.solver.server.SolverListener) File(java.io.File) SimulationJob(cbit.vcell.solver.SimulationJob) ThriftDataAccessException(org.vcell.vcellij.api.ThriftDataAccessException) DataAccessException(org.vcell.util.DataAccessException) SimulationInfo(org.vcell.vcellij.api.SimulationInfo)

Example 2 with TempSimulation

use of cbit.vcell.solver.TempSimulation 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)

Example 3 with TempSimulation

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

the class StochtestRunService method runsolver.

private static void runsolver(Simulation newSimulation, File baseDirectory, int numRuns, TimeSeriesMultitrialData timeSeriesMultitrialData) {
    Simulation versSimulation = null;
    File destDir = null;
    boolean bTimeout = false;
    // int progress = 1;
    for (int trialIndex = 0; trialIndex < numRuns; trialIndex++) {
        System.out.println("\n=====================================\n\nStarting trial " + (trialIndex + 1) + " of " + numRuns + "\n\n==============================\n");
        long startTime = System.currentTimeMillis();
        // }
        try {
            versSimulation = new TempSimulation(newSimulation, false);
            // printout(ruleBasedTestDir.getAbsolutePath());
            destDir = new File(baseDirectory, timeSeriesMultitrialData.datasetName);
            SimulationTask simTask = new SimulationTask(new SimulationJob(versSimulation, 0, null), 0);
            Solver solver = ClientSimManager.createQuickRunSolver(destDir, simTask);
            solver.startSolver();
            while (true) {
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (System.currentTimeMillis() - startTime > 30 * 1000) {
                    // timeout after 30 seconds .. otherwise multiple runs will take forever
                    bTimeout = true;
                    solver.stopSolver();
                    throw new RuntimeException("timed out");
                }
                SolverStatus solverStatus = solver.getSolverStatus();
                if (solverStatus != null) {
                    if (solverStatus.getStatus() == SolverStatus.SOLVER_ABORTED) {
                        throw new RuntimeException(solverStatus.getSimulationMessage().getDisplayMessage());
                    }
                    if (solverStatus.getStatus() != SolverStatus.SOLVER_STARTING && solverStatus.getStatus() != SolverStatus.SOLVER_READY && solverStatus.getStatus() != SolverStatus.SOLVER_RUNNING) {
                        break;
                    }
                }
            }
            SimulationData simData = new SimulationData(simTask.getSimulationJob().getVCDataIdentifier(), destDir, null, null);
            ODEDataBlock odeDataBlock = simData.getODEDataBlock();
            ODESimData odeSimData = odeDataBlock.getODESimData();
            timeSeriesMultitrialData.addDataSet(odeSimData, trialIndex);
        } catch (Exception e) {
            e.printStackTrace();
            File file = new File(baseDirectory, Simulation.createSimulationID(versSimulation.getKey()) + "_solverExc.txt");
            StochtestFileUtils.writeMessageTofile(file, e.getMessage());
            if (bTimeout) {
                throw new RuntimeException("timed out");
            } else {
                throw new RuntimeException("solver failed : " + e.getMessage(), e);
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        StochtestFileUtils.clearDir(destDir);
    }
// printout("\n");
}
Also used : Solver(cbit.vcell.solver.server.Solver) SimulationTask(cbit.vcell.messaging.server.SimulationTask) TempSimulation(cbit.vcell.solver.TempSimulation) ODESimData(cbit.vcell.solver.ode.ODESimData) PropertyVetoException(java.beans.PropertyVetoException) SQLException(java.sql.SQLException) XmlParseException(cbit.vcell.xml.XmlParseException) ImageException(cbit.image.ImageException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) GeometryException(cbit.vcell.geometry.GeometryException) TempSimulation(cbit.vcell.solver.TempSimulation) Simulation(cbit.vcell.solver.Simulation) SimulationData(cbit.vcell.simdata.SimulationData) ODEDataBlock(cbit.vcell.simdata.ODEDataBlock) File(java.io.File) SolverStatus(cbit.vcell.solver.server.SolverStatus) SimulationJob(cbit.vcell.solver.SimulationJob)

Example 4 with TempSimulation

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

the class ClientSimManager method runQuickSimulation.

public void runQuickSimulation(final Simulation originalSimulation, ViewerType viewerType) {
    Collection<AsynchClientTask> taskList = new ArrayList<AsynchClientTask>();
    final SimulationOwner simulationOwner = simWorkspace.getSimulationOwner();
    // ----------- update math if it is from biomodel (simulationContext)
    if (simulationOwner instanceof SimulationContext) {
        Collection<AsynchClientTask> ut = ClientRequestManager.updateMath(documentWindowManager.getComponent(), ((SimulationContext) simulationOwner), false, NetworkGenerationRequirements.ComputeFullStandardTimeout);
        taskList.addAll(ut);
    }
    // ----------- run simulation(s)
    final File localSimDataDir = ResourceUtil.getLocalSimDir(User.tempUser.getName());
    AsynchClientTask runSimTask = new AsynchClientTask("running simulation", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            Simulation simulation = new TempSimulation(originalSimulation, false);
            SimulationTask simTask = new SimulationTask(new SimulationJob(simulation, 0, null), 0);
            Solver solver = createQuickRunSolver(localSimDataDir, simTask);
            if (solver == null) {
                throw new RuntimeException("null solver");
            }
            // check if spatial stochastic simulation (smoldyn solver) has data processing instructions with field data - need to access server for field data, so cannot do local simulation run.
            if (solver instanceof SmoldynSolver) {
                DataProcessingInstructions dpi = simulation.getDataProcessingInstructions();
                if (dpi != null) {
                    FieldDataIdentifierSpec fdis = dpi.getSampleImageFieldData(simulation.getVersion().getOwner());
                    if (fdis != null) {
                        throw new RuntimeException("Spatial Stochastic simulation '" + simulation.getName() + "' (Smoldyn solver) with field data (in data processing instructions) cannot be run locally at this time since field data needs to be retrieved from the VCell server.");
                    }
                }
            }
            solver.addSolverListener(new SolverListener() {

                public void solverStopped(SolverEvent event) {
                    getClientTaskStatusSupport().setMessage(event.getSimulationMessage().getDisplayMessage());
                }

                public void solverStarting(SolverEvent event) {
                    String displayMessage = event.getSimulationMessage().getDisplayMessage();
                    System.out.println(displayMessage);
                    getClientTaskStatusSupport().setMessage(displayMessage);
                    if (displayMessage.equals(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INIT.getDisplayMessage())) {
                        getClientTaskStatusSupport().setProgress(75);
                    } else if (displayMessage.equals(SimulationMessage.MESSAGE_SOLVER_RUNNING_INPUT_FILE.getDisplayMessage())) {
                        getClientTaskStatusSupport().setProgress(90);
                    }
                }

                public void solverProgress(SolverEvent event) {
                    getClientTaskStatusSupport().setMessage("Running...");
                    int progress = (int) (event.getProgress() * 100);
                    getClientTaskStatusSupport().setProgress(progress);
                }

                public void solverPrinted(SolverEvent event) {
                    getClientTaskStatusSupport().setMessage("Running...");
                }

                public void solverFinished(SolverEvent event) {
                    getClientTaskStatusSupport().setMessage(event.getSimulationMessage().getDisplayMessage());
                }

                public void solverAborted(SolverEvent event) {
                    getClientTaskStatusSupport().setMessage(event.getSimulationMessage().getDisplayMessage());
                }
            });
            solver.startSolver();
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
                if (getClientTaskStatusSupport().isInterrupted()) {
                    solver.stopSolver();
                    throw UserCancelException.CANCEL_GENERIC;
                }
                SolverStatus solverStatus = solver.getSolverStatus();
                if (solverStatus != null) {
                    if (solverStatus.getStatus() == SolverStatus.SOLVER_ABORTED) {
                        throw new RuntimeException(solverStatus.getSimulationMessage().getDisplayMessage());
                    }
                    if (solverStatus.getStatus() != SolverStatus.SOLVER_STARTING && solverStatus.getStatus() != SolverStatus.SOLVER_READY && solverStatus.getStatus() != SolverStatus.SOLVER_RUNNING) {
                        break;
                    }
                }
            }
            ArrayList<AnnotatedFunction> outputFunctionsList = getSimWorkspace().getSimulationOwner().getOutputFunctionContext().getOutputFunctionsList();
            OutputContext outputContext = new OutputContext(outputFunctionsList.toArray(new AnnotatedFunction[outputFunctionsList.size()]));
            Simulation[] simsArray = new Simulation[] { simulation };
            hashTable.put("outputContext", outputContext);
            hashTable.put("simsArray", simsArray);
        }
    };
    taskList.add(runSimTask);
    // --------- add tasks from showSimResults : retrieve data, display results
    AsynchClientTask[] showResultsTask = showSimulationResults0(true, viewerType);
    for (AsynchClientTask task : showResultsTask) {
        taskList.add(task);
    }
    // ------- dispatch
    AsynchClientTask[] taskArray = new AsynchClientTask[taskList.size()];
    taskList.toArray(taskArray);
    ClientTaskDispatcher.dispatch(documentWindowManager.getComponent(), new Hashtable<String, Object>(), taskArray, true, true, null);
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) SmoldynSolver(org.vcell.solver.smoldyn.SmoldynSolver) Solver(cbit.vcell.solver.server.Solver) SimulationTask(cbit.vcell.messaging.server.SimulationTask) ArrayList(java.util.ArrayList) SimulationOwner(cbit.vcell.solver.SimulationOwner) DataProcessingInstructions(cbit.vcell.solver.DataProcessingInstructions) SolverListener(cbit.vcell.solver.server.SolverListener) SolverStatus(cbit.vcell.solver.server.SolverStatus) SimulationJob(cbit.vcell.solver.SimulationJob) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Hashtable(java.util.Hashtable) TempSimulation(cbit.vcell.solver.TempSimulation) SimulationContext(cbit.vcell.mapping.SimulationContext) OutputContext(cbit.vcell.simdata.OutputContext) SolverEvent(cbit.vcell.solver.server.SolverEvent) Simulation(cbit.vcell.solver.Simulation) TempSimulation(cbit.vcell.solver.TempSimulation) FieldDataIdentifierSpec(cbit.vcell.field.FieldDataIdentifierSpec) SmoldynSolver(org.vcell.solver.smoldyn.SmoldynSolver) EventObject(java.util.EventObject) File(java.io.File)

Example 5 with TempSimulation

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

the class RuleBasedTest method runsolver.

// private static void printout(String printThis){
// System.out.flush();
// disableSystemOut(false);
// System.out.print(printThis);
// System.out.flush();
// disableSystemOut(true);
// }
private static void runsolver(Simulation newSimulation, File baseDirectory, int numRuns, TimeSeriesMultitrialData timeSeriesMultitrialData) {
    Simulation versSimulation = null;
    File destDir = null;
    // int progress = 1;
    for (int trialIndex = 0; trialIndex < numRuns; trialIndex++) {
        // }
        try {
            versSimulation = new TempSimulation(newSimulation, false);
            // printout(ruleBasedTestDir.getAbsolutePath());
            destDir = new File(baseDirectory, timeSeriesMultitrialData.datasetName);
            SimulationTask simTask = new SimulationTask(new SimulationJob(versSimulation, 0, null), 0);
            Solver solver = ClientSimManager.createQuickRunSolver(destDir, simTask);
            solver.startSolver();
            while (true) {
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                SolverStatus solverStatus = solver.getSolverStatus();
                if (solverStatus != null) {
                    if (solverStatus.getStatus() == SolverStatus.SOLVER_ABORTED) {
                        throw new RuntimeException(solverStatus.getSimulationMessage().getDisplayMessage());
                    }
                    if (solverStatus.getStatus() != SolverStatus.SOLVER_STARTING && solverStatus.getStatus() != SolverStatus.SOLVER_READY && solverStatus.getStatus() != SolverStatus.SOLVER_RUNNING) {
                        break;
                    }
                }
            }
            SimulationData simData = new SimulationData(simTask.getSimulationJob().getVCDataIdentifier(), destDir, null, null);
            ODEDataBlock odeDataBlock = simData.getODEDataBlock();
            ODESimData odeSimData = odeDataBlock.getODESimData();
            timeSeriesMultitrialData.addDataSet(odeSimData, trialIndex);
        } catch (Exception e) {
            e.printStackTrace();
            File file = new File(baseDirectory, Simulation.createSimulationID(versSimulation.getKey()) + "_solverExc.txt");
            writeMessageTofile(file, e.getMessage());
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        clearDir(destDir);
    }
// printout("\n");
}
Also used : Solver(cbit.vcell.solver.server.Solver) SimulationTask(cbit.vcell.messaging.server.SimulationTask) TempSimulation(cbit.vcell.solver.TempSimulation) ODESimData(cbit.vcell.solver.ode.ODESimData) TempSimulation(cbit.vcell.solver.TempSimulation) Simulation(cbit.vcell.solver.Simulation) SimulationData(cbit.vcell.simdata.SimulationData) ODEDataBlock(cbit.vcell.simdata.ODEDataBlock) File(java.io.File) SolverStatus(cbit.vcell.solver.server.SolverStatus) SimulationJob(cbit.vcell.solver.SimulationJob)

Aggregations

SimulationTask (cbit.vcell.messaging.server.SimulationTask)6 Simulation (cbit.vcell.solver.Simulation)6 SimulationJob (cbit.vcell.solver.SimulationJob)6 TempSimulation (cbit.vcell.solver.TempSimulation)6 File (java.io.File)6 Solver (cbit.vcell.solver.server.Solver)4 SolverStatus (cbit.vcell.solver.server.SolverStatus)4 SimulationContext (cbit.vcell.mapping.SimulationContext)3 ODEDataBlock (cbit.vcell.simdata.ODEDataBlock)3 SimulationData (cbit.vcell.simdata.SimulationData)3 ODESimData (cbit.vcell.solver.ode.ODESimData)3 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)2 SimulationOwner (cbit.vcell.solver.SimulationOwner)2 SolverEvent (cbit.vcell.solver.server.SolverEvent)2 SolverListener (cbit.vcell.solver.server.SolverListener)2 XmlParseException (cbit.vcell.xml.XmlParseException)2 IOException (java.io.IOException)2 EventObject (java.util.EventObject)2 Hashtable (java.util.Hashtable)2 DataAccessException (org.vcell.util.DataAccessException)2