Search in sources :

Example 41 with BioModel

use of cbit.vcell.biomodel.BioModel in project vcell by virtualcell.

the class ChooseFile method showBioModelXMLFileChooser.

/**
 * Insert the method's description here.
 * Creation date: (5/31/2004 6:04:14 PM)
 */
private File showBioModelXMLFileChooser(Hashtable<String, Object> hashTable) throws java.lang.Exception {
    BioModel bioModel = (BioModel) hashTable.get("documentToExport");
    JFrame currentWindow = (JFrame) hashTable.get("currentWindow");
    UserPreferences userPreferences = (UserPreferences) hashTable.get("userPreferences");
    TopLevelWindowManager topLevelWindowManager = (TopLevelWindowManager) hashTable.get("topLevelWindowManager");
    SelectorExtensionFilter forceFileFilter = null;
    {
        Object obj = hashTable.get(FORCE_FILE_FILTER);
        if (obj != null) {
            VCAssert.ofType(obj, SelectorExtensionFilter.class);
            forceFileFilter = (SelectorExtensionFilter) obj;
            VCAssert.assertTrue(forceFileFilter.supports(Selector.FULL_MODEL), "only " + Selector.FULL_MODEL + " filters supported for force file filter");
        }
    }
    if (topLevelWindowManager == null) {
        throw new RuntimeException("toplLevelWindowManager required");
    }
    File defaultPath = userPreferences.getCurrentDialogPath();
    // JFileChooser fileChooser = new JFileChooser(defaultPath);
    VCFileChooser fileChooser = new VCFileChooser(defaultPath);
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    final SimulationContext[] simContexts = bioModel.getSimulationContexts();
    boolean spatialDeterministicSim = false;
    boolean nonspatialDeterministicSim = false;
    boolean stochasticSim = false;
    @SuppressWarnings("unused") boolean // add logic to set this
    bnglSim = false;
    for (SimulationContext sc : simContexts) {
        if (sc.getApplicationType() == Application.NETWORK_STOCHASTIC) {
            stochasticSim = true;
        } else {
            if (sc.getGeometry().getDimension() > 0) {
                spatialDeterministicSim = true;
            } else {
                nonspatialDeterministicSim = true;
            }
        }
    }
    FileFilter defaultFileFilter;
    if (forceFileFilter == null) {
        List<FileFilter> dlist = FileFilters.supports(SelectorExtensionFilter.Selector.DEFAULT);
        VCAssert.assertTrue(dlist.size() == 1, "Exactly one filter must be designated default");
        defaultFileFilter = dlist.get(0);
        // use a set to avoid duplicated entries; TreeSet show listing is alphabetical
        Set<FileFilter> filters = new TreeSet<>();
        filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.FULL_MODEL));
        if (spatialDeterministicSim) {
            filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.DETERMINISTIC, SelectorExtensionFilter.Selector.SPATIAL));
        }
        if (nonspatialDeterministicSim) {
            filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.DETERMINISTIC, SelectorExtensionFilter.Selector.NONSPATIAL));
        }
        if (stochasticSim) {
            filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.STOCHASTIC));
        }
        /*add BNGL selector here
		if (bnglSim) {
			filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.BNGL));
		}
		*/
        fileChooser.addChoosableFileFilter(defaultFileFilter);
        for (FileFilter f : filters) {
            if (f == defaultFileFilter) {
                continue;
            }
            fileChooser.addChoosableFileFilter(f);
        }
    /*
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_12);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_21);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_22);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_23);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_24);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_31_CORE);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_31_SPATIAL);
	//	fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_CELLML);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SEDML);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_VCML);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_MATLABV6);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_PDF);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SMOLDYN_INPUT);
		*/
    } else {
        defaultFileFilter = forceFileFilter;
    }
    // remove all selectors
    fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
    // Set the default file filter...
    fileChooser.setFileFilter(defaultFileFilter);
    fileChooser.setSelectedFile(new java.io.File(TokenMangler.fixTokenStrict(bioModel.getName())));
    fileChooser.setDialogTitle("Export Virtual Cell BioModel As...");
    if (fileChooser.showSaveDialog(currentWindow) != JFileChooser.APPROVE_OPTION) {
        // user didn't choose save
        throw UserCancelException.CANCEL_FILE_SELECTION;
    }
    File selectedFile = fileChooser.getSelectedFile();
    FileFilter gfileFilter = fileChooser.getFileFilter();
    VCAssert.ofType(gfileFilter, SelectorExtensionFilter.class);
    // only ExtensionFilters should have been added;
    SelectorExtensionFilter fileFilter = (SelectorExtensionFilter) gfileFilter;
    if (selectedFile == null) {
        // no file selected (no name given)
        throw UserCancelException.CANCEL_FILE_SELECTION;
    }
    final File fileUserSpecified = selectedFile.getCanonicalFile();
    // /
    String selectedFileName = recordAndRemoveExtension(selectedFile.getPath());
    if (extensionUserProvided != null && !extensionUserProvided.isEmpty() && !extensionUserProvided.startsWith(".")) {
        extensionUserProvided = "." + extensionUserProvided;
    }
    if (fileFilter.isValidExtension(extensionUserProvided)) {
        selectedFileName += extensionUserProvided;
    } else {
        selectedFileName += fileFilter.getPrimaryExtension();
    }
    selectedFile = new File(selectedFileName);
    checkForOverwrites(selectedFile, topLevelWindowManager.getComponent(), userPreferences);
    // put the filter in the hash so the export task knows what to do...
    hashTable.put(FILE_FILTER, fileFilter);
    if (fileFilter.supports(SelectorExtensionFilter.Selector.FULL_MODEL)) {
        // nothing more to do in this case
        resetPreferredFilePath(selectedFile, userPreferences);
        return selectedFile;
    }
    // ArrayList<String> applicableAppNameList = new ArrayList<String>();
    ArrayList<SimulationContext> applicableSimContexts = new ArrayList<>();
    for (SimulationContext sc : simContexts) {
        if (sc.getGeometry().getDimension() == 0) {
            if (!fileFilter.supports(SelectorExtensionFilter.Selector.NONSPATIAL)) {
                continue;
            }
        } else if (!fileFilter.supports(SelectorExtensionFilter.Selector.SPATIAL)) {
            continue;
        }
        if (sc.getApplicationType() == Application.NETWORK_STOCHASTIC) {
            if (!fileFilter.supports(SelectorExtensionFilter.Selector.STOCHASTIC)) {
                continue;
            }
        } else if (!fileFilter.supports(SelectorExtensionFilter.Selector.DETERMINISTIC)) {
            continue;
        }
        applicableSimContexts.add(sc);
    }
    /*
		{} else {
			// all apps
			for (int i=0;i<simContexts.length;i++){
				applicableAppNameList.add(simContexts[i].getName());
			}
		}
	 */
    SimulationContext chosenSimContext = null;
    if (applicableSimContexts.size() == 1) {
        chosenSimContext = applicableSimContexts.get(0);
    } else /*
		else if (!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_PDF.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_12.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_21.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_22.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_23.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_24.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_31_CORE.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_31_SPATIAL.getDescription())) {
			if(fileFilter.getDescription().equals(FileFilters.FILE_FILTER_BNGL.getDescription())) {
				boolean hasReactions = bioModel.getModel().getReactionSteps().length > 0 ? true : false;
				System.out.println(hasReactions);
				if(hasReactions) {					// mixed
					String errMsg = "Simple Reactions cannot be exported to .bngl format.";
					errMsg += "<br>Some information will be lost.";
					errMsg += "<br><br>Continue anyway?";
					errMsg = "<html>" + errMsg + "</html>";
					int dialogButton = JOptionPane.YES_NO_OPTION;
					int returnCode = JOptionPane.showConfirmDialog(topLevelWindowManager.getComponent(), errMsg, "Exporting to .bngl", dialogButton);
					if (returnCode != JOptionPane.YES_OPTION) {
						throw UserCancelException.CANCEL_FILE_SELECTION;
					}
				}
			}

			//String[] applicationNames = (String[])org.vcell.util.BeanUtils.getArray(applicableAppNameList,String.class);
		}	 */
    {
        // String[] applicationNames = applicableAppNameList.toArray(new String[applicableAppNameList.size()]);
        SimContextAdapter[] scarray = adapt(applicableSimContexts);
        Object choice = PopupGenerator.showListDialog(topLevelWindowManager, scarray, "Please select Application");
        if (choice == null) {
            throw UserCancelException.CANCEL_FILE_SELECTION;
        }
        VCAssert.ofType(choice, SimContextAdapter.class);
        SimContextAdapter sca = (SimContextAdapter) choice;
        chosenSimContext = sca.simCtx;
    }
    hashTable.put(SIM_CONTEXT, chosenSimContext);
    // boolean isSbml = fileFilter.supports(SelectorExtensionFilter.Selector.SBML);
    if (fileFilter.requiresMoreChoices()) {
        ExtensionFilter.ChooseContext ctx = new ExtensionFilter.ChooseContext(hashTable, topLevelWindowManager, currentWindow, chosenSimContext, selectedFile, selectedFileName);
        fileFilter.askUser(ctx);
    }
    {
        boolean showConfirm = false;
        final boolean someContextsFiltered = simContexts.length > applicableSimContexts.size();
        showConfirm = someContextsFiltered;
        if (!showConfirm) {
            final File fileAfterProcessing = selectedFile.getCanonicalFile();
            if (!fileAfterProcessing.equals(fileUserSpecified)) {
                final String nameUserSpecified = fileUserSpecified.getCanonicalPath();
                final String nameAfterProcessing = fileAfterProcessing.getCanonicalPath();
                if (FilenameUtils.indexOfExtension(nameUserSpecified) > 0) {
                    // have extension on user path
                    showConfirm = true;
                } else {
                    // don't prompt if user left extension off
                    String nameAfterNoExtension = FilenameUtils.getFullPath(nameAfterProcessing) + FilenameUtils.getBaseName(nameAfterProcessing);
                    if (!nameAfterNoExtension.equals(nameUserSpecified)) {
                        showConfirm = true;
                    }
                }
            }
        }
        if (showConfirm) {
            final String exportDesc = fileFilter.getShortDescription();
            StringBuilder sb = new StringBuilder();
            List<SimulationContext> all = new ArrayList<>(Arrays.asList(simContexts));
            all.removeAll(applicableSimContexts);
            if (!all.isEmpty()) {
                SimContextAdapter[] removed = adapt(all);
                sb.append("The following simulations are not supported by ");
                sb.append(exportDesc);
                sb.append(" and have been removed: ");
                sb.append(StringUtils.join(removed, ", "));
                sb.append(".\n\n");
            }
            SimContextAdapter[] included = adapt(applicableSimContexts);
            sb.append("Export model with simulations ");
            sb.append(StringUtils.join(included, ", "));
            sb.append(" to file of type ");
            sb.append(exportDesc);
            sb.append(' ');
            sb.append(selectedFile.getCanonicalPath());
            sb.append('?');
            String reply = DialogUtils.showOKCancelWarningDialog(currentWindow, "Verify Export", sb.toString());
            if (!SimpleUserMessage.OPTION_OK.equals(reply)) {
                throw UserCancelException.CANCEL_GENERIC;
            }
        }
    }
    resetPreferredFilePath(selectedFile, userPreferences);
    return selectedFile;
}
Also used : UserPreferences(cbit.vcell.client.server.UserPreferences) TopLevelWindowManager(cbit.vcell.client.TopLevelWindowManager) ArrayList(java.util.ArrayList) JFrame(javax.swing.JFrame) TreeSet(java.util.TreeSet) ExtensionFilter(org.vcell.util.gui.exporter.ExtensionFilter) SelectorExtensionFilter(org.vcell.util.gui.exporter.SelectorExtensionFilter) VCFileChooser(org.vcell.util.gui.VCFileChooser) ArrayList(java.util.ArrayList) List(java.util.List) FileFilter(javax.swing.filechooser.FileFilter) SelectorExtensionFilter(org.vcell.util.gui.exporter.SelectorExtensionFilter) SimulationContext(cbit.vcell.mapping.SimulationContext) File(java.io.File) BioModel(cbit.vcell.biomodel.BioModel) File(java.io.File)

Example 42 with BioModel

use of cbit.vcell.biomodel.BioModel in project vcell by virtualcell.

the class DocumentValidTask 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 {
    DocumentWindowManager documentWindowManager = (DocumentWindowManager) hashTable.get(CommonTask.DOCUMENT_WINDOW_MANAGER.name);
    if (documentWindowManager.getVCDocument() instanceof BioModel) {
        // try to successfully generate math and geometry region info
        BioModel bioModel = (BioModel) documentWindowManager.getVCDocument();
        SimulationContext[] scArray = bioModel.getSimulationContexts();
        if (scArray != null) {
            MathDescription[] mathDescArray = new MathDescription[scArray.length];
            for (int i = 0; i < scArray.length; i++) {
                // check if all structure sizes are specified
                scArray[i].checkValidity();
                // 
                // compute Geometric Regions if necessary
                // 
                cbit.vcell.geometry.surface.GeometrySurfaceDescription geoSurfaceDescription = scArray[i].getGeometry().getGeometrySurfaceDescription();
                if (geoSurfaceDescription != null && geoSurfaceDescription.getGeometricRegions() == null) {
                    cbit.vcell.geometry.surface.GeometrySurfaceUtils.updateGeometricRegions(geoSurfaceDescription);
                }
                if (scArray[i].getModel() != bioModel.getModel()) {
                    throw new Exception("The BioModel's physiology doesn't match that for Application '" + scArray[i].getName() + "'");
                }
                // 
                // create new MathDescription
                // 
                MathDescription math = scArray[i].createNewMathMapping().getMathDescription();
                // 
                // load MathDescription into SimulationContext
                // (BioModel is responsible for propagating this to all applicable Simulations).
                // 
                mathDescArray[i] = math;
            }
            hashTable.put("mathDescArray", mathDescArray);
        }
        // check issues for errors
        DocumentValidUtil.checkIssuesForErrors(bioModel);
    // Vector<Issue> issueList = new Vector<Issue>();
    // IssueContext issueContext = new IssueContext();
    // bioModel.gatherIssues(issueContext,issueList);
    // for (int i = 0; i < issueList.size(); i++){
    // Issue issue = issueList.elementAt(i);
    // if (issue.getSeverity() == Issue.SEVERITY_ERROR){
    // String errMsg = "Error: ";
    // Object issueSource = issue.getSource();
    // if (issueSource instanceof OutputFunctionIssueSource) {
    // SimulationOwner simulationOwner = ((OutputFunctionIssueSource)issueSource).getOutputFunctionContext().getSimulationOwner();
    // String funcName = ((OutputFunctionIssueSource)issueSource).getAnnotatedFunction().getDisplayName();
    // if (simulationOwner instanceof SimulationContext) {
    // String opErrMsg = "Output Function '" + funcName + "' in application '" + simulationOwner.getName() + "' ";
    // if (issue.getCategory().equals(IssueCategory.OUTPUTFUNCTIONCONTEXT_FUNCTION_EXPBINDING)) {
    // opErrMsg += "refers to an unknown variable. Either the model changed or this version of VCell generates variable names differently.\n\n";
    // }
    // errMsg += opErrMsg;
    // }
    // }
    // throw new Exception(errMsg + issue.getMessage());
    // }
    // }
    }
    if (documentWindowManager.getVCDocument() instanceof cbit.vcell.geometry.Geometry) {
        // try to successfully generate GeometricRegions if spatial and not present.
        cbit.vcell.geometry.Geometry geometry = (cbit.vcell.geometry.Geometry) documentWindowManager.getVCDocument();
        if (geometry.getGeometrySurfaceDescription() != null && geometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
            try {
                cbit.vcell.geometry.surface.GeometrySurfaceUtils.updateGeometricRegions(geometry.getGeometrySurfaceDescription());
            } catch (Exception e) {
                throw new Exception("Error determining regions in spatial geometry '" + geometry.getName() + "': \n" + e.getMessage());
            }
        }
    }
    if (documentWindowManager.getVCDocument() instanceof cbit.vcell.mathmodel.MathModel) {
        // try to successfully generate GeometricRegions if spatial and not present.
        cbit.vcell.mathmodel.MathModel mathModel = (cbit.vcell.mathmodel.MathModel) documentWindowManager.getVCDocument();
        cbit.vcell.geometry.Geometry geometry = mathModel.getMathDescription().getGeometry();
        if (geometry.getGeometrySurfaceDescription() != null && geometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
            try {
                cbit.vcell.geometry.surface.GeometrySurfaceUtils.updateGeometricRegions(geometry.getGeometrySurfaceDescription());
            } catch (Exception e) {
                throw new Exception("Error determining regions in spatial geometry '" + geometry.getName() + "': \n" + e.getMessage());
            }
        }
    }
}
Also used : MathDescription(cbit.vcell.math.MathDescription) SimulationContext(cbit.vcell.mapping.SimulationContext) DocumentWindowManager(cbit.vcell.client.DocumentWindowManager) BioModel(cbit.vcell.biomodel.BioModel)

Example 43 with BioModel

use of cbit.vcell.biomodel.BioModel 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 44 with BioModel

use of cbit.vcell.biomodel.BioModel in project vcell by virtualcell.

the class BioModelTreeModel method propertyChange.

/**
 * Insert the method's description here.
 * Creation date: (5/9/01 8:28:22 AM)
 * @param evt java.beans.PropertyChangeEvent
 */
public void propertyChange(java.beans.PropertyChangeEvent evt) {
    try {
        if (evt.getSource() == getBioModel() && evt.getPropertyName().equals("simulations")) {
            refreshTree();
            Simulation[] oldSims = (Simulation[]) evt.getOldValue();
            if (oldSims != null) {
                for (int i = 0; i < oldSims.length; i++) {
                    oldSims[i].removePropertyChangeListener(this);
                }
            }
            Simulation[] newSims = (Simulation[]) evt.getNewValue();
            if (newSims != null) {
                for (int i = 0; i < newSims.length; i++) {
                    newSims[i].addPropertyChangeListener(this);
                }
            }
        } else if (evt.getSource() == getBioModel() && evt.getPropertyName().equals("simulationContexts")) {
            refreshTree();
            SimulationContext[] oldSCs = (SimulationContext[]) evt.getOldValue();
            if (oldSCs != null) {
                for (int i = 0; i < oldSCs.length; i++) {
                    oldSCs[i].removePropertyChangeListener(this);
                }
            }
            SimulationContext[] newSCs = (SimulationContext[]) evt.getNewValue();
            if (newSCs != null) {
                for (int i = 0; i < newSCs.length; i++) {
                    newSCs[i].addPropertyChangeListener(this);
                }
            }
        } else if (evt.getSource() == getBioModel() && evt.getPropertyName().equals("description")) {
            BioModel bioModel = (BioModel) evt.getSource();
            BioModelNode bioModelNode = ((BioModelNode) getRoot()).findNodeByUserObject(bioModel);
            BioModelNode annotNode = bioModelNode.findNodeByUserObject(new Annotation((String) evt.getOldValue()));
            if (annotNode == null && evt.getNewValue() != null && !((String) evt.getNewValue()).equals("")) {
                // 
                // must add annotation node (was null string)
                // 
                bioModelNode.insert(new BioModelNode(new Annotation((String) evt.getNewValue()), false), 0);
                nodeStructureChanged(bioModelNode);
            } else if (annotNode != null && evt.getNewValue() != null && !((String) evt.getNewValue()).equals("")) {
                // 
                // change annotation content for annotation node
                // 
                annotNode.setUserObject(new Annotation((String) evt.getNewValue()));
                nodeChanged(annotNode);
            } else if (annotNode != null && (evt.getNewValue() == null || ((String) evt.getNewValue()).equals(""))) {
                // 
                // delete annotation node
                // 
                removeNodeFromParent(annotNode);
            }
        } else if (evt.getSource() instanceof Simulation) {
            if (evt.getPropertyName().equals("name")) {
                Simulation sim = (Simulation) evt.getSource();
                BioModelNode simNode = ((BioModelNode) getRoot()).findNodeByUserObject(sim);
                nodeChanged(simNode);
            } else if (evt.getPropertyName().equals("description")) {
                Simulation sim = (Simulation) evt.getSource();
                BioModelNode simNode = ((BioModelNode) getRoot()).findNodeByUserObject(sim);
                BioModelNode annotNode = simNode.findNodeByUserObject(new Annotation((String) evt.getOldValue()));
                if (annotNode == null && evt.getNewValue() != null && !((String) evt.getNewValue()).equals("")) {
                    // 
                    // must add annotation node (was null string)
                    // 
                    simNode.insert(new BioModelNode(new Annotation((String) evt.getNewValue()), false), 0);
                    nodeStructureChanged(simNode);
                } else if (annotNode != null && evt.getNewValue() != null && !((String) evt.getNewValue()).equals("")) {
                    // 
                    // change annotation content for annotation node
                    // 
                    annotNode.setUserObject(new Annotation((String) evt.getNewValue()));
                    nodeChanged(annotNode);
                } else if (annotNode != null && (evt.getNewValue() == null || ((String) evt.getNewValue()).equals(""))) {
                    // 
                    // delete annotation node
                    // 
                    removeNodeFromParent(annotNode);
                }
            }
        } else if (evt.getSource() instanceof SimulationContext) {
            if (evt.getPropertyName().equals("geometry")) {
                Geometry oldGeometry = (Geometry) evt.getOldValue();
                Geometry newGeometry = (Geometry) evt.getNewValue();
                BioModelNode geoNode = ((BioModelNode) getRoot()).findNodeByUserObject(oldGeometry);
                geoNode.setUserObject(newGeometry);
                nodeChanged(geoNode);
            } else if (evt.getPropertyName().equals("name")) {
                SimulationContext simContext = (SimulationContext) evt.getSource();
                BioModelNode scNode = ((BioModelNode) getRoot()).findNodeByUserObject(simContext);
                nodeChanged(scNode);
            } else if (evt.getPropertyName().equals("description")) {
                SimulationContext simContext = (SimulationContext) evt.getSource();
                BioModelNode scNode = ((BioModelNode) getRoot()).findNodeByUserObject(simContext);
                BioModelNode annotNode = scNode.findNodeByUserObject(new Annotation((String) evt.getOldValue()));
                if (annotNode == null && evt.getNewValue() != null && !((String) evt.getNewValue()).equals("")) {
                    // 
                    // must add annotation node (was null string)
                    // 
                    scNode.insert(new BioModelNode(new Annotation((String) evt.getNewValue()), false), 0);
                    nodeStructureChanged(scNode);
                } else if (annotNode != null && evt.getNewValue() != null && !((String) evt.getNewValue()).equals("")) {
                    // 
                    // change annotation content for annotation node
                    // 
                    annotNode.setUserObject(new Annotation((String) evt.getNewValue()));
                    nodeChanged(annotNode);
                } else if (annotNode != null && (evt.getNewValue() == null || ((String) evt.getNewValue()).equals(""))) {
                    // 
                    // delete annotation node
                    // 
                    removeNodeFromParent(annotNode);
                }
            } else if (evt.getPropertyName().equals("mathDescription")) {
                SimulationContext simContext = (SimulationContext) evt.getSource();
                BioModelNode scNode = ((BioModelNode) getRoot()).findNodeByUserObject(simContext);
                nodeStructureChanged(scNode);
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}
Also used : Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) BioModel(cbit.vcell.biomodel.BioModel) SimulationContext(cbit.vcell.mapping.SimulationContext)

Example 45 with BioModel

use of cbit.vcell.biomodel.BioModel in project vcell by virtualcell.

the class BioModelTreeModel method setBioModel.

/**
 * Sets the bioModel property (cbit.vcell.biomodel.BioModel) value.
 * @param bioModel The new value for the property.
 * @see #getBioModel
 */
public void setBioModel(cbit.vcell.biomodel.BioModel bioModel) {
    cbit.vcell.biomodel.BioModel oldValue = fieldBioModel;
    if (oldValue != null) {
        oldValue.removePropertyChangeListener(this);
        SimulationContext[] SCs = oldValue.getSimulationContexts();
        for (int i = 0; SCs != null && i < SCs.length; i++) {
            SCs[i].removePropertyChangeListener(this);
            SCs[i].getGeometryContext().removePropertyChangeListener(this);
        }
        Simulation[] sims = oldValue.getSimulations();
        for (int i = 0; sims != null && i < sims.length; i++) {
            sims[i].removePropertyChangeListener(this);
        }
        oldValue.getVCMetaData().removeAnnotationEventListener(this);
    }
    fieldBioModel = bioModel;
    if (bioModel != null) {
        bioModel.addPropertyChangeListener(this);
        SimulationContext[] SCs = bioModel.getSimulationContexts();
        for (int i = 0; SCs != null && i < SCs.length; i++) {
            SCs[i].addPropertyChangeListener(this);
            SCs[i].getGeometryContext().addPropertyChangeListener(this);
        }
        Simulation[] sims = bioModel.getSimulations();
        for (int i = 0; sims != null && i < sims.length; i++) {
            sims[i].addPropertyChangeListener(this);
        }
        bioModel.getVCMetaData().addAnnotationEventListener(this);
    }
    firePropertyChange("bioModel", oldValue, bioModel);
    refreshTree();
}
Also used : Simulation(cbit.vcell.solver.Simulation) BioModel(cbit.vcell.biomodel.BioModel) SimulationContext(cbit.vcell.mapping.SimulationContext)

Aggregations

BioModel (cbit.vcell.biomodel.BioModel)158 SimulationContext (cbit.vcell.mapping.SimulationContext)72 Simulation (cbit.vcell.solver.Simulation)53 XMLSource (cbit.vcell.xml.XMLSource)37 KeyValue (org.vcell.util.document.KeyValue)36 MathModel (cbit.vcell.mathmodel.MathModel)33 DataAccessException (org.vcell.util.DataAccessException)29 XmlParseException (cbit.vcell.xml.XmlParseException)28 File (java.io.File)28 Model (cbit.vcell.model.Model)27 BioModelInfo (org.vcell.util.document.BioModelInfo)25 MathDescription (cbit.vcell.math.MathDescription)24 IOException (java.io.IOException)24 BigString (org.vcell.util.BigString)22 Geometry (cbit.vcell.geometry.Geometry)21 UserCancelException (org.vcell.util.UserCancelException)20 User (org.vcell.util.document.User)20 ObjectNotFoundException (org.vcell.util.ObjectNotFoundException)19 SpeciesContext (cbit.vcell.model.SpeciesContext)17 VCDocument (org.vcell.util.document.VCDocument)16