Search in sources :

Example 1 with ExternalDocInfo

use of cbit.vcell.xml.ExternalDocInfo 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_MODELS = "SedMLModels";
    final String BNG_UNIT_SYSTEM = "bngUnitSystem";
    final String BMDB_DEFAULT_APPLICATION = "Deterministic";
    /* 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);
    hashTable.put("isBMDB", false);
    hashTable.put("isSEDML", false);
    // 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());
                List<SedML> sedmls = new ArrayList<>();
                sedmls.add(sedml);
                hashTable.put(SEDML_MODELS, sedmls);
            // 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));
                List<SEDMLDocument> docs = ac.getSedmlDocuments();
                List<SedML> sedmls = new ArrayList<>();
                for (SEDMLDocument doc : docs) {
                    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());
                    }
                    sedmls.add(sedml);
                }
                // AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(),
                // file.getName());
                hashTable.put(SEDML_MODELS, sedmls);
            // 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;
            List<VCDocument> docs = new ArrayList<>();
            boolean isBMDB = false;
            boolean isSEDML = false;
            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);
                    // iterate through one or more SEDML objects
                    List<SedML> sedmls = (List<SedML>) hashTable.get(SEDML_MODELS);
                    for (SedML sedml : sedmls) {
                        // default to import all tasks
                        List<VCDocument> vcdocs = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, sedml, null, null, false);
                        for (VCDocument vcdoc : vcdocs) {
                            docs.add(vcdoc);
                        }
                    }
                    // treat the same since OMEX is just and archive with SED-ML file(s)
                    isSEDML = true;
                } 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,
                            Element modelElement = childElementList.get(0);
                            // mathmodel or geometry.
                            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);
                            isBMDB = externalDocInfo.isBioModelsNet();
                            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)) {
                            // we know it is a single SedML since it is an actual XML source
                            List<SedML> sedmls = (List<SedML>) hashTable.get(SEDML_MODELS);
                            SedML sedml = sedmls.get(0);
                            // default to import all tasks
                            docs = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, sedml, null, externalDocInfo.getFile().getAbsolutePath(), false);
                            isSEDML = true;
                        } 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 && docs == 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("isBMDB", isBMDB);
            hashTable.put("isSEDML", isSEDML);
            if (!isSEDML) {
                hashTable.put("doc", doc);
            } else {
                hashTable.put("docs", docs);
            }
        }
    };
    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) {
                    boolean isSEDML = (boolean) hashTable.get("isSEDML");
                    if (isSEDML) {
                        List<VCDocument> docs = (List<VCDocument>) hashTable.get("docs");
                        List<DocumentWindowManager> windowManagers = new ArrayList<DocumentWindowManager>();
                        for (VCDocument doc : docs) {
                            DocumentWindowManager windowManager = createDocumentWindowManager(doc);
                            getMdiManager().createNewDocumentWindow(windowManager);
                            windowManagers.add(windowManager);
                        }
                        hashTable.put("managers", windowManagers);
                        hashTable.put("docs", docs);
                    } else {
                        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);
                        } 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);
                        hashTable.put("doc", doc);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            // TODO: check why getMdiManager().createNewDocumentWindow(windowManager) fails sometimes
            } 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 {
            if (documentInfo instanceof ExternalDocInfo) {
                ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
                boolean isSEDML = (boolean) hashTable.get("isSEDML");
                if (externalDocInfo.isBioModelsNet() || externalDocInfo.isFromXmlFile() || !isSEDML) {
                    DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
                    if (windowManager instanceof BioModelWindowManager) {
                        ((BioModelWindowManager) windowManager).specialLayout();
                    }
                }
                if (isSEDML) {
                    List<DocumentWindowManager> windowManagers = (List<DocumentWindowManager>) hashTable.get("managers");
                    if (windowManagers != null) {
                        for (DocumentWindowManager manager : windowManagers) {
                            ((BioModelWindowManager) manager).specialLayout();
                        }
                    }
                }
            }
        }
    };
    AsynchClientTask task4 = new AsynchClientTaskFunction(ClientRequestManager::setWindowFocus, "Set window focus", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false);
    AsynchClientTask task6 = new AsynchClientTask("Renaming, please wait...", // TASKTYPE_NONSWING_BLOCKING
    AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, // TASKTYPE_NONSWING_BLOCKING
    false, // TASKTYPE_NONSWING_BLOCKING
    false) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            VCDocument doc = (VCDocument) hashTable.get("doc");
            if (!(doc instanceof BioModel)) {
                return;
            }
            boolean isBMDB = (boolean) hashTable.get("isBMDB");
            if (documentInfo instanceof ExternalDocInfo) {
                if (isBMDB) {
                    idToNameConversion(doc);
                }
            }
            if (isBMDB) {
                BioModel bioModel = (BioModel) doc;
                SimulationContext simulationContext = bioModel.getSimulationContext(0);
                simulationContext.setName(BMDB_DEFAULT_APPLICATION);
                MathMappingCallback callback = new MathMappingCallback() {

                    @Override
                    public void setProgressFraction(float fractionDone) {
                    }

                    @Override
                    public void setMessage(String message) {
                    }

                    @Override
                    public boolean isInterrupted() {
                        return false;
                    }
                };
                MathMapping mathMapping = simulationContext.createNewMathMapping(callback, NetworkGenerationRequirements.ComputeFullNoTimeout);
                MathDescription mathDesc = null;
                try {
                    mathDesc = mathMapping.getMathDescription(callback);
                    simulationContext.setMathDescription(mathDesc);
                    Simulation sim = new Simulation(mathDesc);
                    sim.setName(simulationContext.getBioModel().getFreeSimulationName());
                    simulationContext.addSimulation(sim);
                    bioModel.refreshDependencies();
                } catch (MappingException | MathException | MatrixException | ExpressionException | ModelException e1) {
                    e1.printStackTrace();
                }
                hashTable.put("doc", doc);
            }
        }
    };
    ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] { task0, task1, task6, task2, task3, task4 }, false);
}
Also used : SetMathDescription(cbit.vcell.client.task.SetMathDescription) MathDescription(cbit.vcell.math.MathDescription) ArrayList(java.util.ArrayList) UserCancelException(org.vcell.util.UserCancelException) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) SedML(org.jlibsedml.SedML) ExternalDocInfo(cbit.vcell.xml.ExternalDocInfo) AsynchClientTaskFunction(cbit.vcell.client.task.AsynchClientTaskFunction) MatrixException(cbit.vcell.matrix.MatrixException) VCMetaData(cbit.vcell.biomodel.meta.VCMetaData) BnglObjectConstructionVisitor(org.vcell.model.rbm.RbmUtils.BnglObjectConstructionVisitor) RbmModelContainer(cbit.vcell.model.Model.RbmModelContainer) GeometryInfo(cbit.vcell.geometry.GeometryInfo) ArrayList(java.util.ArrayList) List(java.util.List) VCDocument(org.vcell.util.document.VCDocument) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) ModelException(cbit.vcell.model.ModelException) 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) MathMapping(cbit.vcell.mapping.MathMapping) CSGObject(cbit.vcell.geometry.CSGObject) ChooseFile(cbit.vcell.client.task.ChooseFile) File(java.io.File) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) 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) MatrixException(cbit.vcell.matrix.MatrixException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) ModelException(cbit.vcell.model.ModelException) DataFormatException(java.util.zip.DataFormatException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) UserCancelException(org.vcell.util.UserCancelException) Simulation(cbit.vcell.solver.Simulation) VCDocumentInfo(org.vcell.util.document.VCDocumentInfo) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) BioModel(cbit.vcell.biomodel.BioModel) XMLSource(cbit.vcell.xml.XMLSource) Element(org.jdom.Element) ASTModel(org.vcell.model.bngl.ASTModel)

Example 2 with ExternalDocInfo

use of cbit.vcell.xml.ExternalDocInfo in project vcell by virtualcell.

the class BNGWindowManager method importSbml.

/**
 * Comment
 */
public void importSbml(String bngSbmlStr) {
    if (bngSbmlStr == null || bngSbmlStr.length() == 0) {
        throw new RuntimeException("SBMl string is empty, cannot import into VCell.");
    }
    // 
    // 1. Convert SBML string from BNG to SBML model, add unitDefintions to SBML model using VCell sbml compatible unit system
    // 2. Import unit modified SBML model into VCell as biomodel
    // 3. Enforce "cleaner" (looking) units on this imported biomodel (can use the units added to the sbml model above)
    // 4. Convert all LumpedKinetics reactions into DistributedKinetics.
    // 4. Convert this biomodel into vcml string and pass it into XMLInfo and then to RequestManager to open document.
    // 
    ModelUnitSystem mus = ModelUnitSystem.createDefaultVCModelUnitSystem();
    ModelUnitSystem sbmlCompatibleVCModelUnitSystem = ModelUnitSystem.createSBMLUnitSystem(mus.getVolumeSubstanceUnit(), mus.getVolumeUnit(), mus.getAreaUnit(), mus.getLengthUnit(), mus.getTimeUnit());
    // display to user to change units if desired.
    UnitSystemSelectionPanel unitSystemSelectionPanel = new UnitSystemSelectionPanel(true);
    unitSystemSelectionPanel.initialize(sbmlCompatibleVCModelUnitSystem);
    int retcode = DialogUtils.showComponentOKCancelDialog(getBngOutputPanel(), unitSystemSelectionPanel, "Select new unit system to import into VCell");
    ModelUnitSystem forcedModelUnitSystem = null;
    while (retcode == JOptionPane.OK_OPTION) {
        try {
            forcedModelUnitSystem = unitSystemSelectionPanel.createModelUnitSystem();
            break;
        } catch (Exception e) {
            e.printStackTrace(System.out);
            DialogUtils.showErrorDialog(getBngOutputPanel(), e.getMessage(), e);
            retcode = DialogUtils.showComponentOKCancelDialog(getBngOutputPanel(), unitSystemSelectionPanel, "Select new unit system to import into VCell");
        }
    }
    if (forcedModelUnitSystem == null) {
        DialogUtils.showErrorDialog(getBngOutputPanel(), "Units are required for import into Virtual Cell.");
    }
    try {
        // SBMLUnitTranslator.addUnitDefinitionsToSbmlModel(bngSbmlStr, forcedModelUnitSystem);
        String modifiedSbmlStr = bngSbmlStr;
        // Create a default VCLogger - SBMLImporter needs it
        cbit.util.xml.VCLogger logger = new cbit.util.xml.VCLogger() {

            @Override
            public void sendMessage(Priority p, ErrorType et, String message) throws Exception {
                System.err.println("LOGGER: msgLevel=" + p + ", msgType=" + et + ", " + message);
                if (p == VCLogger.Priority.HighPriority) {
                    throw new RuntimeException("Import failed : " + message);
                }
            }

            public void sendAllMessages() {
            }

            public boolean hasMessages() {
                return false;
            }
        };
        // import sbml String into VCell biomodel
        File sbmlFile = File.createTempFile("temp", ".xml");
        sbmlFile.deleteOnExit();
        XmlUtil.writeXMLStringToFile(modifiedSbmlStr, sbmlFile.getAbsolutePath(), true);
        org.vcell.sbml.vcell.SBMLImporter sbmlImporter = new SBMLImporter(sbmlFile.getAbsolutePath(), logger, false);
        BioModel bioModel = sbmlImporter.getBioModel();
        // enforce 'cleaner looking' units on vc biomodel (the process of adding unit defintion to sbml model messes up the units, though they are correct units (eg., 1e-6m for um).
        BioModel modifiedBiomodel = ModelUnitConverter.createBioModelWithNewUnitSystem(bioModel, forcedModelUnitSystem);
        // convert any reaction that has GeneralLumpedKinetics to GeneralKinetics
        for (ReactionStep rs : modifiedBiomodel.getModel().getReactionSteps()) {
            Kinetics kinetics = rs.getKinetics();
            if (kinetics instanceof LumpedKinetics) {
                rs.setKinetics(DistributedKinetics.toDistributedKinetics((LumpedKinetics) kinetics));
            }
        }
        // convert biomodel to vcml string
        String vcmlString = XmlHelper.bioModelToXML(modifiedBiomodel);
        ExternalDocInfo externalDocInfo = new ExternalDocInfo(vcmlString);
        if (externalDocInfo != null) {
            getRequestManager().openDocument(externalDocInfo, this, true);
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("Cound not convert BNG sbml string to VCell biomodel : ", e);
    }
}
Also used : SBMLImporter(org.vcell.sbml.vcell.SBMLImporter) LumpedKinetics(cbit.vcell.model.LumpedKinetics) UnitSystemSelectionPanel(cbit.vcell.client.desktop.biomodel.UnitSystemSelectionPanel) VCLogger(cbit.util.xml.VCLogger) SBMLImporter(org.vcell.sbml.vcell.SBMLImporter) IOException(java.io.IOException) UserCancelException(org.vcell.util.UserCancelException) ExternalDocInfo(cbit.vcell.xml.ExternalDocInfo) BioModel(cbit.vcell.biomodel.BioModel) ReactionStep(cbit.vcell.model.ReactionStep) DistributedKinetics(cbit.vcell.model.DistributedKinetics) LumpedKinetics(cbit.vcell.model.LumpedKinetics) Kinetics(cbit.vcell.model.Kinetics) File(java.io.File) VCLogger(cbit.util.xml.VCLogger) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 3 with ExternalDocInfo

use of cbit.vcell.xml.ExternalDocInfo in project vcell by virtualcell.

the class VCellSedMLSolver method main.

// static String inString = "/usr/local/app/vcell/simulation";
// static String outRootString = "/usr/local/app/vcell/simulation/out";
public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    // place the sedml file and the sbml file(s) in inDir directory
    Options options = getCommandLineOptions();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.getOptions().length == 0) {
            System.out.println("usage: vcell [-h] [-q] -i ARCHIVE [-o OUT_DIR] [-v]");
            System.exit(1);
        }
        if (args[0].contains("-h") || args[0].contains("--help")) {
            formatter.printHelp("vcell [-h] [-q] -i ARCHIVE [-o OUT_DIR] [-v]", "\nBioSimulators-compliant command-line interface to the VCell simulation program <http://vcell.org>.\n\n" + "optional arguments:\n\n", options, "");
            System.exit(1);
        }
        IN_ROOT_STRING = cmd.getOptionValue("archive");
        OUT_ROOT_STRING = cmd.getOptionValue("out-dir");
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        System.exit(1);
    }
    if (IN_ROOT_STRING == null || OUT_ROOT_STRING == null) {
        formatter.printHelp("vcell", options);
        System.exit(1);
    }
    // CombineArchive omex = new CombineArchive();
    // boolean isInitialized = omex.initializeFromArchive(IN_ROOT_STRING);
    // boolean isExtracted = omex.extractTo(tempDir)
    File tempDir = Files.createTempDir();
    ArrayList<String> sedmlLocations = new ArrayList<>();
    try {
        System.loadLibrary("combinej");
        CombineArchive omex = new CombineArchive();
        boolean isInitialized = omex.initializeFromArchive(IN_ROOT_STRING);
        boolean isExtracted = omex.extractTo(tempDir.getAbsolutePath());
        CaOmexManifest manifest = omex.getManifest();
        CaListOfContents contents = manifest.getListOfContents();
        System.out.println("Contents fetched");
        for (int contentIndex = 0; contentIndex < contents.getNumContents(); contentIndex++) {
            CaContent content = (CaContent) contents.get(contentIndex);
            if (content.isFormat("sedml")) {
                sedmlLocations.add(content.getLocation());
            }
        }
        System.out.println("All SEDML locations fetched");
    // unzip(IN_ROOT_STRING, tempDir);
    } catch (Exception ex) {
        System.err.println("Cannot extract Omex");
        System.exit(1);
    }
    File inDir = tempDir;
    File outRootDir = new File(OUT_ROOT_STRING);
    // delete the output directory and all its content recursively
    if (outRootDir.exists()) {
        try {
            deleteRecursively(outRootDir);
        } catch (IOException e) {
            System.err.println("Failed to empty outRootDir.");
            System.exit(99);
        }
    }
    if (!outRootDir.exists()) {
        outRootDir.mkdirs();
    }
    // }
    for (int sedmlIndex = 0; sedmlIndex < sedmlLocations.size(); sedmlIndex++) {
        try {
            String completeSedmlPath = tempDir.getAbsolutePath() + "/" + sedmlLocations.get(sedmlIndex);
            File sedmlFile = new File(completeSedmlPath);
            SedML sedml = Libsedml.readDocument(sedmlFile).getSedMLModel();
            if (sedml == null || sedml.getModels().isEmpty()) {
                System.err.println("the sedml file '" + sedmlFile.getName() + "'does not contain a valid document");
                System.exit(99);
            }
            VCellSedMLSolver vCellSedMLSolver = new VCellSedMLSolver();
            ExternalDocInfo externalDocInfo = new ExternalDocInfo(sedmlFile, true);
            for (AbstractTask at : sedml.getTasks()) {
                vCellSedMLSolver.doWork(externalDocInfo, at, sedml);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
    // try {
    // SedML sedml = Libsedml.readDocument(sedmlFile).getSedMLModel();
    // if (sedml == null || sedml.getModels().isEmpty()) {
    // System.err.println("the sedml file '" + sedmlFile.getName() + "'does not contain a valid document");
    // System.exit(99);
    // }
    // VCellSedMLSolver vCellSedMLSolver = new VCellSedMLSolver();
    // ExternalDocInfo externalDocInfo = new ExternalDocInfo(sedmlFile, true);
    // for(AbstractTask at : sedml.getTasks()) {
    // vCellSedMLSolver.doWork(externalDocInfo, at, sedml);
    // }
    // } catch (Exception e) {
    // System.err.println(e.getMessage());
    // } finally {
    deleteDirectory(tempDir);
// }
}
Also used : Options(org.apache.commons.cli.Options) AbstractTask(org.jlibsedml.AbstractTask) JsonParseException(com.fasterxml.jackson.core.JsonParseException) SBMLImportException(org.vcell.sbml.vcell.SBMLImportException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) HelpFormatter(org.apache.commons.cli.HelpFormatter) SedML(org.jlibsedml.SedML) ExternalDocInfo(cbit.vcell.xml.ExternalDocInfo) CommandLine(org.apache.commons.cli.CommandLine) CommandLineParser(org.apache.commons.cli.CommandLineParser) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 4 with ExternalDocInfo

use of cbit.vcell.xml.ExternalDocInfo in project vcell by virtualcell.

the class BioModelsNetJPanel method searchImport.

private void searchImport() {
    AsynchClientTask searchTask = new AsynchClientTask("Search BioModels", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            Hashtable<String, String> vcellCompatibleBioModels_ID_Name_Hash = readVCellCompatibleBioModels_ID_Name_Hash();
            ClientTaskStatusSupport clientTaskStatusSupport = getClientTaskStatusSupport();
            // clientTaskStatusSupport.setProgress(0);
            clientTaskStatusSupport.setMessage("Initializing BioModels Search...");
            BioModelsWebServicesServiceLocator bioModelsWebServicesServiceLocator = new BioModelsWebServicesServiceLocator();
            BioModelsWebServices bioModelsWebServices = bioModelsWebServicesServiceLocator.getBioModelsWebServices();
            // clientTaskStatusSupport.setProgress(10);
            clientTaskStatusSupport.setMessage("Executing BioModels Search...");
            TreeSet<String> modelIDsMergedSearch = new TreeSet<String>();
            boolean bHasModelEntryID = modelEntryIDTextField.getText() != null && modelEntryIDTextField.getText().length() > 0;
            if (bHasModelEntryID) {
                clientTaskStatusSupport.setMessage("Executing BioModels Search (Model ID matches)...");
                // String[] modelIDsAll = bioModelsWebServices.getAllModelsId();
                String[] modelIDsAll = vcellCompatibleBioModels_ID_Name_Hash.keySet().toArray(new String[0]);
                for (int i = 0; i < modelIDsAll.length; i++) {
                    if (modelIDsAll[i].toUpperCase().indexOf(modelEntryIDTextField.getText().toUpperCase()) != -1) {
                        modelIDsMergedSearch.add(modelIDsAll[i]);
                    }
                }
            }
            boolean bHasModelName = modelNameTextField.getText() != null && modelNameTextField.getText().length() > 0;
            if (bHasModelName) {
                clientTaskStatusSupport.setMessage("Executing BioModels Search (Model Name matches)...");
                TreeSet<String> modelIDsByNameSet = new TreeSet<String>();
                // String[] modelIDsByName = bioModelsWebServices.getModelsIdByName(modelNameTextField.getText());
                String[] modelIDsAll = vcellCompatibleBioModels_ID_Name_Hash.keySet().toArray(new String[0]);
                for (int i = 0; i < modelIDsAll.length; i++) {
                    if (vcellCompatibleBioModels_ID_Name_Hash.get(modelIDsAll[i]).toUpperCase().indexOf(modelNameTextField.getText().toUpperCase()) != -1) {
                        modelIDsByNameSet.add(modelIDsAll[i]);
                    }
                }
                // }
                if (bHasModelEntryID) {
                    // intersection
                    modelIDsMergedSearch.retainAll(modelIDsByNameSet);
                } else {
                    modelIDsMergedSearch = modelIDsByNameSet;
                }
            }
            boolean bHasModelPublication = publicationTextField.getText() != null && publicationTextField.getText().length() > 0;
            if (bHasModelPublication) {
                clientTaskStatusSupport.setMessage("Executing BioModels Search (Publication matches)...");
                TreeSet<String> modelIDsByPublicationSet = new TreeSet<String>();
                String[] modelIDsbyPublication = bioModelsWebServices.getModelsIdByPublication(publicationTextField.getText());
                for (int i = 0; i < modelIDsbyPublication.length; i++) {
                    modelIDsByPublicationSet.add(modelIDsbyPublication[i]);
                }
                if (bHasModelEntryID || bHasModelName) {
                    // intersection
                    modelIDsMergedSearch.retainAll(modelIDsByPublicationSet);
                } else {
                    modelIDsMergedSearch = modelIDsByPublicationSet;
                }
            }
            if (!(bHasModelEntryID || bHasModelName || bHasModelPublication)) {
                // Get all models
                // modelIDsMergedSearch.addAll(Arrays.asList(bioModelsWebServices.getAllModelsId()));
                modelIDsMergedSearch.addAll(Arrays.asList(vcellCompatibleBioModels_ID_Name_Hash.keySet().toArray(new String[0])));
            }
            // clientTaskStatusSupport.setProgress(COLLECTION_PROGRESS);
            if (modelIDsMergedSearch.size() > 0) {
                // Intersect with supported BioModel IDs
                modelIDsMergedSearch.retainAll(Arrays.asList(vcellCompatibleBioModels_ID_Name_Hash.keySet().toArray(new String[0])));
                clientTaskStatusSupport.setMessage("Found " + modelIDsMergedSearch.size() + " VCell compatible BioModels");
                String[] modelIDMergedSearchArr = modelIDsMergedSearch.toArray(new String[0]);
                TreeMap<String, String> model_ID_Name_Map = new TreeMap<String, String>();
                String nameNotfound = "NameNotFound_0";
                for (int i = 0; i < modelIDMergedSearchArr.length; i++) {
                    if (clientTaskStatusSupport.isInterrupted()) {
                        // DialogUtils.showWarningDialog(BioModelsNetJPanel.this, "Search Cancelled");
                        throw UserCancelException.CANCEL_GENERIC;
                    }
                    try {
                        // clientTaskStatusSupport.setMessage("Retrieving "+modelIDMergedSearchArr[i]+" "+(i+1)+" of "+modelIDMergedSearchArr.length);
                        // String modelName = bioModelsWebServices.getModelNameById(modelIDMergedSearchArr[i]);
                        String modelName = vcellCompatibleBioModels_ID_Name_Hash.get(modelIDMergedSearchArr[i]);
                        // Assume model names are unique
                        model_ID_Name_Map.put(modelName, modelIDMergedSearchArr[i]);
                    } catch (Exception e) {
                        // For some reason Web Service API sometimes throws java.util.NoSuchElementException
                        // if id exists but name can't be found.
                        e.printStackTrace();
                        model_ID_Name_Map.put(nameNotfound, modelIDMergedSearchArr[i]);
                        nameNotfound = TokenMangler.getNextEnumeratedToken(nameNotfound);
                    }
                }
                // Make name,id rowdata for tablelist to allow user selection
                String[] sortedModelNames = model_ID_Name_Map.keySet().toArray(new String[0]);
                final String[][] rowData = new String[sortedModelNames.length][2];
                for (int i = 0; i < sortedModelNames.length; i++) {
                    rowData[i][0] = sortedModelNames[i];
                    rowData[i][1] = model_ID_Name_Map.get(sortedModelNames[i]);
                }
                // Allow user to select model for opening
                final String importNow = "Import";
                final String cancel = "Cancel";
                DialogUtils.TableListResult result = DialogUtils.showComponentOptionsTableList(BioModelsNetJPanel.this, "Select a BioModel to import", new String[] { "Model Names", "BioModels Entry ID" }, rowData, ListSelectionModel.SINGLE_SELECTION, null, new String[] { importNow, cancel }, importNow, new Comparator<Object>() {

                    public int compare(Object o1, Object o2) {
                        if (o1 instanceof String && o2 instanceof String) {
                            return ((String) o1).compareTo((String) o2);
                        }
                        throw new RuntimeException("row data should only be String");
                    }
                });
                if (result.selectedOption != null && result.selectedOption.equals(importNow)) {
                    // Close Dialog showing "this" panel so ProgressPopup not obscured during openDocument
                    SwingUtilities.invokeAndWait(new Runnable() {

                        public void run() {
                            disposeParentDialog();
                        }
                    });
                    closeClientTaskStatusSupport(clientTaskStatusSupport);
                    // Download and open (in new window) SBML document selected by user
                    String bioModelSBML = bioModelsWebServices.getModelSBMLById(rowData[result.selectedTableRows[0]][1]);
                    final ExternalDocInfo externalDocInfo = new ExternalDocInfo(bioModelSBML, sortedModelNames[result.selectedTableRows[0]]);
                    new Thread(new Runnable() {

                        public void run() {
                            documentWindow.getTopLevelWindowManager().getRequestManager().openDocument(externalDocInfo, documentWindow.getTopLevelWindowManager(), true);
                        }
                    }).start();
                }
            } else {
                closeClientTaskStatusSupport(clientTaskStatusSupport);
                DialogUtils.showWarningDialog(BioModelsNetJPanel.this, "No BioModels found matching current search criteria.");
                throw UserCancelException.CANCEL_GENERIC;
            }
        }
    };
    ClientTaskDispatcher.dispatch(BioModelsNetJPanel.this, new Hashtable<String, Object>(), new AsynchClientTask[] { searchTask }, true, true, null, true);
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) ExternalDocInfo(cbit.vcell.xml.ExternalDocInfo) TreeSet(java.util.TreeSet) ClientTaskStatusSupport(org.vcell.util.ClientTaskStatusSupport) BioModelsWebServicesServiceLocator(uk.ac.ebi.www.biomodels_main.services.BioModelsWebServices.BioModelsWebServicesServiceLocator) Hashtable(java.util.Hashtable) TreeMap(java.util.TreeMap) FileNotFoundException(java.io.FileNotFoundException) UserCancelException(org.vcell.util.UserCancelException) DialogUtils(org.vcell.util.gui.DialogUtils) BioModelsWebServices(uk.ac.ebi.www.biomodels_main.services.BioModelsWebServices.BioModelsWebServices)

Example 5 with ExternalDocInfo

use of cbit.vcell.xml.ExternalDocInfo in project vcell by virtualcell.

the class CLIStandalone method singleExecOmex.

private static void singleExecOmex(CLIUtils utils, String outputBaseDir, boolean keepTempFiles, boolean exactMatchOnly, String[] args) throws Exception {
    OmexHandler omexHandler = null;
    CLIHandler cliHandler;
    String inputFile;
    // input file without the path
    String bioModelBaseName = "";
    String outputDir;
    ArrayList<String> sedmlLocations;
    int nModels;
    int nSimulations;
    int nSedml;
    int nTasks;
    int nOutputs;
    List<Output> outputs;
    int nReportsCount = 0;
    int nPlots2DCount = 0;
    int nPlots3DCount = 0;
    SedML sedml;
    Path sedmlPath2d3d = null;
    File sedmlPathwith2dand3d = null;
    SedML sedmlFromPseudo = null;
    long startTimeOmex = System.currentTimeMillis();
    try {
        cliHandler = new CLIHandler(args);
        inputFile = cliHandler.getInputFilePath();
        bioModelBaseName = org.vcell.util.FileUtils.getBaseName(inputFile);
        outputDir = cliHandler.getOutputDirPath();
        sedmlPath2d3d = Paths.get(outputDir, "temp");
        System.out.println("VCell CLI input archive " + inputFile);
        CLIUtils.drawBreakLine("-", 100);
        omexHandler = new OmexHandler(inputFile, outputDir);
        omexHandler.extractOmex();
        sedmlLocations = omexHandler.getSedmlLocationsAbsolute();
        nSedml = sedmlLocations.size();
    // any error up to now is fatal (unlikely, but still...)
    } catch (Throwable exc) {
        assert omexHandler != null;
        omexHandler.deleteExtractedOmex();
        String error = exc.getMessage() + ", error for archive " + args[1];
        writeErrorList(outputBaseDir, bioModelBaseName);
        writeDetailedResultList(outputBaseDir, bioModelBaseName + ", " + ",unknown error with the archive file");
        throw new Exception(error);
    }
    // check python installation
    CLIUtils.checkInstallationError();
    // generate Status YAML
    utils.generateStatusYaml(inputFile, outputDir);
    // from here on, we need to collect errors, since some subtasks may succeed while other do not
    // we now have the log file created, so that we also have a place to put them
    // set to true if at least one sedml document run is successful
    boolean oneSedmlDocumentSucceeded = false;
    // set to true if at least one sedml document run fails
    boolean oneSedmlDocumentFailed = false;
    String logOmexMessage = "";
    // not used for now
    String logOmexError = "";
    for (String sedmlLocation : sedmlLocations) {
        // for each sedml document
        // shows that the current document suffered a partial or total failuri
        boolean somethingFailed = false;
        String logDocumentMessage = "Initializing sedml document... ";
        String logDocumentError = "";
        HashMap<String, ODESolverResultSet> resultsHash;
        HashMap<String, File> reportsHash = null;
        String sedmlName = "";
        File completeSedmlPath = new File(sedmlLocation);
        File outDirForCurrentSedml = new File(omexHandler.getOutputPathFromSedml(sedmlLocation));
        try {
            CLIUtils.makeDirs(outDirForCurrentSedml);
            SedML sedmlFromOmex = Libsedml.readDocument(completeSedmlPath).getSedMLModel();
            String[] sedmlNameSplit;
            if (CLIUtils.isWindowsPlatform)
                sedmlNameSplit = sedmlLocation.split("\\\\", -2);
            else
                sedmlNameSplit = sedmlLocation.split("/", -2);
            sedmlName = sedmlNameSplit[sedmlNameSplit.length - 1];
            logOmexMessage += "Processing " + sedmlName + ". ";
            nModels = sedmlFromOmex.getModels().size();
            nTasks = sedmlFromOmex.getTasks().size();
            outputs = sedmlFromOmex.getOutputs();
            nOutputs = outputs.size();
            for (Output output : outputs) {
                if (output instanceof Report)
                    nReportsCount++;
                if (output instanceof Plot2D)
                    nPlots2DCount++;
                if (output instanceof Plot3D)
                    nPlots3DCount++;
            }
            nSimulations = sedmlFromOmex.getSimulations().size();
            String summarySedmlContentString = "Found " + nSedml + " SED-ML document(s) with " + nModels + " model(s), " + nSimulations + " simulation(s), " + nTasks + " task(s), " + nReportsCount + "  report(s),  " + nPlots2DCount + " plot2D(s), and " + nPlots3DCount + " plot3D(s)\n";
            System.out.println(summarySedmlContentString);
            logDocumentMessage += "done. ";
            String str = "Successful translation of SED-ML file";
            logDocumentMessage += str + ". ";
            System.out.println(str + " : " + sedmlName);
            CLIUtils.drawBreakLine("-", 100);
            // For appending data for SED Plot2D and Plot3d to HDF5 files following a temp convention
            utils.genSedmlForSed2DAnd3D(inputFile, outputDir);
            // SED-ML file generated by python VCell_cli_util
            sedmlPathwith2dand3d = new File(String.valueOf(sedmlPath2d3d), "simulation_" + sedmlName);
            Path path = Paths.get(sedmlPathwith2dand3d.getAbsolutePath());
            if (!Files.exists(path)) {
                String message = "Failed to create file " + sedmlPathwith2dand3d.getAbsolutePath();
                writeDetailedResultList(outputBaseDir, bioModelBaseName + "," + sedmlName + "," + message);
                throw new RuntimeException(message);
            }
            // Converting pseudo SED-ML to biomodel
            sedmlFromPseudo = Libsedml.readDocument(sedmlPathwith2dand3d).getSedMLModel();
            /* If SED-ML has only plots as an output, we will use SED-ML that got generated from vcell_cli_util python code
                * As of now, we are going to create a resultant dataSet for Plot output, using their respective data generators */
            sedml = sedmlFromPseudo;
        } catch (Exception e) {
            String prefix = "SED-ML processing for " + sedmlLocation + " failed with error: ";
            logDocumentError = prefix + e.getMessage();
            String type = e.getClass().getSimpleName();
            utils.setOutputMessage(sedmlLocation, sedmlName, outputDir, "sedml", logDocumentMessage);
            utils.setExceptionMessage(sedmlLocation, sedmlName, outputDir, "sedml", type, logDocumentError);
            writeDetailedErrorList(outputBaseDir, bioModelBaseName + ",  doc:    " + type + ": " + logDocumentError);
            writeDetailedResultList(outputBaseDir, bioModelBaseName + "," + sedmlName + "," + logDocumentError);
            System.err.println(prefix + e.getMessage());
            e.printStackTrace(System.err);
            somethingFailed = true;
            oneSedmlDocumentFailed = true;
            utils.updateSedmlDocStatusYml(sedmlLocation, Status.FAILED, outputDir);
            continue;
        }
        // Run solvers and make reports; all failures/exceptions are being caught
        SolverHandler solverHandler = new SolverHandler();
        // we send both the whole OMEX file and the extracted SEDML file path
        // XmlHelper code uses two types of resolvers to handle absolute or relative paths
        ExternalDocInfo externalDocInfo = new ExternalDocInfo(new File(inputFile), true);
        resultsHash = new LinkedHashMap<String, ODESolverResultSet>();
        try {
            String str = "Starting simulate all tasks... ";
            System.out.println(str);
            logDocumentMessage += str;
            resultsHash = solverHandler.simulateAllTasks(utils, externalDocInfo, sedml, outDirForCurrentSedml, outputDir, outputBaseDir, sedmlLocation, keepTempFiles, exactMatchOnly);
        } catch (Exception e) {
            somethingFailed = true;
            oneSedmlDocumentFailed = true;
            // probably the hash is empty
            logDocumentError = e.getMessage();
        // still possible to have some data in the hash, from some task that was successful - that would be partial success
        }
        String message = nModels + ",";
        message += nSimulations + ",";
        message += nTasks + ",";
        message += nOutputs + ",";
        message += solverHandler.countBioModels + ",";
        message += solverHandler.countSuccessfulSimulationRuns;
        writeDetailedResultList(outputBaseDir, bioModelBaseName + "," + sedmlName + ", ," + message);
        // 
        try {
            if (resultsHash.containsValue(null)) {
                // some tasks failed, but not all
                oneSedmlDocumentFailed = true;
                somethingFailed = true;
                logDocumentMessage += "Failed to execute one or more tasks. ";
            }
            logDocumentMessage += "Generating outputs... ";
            reportsHash = utils.generateReportsAsCSV(sedml, resultsHash, outDirForCurrentSedml, outputDir, sedmlLocation);
            if (reportsHash == null || reportsHash.size() == 0) {
                oneSedmlDocumentFailed = true;
                somethingFailed = true;
                String msg = "Failed to generate any reports. ";
                throw new RuntimeException(msg);
            }
            if (reportsHash.containsValue(null)) {
                oneSedmlDocumentFailed = true;
                somethingFailed = true;
                String msg = "Failed to generate one or more reports. ";
                logDocumentMessage += msg;
            } else {
                logDocumentMessage += "Done. ";
            }
            logDocumentMessage += "Generating HDF5 file... ";
            // create the HDF5 file
            utils.execPlotOutputSedDoc(inputFile, outputDir);
            if (!containsExtension(outputDir, "h5")) {
                oneSedmlDocumentFailed = true;
                somethingFailed = true;
                throw new RuntimeException("Failed to generate the HDF5 output file. ");
            } else {
                logDocumentMessage += "Done. ";
            }
            // generate the plots
            utils.genPlotsPseudoSedml(sedmlLocation, outDirForCurrentSedml.toString());
            oneSedmlDocumentSucceeded = true;
        } catch (Exception e) {
            somethingFailed = true;
            oneSedmlDocumentFailed = true;
            logDocumentError += e.getMessage();
            String type = e.getClass().getSimpleName();
            utils.setOutputMessage(sedmlLocation, sedmlName, outputDir, "sedml", logDocumentMessage);
            utils.setExceptionMessage(sedmlLocation, sedmlName, outputDir, "sedml", type, logDocumentError);
            writeDetailedErrorList(outputBaseDir, bioModelBaseName + ",  doc:    " + type + ": " + logDocumentError);
            utils.updateSedmlDocStatusYml(sedmlLocation, Status.FAILED, outputDir);
            // removing temp path generated from python
            org.apache.commons.io.FileUtils.deleteDirectory(new File(String.valueOf(sedmlPath2d3d)));
            continue;
        }
        if (somethingFailed == true) {
            // something went wrong but no exception was fired
            Exception e = new RuntimeException("Failure executing the sed document. ");
            logDocumentError += e.getMessage();
            String type = e.getClass().getSimpleName();
            utils.setOutputMessage(sedmlLocation, sedmlName, outputDir, "sedml", logDocumentMessage);
            utils.setExceptionMessage(sedmlLocation, sedmlName, outputDir, "sedml", type, logDocumentError);
            writeDetailedErrorList(outputBaseDir, bioModelBaseName + ",  doc:    " + type + ": " + logDocumentError);
            utils.updateSedmlDocStatusYml(sedmlLocation, Status.FAILED, outputDir);
            // removing temp path generated from python
            org.apache.commons.io.FileUtils.deleteDirectory(new File(String.valueOf(sedmlPath2d3d)));
            continue;
        }
        // removing temp path generated from python
        org.apache.commons.io.FileUtils.deleteDirectory(new File(String.valueOf(sedmlPath2d3d)));
        // archiving res files
        CLIUtils.zipResFiles(new File(outputDir));
        utils.setOutputMessage(sedmlLocation, sedmlName, outputDir, "sedml", logDocumentMessage);
        utils.updateSedmlDocStatusYml(sedmlLocation, Status.SUCCEEDED, outputDir);
    }
    omexHandler.deleteExtractedOmex();
    long endTimeOmex = System.currentTimeMillis();
    long elapsedTime = endTimeOmex - startTimeOmex;
    int duration = (int) Math.ceil(elapsedTime / 1000.0);
    // 
    if (oneSedmlDocumentFailed) {
        String error = " All sedml documents in this archive failed to execute";
        if (oneSedmlDocumentSucceeded) {
            // some succeeded, some failed
            error = " At least one document in this archive failed to execute";
        }
        utils.updateOmexStatusYml(CLIUtils.Status.FAILED, outputDir, duration + "");
        System.err.println(error);
        logOmexMessage += error;
        writeErrorList(outputBaseDir, bioModelBaseName);
    } else {
        utils.updateOmexStatusYml(CLIUtils.Status.SUCCEEDED, outputDir, duration + "");
        writeFullSuccessList(outputBaseDir, bioModelBaseName);
        logOmexMessage += " Done";
    }
    utils.setOutputMessage("null", "null", outputDir, "omex", logOmexMessage);
}
Also used : ExternalDocInfo(cbit.vcell.xml.ExternalDocInfo) ODESolverResultSet(cbit.vcell.solver.ode.ODESolverResultSet) Path(java.nio.file.Path) RuntimeCryptoException(com.lowagie.text.pdf.crypto.RuntimeCryptoException) FileSystemException(java.nio.file.FileSystemException) IOException(java.io.IOException) File(java.io.File)

Aggregations

ExternalDocInfo (cbit.vcell.xml.ExternalDocInfo)10 IOException (java.io.IOException)6 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)5 File (java.io.File)5 Hashtable (java.util.Hashtable)5 BioModel (cbit.vcell.biomodel.BioModel)3 UserCancelException (org.vcell.util.UserCancelException)3 SimulationContext (cbit.vcell.mapping.SimulationContext)2 Structure (cbit.vcell.model.Structure)2 XMLSource (cbit.vcell.xml.XMLSource)2 PropertyVetoException (java.beans.PropertyVetoException)2 FileNotFoundException (java.io.FileNotFoundException)2 Reader (java.io.Reader)2 ArrayList (java.util.ArrayList)2 DataConversionException (org.jdom.DataConversionException)2 Element (org.jdom.Element)2 SedML (org.jlibsedml.SedML)2 ASTModel (org.vcell.model.bngl.ASTModel)2 BngUnitSystem (org.vcell.model.bngl.BngUnitSystem)2 BNGLDebuggerPanel (org.vcell.model.bngl.gui.BNGLDebuggerPanel)2