Search in sources :

Example 1 with VCDocument

use of org.vcell.util.document.VCDocument in project vcell by virtualcell.

the class PDEExportDataPanel method createSimulationSelector.

private ExportSpecs.SimulationSelector createSimulationSelector() {
    ExportSpecs.SimulationSelector simulationSelector = new ExportSpecs.SimulationSelector() {

        private ExportSpecs.SimNameSimDataID[] multiSimNameSimDataIDs;

        // private ExportSpecs.ExportParamScanInfo exportParamScanInfo;
        private int[] selectedParamScanIndexes;

        private Simulation[] simulations;

        public SimNameSimDataID[] getSelectedSimDataInfo() {
            // }
            if (multiSimNameSimDataIDs == null) {
                return new ExportSpecs.SimNameSimDataID[] { currentSimNameSimDataID };
            }
            return multiSimNameSimDataIDs;
        }

        public void selectSimulations() {
            getNumAvailableSimulations();
            String[][] rowData = new String[simulations.length][5];
            for (int i = 0; i < rowData.length; i++) {
                rowData[i][0] = simulations[i].getName();
                rowData[i][1] = simulations[i].getMeshSpecification().getSamplingSize().toString();
                rowData[i][2] = simulations[i].getSolverTaskDescription().getExpectedNumTimePoints() + "";
                rowData[i][3] = simulations[i].getSolverTaskDescription().getTimeBounds().getEndingTime() + "";
                rowData[i][4] = simulations[i].getSolverTaskDescription().getOutputTimeSpec().getShortDescription();
            }
            try {
                int[] choices = DialogUtils.showComponentOKCancelTableList(PDEExportDataPanel.this, "Choose Sims to export together", new String[] { "Simulation", "Mesh x,y,z", "NumTimePoints", "EndTime", "Output Descr." }, rowData, ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
                if (choices != null) {
                    multiSimNameSimDataIDs = new ExportSpecs.SimNameSimDataID[choices.length];
                    for (int i = 0; i < choices.length; i++) {
                        multiSimNameSimDataIDs[i] = new ExportSpecs.SimNameSimDataID(simulations[choices[i]].getName(), simulations[choices[i]].getSimulationInfo().getAuthoritativeVCSimulationIdentifier(), SimResultsViewer.getParamScanInfo(simulations[choices[i]], (currentSimNameSimDataID == null ? 0 : currentSimNameSimDataID.getDefaultJobIndex())));
                    }
                }
            } catch (UserCancelException uce) {
            // ignore
            }
        }

        public void selectParamScanInfo() {
            String[][] rowData = new String[currentSimNameSimDataID.getExportParamScanInfo().getParamScanJobIndexes().length][currentSimNameSimDataID.getExportParamScanInfo().getParamScanConstantNames().length];
            for (int i = 0; i < rowData.length; i++) {
                for (int j = 0; j < rowData[i].length; j++) {
                    rowData[i][j] = currentSimNameSimDataID.getExportParamScanInfo().getParamScanConstantValues()[i][j];
                }
            }
            try {
                int[] choices = DialogUtils.showComponentOKCancelTableList(PDEExportDataPanel.this, "Choose ParameterScans to export together", currentSimNameSimDataID.getExportParamScanInfo().getParamScanConstantNames(), rowData, ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
                if (choices != null && choices.length > 0) {
                    selectedParamScanIndexes = new int[choices.length];
                    // String[][] selectedParamScanValues = new String[choices.length][currentSimNameSimDataID.getExportParamScanInfo().getParamScanConstantNames().length];
                    for (int i = 0; i < choices.length; i++) {
                        selectedParamScanIndexes[i] = choices[i];
                    // for (int j = 0; j < currentSimNameSimDataID.getExportParamScanInfo().getParamScanConstantNames().length; j++) {
                    // selectedParamScanValues[i][j] = currentSimNameSimDataID.getExportParamScanInfo().getParamScanConstantValues()[choices[i]][j];
                    // }
                    }
                // exportParamScanInfo =
                // new ExportSpecs.ExportParamScanInfo(selectedParamScanIndexes, selectedParamScanIndexes[0], currentSimNameSimDataID.getExportParamScanInfo().getParamScanConstantNames(), selectedParamScanValues);
                } else {
                    selectedParamScanIndexes = null;
                }
            } catch (UserCancelException uce) {
            // ignore
            }
        }

        public int[] getselectedParamScanIndexes() {
            return selectedParamScanIndexes;
        }

        public int getNumAvailableParamScans() {
            if (currentSimNameSimDataID == null || currentSimNameSimDataID.getExportParamScanInfo() == null) {
                return 0;
            }
            return currentSimNameSimDataID.getExportParamScanInfo().getParamScanJobIndexes().length;
        }

        public int getNumAvailableSimulations() {
            if (simulations == null) {
                VCDocument thisDocument = (getDataViewerManager() instanceof DocumentWindowManager ? ((DocumentWindowManager) getDataViewerManager()).getVCDocument() : null);
                if (thisDocument instanceof BioModel) {
                    String thisSimContextName = dataInfoProvider.getSimulationModelInfo().getContextName();
                    SimulationContext[] simContexts = ((BioModel) thisDocument).getSimulationContexts();
                    SimulationContext thisSimulationContext = null;
                    for (int i = 0; i < simContexts.length; i++) {
                        if (thisSimContextName.equals(thisDocument.getName() + "::" + simContexts[i].getName())) {
                            thisSimulationContext = simContexts[i];
                            break;
                        }
                    }
                    simulations = thisSimulationContext.getSimulations();
                } else if (thisDocument instanceof MathModel) {
                    simulations = ((MathModel) thisDocument).getSimulations();
                } else {
                    simulations = new Simulation[0];
                }
            }
            return simulations.length;
        }
    };
    return simulationSelector;
}
Also used : MathModel(cbit.vcell.mathmodel.MathModel) VCDocument(org.vcell.util.document.VCDocument) ExportSpecs(cbit.vcell.export.server.ExportSpecs) UserCancelException(org.vcell.util.UserCancelException) SimulationContext(cbit.vcell.mapping.SimulationContext) SimNameSimDataID(cbit.vcell.export.server.ExportSpecs.SimNameSimDataID) Simulation(cbit.vcell.solver.Simulation) SimNameSimDataID(cbit.vcell.export.server.ExportSpecs.SimNameSimDataID) DocumentWindowManager(cbit.vcell.client.DocumentWindowManager) BioModel(cbit.vcell.biomodel.BioModel)

Example 2 with VCDocument

use of org.vcell.util.document.VCDocument in project vcell by virtualcell.

the class TMLPanel method processComparisonResult.

// process events for loading the model displayed in the comparison panel
public VCDocument processComparisonResult() throws Exception {
    try {
        NodeInfo root = (NodeInfo) getTree().getModel().getRoot();
        // if (!isNormal(root)) {
        // displayMessage(this, "Please resolve all tagged elements/attributes before proceeding.");
        // }
        String xmlStr = root.toXmlString();
        // System.out.println(xmlStr);
        Element rootElement = (XmlUtil.stringToXML(xmlStr, null)).getRootElement();
        // ?
        XmlReader reader = new XmlReader(true);
        String rootName = rootElement.getName();
        Document doc = rootElement.getDocument();
        VCDocument vcDoc = null;
        if (rootName.equals(XMLTags.BioModelTag)) {
            String docSoftwareVersion = rootElement.getAttributeValue(XMLTags.SoftwareVersionAttrTag);
            vcDoc = reader.getBioModel(rootElement, (docSoftwareVersion == null ? null : VCellSoftwareVersion.fromString(docSoftwareVersion)));
        } else if (rootName.equals(XMLTags.MathModelTag)) {
            vcDoc = reader.getMathModel(rootElement);
        } else if (rootName.equals(XMLTags.GeometryTag)) {
            vcDoc = reader.getGeometry(rootElement);
        } else {
            throw new Exception("Invalid root for the tree");
        }
        return vcDoc;
    } catch (java.lang.Exception ivjExc) {
        handleException(ivjExc);
        throw ivjExc;
    }
}
Also used : VCDocument(org.vcell.util.document.VCDocument) NodeInfo(cbit.xml.merge.NodeInfo) ChangedNodeInfo(cbit.xml.merge.ChangedNodeInfo) Element(org.jdom.Element) XmlReader(cbit.vcell.xml.XmlReader) VCDocument(org.vcell.util.document.VCDocument) Document(org.jdom.Document)

Example 3 with VCDocument

use of org.vcell.util.document.VCDocument in project vcell by virtualcell.

the class ClientRequestManager method processComparisonResult.

public void processComparisonResult(TMLPanel comparePanel, TopLevelWindowManager requester) {
    if (comparePanel == null || requester == null) {
        throw new IllegalArgumentException("Invalid params: " + comparePanel + " " + requester);
    }
    try {
        final VCDocument vcDoc = comparePanel.processComparisonResult();
        if (requester instanceof DatabaseWindowManager) {
            final DatabaseWindowManager dataWinManager = (DatabaseWindowManager) requester;
            final VCDocumentInfo vcDocInfo = getMatchingDocumentInfo(vcDoc);
            this.openDocument(vcDocInfo, dataWinManager, true);
            Thread waiter = new Thread() {

                public void run() {
                    try {
                        BeanUtils.setCursorThroughout((Container) dataWinManager.getComponent(), Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        while (bOpening) {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                            }
                        }
                        String ID = vcDocInfo.getVersion().getVersionKey().toString();
                        DocumentWindowManager dwm = (DocumentWindowManager) ClientRequestManager.this.getMdiManager().getWindowManager(ID);
                        dwm.resetDocument(vcDoc);
                    } finally {
                        BeanUtils.setCursorThroughout((Container) dataWinManager.getComponent(), Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                    }
                }
            };
            waiter.start();
        } else if (requester instanceof DocumentWindowManager) {
            DocumentWindowManager docWinManager = (DocumentWindowManager) requester;
            docWinManager.resetDocument(vcDoc);
        } else {
            throw new IllegalArgumentException("Invalid TopLevelWindowManager instance: " + requester.getClass().getName());
        }
        System.out.println("Processing new model ..." + vcDoc.getVersion().getName());
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException(e.getMessage());
    }
}
Also used : VCDocument(org.vcell.util.document.VCDocument) VCDocumentInfo(org.vcell.util.document.VCDocumentInfo) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) DataFormatException(java.util.zip.DataFormatException) UserCancelException(org.vcell.util.UserCancelException)

Example 4 with VCDocument

use of org.vcell.util.document.VCDocument in project vcell by virtualcell.

the class ClientRequestManager method newDocument.

/**
 * Insert the method's description here.
 * Creation date: (5/21/2004 4:20:47 AM)
 * @param documentType int
 */
public AsynchClientTask[] newDocument(TopLevelWindowManager requester, final VCDocument.DocumentCreationInfo documentCreationInfo) {
    // gcwtodo
    AsynchClientTask createNewDocumentTask = new AsynchClientTask("Creating New Document", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            VCDocument doc = (VCDocument) hashTable.get("doc");
            DocumentWindowManager windowManager = createDocumentWindowManager(doc);
            DocumentWindow dw = getMdiManager().createNewDocumentWindow(windowManager);
            if (windowManager != null) {
                hashTable.put("windowManager", windowManager);
            }
            setFinalWindow(hashTable, dw);
        }
    };
    if (documentCreationInfo.getDocumentType() == VCDocumentType.MATHMODEL_DOC && documentCreationInfo.getOption() == VCDocument.MATH_OPTION_SPATIAL_NEW) {
        final AsynchClientTask createSpatialMathModelTask = new AsynchClientTask("creating mathmodel", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

            @Override
            public void run(Hashtable<String, Object> hashTable) throws Exception {
                Geometry geometry = null;
                geometry = (Geometry) hashTable.get("doc");
                MathModel mathModel = createMathModel("Untitled", geometry);
                mathModel.setName("MathModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1));
                hashTable.put("doc", mathModel);
            }
        };
        requester.createGeometry(null, new AsynchClientTask[] { createSpatialMathModelTask, createNewDocumentTask }, "Choose geometry type to start MathModel creation", "Create MathModel", null);
        return null;
    }
    /* asynchronous and not blocking any window */
    AsynchClientTask[] taskArray = null;
    if (documentCreationInfo.getPreCreatedDocument() == null) {
        AsynchClientTask[] taskArray1 = createNewDocument(requester, documentCreationInfo);
        taskArray = new AsynchClientTask[taskArray1.length + 1];
        System.arraycopy(taskArray1, 0, taskArray, 0, taskArray1.length);
    } else {
        taskArray = new AsynchClientTask[2];
        taskArray[0] = new AsynchClientTask("Setting document...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

            @Override
            public void run(Hashtable<String, Object> hashTable) throws Exception {
                hashTable.put("doc", documentCreationInfo.getPreCreatedDocument());
            }
        };
    }
    taskArray[taskArray.length - 1] = createNewDocumentTask;
    return taskArray;
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) MathModel(cbit.vcell.mathmodel.MathModel) VCDocument(org.vcell.util.document.VCDocument) Hashtable(java.util.Hashtable) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) DataFormatException(java.util.zip.DataFormatException) UserCancelException(org.vcell.util.UserCancelException) DocumentWindow(cbit.vcell.client.desktop.DocumentWindow) Geometry(cbit.vcell.geometry.Geometry) CSGObject(cbit.vcell.geometry.CSGObject)

Example 5 with VCDocument

use of org.vcell.util.document.VCDocument in project vcell by virtualcell.

the class ClientRequestManager method openAfterChecking.

private void openAfterChecking(VCDocumentInfo documentInfo, final TopLevelWindowManager requester, final boolean inNewWindow) {
    final String DOCUMENT_INFO = "documentInfo";
    final String SEDML_TASK = "SedMLTask";
    final String SEDML_MODEL = "SedMLModel";
    final String BNG_UNIT_SYSTEM = "bngUnitSystem";
    /* asynchronous and not blocking any window */
    bOpening = true;
    Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
    // may want to insert corrected VCDocumentInfo later if our import debugger corrects it (BNGL Debugger).
    hashTable.put(DOCUMENT_INFO, documentInfo);
    // start a thread that gets it and updates the GUI by creating a new document desktop
    String taskName = null;
    if (documentInfo instanceof ExternalDocInfo) {
        taskName = "Importing document";
        ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
        File file = externalDocInfo.getFile();
        if (file != null && !file.getName().isEmpty() && file.getName().endsWith("bngl")) {
            BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
            String fileText;
            String originalFileText;
            try {
                fileText = BeanUtils.readBytesFromFile(file, null);
                originalFileText = new String(fileText);
            } catch (IOException e1) {
                e1.printStackTrace();
                DialogUtils.showErrorDialog(requester.getComponent(), "<html>Error reading file " + file.getPath() + "</html>");
                return;
            }
            Reader reader = externalDocInfo.getReader();
            boolean bException = true;
            while (bException) {
                try {
                    BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
                    boolean bStochastic = true;
                    boolean bRuleBased = true;
                    SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("temp NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
                    List<SimulationContext> appList = new ArrayList<SimulationContext>();
                    appList.add(ruleBasedSimContext);
                    RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
                    RbmUtils.reactionRuleLabelIndex = 0;
                    RbmUtils.reactionRuleNames.clear();
                    ASTModel astModel = RbmUtils.importBnglFile(reader);
                    // for now, hasUnitSystem() always returns false
                    if (astModel.hasUnitSystem()) {
                        bngUnitSystem = astModel.getUnitSystem();
                    }
                    if (astModel.hasCompartments()) {
                        Structure struct = bioModel.getModel().getStructure(0);
                        if (struct != null) {
                            bioModel.getModel().removeStructure(struct);
                        }
                    }
                    BnglObjectConstructionVisitor constructionVisitor = null;
                    if (!astModel.hasMolecularDefinitions()) {
                        System.out.println("Molecular Definition Block missing.");
                        constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
                    } else {
                        constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
                    }
                    astModel.jjtAccept(constructionVisitor, rbmModelContainer);
                    bException = false;
                } catch (final Exception e) {
                    e.printStackTrace(System.out);
                    BNGLDebuggerPanel panel = new BNGLDebuggerPanel(fileText, e);
                    int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, "Bngl Debugger: " + file.getName());
                    if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
                        throw new UserCancelException("Canceling Import");
                    }
                    // inserting <potentially> corrected DocumentInfo
                    fileText = panel.getText();
                    externalDocInfo = new ExternalDocInfo(panel.getText());
                    reader = externalDocInfo.getReader();
                    hashTable.put(DOCUMENT_INFO, externalDocInfo);
                }
            }
            if (!originalFileText.equals(fileText)) {
                // file has been modified
                String message = "Importing <b>" + file.getName() + "</b> into vCell. <br>Overwrite the file on the disk?<br>";
                message = "<html>" + message + "</html>";
                Object[] options = { "Overwrite and Import", "Import Only", "Cancel" };
                int returnCode = JOptionPane.showOptionDialog(requester.getComponent(), message, "Bngl Debugger", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
                if (returnCode == JOptionPane.YES_OPTION) {
                    try {
                        FileWriter fw = new FileWriter(file);
                        fw.write(fileText);
                        fw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (returnCode == JOptionPane.CANCEL_OPTION || returnCode == JOptionPane.CLOSED_OPTION) {
                    return;
                }
            }
            if (!(bngUnitSystem.getOrigin() == BngUnitOrigin.PARSER)) {
                BNGLUnitsPanel panel = new BNGLUnitsPanel(bngUnitSystem);
                int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, " Bngl Units Selector", null, false);
                if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
                    // TODO: or do nothing and continue with default values?
                    return;
                } else {
                    bngUnitSystem = panel.getUnits();
                }
            }
            hashTable.put(BNG_UNIT_SYSTEM, bngUnitSystem);
        } else if (file != null && !file.getName().isEmpty() && file.getName().toLowerCase().endsWith(".sedml")) {
            try {
                XMLSource xmlSource = externalDocInfo.createXMLSource();
                File sedmlFile = xmlSource.getXmlFile();
                SedML sedml = Libsedml.readDocument(sedmlFile).getSedMLModel();
                if (sedml == null || sedml.getModels().isEmpty()) {
                    return;
                }
                AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(), file.getName());
                hashTable.put(SEDML_MODEL, sedml);
                hashTable.put(SEDML_TASK, chosenTask);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("failed to read document: " + e.getMessage(), e);
            }
        } else if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
            try {
                ArchiveComponents ac = null;
                ac = Libsedml.readSEDMLArchive(new FileInputStream(file));
                SEDMLDocument doc = ac.getSedmlDocument();
                SedML sedml = doc.getSedMLModel();
                if (sedml == null) {
                    throw new RuntimeException("Failed importing " + file.getName());
                }
                if (sedml.getModels().isEmpty()) {
                    throw new RuntimeException("Unable to find any model in " + file.getName());
                }
                AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(), file.getName());
                hashTable.put(SEDML_MODEL, sedml);
                hashTable.put(SEDML_TASK, chosenTask);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("failed to read archive: " + e.getMessage(), e);
            }
        }
    } else {
        taskName = "Loading document '" + documentInfo.getVersion().getName() + "' from database";
    }
    AsynchClientTask task0 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        public void run(Hashtable<String, Object> hashTable) throws Exception {
            if (!inNewWindow) {
                // request was to replace the document in an existing window
                getMdiManager().blockWindow(requester.getManagerID());
            }
        }
    };
    AsynchClientTask task1 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            VCDocument doc = null;
            VCDocumentInfo documentInfo = (VCDocumentInfo) hashTable.get(DOCUMENT_INFO);
            if (documentInfo instanceof BioModelInfo) {
                BioModelInfo bmi = (BioModelInfo) documentInfo;
                doc = getDocumentManager().getBioModel(bmi);
            } else if (documentInfo instanceof MathModelInfo) {
                MathModelInfo mmi = (MathModelInfo) documentInfo;
                doc = getDocumentManager().getMathModel(mmi);
            } else if (documentInfo instanceof GeometryInfo) {
                GeometryInfo gmi = (GeometryInfo) documentInfo;
                doc = getDocumentManager().getGeometry(gmi);
            } else if (documentInfo instanceof ExternalDocInfo) {
                ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
                File file = externalDocInfo.getFile();
                if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
                    TranslationLogger transLogger = new TranslationLogger(requester);
                    doc = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, (SedML) hashTable.get(SEDML_MODEL), (AbstractTask) hashTable.get(SEDML_TASK));
                } else if (!externalDocInfo.isXML()) {
                    if (hashTable.containsKey(BNG_UNIT_SYSTEM)) {
                        // not XML, look for BNGL etc.
                        // we use the BngUnitSystem already created during the 1st pass
                        BngUnitSystem bngUnitSystem = (BngUnitSystem) hashTable.get(BNG_UNIT_SYSTEM);
                        BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
                        SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
                        SimulationContext odeSimContext = bioModel.addNewSimulationContext("BioNetGen app", SimulationContext.Application.NETWORK_DETERMINISTIC);
                        List<SimulationContext> appList = new ArrayList<SimulationContext>();
                        appList.add(ruleBasedSimContext);
                        appList.add(odeSimContext);
                        // set convention for initial conditions in generated application for seed species (concentration or count)
                        ruleBasedSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
                        odeSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
                        RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
                        RbmUtils.reactionRuleLabelIndex = 0;
                        RbmUtils.reactionRuleNames.clear();
                        Reader reader = externalDocInfo.getReader();
                        ASTModel astModel = RbmUtils.importBnglFile(reader);
                        if (bioModel.getModel() != null && bioModel.getModel().getVcMetaData() != null) {
                            VCMetaData vcMetaData = bioModel.getModel().getVcMetaData();
                            vcMetaData.setFreeTextAnnotation(bioModel, astModel.getProlog());
                        }
                        if (astModel.hasCompartments()) {
                            Structure struct = bioModel.getModel().getStructure(0);
                            if (struct != null) {
                                bioModel.getModel().removeStructure(struct);
                            }
                        }
                        BnglObjectConstructionVisitor constructionVisitor = null;
                        if (!astModel.hasMolecularDefinitions()) {
                            System.out.println("Molecular Definition Block missing. Extracting it from Species, Reactions, Obserbables.");
                            constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
                        } else {
                            constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
                        }
                        // we'll convert the kinetic parameters to BngUnitSystem inside the visit(ASTKineticsParameter...)
                        astModel.jjtAccept(constructionVisitor, rbmModelContainer);
                        // set the volume in the newly created application to BngUnitSystem.bnglModelVolume
                        // TODO: set the right values if we import compartments from the bngl file!
                        // if(!bngUnitSystem.isConcentration()) {
                        Expression sizeExpression = new Expression(bngUnitSystem.getVolume());
                        ruleBasedSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
                        odeSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
                        // }
                        // we remove the NFSim application if any seed species is clamped because NFSim doesn't know what to do with it
                        boolean bClamped = false;
                        for (SpeciesContextSpec scs : ruleBasedSimContext.getReactionContext().getSpeciesContextSpecs()) {
                            if (scs.isConstant()) {
                                bClamped = true;
                                break;
                            }
                        }
                        if (bClamped) {
                            bioModel.removeSimulationContext(ruleBasedSimContext);
                        }
                        // // TODO: DON'T delete this code
                        // // the code below is needed if we also want to create simulations, example for 1 rule based simulation
                        // // it is rule-based so it wont have to flatten, should be fast.
                        // MathMappingCallback callback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
                        // NetworkGenerationRequirements networkGenerationRequirements = null; // network generation should not be executed.
                        // ruleBasedSimContext.refreshMathDescription(callback,networkGenerationRequirements);
                        // Simulation sim = ruleBasedSimContext.addNewSimulation(SimulationOwner.DEFAULT_SIM_NAME_PREFIX,callback,networkGenerationRequirements);
                        doc = bioModel;
                    }
                } else {
                    // is XML
                    try (TranslationLogger transLogger = new TranslationLogger(requester)) {
                        XMLSource xmlSource = externalDocInfo.createXMLSource();
                        org.jdom.Element rootElement = xmlSource.getXmlDoc().getRootElement();
                        String xmlType = rootElement.getName();
                        String modelXmlType = null;
                        if (xmlType.equals(XMLTags.VcmlRootNodeTag)) {
                            // For now, assuming that <vcml> element has only one child (biomodel, mathmodel or geometry).
                            // Will deal with multiple children of <vcml> Element when we get to model composition.
                            @SuppressWarnings("unchecked") List<Element> childElementList = rootElement.getChildren();
                            // assuming first child is the biomodel, mathmodel or geometry.
                            Element modelElement = childElementList.get(0);
                            modelXmlType = modelElement.getName();
                        }
                        if (xmlType.equals(XMLTags.BioModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.BioModelTag))) {
                            doc = XmlHelper.XMLToBioModel(xmlSource);
                        } else if (xmlType.equals(XMLTags.MathModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.MathModelTag))) {
                            doc = XmlHelper.XMLToMathModel(xmlSource);
                        } else if (xmlType.equals(XMLTags.GeometryTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.GeometryTag))) {
                            doc = XmlHelper.XMLToGeometry(xmlSource);
                        } else if (xmlType.equals(XMLTags.SbmlRootNodeTag)) {
                            Namespace namespace = rootElement.getNamespace(XMLTags.SBML_SPATIAL_NS_PREFIX);
                            boolean bIsSpatial = (namespace == null) ? false : true;
                            doc = XmlHelper.importSBML(transLogger, xmlSource, bIsSpatial);
                        } else if (xmlType.equals(XMLTags.CellmlRootNodeTag)) {
                            if (requester instanceof BioModelWindowManager) {
                                doc = XmlHelper.importBioCellML(transLogger, xmlSource);
                            } else {
                                doc = XmlHelper.importMathCellML(transLogger, xmlSource);
                            }
                        } else if (xmlType.equals(MicroscopyXMLTags.FRAPStudyTag)) {
                            doc = VFrapXmlHelper.VFRAPToBioModel(hashTable, xmlSource, getDocumentManager(), requester);
                        } else if (xmlType.equals(XMLTags.SedMLTypeTag)) {
                            doc = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, (SedML) hashTable.get(SEDML_MODEL), (AbstractTask) hashTable.get(SEDML_TASK));
                        } else {
                            // unknown XML format
                            throw new RuntimeException("unsupported XML format, first element tag is <" + rootElement.getName() + ">");
                        }
                        if (externalDocInfo.getDefaultName() != null) {
                            doc.setName(externalDocInfo.getDefaultName());
                        }
                    }
                }
                if (doc == null) {
                    File f = externalDocInfo.getFile();
                    if (f != null) {
                        throw new RuntimeException("Unable to determine type of file " + f.getCanonicalPath());
                    }
                    throw new ProgrammingException();
                }
            }
            // create biopax objects using annotation
            if (doc instanceof BioModel) {
                BioModel bioModel = (BioModel) doc;
                try {
                    bioModel.getVCMetaData().createBioPaxObjects(bioModel);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            requester.prepareDocumentToLoad(doc, inNewWindow);
            hashTable.put("doc", doc);
        }
    };
    AsynchClientTask task2 = new AsynchClientTask("Showing document", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            try {
                Throwable exc = (Throwable) hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR);
                if (exc == null) {
                    VCDocument doc = (VCDocument) hashTable.get("doc");
                    DocumentWindowManager windowManager = null;
                    if (inNewWindow) {
                        windowManager = createDocumentWindowManager(doc);
                        // request was to create a new top-level window with this doc
                        getMdiManager().createNewDocumentWindow(windowManager);
                    // if (windowManager instanceof BioModelWindowManager) {
                    // ((BioModelWindowManager)windowManager).preloadApps();
                    // }
                    } else {
                        // request was to replace the document in an existing window
                        windowManager = (DocumentWindowManager) requester;
                        getMdiManager().setCanonicalTitle(requester.getManagerID());
                        windowManager.resetDocument(doc);
                    }
                    hashTable.put(WIN_MGR_KEY, windowManager);
                }
            } finally {
                if (!inNewWindow) {
                    getMdiManager().unBlockWindow(requester.getManagerID());
                }
                bOpening = false;
            }
        }
    };
    AsynchClientTask task3 = new AsynchClientTask("Special Layout", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            // TODO Auto-generated method stub
            if (documentInfo instanceof ExternalDocInfo) {
                ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
                if (externalDocInfo.isBioModelsNet()) {
                    DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
                    if (windowManager instanceof BioModelWindowManager) {
                        ((BioModelWindowManager) windowManager).specialLayout();
                    }
                }
            }
        }
    };
    AsynchClientTask task4 = new AsynchClientTaskFunction(ClientRequestManager::setWindowFocus, "Set window focus", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false);
    ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] { task0, task1, task2, task3, task4 }, false);
}
Also used : ArrayList(java.util.ArrayList) UserCancelException(org.vcell.util.UserCancelException) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) SedML(org.jlibsedml.SedML) ExternalDocInfo(cbit.vcell.xml.ExternalDocInfo) AsynchClientTaskFunction(cbit.vcell.client.task.AsynchClientTaskFunction) VCMetaData(cbit.vcell.biomodel.meta.VCMetaData) BnglObjectConstructionVisitor(org.vcell.model.rbm.RbmUtils.BnglObjectConstructionVisitor) RbmModelContainer(cbit.vcell.model.Model.RbmModelContainer) GeometryInfo(cbit.vcell.geometry.GeometryInfo) VCDocument(org.vcell.util.document.VCDocument) FileInputStream(java.io.FileInputStream) Namespace(org.jdom.Namespace) BngUnitSystem(org.vcell.model.bngl.BngUnitSystem) BNGLDebuggerPanel(org.vcell.model.bngl.gui.BNGLDebuggerPanel) SEDMLDocument(org.jlibsedml.SEDMLDocument) CSGObject(cbit.vcell.geometry.CSGObject) ChooseFile(cbit.vcell.client.task.ChooseFile) File(java.io.File) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) AbstractTask(org.jlibsedml.AbstractTask) FileWriter(java.io.FileWriter) Element(org.jdom.Element) StlReader(cbit.vcell.geometry.surface.StlReader) FileReader(java.io.FileReader) ImageDatasetReader(org.vcell.vcellij.ImageDatasetReader) Reader(java.io.Reader) BufferedReader(java.io.BufferedReader) ArchiveComponents(org.jlibsedml.ArchiveComponents) ProgrammingException(org.vcell.util.ProgrammingException) Structure(cbit.vcell.model.Structure) Hashtable(java.util.Hashtable) BNGLUnitsPanel(org.vcell.model.bngl.gui.BNGLUnitsPanel) BioModelInfo(org.vcell.util.document.BioModelInfo) IOException(java.io.IOException) MathModelInfo(org.vcell.util.document.MathModelInfo) SimulationContext(cbit.vcell.mapping.SimulationContext) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) DataFormatException(java.util.zip.DataFormatException) UserCancelException(org.vcell.util.UserCancelException) VCDocumentInfo(org.vcell.util.document.VCDocumentInfo) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) XMLSource(cbit.vcell.xml.XMLSource) Element(org.jdom.Element) ASTModel(org.vcell.model.bngl.ASTModel)

Aggregations

VCDocument (org.vcell.util.document.VCDocument)38 BioModel (cbit.vcell.biomodel.BioModel)14 MathModel (cbit.vcell.mathmodel.MathModel)11 UserCancelException (org.vcell.util.UserCancelException)11 Simulation (cbit.vcell.solver.Simulation)10 DataAccessException (org.vcell.util.DataAccessException)10 DocumentWindowManager (cbit.vcell.client.DocumentWindowManager)9 IOException (java.io.IOException)9 VCDocumentInfo (org.vcell.util.document.VCDocumentInfo)8 PropertyVetoException (java.beans.PropertyVetoException)7 File (java.io.File)7 DocumentManager (cbit.vcell.clientdb.DocumentManager)6 Geometry (cbit.vcell.geometry.Geometry)6 SimulationContext (cbit.vcell.mapping.SimulationContext)6 UtilCancelException (org.vcell.util.UtilCancelException)6 ImageException (cbit.image.ImageException)5 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)5 GeometryException (cbit.vcell.geometry.GeometryException)5 ExpressionException (cbit.vcell.parser.ExpressionException)5 Hashtable (java.util.Hashtable)5