Search in sources :

Example 11 with SimulationTask

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

the class XmlHelper method XMLToSimTask.

public static SimulationTask XMLToSimTask(String xmlString) throws XmlParseException, ExpressionException {
    Namespace ns = Namespace.getNamespace(XMLTags.VCML_NS);
    try {
        if (xmlString == null || xmlString.length() == 0) {
            throw new XmlParseException("Invalid xml for Simulation: " + xmlString);
        }
        // default parser and no validation
        Element root = (XmlUtil.stringToXML(xmlString, null)).getRootElement();
        if (!root.getName().equals(SimulationTask_tag)) {
            throw new RuntimeException("expecting top level element to be " + SimulationTask_tag);
        }
        int taskId = Integer.parseInt(root.getAttributeValue(TaskId_attr));
        int jobIndex = Integer.parseInt(root.getAttributeValue(JobIndex_attr));
        String computeResource = root.getChildTextTrim(ComputeResource_tag, ns);
        List<?> children = root.getChildren(FieldFunctionIdentifierSpec_tag, ns);
        ArrayList<FieldDataIdentifierSpec> fdisArrayList = new ArrayList<FieldDataIdentifierSpec>();
        for (Object child : children) {
            if (child instanceof Element) {
                String fdisText = ((Element) child).getTextTrim();
                FieldDataIdentifierSpec fdis = FieldDataIdentifierSpec.fromCSVString(fdisText);
                fdisArrayList.add(fdis);
            }
        }
        FieldDataIdentifierSpec[] fdisArray = fdisArrayList.toArray(new FieldDataIdentifierSpec[0]);
        Element simElement = root.getChild(XMLTags.SimulationTag, ns);
        Element mdElement = root.getChild(XMLTags.MathDescriptionTag, ns);
        Element geomElement = root.getChild(XMLTags.GeometryTag, ns);
        XmlReader reader = new XmlReader(true, ns);
        Geometry geom = null;
        if (geomElement != null) {
            geom = reader.getGeometry(geomElement);
        }
        MathDescription md = reader.getMathDescription(mdElement, geom);
        Simulation sim = reader.getSimulation(simElement, md);
        sim.refreshDependencies();
        SimulationJob simJob = new SimulationJob(sim, jobIndex, fdisArray);
        SimulationTask simTask = new SimulationTask(simJob, taskId, computeResource);
        return simTask;
    } catch (Exception pve) {
        pve.printStackTrace();
        throw new XmlParseException("Unable to parse simulation string.", pve);
    }
}
Also used : SimulationTask(cbit.vcell.messaging.server.SimulationTask) MathDescription(cbit.vcell.math.MathDescription) Element(org.jdom.Element) ArrayList(java.util.ArrayList) Namespace(org.jdom.Namespace) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) SBMLException(org.sbml.jsbml.SBMLException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) FieldDataIdentifierSpec(cbit.vcell.field.FieldDataIdentifierSpec) SimulationJob(cbit.vcell.solver.SimulationJob)

Example 12 with SimulationTask

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

the class SimulationData method getVarAndFunctionDataIdentifiers.

/**
 * This method was created in VisualAge.
 * @return java.lang.String[]
 */
public synchronized DataIdentifier[] getVarAndFunctionDataIdentifiers(OutputContext outputContext) throws IOException, DataAccessException {
    // Is this zip format?
    boolean bIsChombo = false;
    try {
        bIsChombo = isChombo();
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.out);
    }
    File zipFile1 = getZipFile(bIsChombo, null);
    File zipFile2 = getZipFile(bIsChombo, 0);
    bZipFormat1 = false;
    bZipFormat2 = false;
    if (zipFile1.exists()) {
        bZipFormat1 = true;
    } else if (zipFile2.exists()) {
        bZipFormat2 = true;
    }
    refreshLogFile();
    if (!isComsol()) {
        try {
            refreshMeshFile();
        } catch (MathException e) {
            e.printStackTrace(System.out);
            throw new DataAccessException(e.getMessage());
        }
    }
    if (!isRulesData && !getIsODEData() && !isComsol() && dataFilenames != null) {
        // read variables only when I have never read the file since variables don't change
        if (dataSetIdentifierList.size() == 0) {
            File file = getPDEDataFile(0.0);
            DataSet dataSet = getPDEDataSet(file, 0.0);
            String[] varNames = dataSet.getDataNames();
            int[] varTypeInts = dataSet.getVariableTypeIntegers();
            if (varNames == null) {
                return null;
            }
            dataSetIdentifierList.clear();
            for (int i = 0; i < varNames.length; i++) {
                VariableType varType = null;
                try {
                    varType = VariableType.getVariableTypeFromInteger(varTypeInts[i]);
                } catch (IllegalArgumentException e) {
                    if (LG.isEnabledFor(Level.WARN)) {
                        LG.warn("Exception typing " + varNames[i] + " has unsupported type " + varTypeInts[i] + ": " + e.getMessage());
                    }
                    varType = SimulationData.getVariableTypeFromLength(mesh, dataSet.getDataLength(varNames[i]));
                }
                Domain domain = Variable.getDomainFromCombinedIdentifier(varNames[i]);
                String varName = Variable.getNameFromCombinedIdentifier(varNames[i]);
                dataSetIdentifierList.addElement(new DataSetIdentifier(varName, varType, domain));
            }
            refreshDataProcessingOutputInfo(outputContext);
            if (dataProcessingOutputInfo != null) {
                for (int i = 0; i < dataProcessingOutputInfo.getVariableNames().length; i++) {
                    if (dataProcessingOutputInfo.getPostProcessDataType(dataProcessingOutputInfo.getVariableNames()[i]).equals(DataProcessingOutputInfo.PostProcessDataType.image)) {
                        dataSetIdentifierList.addElement(new DataSetIdentifier(dataProcessingOutputInfo.getVariableNames()[i], VariableType.POSTPROCESSING, null));
                    }
                }
            }
        }
        // always read functions file since functions might change
        getFunctionDataIdentifiers(outputContext);
    }
    if ((isRulesData || getIsODEData()) && dataSetIdentifierList.size() == 0) {
        ODEDataBlock odeDataBlock = getODEDataBlock();
        if (odeDataBlock == null) {
            throw new DataAccessException("Results are not availabe yet. Please try again later.");
        }
        ODESimData odeSimData = odeDataBlock.getODESimData();
        int colCount = odeSimData.getColumnDescriptionsCount();
        // assume index=0 is time "t"
        int DATA_OFFSET = 1;
        dataSetIdentifierList.clear();
        for (int i = 0; i < (colCount - DATA_OFFSET); i++) {
            String varName = odeSimData.getColumnDescriptions(i + DATA_OFFSET).getDisplayName();
            // TODO domain
            Domain domain = null;
            dataSetIdentifierList.addElement(new DataSetIdentifier(varName, VariableType.NONSPATIAL, domain));
        }
    }
    if (isComsol() && dataSetIdentifierList.size() == 0) {
        ComsolSimFiles comsolSimFiles = getComsolSimFiles();
        if (comsolSimFiles.simTaskXMLFile != null) {
            try {
                String xmlString = FileUtils.readFileToString(comsolSimFiles.simTaskXMLFile);
                SimulationTask simTask = XmlHelper.XMLToSimTask(xmlString);
                Enumeration<Variable> variablesEnum = simTask.getSimulation().getMathDescription().getVariables();
                while (variablesEnum.hasMoreElements()) {
                    Variable var = variablesEnum.nextElement();
                    if (var instanceof VolVariable) {
                        dataSetIdentifierList.addElement(new DataSetIdentifier(var.getName(), VariableType.VOLUME, var.getDomain()));
                    } else if (var instanceof MemVariable) {
                        dataSetIdentifierList.addElement(new DataSetIdentifier(var.getName(), VariableType.MEMBRANE, var.getDomain()));
                    } else if (var instanceof Function) {
                        VariableType varType = VariableType.UNKNOWN;
                        if (var.getDomain() != null && var.getDomain().getName() != null) {
                            SubDomain subDomain = simTask.getSimulation().getMathDescription().getSubDomain(var.getDomain().getName());
                            if (subDomain instanceof CompartmentSubDomain) {
                                varType = VariableType.VOLUME;
                            } else if (subDomain instanceof MembraneSubDomain) {
                                varType = VariableType.MEMBRANE;
                            } else if (subDomain instanceof FilamentSubDomain) {
                                throw new RuntimeException("filament subdomains not supported");
                            } else if (subDomain instanceof PointSubDomain) {
                                varType = VariableType.POINT_VARIABLE;
                            }
                        }
                        dataSetIdentifierList.addElement(new DataSetIdentifier(var.getName(), varType, var.getDomain()));
                    } else if (var instanceof Constant) {
                        System.out.println("ignoring Constant " + var.getName());
                    } else if (var instanceof InsideVariable) {
                        System.out.println("ignoring InsideVariable " + var.getName());
                    } else if (var instanceof OutsideVariable) {
                        System.out.println("ignoring OutsideVariable " + var.getName());
                    } else {
                        throw new RuntimeException("unexpected variable " + var.getName() + " of type " + var.getClass().getName());
                    }
                }
            } catch (XmlParseException | ExpressionException e) {
                e.printStackTrace();
                throw new RuntimeException("failed to read sim task file, msg: " + e.getMessage(), e);
            }
        }
    }
    DataIdentifier[] dis = new DataIdentifier[dataSetIdentifierList.size()];
    for (int i = 0; i < dataSetIdentifierList.size(); i++) {
        DataSetIdentifier dsi = (DataSetIdentifier) dataSetIdentifierList.elementAt(i);
        String displayName = dsi.getName();
        if (dsi.isFunction()) {
            AnnotatedFunction f = null;
            for (int j = 0; j < annotatedFunctionList.size(); j++) {
                AnnotatedFunction function = (AnnotatedFunction) annotatedFunctionList.elementAt(j);
                if (function.getName().equals(dsi.getName())) {
                    f = function;
                    break;
                }
            }
            if (f != null) {
                displayName = f.getDisplayName();
            }
        }
        dis[i] = new DataIdentifier(dsi.getName(), dsi.getVariableType(), dsi.getDomain(), dsi.isFunction(), displayName);
    }
    return dis;
}
Also used : MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) SimulationTask(cbit.vcell.messaging.server.SimulationTask) InsideVariable(cbit.vcell.math.InsideVariable) VolVariable(cbit.vcell.math.VolVariable) ReservedVariable(cbit.vcell.math.ReservedVariable) MemVariable(cbit.vcell.math.MemVariable) OutsideVariable(cbit.vcell.math.OutsideVariable) Variable(cbit.vcell.math.Variable) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) ExternalDataIdentifier(org.vcell.util.document.ExternalDataIdentifier) Constant(cbit.vcell.math.Constant) FileNotFoundException(java.io.FileNotFoundException) PointSubDomain(cbit.vcell.math.PointSubDomain) ODESimData(cbit.vcell.solver.ode.ODESimData) InsideVariable(cbit.vcell.math.InsideVariable) ExpressionException(cbit.vcell.parser.ExpressionException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) FilamentSubDomain(cbit.vcell.math.FilamentSubDomain) SubDomain(cbit.vcell.math.SubDomain) PointSubDomain(cbit.vcell.math.PointSubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) Function(cbit.vcell.math.Function) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) MemVariable(cbit.vcell.math.MemVariable) DataAccessException(org.vcell.util.DataAccessException) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) ComsolSimFiles(org.vcell.vis.io.ComsolSimFiles) VariableType(cbit.vcell.math.VariableType) VolVariable(cbit.vcell.math.VolVariable) XmlParseException(cbit.vcell.xml.XmlParseException) FilamentSubDomain(cbit.vcell.math.FilamentSubDomain) MathException(cbit.vcell.math.MathException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) OutsideVariable(cbit.vcell.math.OutsideVariable) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) FilamentSubDomain(cbit.vcell.math.FilamentSubDomain) SubDomain(cbit.vcell.math.SubDomain) PointSubDomain(cbit.vcell.math.PointSubDomain) Domain(cbit.vcell.math.Variable.Domain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File)

Example 13 with SimulationTask

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

the class ExportDocument method run.

/**
 * Insert the method's description here.
 * Creation date: (5/31/2004 6:04:14 PM)
 * @param hashTable java.util.Hashtable
 * @param clientWorker cbit.vcell.desktop.controls.ClientWorker
 */
public void run(Hashtable<String, Object> hashTable) throws java.lang.Exception {
    VCDocument documentToExport = (VCDocument) hashTable.get("documentToExport");
    File exportFile = fetch(hashTable, EXPORT_FILE, File.class, true);
    ExtensionFilter fileFilter = fetch(hashTable, FILE_FILTER, ExtensionFilter.class, true);
    DocumentManager documentManager = fetch(hashTable, DocumentManager.IDENT, DocumentManager.class, true);
    String resultString = null;
    FileCloseHelper closeThis = null;
    try {
        if (documentToExport instanceof BioModel) {
            if (!(fileFilter instanceof SelectorExtensionFilter)) {
                throw new Exception("Expecting fileFilter type " + SelectorExtensionFilter.class.getName() + " but got " + fileFilter.getClass().getName());
            }
            BioModel bioModel = (BioModel) documentToExport;
            SimulationContext chosenSimContext = fetch(hashTable, SIM_CONTEXT, SimulationContext.class, false);
            ((SelectorExtensionFilter) fileFilter).writeBioModel(documentManager, bioModel, exportFile, chosenSimContext);
        /*		DELETE this after finishing validation testing
			
			// check format requested
			if (fileFilter.getDescription().equals(FileFilters.FILE_FILTER_MATLABV6.getDescription())){
				// matlab from application; get application
		
				SimulationContext chosenSimContext = fetch(hashTable,SIM_CONTEXT,SimulationContext.class, true);
				// regenerate a fresh MathDescription
				MathMapping mathMapping = chosenSimContext.createNewMathMapping();
				MathDescription mathDesc = mathMapping.getMathDescription();
				if(mathDesc != null && !mathDesc.isSpatial() && !mathDesc.isNonSpatialStoch()){
					// do export
					resultString = exportMatlab(exportFile, fileFilter, mathDesc);
				}else{
					throw new Exception("Matlab export failed: NOT an non-spatial deterministic application!");
				}
			} else if (fileFilter.equals(FileFilters.FILE_FILTER_PDF)) {   
				FileOutputStream fos = null;
				try {
					fos = new FileOutputStream(exportFile);
					documentManager.generatePDF(bioModel, fos);				
				} finally {
					if(fos != null) {
						fos.close();					
					}
				}
				return; 									//will take care of writing to the file as well.
			}
			//Export a simulation to Smoldyn input file, if there are parameter scans
			//in simulation, we'll export multiple Smoldyn input files.
			else if (fileFilter.equals(FileFilters.FILE_FILTER_SMOLDYN_INPUT)) 
			{ 
				Simulation selectedSim = (Simulation)hashTable.get("selectedSimulation");
				if (selectedSim != null) {
					int scanCount = selectedSim.getScanCount();
					if(scanCount > 1) // has parameter scan
					{
						String baseExportFileName = exportFile.getPath().substring(0, exportFile.getPath().indexOf("."));
						for(int i=0; i<scanCount; i++)
						{
							SimulationTask simTask = new SimulationTask(new SimulationJob(selectedSim, i, null),0);
							// Need to export each parameter scan into a separate file
							String newExportFileName = baseExportFileName + "_" + i + SMOLDYN_INPUT_FILE_EXTENSION;
							exportFile = new File(newExportFileName);
							
							PrintWriter pw = new PrintWriter(exportFile);
							SmoldynFileWriter smf = new SmoldynFileWriter(pw, true, null, simTask, false);
							smf.write();
							pw.close();	
						}
					}
					else if(scanCount == 1)// regular simulation, no parameter scan
					{
						SimulationTask simTask = new SimulationTask(new SimulationJob(selectedSim, 0, null),0);
						// export the simulation to the selected file
						PrintWriter pw = new PrintWriter(exportFile);
						SmoldynFileWriter smf = new SmoldynFileWriter(pw, true, null, simTask, false);
						smf.write();
						pw.close();
					}
					else
					{
						throw new Exception("Simulation scan count is smaller than 1.");
					}
				}
				return;
													
			} else {
				// convert it if other format
				if (!fileFilter.equals(FileFilters.FILE_FILTER_VCML)) {
					// SBML or CellML; get application name
					if ((fileFilter.equals(FileFilters.FILE_FILTER_SBML_12)) || (fileFilter.equals(FileFilters.FILE_FILTER_SBML_21)) || 
						(fileFilter.equals(FileFilters.FILE_FILTER_SBML_22)) || (fileFilter.equals(FileFilters.FILE_FILTER_SBML_23)) || 
						(fileFilter.equals(FileFilters.FILE_FILTER_SBML_24)) || (fileFilter.equals(FileFilters.FILE_FILTER_SBML_31_CORE)) || 
						(fileFilter.equals(FileFilters.FILE_FILTER_SBML_31_SPATIAL)) ) {
						SimulationContext selectedSimContext = (SimulationContext)hashTable.get("selectedSimContext");
						Simulation selectedSim = (Simulation)hashTable.get("selectedSimulation");
						int sbmlLevel = 0;
						int sbmlVersion = 0;
						int sbmlPkgVersion = 0;
						boolean bIsSpatial = false;
						if ((fileFilter.equals(FileFilters.FILE_FILTER_SBML_12))) {
							sbmlLevel = 1;
							sbmlVersion = 2;
						} else if (fileFilter.equals(FileFilters.FILE_FILTER_SBML_21)) {
							sbmlLevel = 2;
							sbmlVersion = 1;
						} else if (fileFilter.equals(FileFilters.FILE_FILTER_SBML_22)) {
							sbmlLevel = 2;
							sbmlVersion = 2;
						} else if (fileFilter.equals(FileFilters.FILE_FILTER_SBML_23)) {
							sbmlLevel = 2;
							sbmlVersion = 3;
						} else if (fileFilter.equals(FileFilters.FILE_FILTER_SBML_24)) {
							sbmlLevel = 2;
							sbmlVersion = 4;
						} else if (fileFilter.equals(FileFilters.FILE_FILTER_SBML_31_CORE)) {
							sbmlLevel = 3;
							sbmlVersion = 1;
						} else if (fileFilter.equals(FileFilters.FILE_FILTER_SBML_31_SPATIAL)) {
							sbmlLevel = 3;
							sbmlVersion = 1;
							sbmlPkgVersion = 1;
							bIsSpatial = true;
						}
						if (selectedSim == null) {
							resultString = XmlHelper.exportSBML(bioModel, sbmlLevel, sbmlVersion, sbmlPkgVersion, bIsSpatial, selectedSimContext, null);
							XmlUtil.writeXMLStringToFile(resultString, exportFile.getAbsolutePath(), true);
							return;
						} else {
							for (int sc = 0; sc < selectedSim.getScanCount(); sc++) {
								SimulationJob simJob = new SimulationJob(selectedSim, sc, null);
								resultString = XmlHelper.exportSBML(bioModel, sbmlLevel, sbmlVersion, sbmlPkgVersion, bIsSpatial, selectedSimContext, simJob);
								// Need to export each parameter scan into a separate file 
								String newExportFileName = exportFile.getPath().substring(0, exportFile.getPath().indexOf(".xml")) + "_" + sc + ".xml";
								exportFile.renameTo(new File(newExportFileName));
								XmlUtil.writeXMLStringToFile(resultString, exportFile.getAbsolutePath(), true);
							}
							return;
						}
					} else if (fileFilter.equals(FileFilters.FILE_FILTER_BNGL)) {
						RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
						StringWriter bnglStringWriter = new StringWriter();
						PrintWriter pw = new PrintWriter(bnglStringWriter);
						RbmNetworkGenerator.writeBngl(bioModel, pw);
						resultString = bnglStringWriter.toString();
						pw.close();
						
					} else if (fileFilter.equals(FileFilters.FILE_FILTER_NFSIM)) {
						// TODO: get the first thing we find for now, in the future we'll need to modify ChooseFile 
						//       to only offer the applications / simulations with bngl content
						SimulationContext simContexts[] = bioModel.getSimulationContexts();
						SimulationContext aSimulationContext = simContexts[0];
						Simulation selectedSim = aSimulationContext.getSimulations(0);
						//Simulation selectedSim = (Simulation)hashTable.get("selectedSimulation");
						SimulationTask simTask = new SimulationTask(new SimulationJob(selectedSim, 0, null),0);
						long randomSeed = 0;	// a fixed seed will allow us to run reproducible simulations
						//long randomSeed = System.currentTimeMillis();
						NFsimSimulationOptions nfsimSimulationOptions = new NFsimSimulationOptions();
						// we get the data we need from the math description
						Element root = NFsimXMLWriter.writeNFsimXML(simTask, randomSeed, nfsimSimulationOptions);
						Document doc = new Document();
						doc.setRootElement(root);
						XMLOutputter xmlOut = new XMLOutputter();
						resultString = xmlOut.outputString(doc);
	
					} else if (fileFilter.equals(FileFilters.FILE_FILTER_CELLML)) {
						Integer chosenSimContextIndex = (Integer)hashTable.get("chosenSimContextIndex");
						String applicationName = bioModel.getSimulationContext(chosenSimContextIndex.intValue()).getName();
						resultString = XmlHelper.exportCellML(bioModel, applicationName);
						// cellml still uses default character encoding for now ... maybe UTF-8 in the future
					} else if (fileFilter.equals(FileFilters.FILE_FILTER_SEDML)) {
						// export the entire biomodel to a SEDML file (for now, only non-spatial,non-stochastic applns)
						int sedmlLevel = 1;
						int sedmlVersion = 1;
						String sPath = FileUtils.getFullPathNoEndSeparator(exportFile.getAbsolutePath());
						String sFile = FileUtils.getBaseName(exportFile.getAbsolutePath());
						String sExt = FileUtils.getExtension(exportFile.getAbsolutePath());
						
						SEDMLExporter sedmlExporter = null;
						if (bioModel instanceof BioModel) {
							sedmlExporter = new SEDMLExporter(bioModel, sedmlLevel, sedmlVersion);
							resultString = sedmlExporter.getSEDMLFile(sPath);
						} else {
							throw new RuntimeException("unsupported Document Type " + bioModel.getClass().getName() + " for SedML export");
						}
						if(sExt.equals("sedx")) {
							sedmlExporter.createManifest(sPath, sFile);
							String sedmlFileName = sPath + FileUtils.WINDOWS_SEPARATOR + sFile + ".sedml";
							XmlUtil.writeXMLStringToFile(resultString, sedmlFileName, true);
							sedmlExporter.addSedmlFileToList(sFile + ".sedml");
							sedmlExporter.addSedmlFileToList("manifest.xml");
							sedmlExporter.createZipArchive(sPath, sFile);
							return;
						} else {
							XmlUtil.writeXMLStringToFile(resultString, exportFile.getAbsolutePath(), true);
						}
					}
				} else {
					// if format is VCML, get it from biomodel.
					bioModel.getVCMetaData().cleanupMetadata();
					resultString = XmlHelper.bioModelToXML(bioModel);
					XmlUtil.writeXMLStringToFile(resultString, exportFile.getAbsolutePath(), true);
					return;
				}
			}*/
        } else if (documentToExport instanceof MathModel) {
            MathModel mathModel = (MathModel) documentToExport;
            // check format requested
            if (fileFilter.equals(FileFilters.FILE_FILTER_MATLABV6)) {
                // check if it's ODE
                if (mathModel.getMathDescription() != null && (!mathModel.getMathDescription().isSpatial() && !mathModel.getMathDescription().isNonSpatialStoch())) {
                    MathDescription mathDesc = mathModel.getMathDescription();
                    resultString = exportMatlab(exportFile, fileFilter, mathDesc);
                } else {
                    throw new Exception("Matlab export failed: NOT an non-spatial deterministic model.");
                }
            } else if (fileFilter.equals(FileFilters.FILE_FILTER_PDF)) {
                FileOutputStream fos = new FileOutputStream(exportFile);
                documentManager.generatePDF(mathModel, fos);
                fos.close();
                // will take care of writing to the file as well.
                return;
            } else if (fileFilter.equals(FileFilters.FILE_FILTER_VCML)) {
                resultString = XmlHelper.mathModelToXML(mathModel);
            } else if (fileFilter.equals(FileFilters.FILE_FILTER_CELLML)) {
                resultString = XmlHelper.exportCellML(mathModel, null);
            } else if (fileFilter.equals(FileFilters.FILE_FILTER_SBML_23)) {
                resultString = XmlHelper.exportSBML(mathModel, 2, 3, 0, false, null, null);
            } else if (fileFilter.equals(FileFilters.FILE_FILTER_SBML_24)) {
                resultString = XmlHelper.exportSBML(mathModel, 2, 4, 0, false, null, null);
            } else // in simulation, we'll export multiple Smoldyn input files.
            if (fileFilter.equals(FileFilters.FILE_FILTER_SMOLDYN_INPUT)) {
                Simulation selectedSim = (Simulation) hashTable.get("selectedSimulation");
                if (selectedSim != null) {
                    int scanCount = selectedSim.getScanCount();
                    // -----
                    String baseExportFileName = (scanCount == 1 ? null : exportFile.getPath().substring(0, exportFile.getPath().indexOf(".")));
                    for (int i = 0; i < scanCount; i++) {
                        SimulationTask simTask = new SimulationTask(new SimulationJob(selectedSim, i, null), 0);
                        // Need to export each parameter scan into a separate file
                        File localExportFile = (scanCount == 1 ? exportFile : new File(baseExportFileName + "_" + i + SMOLDYN_INPUT_FILE_EXTENSION));
                        FileCloseHelper localCloseThis = new FileCloseHelper(localExportFile);
                        try {
                            SmoldynFileWriter smf = new SmoldynFileWriter(localCloseThis.getPrintWriter(), true, null, simTask, false);
                            smf.write();
                        } finally {
                            if (localCloseThis != null) {
                                localCloseThis.close();
                            }
                        }
                    }
                }
                return;
            }
        } else if (documentToExport instanceof Geometry) {
            Geometry geom = (Geometry) documentToExport;
            if (fileFilter.equals(FileFilters.FILE_FILTER_PDF)) {
                documentManager.generatePDF(geom, (closeThis = new FileCloseHelper(exportFile)).getFileOutputStream());
            } else if (fileFilter.equals(FileFilters.FILE_FILTER_VCML)) {
                resultString = XmlHelper.geometryToXML(geom);
            } else if (fileFilter.equals(FileFilters.FILE_FILTER_AVS)) {
                cbit.vcell.export.AVS_UCD_Exporter.writeUCDGeometryOnly(geom.getGeometrySurfaceDescription(), (closeThis = new FileCloseHelper(exportFile)).getFileWriter());
            } else if (fileFilter.equals(FileFilters.FILE_FILTER_STL)) {
                // make sure filename end with .stl
                File stlFile = exportFile;
                if (!exportFile.getName().toLowerCase().endsWith(".stl")) {
                    stlFile = new File(exportFile.getParentFile(), exportFile.getName() + ".stl");
                }
                cbit.vcell.geometry.surface.StlExporter.writeBinaryStl(geom.getGeometrySurfaceDescription(), (closeThis = new FileCloseHelper(stlFile)).getRandomAccessFile("rw"));
            } else if (fileFilter.equals(FileFilters.FILE_FILTER_PLY)) {
                writeStanfordPolygon(geom.getGeometrySurfaceDescription(), (closeThis = new FileCloseHelper(exportFile)).getFileWriter());
            }
        }
        if (resultString != null) {
            (closeThis = new FileCloseHelper(exportFile)).getFileWriter().write(resultString);
        }
    } finally {
        if (closeThis != null) {
            closeThis.close();
        }
    }
}
Also used : MathModel(cbit.vcell.mathmodel.MathModel) SimulationTask(cbit.vcell.messaging.server.SimulationTask) VCDocument(org.vcell.util.document.VCDocument) SmoldynFileWriter(org.vcell.solver.smoldyn.SmoldynFileWriter) MathDescription(cbit.vcell.math.MathDescription) DocumentManager(cbit.vcell.clientdb.DocumentManager) SelectorExtensionFilter(org.vcell.util.gui.exporter.SelectorExtensionFilter) SimulationContext(cbit.vcell.mapping.SimulationContext) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) ExtensionFilter(org.vcell.util.gui.exporter.ExtensionFilter) SelectorExtensionFilter(org.vcell.util.gui.exporter.SelectorExtensionFilter) BioModel(cbit.vcell.biomodel.BioModel) FileOutputStream(java.io.FileOutputStream) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) SimulationJob(cbit.vcell.solver.SimulationJob)

Example 14 with SimulationTask

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

the class RunRefSimulationFastOp method runFVSolverStandalone.

private void runFVSolverStandalone(File simulationDataDir, Simulation sim, ExternalDataIdentifier initialConditionExtDataID, ExternalDataIdentifier roiExtDataID, ExternalDataIdentifier psfExtDataID, ClientTaskStatusSupport progressListener, boolean bCheckSteadyState) throws Exception {
    FieldFunctionArguments[] fieldFunctionArgs = FieldUtilities.getFieldFunctionArguments(sim.getMathDescription());
    FieldDataIdentifierSpec[] fieldDataIdentifierSpecs = new FieldDataIdentifierSpec[fieldFunctionArgs.length];
    for (int i = 0; i < fieldDataIdentifierSpecs.length; i++) {
        if (fieldFunctionArgs[i].getFieldName().equals(initialConditionExtDataID.getName())) {
            fieldDataIdentifierSpecs[i] = new FieldDataIdentifierSpec(fieldFunctionArgs[i], initialConditionExtDataID);
        } else if (fieldFunctionArgs[i].getFieldName().equals(roiExtDataID.getName())) {
            fieldDataIdentifierSpecs[i] = new FieldDataIdentifierSpec(fieldFunctionArgs[i], roiExtDataID);
        } else if (fieldFunctionArgs[i].getFieldName().equals(psfExtDataID.getName())) {
            fieldDataIdentifierSpecs[i] = new FieldDataIdentifierSpec(fieldFunctionArgs[i], psfExtDataID);
        } else {
            throw new RuntimeException("failed to resolve field named " + fieldFunctionArgs[i].getFieldName());
        }
    }
    int jobIndex = 0;
    SimulationTask simTask = new SimulationTask(new SimulationJob(sim, jobIndex, fieldDataIdentifierSpecs), 0);
    SolverUtilities.prepareSolverExecutable(sim.getSolverTaskDescription().getSolverDescription());
    // if we need to check steady state, do the following two lines
    if (bCheckSteadyState) {
        simTask.getSimulation().getSolverTaskDescription().setStopAtSpatiallyUniformErrorTolerance(ErrorTolerance.getDefaultSpatiallyUniformErrorTolerance());
    }
    FVSolverStandalone fvSolver = new FVSolverStandalone(simTask, simulationDataDir, false);
    fvSolver.startSolver();
    // fvSolver.runSolver();
    SolverStatus status = fvSolver.getSolverStatus();
    while (status.getStatus() != SolverStatus.SOLVER_FINISHED && status.getStatus() != SolverStatus.SOLVER_ABORTED && status.getStatus() != SolverStatus.SOLVER_STOPPED) {
        if (progressListener != null) {
            progressListener.setProgress((int) (fvSolver.getProgress() * 100));
            if (progressListener.isInterrupted()) {
                fvSolver.stopSolver();
                throw UserCancelException.CANCEL_GENERIC;
            }
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            ex.printStackTrace(System.out);
        // catch interrupted exception and ignore it, otherwise it will popup a dialog in user interface saying"sleep interrupted"
        }
        status = fvSolver.getSolverStatus();
    }
    if (status.getStatus() != SolverStatus.SOLVER_FINISHED) {
        throw new Exception("Sover did not finish normally." + status);
    }
}
Also used : SimulationTask(cbit.vcell.messaging.server.SimulationTask) FieldFunctionArguments(cbit.vcell.field.FieldFunctionArguments) FieldDataIdentifierSpec(cbit.vcell.field.FieldDataIdentifierSpec) SolverStatus(cbit.vcell.solver.server.SolverStatus) SimulationJob(cbit.vcell.solver.SimulationJob) FVSolverStandalone(cbit.vcell.solvers.FVSolverStandalone) ImageException(cbit.image.ImageException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) IOException(java.io.IOException) UserCancelException(org.vcell.util.UserCancelException)

Example 15 with SimulationTask

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

the class RunRefSimulationOp method runFVSolverStandalone.

private static void runFVSolverStandalone(File simulationDataDir, Simulation sim, ExternalDataIdentifier initialConditionExtDataID, ClientTaskStatusSupport progressListener, boolean bCheckSteadyState) throws Exception {
    FieldFunctionArguments[] fieldFunctionArgs = FieldUtilities.getFieldFunctionArguments(sim.getMathDescription());
    FieldDataIdentifierSpec[] fieldDataIdentifierSpecs = new FieldDataIdentifierSpec[fieldFunctionArgs.length];
    for (int i = 0; i < fieldDataIdentifierSpecs.length; i++) {
        if (fieldFunctionArgs[i].getFieldName().equals(initialConditionExtDataID.getName())) {
            fieldDataIdentifierSpecs[i] = new FieldDataIdentifierSpec(fieldFunctionArgs[i], initialConditionExtDataID);
        } else {
            throw new RuntimeException("failed to resolve field named " + fieldFunctionArgs[i].getFieldName());
        }
    }
    int jobIndex = 0;
    SimulationTask simTask = new SimulationTask(new SimulationJob(sim, jobIndex, fieldDataIdentifierSpecs), 0);
    SolverUtilities.prepareSolverExecutable(sim.getSolverTaskDescription().getSolverDescription());
    // if we need to check steady state, do the following two lines
    if (bCheckSteadyState) {
        simTask.getSimulation().getSolverTaskDescription().setStopAtSpatiallyUniformErrorTolerance(ErrorTolerance.getDefaultSpatiallyUniformErrorTolerance());
    }
    FVSolverStandalone fvSolver = new FVSolverStandalone(simTask, simulationDataDir, false);
    fvSolver.startSolver();
    // fvSolver.runSolver();
    SolverStatus status = fvSolver.getSolverStatus();
    while (status.getStatus() != SolverStatus.SOLVER_FINISHED && status.getStatus() != SolverStatus.SOLVER_ABORTED && status.getStatus() != SolverStatus.SOLVER_STOPPED) {
        if (progressListener != null) {
            progressListener.setProgress((int) (fvSolver.getProgress() * 100));
            if (progressListener.isInterrupted()) {
                fvSolver.stopSolver();
                throw UserCancelException.CANCEL_GENERIC;
            }
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            ex.printStackTrace(System.out);
        // catch interrupted exception and ignore it, otherwise it will popup a dialog in user interface saying"sleep interrupted"
        }
        status = fvSolver.getSolverStatus();
    }
    if (status.getStatus() != SolverStatus.SOLVER_FINISHED) {
        throw new Exception("Sover did not finish normally." + status);
    }
}
Also used : SimulationTask(cbit.vcell.messaging.server.SimulationTask) FieldFunctionArguments(cbit.vcell.field.FieldFunctionArguments) FieldDataIdentifierSpec(cbit.vcell.field.FieldDataIdentifierSpec) SolverStatus(cbit.vcell.solver.server.SolverStatus) SimulationJob(cbit.vcell.solver.SimulationJob) FVSolverStandalone(cbit.vcell.solvers.FVSolverStandalone) ImageException(cbit.image.ImageException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) IOException(java.io.IOException) UserCancelException(org.vcell.util.UserCancelException)

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