Search in sources :

Example 16 with SolverStatus

use of cbit.vcell.solver.server.SolverStatus 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 17 with SolverStatus

use of cbit.vcell.solver.server.SolverStatus in project vcell by virtualcell.

the class FVSolverStandalone method initialize.

// 
// 
// /**
// * Insert the method's description here.
// * Creation date: (6/27/2001 2:33:03 PM)
// */
// public void propertyChange(java.beans.PropertyChangeEvent event) {
// super.propertyChange(event);
// 
// if (event.getSource() == getMathExecutable() && event.getPropertyName().equals("applicationMessage")) {
// String messageString = (String)event.getNewValue();
// if (messageString==null || messageString.length()==0){
// return;
// }
// ApplicationMessage appMessage = getApplicationMessage(messageString);
// if (appMessage!=null && appMessage.getMessageType() == ApplicationMessage.DATA_MESSAGE) {
// fireSolverPrinted(appMessage.getTimepoint());
// }
// }
// }
/**
 * This method was created by a SmartGuide.
 */
protected void initialize() throws SolverException {
    try {
        Simulation sim = simTask.getSimulation();
        if (sim.isSerialParameterScan()) {
            // write functions file for all the simulations in the scan
            for (int scan = 0; scan < sim.getScanCount(); scan++) {
                SimulationJob simJob = new SimulationJob(sim, scan, simTask.getSimulationJob().getFieldDataIdentifierSpecs());
                // ** Dumping the functions of a simulation into a '.functions' file.
                String basename = new File(getSaveDirectory(), simJob.getSimulationJobID()).getPath();
                String functionFileName = basename + FUNCTIONFILE_EXTENSION;
                Vector<AnnotatedFunction> funcList = simJob.getSimulationSymbolTable().createAnnotatedFunctionsList(simTask.getSimulation().getMathDescription());
                // Try to save existing user defined functions
                try {
                    File existingFunctionFile = new File(functionFileName);
                    if (existingFunctionFile.exists()) {
                        Vector<AnnotatedFunction> oldFuncList = FunctionFileGenerator.readFunctionsFile(existingFunctionFile, simTask.getSimulationJobID());
                        for (AnnotatedFunction func : oldFuncList) {
                            if (func.isOldUserDefined()) {
                                funcList.add(func);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                // ignore
                }
                // Try to save existing user defined functions
                FunctionFileGenerator functionFileGenerator = new FunctionFileGenerator(functionFileName, funcList);
                try {
                    functionFileGenerator.generateFunctionFile();
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Error creating .function file for " + functionFileGenerator.getBasefileName() + e.getMessage());
                }
            }
        } else {
            writeFunctionsFile();
        }
        // not for Chombo solver
        if (!isChombo) {
            writeVCGAndResampleFieldData();
        }
        setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INIT));
        fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INIT);
        setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INPUT_FILE));
        File fvinputFile = new File(getInputFilename());
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new FileWriter(fvinputFile));
            new FiniteVolumeFileWriter(pw, simTask, getResampledGeometry(), getSaveDirectory(), destinationDirectory, bMessaging).write();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        throw new SolverException(ex.getMessage());
    }
}
Also used : FileWriter(java.io.FileWriter) SolverException(cbit.vcell.solver.SolverException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) ExpressionException(cbit.vcell.parser.ExpressionException) Simulation(cbit.vcell.solver.Simulation) SolverException(cbit.vcell.solver.SolverException) File(java.io.File) SolverStatus(cbit.vcell.solver.server.SolverStatus) SimulationJob(cbit.vcell.solver.SimulationJob) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) PrintWriter(java.io.PrintWriter)

Example 18 with SolverStatus

use of cbit.vcell.solver.server.SolverStatus in project vcell by virtualcell.

the class HybridSolver method initialize.

/**
 *  This method takes the place of the old runUnsteady()...
 */
protected void initialize() throws SolverException {
    if (lg.isTraceEnabled())
        lg.trace("HybridSolver.initialize()");
    fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INIT);
    writeFunctionsFile();
    writeLogFile();
    // 
    // file used by precompiled solver.
    String inputFilename = getInputFilename();
    // 
    if (lg.isTraceEnabled())
        lg.trace("HybridSolver.initialize() baseName = " + getBaseName());
    // 
    NetCDFWriter ncWriter = new NetCDFWriter(simTask, inputFilename, bMessaging);
    try {
        ncWriter.initialize();
    } catch (Exception e) {
        setSolverStatus(new cbit.vcell.solver.server.SolverStatus(SolverStatus.SOLVER_ABORTED, SimulationMessage.solverAborted("Could not initialize StochFileWriter...")));
        e.printStackTrace(System.out);
        throw new SolverException("autocode init exception: " + e.getMessage());
    }
    setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_INPUT_FILE));
    fireSolverStarting(SimulationMessage.MESSAGE_SOLVEREVENT_STARTING_INPUT_FILE);
    // 
    try {
        ncWriter.writeHybridInputFile();
    } catch (Exception e) {
        setSolverStatus(new SolverStatus(SolverStatus.SOLVER_ABORTED, SimulationMessage.solverAborted("Could not generate input file: " + e.getMessage())));
        e.printStackTrace(System.err);
        throw new SolverException("solver input file exception: " + e.getMessage());
    }
    // 
    // 
    setSolverStatus(new SolverStatus(SolverStatus.SOLVER_RUNNING, SimulationMessage.MESSAGE_SOLVER_RUNNING_START));
    // get executable path+name.
    // Hybrid solver's usage: ProgramName <NetCDF Filename> <epsilon> <lambda> <MSR_Tolerance> <SDE_Tolerance> <SDE_dt> [-R <Random Seed>] [-OV]
    setMathExecutable(new MathExecutable(getMathExecutableCommand(), getSaveDirectory()));
}
Also used : SolverException(cbit.vcell.solver.SolverException) MathExecutable(cbit.vcell.solvers.MathExecutable) SolverStatus(cbit.vcell.solver.server.SolverStatus) SolverException(cbit.vcell.solver.SolverException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) FileNotFoundException(java.io.FileNotFoundException) MathException(cbit.vcell.math.MathException)

Example 19 with SolverStatus

use of cbit.vcell.solver.server.SolverStatus in project vcell by virtualcell.

the class HybridSolverTester method runHybridTest.

public void runHybridTest(String site) {
    try {
        double[] timePoints = null;
        File mathModelFile = new File(mathModelVCMLFileName);
        XMLSource vcmlSource = new XMLSource(mathModelFile);
        MathModel mathModel = XmlHelper.XMLToMathModel(vcmlSource);
        File simDataDir = mathModelFile.getParentFile();
        Simulation sim = mathModel.getSimulations()[0];
        // run multiple trials and each run will have a simID = origSimID + i
        for (int i = 0; i < numRuns; i++) {
            System.out.println("--------------Trial No: " + (startTrialNo + i) + "----------------");
            // replace random seed
            sim.getSolverTaskDescription().getSmoldynSimulationOptions().setRandomSeed(new Integer(startTrialNo + i));
            // create sim job
            int jobIndex = startTrialNo + i;
            SimulationTask simTask = new SimulationTask(new SimulationJob(sim, jobIndex, null), 0);
            /*
				 * When you want to run the multiple trials on local uncomment the line below.
				 */
            // ResourceUtil.prepareSolverExecutable(sim.getSolverTaskDescription().getSolverDescription());
            /*
				 * When you want to run the multiple trials on server (without VCell user interface), use the next line of code 
				 * Corresponding changes should be made in the shell script runhybridtest for the location of executable on server
				 */
            FVSolverStandalone fvSolver = new FVSolverStandalone(simTask, simDataDir, false);
            fvSolver.startSolver();
            SolverStatus status = fvSolver.getSolverStatus();
            while (status.getStatus() != SolverStatus.SOLVER_FINISHED && status.getStatus() != SolverStatus.SOLVER_ABORTED) {
                System.out.println("progress: " + (int) (fvSolver.getProgress() * 100) + "%");
                // ask status every 2 seconds
                Thread.sleep(2000);
                status = fvSolver.getSolverStatus();
            }
            if (status.getStatus() == SolverStatus.SOLVER_FINISHED) {
                // get data
                VCSimulationIdentifier vcSimID = new VCSimulationIdentifier(sim.getVersion().getVersionKey(), sim.getVersion().getOwner());
                VCSimulationDataIdentifier vcSimDataID = new VCSimulationDataIdentifier(vcSimID, jobIndex);
                File hdf5File = new File(simDataDir, vcSimDataID.getID() + SimDataConstants.DATA_PROCESSING_OUTPUT_EXTENSION_HDF5);
                DataOperationResults.DataProcessingOutputInfo dataProcessingOutputInfo = (DataOperationResults.DataProcessingOutputInfo) DataSetControllerImpl.getDataProcessingOutput(new DataOperation.DataProcessingOutputInfoOP(vcSimDataID, false, null), hdf5File);
                if (i == 0) {
                    // do only one time
                    timePoints = dataProcessingOutputInfo.getVariableTimePoints();
                    for (int j = 0; j < varNames.length; j++) {
                        // row: numTimePoints, col:first col time + numRuns
                        double[][] data = new double[numRuns + 1][timePoints.length];
                        data[0] = timePoints;
                        results.add(data);
                    }
                }
                // write into results after each run
                for (int j = 0; j < varNames.length; j++) {
                    results.get(j)[i + 1] = dataProcessingOutputInfo.getVariableStatValues().get(varNames[j]);
                }
                // delete the file generated for this run
                deleteSimFiles(simDataDir, vcSimDataID);
            } else {
                throw new Exception("Sover did not finish normally." + status);
            }
        }
        // write to output file, tab delimited
        if (results != null && results.size() > 0) {
            for (int j = 0; j < varNames.length; j++) {
                File file = new File(simDataDir, "SimID_" + sim.getVersion().getVersionKey().toString() + "_" + varNames[j] + "_" + startTrialNo + ".txt");
                PrintWriter pw = new PrintWriter(file);
                double[][] data = results.get(j);
                if (data != null) {
                    for (int k = 0; k < data.length; k++) {
                        if (!bPrintTime && k == 0) {
                            continue;
                        }
                        String rowStr = (k == 0) ? "Time\t" : ("trialNo_" + (startTrialNo + k - 1) + "\t");
                        double[] rowData = data[k];
                        for (int q = 0; q < rowData.length; q++) {
                            rowStr += rowData[q] + "\t";
                        }
                        pw.println(rowStr);
                    }
                }
                pw.close();
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : MathModel(cbit.vcell.mathmodel.MathModel) VCSimulationIdentifier(cbit.vcell.solver.VCSimulationIdentifier) SimulationTask(cbit.vcell.messaging.server.SimulationTask) BigString(org.vcell.util.BigString) VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) FVSolverStandalone(cbit.vcell.solvers.FVSolverStandalone) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Simulation(cbit.vcell.solver.Simulation) DataOperationResults(cbit.vcell.simdata.DataOperationResults) File(java.io.File) XMLSource(cbit.vcell.xml.XMLSource) SolverStatus(cbit.vcell.solver.server.SolverStatus) SimulationJob(cbit.vcell.solver.SimulationJob) PrintWriter(java.io.PrintWriter)

Example 20 with SolverStatus

use of cbit.vcell.solver.server.SolverStatus 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

SolverStatus (cbit.vcell.solver.server.SolverStatus)25 IOException (java.io.IOException)14 SimulationJob (cbit.vcell.solver.SimulationJob)12 SimulationTask (cbit.vcell.messaging.server.SimulationTask)11 SolverException (cbit.vcell.solver.SolverException)11 File (java.io.File)11 PrintWriter (java.io.PrintWriter)8 FVSolverStandalone (cbit.vcell.solvers.FVSolverStandalone)7 Simulation (cbit.vcell.solver.Simulation)6 MathExecutable (cbit.vcell.solvers.MathExecutable)6 UserCancelException (org.vcell.util.UserCancelException)6 ImageException (cbit.image.ImageException)5 FieldDataIdentifierSpec (cbit.vcell.field.FieldDataIdentifierSpec)5 ExpressionException (cbit.vcell.parser.ExpressionException)5 FieldFunctionArguments (cbit.vcell.field.FieldFunctionArguments)4 TempSimulation (cbit.vcell.solver.TempSimulation)4 Solver (cbit.vcell.solver.server.Solver)4 MathException (cbit.vcell.math.MathException)3 ODEDataBlock (cbit.vcell.simdata.ODEDataBlock)3 SimulationData (cbit.vcell.simdata.SimulationData)3