Search in sources :

Example 21 with SimulationTask

use of cbit.vcell.messaging.server.SimulationTask in project vcell by virtualcell.

the class SolverPreprocessor method main.

public static void main(java.lang.String[] args) {
    if (args.length < 2) {
        System.out.print(SolverPreprocessor.class.getName() + " ");
        System.out.println(Arrays.toString(args));
        System.out.println("Missing arguments: " + SolverPreprocessor.class.getName() + " [simulationTaskFile] [userdir] <parallel dir> ");
        System.exit(1);
    }
    File parallelDirectory = null;
    if (args.length >= 3) {
        parallelDirectory = new File(args[2]);
        if (!parallelDirectory.exists()) {
            parallelDirectory.mkdirs();
        }
        if (!parallelDirectory.isDirectory() || !parallelDirectory.canWrite()) {
            throw new IllegalArgumentException(parallelDirectory.getAbsolutePath() + " is not a writeable directory");
        }
    }
    Logging.init();
    try {
        PropertyLoader.loadProperties();
        // 
        File simulationFile = new File(args[0]);
        final SimulationTask simTask = XmlHelper.XMLToSimTask(FileUtils.readFileToString(simulationFile));
        if (parallelDirectory != null) {
            // simulation task needs to be written to the "parallel directory" (a temporary directory) here (it is local to the cluster).
            FileUtils.copyFile(simulationFile, new File(parallelDirectory, simulationFile.getName()));
        }
        File userDirectory = new File(args[1]);
        final String hostName = null;
        VCMongoMessage.serviceStartup(ServiceName.solverPreprocessor, Integer.valueOf(simTask.getSimKey().toString()), args);
        // 
        // JMX registration
        // 
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        mbs.registerMBean(new VCellServiceMXBeanImpl(), new ObjectName(VCellServiceMXBean.jmxObjectName));
        final HTCSolver htcSolver = new HTCSolver(simTask, userDirectory, parallelDirectory) {

            public void startSolver() {
                try {
                    super.initialize();
                } catch (Exception e) {
                    e.printStackTrace();
                    SimulationMessage simMessage = SimulationMessage.jobFailed(e.getMessage());
                    try {
                        sendFailureAndExit(this, simTask, hostName, simMessage);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            }

            public void stopSolver() {
            }

            public double getCurrentTime() {
                return 0;
            }

            public double getProgress() {
                return 0;
            }
        };
        SolverListener solverListener = new SolverListener() {

            public void solverStopped(SolverEvent event) {
                VCMongoMessage.sendSolverEvent(event);
                try {
                    sendFailureAndExit(htcSolver, simTask, hostName, event.getSimulationMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            public void solverStarting(SolverEvent event) {
                VCMongoMessage.sendSolverEvent(event);
            }

            public void solverProgress(SolverEvent event) {
                VCMongoMessage.sendSolverEvent(event);
            }

            public void solverPrinted(SolverEvent event) {
                VCMongoMessage.sendSolverEvent(event);
            }

            public void solverFinished(SolverEvent event) {
                VCMongoMessage.sendSolverEvent(event);
            }

            public void solverAborted(SolverEvent event) {
                VCMongoMessage.sendSolverEvent(event);
                try {
                    sendFailureAndExit(htcSolver, simTask, hostName, event.getSimulationMessage());
                } catch (VCMessagingException e) {
                    e.printStackTrace();
                }
            }
        };
        htcSolver.addSolverListener(solverListener);
        htcSolver.startSolver();
        VCMongoMessage.sendInfo("preprocessor done");
        exitWithCode(0);
    } catch (Throwable e) {
        lg.error(e.getMessage(), e);
        exitWithCode(-1);
    }
}
Also used : SimulationTask(cbit.vcell.messaging.server.SimulationTask) VCMessagingException(cbit.vcell.message.VCMessagingException) FileNotFoundException(java.io.FileNotFoundException) ObjectName(javax.management.ObjectName) SolverEvent(cbit.vcell.solver.server.SolverEvent) VCellServiceMXBeanImpl(cbit.vcell.message.server.jmx.VCellServiceMXBeanImpl) SimulationMessage(cbit.vcell.solver.server.SimulationMessage) SolverListener(cbit.vcell.solver.server.SolverListener) VCMessagingException(cbit.vcell.message.VCMessagingException) File(java.io.File) HTCSolver(cbit.vcell.solvers.HTCSolver) MBeanServer(javax.management.MBeanServer)

Example 22 with SimulationTask

use of cbit.vcell.messaging.server.SimulationTask 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 23 with SimulationTask

use of cbit.vcell.messaging.server.SimulationTask in project vcell by virtualcell.

the class VCellClientDataServiceImpl method getSimsFromOpenModels.

@Override
public List<SimulationDataSetRef> getSimsFromOpenModels() {
    ArrayList<SimulationDataSetRef> simulationDataSetRefs = new ArrayList<SimulationDataSetRef>();
    for (TopLevelWindowManager windowManager : vcellClient.getMdiManager().getWindowManagers()) {
        Simulation[] simulations = null;
        VCDocument modelDocument = null;
        if (windowManager instanceof BioModelWindowManager) {
            BioModelWindowManager selectedBioWindowManager = (BioModelWindowManager) windowManager;
            BioModel bioModel = selectedBioWindowManager.getBioModel();
            simulations = bioModel.getSimulations();
            modelDocument = bioModel;
        // simOwnerCount = bioModel.getNumSimulationContexts();
        } else if (windowManager instanceof MathModelWindowManager) {
            MathModelWindowManager selectedMathWindowManager = (MathModelWindowManager) windowManager;
            MathModel mathModel = selectedMathWindowManager.getMathModel();
            simulations = mathModel.getSimulations();
            modelDocument = mathModel;
        // simOwnerCount = 1;
        }
        if (simulations != null) {
            for (Simulation simulation : simulations) {
                if (!isVtkSupported(simulation)) {
                    continue;
                }
                Origin origin = simulation.getMathDescription().getGeometry().getOrigin();
                Extent extent = simulation.getMathDescription().getGeometry().getExtent();
                SimulationInfo simInfo = simulation.getSimulationInfo();
                SimulationStatus simStatus = vcellClient.getRequestManager().getServerSimulationStatus(simInfo);
                for (int jobIndex = 0; jobIndex < simulation.getScanCount(); jobIndex++) {
                    if (simStatus != null && simStatus.getHasData()) {
                        SimulationDataSetRef simulationDataSetReference = VCellClientDataServiceImpl.createSimulationDataSetRef(simulation, modelDocument, jobIndex, false);
                        simulationDataSetRefs.add(simulationDataSetReference);
                    }
                }
            }
        }
    }
    File localSimDir = ResourceUtil.getLocalSimDir(User.tempUser.getName());
    String[] simtaskFilenames = localSimDir.list((dir, name) -> (name.endsWith(".simtask.xml")));
    for (String simtaskFilename : simtaskFilenames) {
        try {
            SimulationTask simTask = XmlHelper.XMLToSimTask(org.apache.commons.io.FileUtils.readFileToString(new File(localSimDir, simtaskFilename)));
            VCDocument modelDocument = null;
            SimulationDataSetRef simulationDataSetReference = VCellClientDataServiceImpl.createSimulationDataSetRef(simTask.getSimulation(), modelDocument, simTask.getSimulationJob().getJobIndex(), true);
            simulationDataSetRefs.add(simulationDataSetReference);
        } catch (ExpressionException | XmlParseException | IOException e) {
            e.printStackTrace();
        }
    }
    return simulationDataSetRefs;
}
Also used : Origin(org.vcell.util.Origin) MathModel(cbit.vcell.mathmodel.MathModel) SimulationTask(cbit.vcell.messaging.server.SimulationTask) VCDocument(org.vcell.util.document.VCDocument) TopLevelWindowManager(cbit.vcell.client.TopLevelWindowManager) Extent(org.vcell.util.Extent) ArrayList(java.util.ArrayList) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) SimulationDataSetRef(cbit.vcell.client.pyvcellproxy.SimulationDataSetRef) MathModelWindowManager(cbit.vcell.client.MathModelWindowManager) ExpressionException(cbit.vcell.parser.ExpressionException) Simulation(cbit.vcell.solver.Simulation) BioModelWindowManager(cbit.vcell.client.BioModelWindowManager) SimulationStatus(cbit.vcell.server.SimulationStatus) BioModel(cbit.vcell.biomodel.BioModel) File(java.io.File) SimulationInfo(cbit.vcell.solver.SimulationInfo)

Example 24 with SimulationTask

use of cbit.vcell.messaging.server.SimulationTask in project vcell by virtualcell.

the class LocalSolverController method solverAborted.

/**
 * Invoked when the solver aborts a calculation (abnormal termination).
 * @param event indicates the solver and the event type
 */
public void solverAborted(SolverEvent event) {
    try {
        if (lg.isTraceEnabled())
            lg.trace("LocalSolverController Caught solverAborted(" + event.getSource().toString() + ",error='" + event.getSimulationMessage() + "')");
        SimulationJob simJob = getSimulationTask().getSimulationJob();
        if (serialParameterScanJobIndex >= 0) {
            SimulationTask newSimTask = new SimulationTask(new SimulationJob(simJob.getSimulation(), serialParameterScanJobIndex, simJob.getFieldDataIdentifierSpecs()), getSimulationTask().getTaskID());
            fireWorkerEvent(new WorkerEvent(WorkerEvent.JOB_FAILURE, this, newSimTask, hostname, event.getSimulationMessage()));
        } else {
            fireWorkerEvent(new WorkerEvent(WorkerEvent.JOB_FAILURE, this, getSimulationTask(), hostname, event.getSimulationMessage()));
        }
    } catch (Throwable e) {
        lg.error(e.getMessage(), e);
    }
}
Also used : SimulationTask(cbit.vcell.messaging.server.SimulationTask) WorkerEvent(cbit.rmi.event.WorkerEvent) SimulationJob(cbit.vcell.solver.SimulationJob)

Example 25 with SimulationTask

use of cbit.vcell.messaging.server.SimulationTask in project vcell by virtualcell.

the class OptXmlWriter method getModelXML.

public static Element getModelXML(PdeObjectiveFunction pdeObjectiveFunction, String[] parameterNames) {
    Element modelElement = new Element(OptXmlTags.Model_Tag);
    try {
        SpatialReferenceData refData = pdeObjectiveFunction.getReferenceData();
        double refDataEndTime = refData.getDataByRow(refData.getNumDataRows() - 1)[0];
        // 
        // post the problem either as an IDA or CVODE model
        // 
        org.vcell.util.document.SimulationVersion simVersion = new org.vcell.util.document.SimulationVersion(new KeyValue("12345"), "name", new org.vcell.util.document.User("user", new KeyValue("123")), new org.vcell.util.document.GroupAccessNone(), // versionBranchPointRef
        null, // branchID
        new java.math.BigDecimal(1.0), new java.util.Date(), org.vcell.util.document.VersionFlag.Archived, "", null);
        Simulation simulation = new Simulation(simVersion, pdeObjectiveFunction.getMathDescription());
        simulation.getMeshSpecification().setSamplingSize(refData.getDataISize());
        double[] times = refData.getDataByColumn(0);
        double minDt = Double.POSITIVE_INFINITY;
        for (int i = 1; i < times.length; i++) {
            minDt = Math.min(minDt, times[i] - times[i - 1]);
        }
        simulation.getSolverTaskDescription().setTimeBounds(new cbit.vcell.solver.TimeBounds(0.0, refDataEndTime));
        simulation.getSolverTaskDescription().setSolverDescription(SolverDescription.FiniteVolume);
        simulation.getSolverTaskDescription().setTimeStep(new TimeStep(minDt / 5, minDt / 5, minDt / 5));
        // clone and resample geometry
        Geometry resampledGeometry = null;
        try {
            resampledGeometry = (Geometry) BeanUtils.cloneSerializable(simulation.getMathDescription().getGeometry());
            GeometrySurfaceDescription geoSurfaceDesc = resampledGeometry.getGeometrySurfaceDescription();
            ISize newSize = simulation.getMeshSpecification().getSamplingSize();
            geoSurfaceDesc.setVolumeSampleSize(newSize);
            geoSurfaceDesc.updateAll();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SolverException(e.getMessage());
        }
        SimulationTask simTask = new SimulationTask(new SimulationJob(simulation, 0, pdeObjectiveFunction.getFieldDataIDSs()), 0);
        StringWriter simulationInputStringWriter = new StringWriter();
        FiniteVolumeFileWriter fvFileWriter = new FiniteVolumeFileWriter(new PrintWriter(simulationInputStringWriter, true), simTask, resampledGeometry, pdeObjectiveFunction.getWorkingDirectory());
        fvFileWriter.write(parameterNames);
        simulationInputStringWriter.close();
        modelElement.setAttribute(OptXmlTags.ModelType_Attr, OptXmlTags.ModelType_Attr_FVSOLVER);
        CDATA simulationInputText = new CDATA(simulationInputStringWriter.getBuffer().toString());
        modelElement.addContent(simulationInputText);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new OptimizationException("failed to create fv input file: " + e.getMessage());
    }
    return modelElement;
}
Also used : OptimizationException(cbit.vcell.opt.OptimizationException) KeyValue(org.vcell.util.document.KeyValue) SimulationTask(cbit.vcell.messaging.server.SimulationTask) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) ISize(org.vcell.util.ISize) Element(org.jdom.Element) FiniteVolumeFileWriter(cbit.vcell.solvers.FiniteVolumeFileWriter) TimeStep(cbit.vcell.solver.TimeStep) StringWriter(java.io.StringWriter) SpatialReferenceData(cbit.vcell.opt.SpatialReferenceData) SimulationJob(cbit.vcell.solver.SimulationJob) PrintWriter(java.io.PrintWriter) Constraint(cbit.vcell.opt.Constraint) OptimizationException(cbit.vcell.opt.OptimizationException) XMLStreamException(javax.xml.stream.XMLStreamException) SBMLException(org.sbml.jsbml.SBMLException) XmlParseException(cbit.vcell.xml.XmlParseException) SolverException(cbit.vcell.solver.SolverException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) SolverException(cbit.vcell.solver.SolverException) CDATA(org.jdom.CDATA)

Aggregations

SimulationTask (cbit.vcell.messaging.server.SimulationTask)34 SimulationJob (cbit.vcell.solver.SimulationJob)26 File (java.io.File)17 Simulation (cbit.vcell.solver.Simulation)15 IOException (java.io.IOException)13 SolverStatus (cbit.vcell.solver.server.SolverStatus)11 XmlParseException (cbit.vcell.xml.XmlParseException)8 FieldDataIdentifierSpec (cbit.vcell.field.FieldDataIdentifierSpec)7 SimulationContext (cbit.vcell.mapping.SimulationContext)7 ExpressionException (cbit.vcell.parser.ExpressionException)7 SolverException (cbit.vcell.solver.SolverException)7 FVSolverStandalone (cbit.vcell.solvers.FVSolverStandalone)7 PrintWriter (java.io.PrintWriter)7 UserCancelException (org.vcell.util.UserCancelException)7 TempSimulation (cbit.vcell.solver.TempSimulation)6 MathDescription (cbit.vcell.math.MathDescription)5 Variable (cbit.vcell.math.Variable)5 DataAccessException (org.vcell.util.DataAccessException)5 ImageException (cbit.image.ImageException)4 ODESimData (cbit.vcell.solver.ode.ODESimData)4