Search in sources :

Example 1 with AsynchClientTaskFunction

use of cbit.vcell.client.task.AsynchClientTaskFunction 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 AsynchClientTaskFunction

use of cbit.vcell.client.task.AsynchClientTaskFunction in project vcell by virtualcell.

the class ClientSimManager method showSimulationResults0.

private AsynchClientTask[] showSimulationResults0(final boolean isLocal, final ViewerType viewerType) {
    // Create the AsynchClientTasks
    ArrayList<AsynchClientTask> taskList = new ArrayList<AsynchClientTask>();
    taskList.add(new AsynchClientTaskFunction(h -> {
        h.put(H_LOCAL_SIM, isLocal);
        h.put(H_VIEWER_TYPE, viewerType);
    }, "setLocal", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING));
    final DocumentWindowManager documentWindowManager = getDocumentWindowManager();
    AsynchClientTask retrieveResultsTask = new AsynchClientTask("Retrieving results", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @SuppressWarnings("unchecked")
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            Simulation[] simsToShow = (Simulation[]) hashTable.get("simsArray");
            for (int i = 0; i < simsToShow.length; i++) {
                final Simulation sim = simsToShow[i];
                final VCSimulationIdentifier vcSimulationIdentifier = sim.getSimulationInfo().getAuthoritativeVCSimulationIdentifier();
                final SimulationWindow simWindow = documentWindowManager.haveSimulationWindow(vcSimulationIdentifier);
                OutputContext outputContext = (OutputContext) hashTable.get("outputContext");
                if (simWindow == null && (viewerType == ViewerType.NativeViewer_only)) {
                    try {
                        // make the manager and wire it up
                        DataViewerController dataViewerController = null;
                        if (!isLocal) {
                            dataViewerController = documentWindowManager.getRequestManager().getDataViewerController(outputContext, sim, 0);
                            // For changes in time or variable
                            documentWindowManager.addDataListener(dataViewerController);
                        } else {
                            // ---- preliminary : construct the localDatasetControllerProvider
                            File primaryDir = ResourceUtil.getLocalRootDir();
                            User usr = sim.getVersion().getOwner();
                            DataSetControllerImpl dataSetControllerImpl = new DataSetControllerImpl(null, primaryDir, null);
                            ExportServiceImpl localExportServiceImpl = new ExportServiceImpl();
                            LocalDataSetControllerProvider localDSCProvider = new LocalDataSetControllerProvider(usr, dataSetControllerImpl, localExportServiceImpl);
                            VCDataManager vcDataManager = new VCDataManager(localDSCProvider);
                            File localSimDir = ResourceUtil.getLocalSimDir(User.tempUser.getName());
                            LocalVCDataIdentifier vcDataId = new LocalVCSimulationDataIdentifier(vcSimulationIdentifier, 0, localSimDir);
                            DataManager dataManager = null;
                            if (sim.isSpatial()) {
                                dataManager = new PDEDataManager(outputContext, vcDataManager, vcDataId);
                            } else {
                                dataManager = new ODEDataManager(outputContext, vcDataManager, vcDataId);
                            }
                            dataViewerController = new SimResultsViewerController(dataManager, sim);
                            dataSetControllerImpl.addDataJobListener(documentWindowManager);
                        }
                        // make the viewer
                        Hashtable<VCSimulationIdentifier, DataViewerController> dataViewerControllers = (Hashtable<VCSimulationIdentifier, DataViewerController>) hashTable.get(H_DATA_VIEWER_CONTROLLERS);
                        if (dataViewerControllers == null) {
                            dataViewerControllers = new Hashtable<VCSimulationIdentifier, DataViewerController>();
                            hashTable.put(H_DATA_VIEWER_CONTROLLERS, dataViewerControllers);
                        }
                        dataViewerControllers.put(vcSimulationIdentifier, dataViewerController);
                    } catch (Throwable exc) {
                        exc.printStackTrace(System.out);
                        saveFailure(hashTable, sim, exc);
                    }
                }
            }
        }
    };
    taskList.add(retrieveResultsTask);
    AsynchClientTask displayResultsTask = new AsynchClientTask("Showing results", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @SuppressWarnings("unchecked")
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            boolean isLocal = fetch(hashTable, H_LOCAL_SIM, Boolean.class, true);
            SimulationWindow.LocalState localState = isLocal ? LocalState.LOCAL : LocalState.SERVER;
            Hashtable<Simulation, Throwable> failures = (Hashtable<Simulation, Throwable>) hashTable.get(H_FAILURES);
            Simulation[] simsToShow = (Simulation[]) hashTable.get("simsArray");
            for (int i = 0; i < simsToShow.length; i++) {
                final Simulation sim = simsToShow[i];
                if (failures != null && failures.containsKey(sim)) {
                    continue;
                }
                final VCSimulationIdentifier vcSimulationIdentifier = simsToShow[i].getSimulationInfo().getAuthoritativeVCSimulationIdentifier();
                final SimulationWindow simWindow = documentWindowManager.haveSimulationWindow(vcSimulationIdentifier);
                if (simWindow != null) {
                    ChildWindowManager childWindowManager = ChildWindowManager.findChildWindowManager(documentWindowManager.getComponent());
                    ChildWindow childWindow = childWindowManager.getChildWindowFromContext(simWindow);
                    if (childWindow == null) {
                        childWindow = childWindowManager.addChildWindow(simWindow.getDataViewer(), simWindow);
                        childWindow.pack();
                        childWindow.setIsCenteredOnParent();
                        childWindow.show();
                    }
                    setFinalWindow(hashTable, childWindow);
                    simWindow.setLocalState(localState);
                } else {
                    // wire it up the viewer
                    Hashtable<VCSimulationIdentifier, DataViewerController> dataViewerControllers = (Hashtable<VCSimulationIdentifier, DataViewerController>) hashTable.get(H_DATA_VIEWER_CONTROLLERS);
                    DataViewerController viewerController = dataViewerControllers.get(vcSimulationIdentifier);
                    Throwable ex = (failures == null ? null : failures.get(sim));
                    if (viewerController != null && ex == null) {
                        // no failure
                        DataViewer viewer = viewerController.createViewer();
                        getSimWorkspace().getSimulationOwner().getOutputFunctionContext().addPropertyChangeListener(viewerController);
                        documentWindowManager.addExportListener(viewer);
                        // For data related activities such as calculating statistics
                        documentWindowManager.addDataJobListener(viewer);
                        viewer.setSimulationModelInfo(new SimulationWorkspaceModelInfo(getSimWorkspace().getSimulationOwner(), sim.getName()));
                        viewer.setDataViewerManager(documentWindowManager);
                        SimulationWindow newWindow = new SimulationWindow(vcSimulationIdentifier, sim, getSimWorkspace().getSimulationOwner(), viewer);
                        BeanUtils.addCloseWindowKeyboardAction(newWindow.getDataViewer());
                        documentWindowManager.addResultsFrame(newWindow);
                        setFinalWindow(hashTable, viewer);
                        newWindow.setLocalState(localState);
                    }
                }
            }
            StringBuffer failMessage = new StringBuffer();
            if (failures != null) {
                if (!failures.isEmpty()) {
                    failMessage.append("Error, " + failures.size() + " of " + simsToShow.length + " sim results failed to display:\n");
                    Enumeration<Simulation> en = failures.keys();
                    while (en.hasMoreElements()) {
                        Simulation sim = en.nextElement();
                        Throwable exc = (Throwable) failures.get(sim);
                        failMessage.append("'" + sim.getName() + "' - " + exc.getMessage());
                    }
                }
            }
            if (failMessage.length() > 0) {
                PopupGenerator.showErrorDialog(ClientSimManager.this.getDocumentWindowManager(), failMessage.toString());
            }
        }
    };
    if (viewerType == ViewerType.NativeViewer_only) {
        taskList.add(displayResultsTask);
    }
    // Dispatch the tasks using the ClientTaskDispatcher.
    AsynchClientTask[] taskArray = new AsynchClientTask[taskList.size()];
    taskList.toArray(taskArray);
    return taskArray;
}
Also used : User(org.vcell.util.document.User) SimulationMessage(cbit.vcell.solver.server.SimulationMessage) Enumeration(java.util.Enumeration) Version(org.vcell.util.document.Version) Vector(java.util.Vector) Map(java.util.Map) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) SimulationContext(cbit.vcell.mapping.SimulationContext) PrintWriter(java.io.PrintWriter) NetworkGenerationRequirements(cbit.vcell.mapping.SimulationContext.NetworkGenerationRequirements) VCDataManager(cbit.vcell.simdata.VCDataManager) BeanUtils(org.vcell.util.BeanUtils) ODESimData(cbit.vcell.solver.ode.ODESimData) WindowAdapter(java.awt.event.WindowAdapter) SimulationWorkspace(cbit.vcell.client.desktop.simulation.SimulationWorkspace) SolverListener(cbit.vcell.solver.server.SolverListener) VtkManager(cbit.vcell.simdata.VtkManager) SimulationJob(cbit.vcell.solver.SimulationJob) VCellClientTest(cbit.vcell.client.test.VCellClientTest) ExportServiceImpl(cbit.vcell.export.server.ExportServiceImpl) DataProcessingInstructions(cbit.vcell.solver.DataProcessingInstructions) VCellClientDataServiceImpl(cbit.vcell.client.data.VCellClientDataServiceImpl) OutputContext(cbit.vcell.simdata.OutputContext) SimulationTask(cbit.vcell.messaging.server.SimulationTask) VCDocument(org.vcell.util.document.VCDocument) TempSimulation(cbit.vcell.solver.TempSimulation) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) SolverFactory(cbit.vcell.solver.server.SolverFactory) SolverStatus(cbit.vcell.solver.server.SolverStatus) SimulationInfo(cbit.vcell.solver.SimulationInfo) Container(java.awt.Container) PDEDataManager(cbit.vcell.simdata.PDEDataManager) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) UserPreferences(cbit.vcell.client.server.UserPreferences) BioModel(cbit.vcell.biomodel.BioModel) BufferedWriter(java.io.BufferedWriter) RemoteProxyException(cbit.vcell.message.server.bootstrap.client.RemoteProxyVCellConnectionFactory.RemoteProxyException) Window(java.awt.Window) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyLoader(cbit.vcell.resource.PropertyLoader) InputStreamReader(java.io.InputStreamReader) File(java.io.File) SolverUtilities(cbit.vcell.solver.SolverUtilities) DialogUtils(org.vcell.util.gui.DialogUtils) DataViewerController(cbit.vcell.client.data.DataViewerController) SimResultsViewer(cbit.vcell.client.data.SimResultsViewer) LocalVCDataIdentifier(org.vcell.util.document.LocalVCDataIdentifier) SimulationWindow(cbit.vcell.client.desktop.simulation.SimulationWindow) EventObject(java.util.EventObject) VCSimulationIdentifier(cbit.vcell.solver.VCSimulationIdentifier) DataViewer(cbit.vcell.client.data.DataViewer) ColumnDescription(cbit.vcell.util.ColumnDescription) FieldDataIdentifierSpec(cbit.vcell.field.FieldDataIdentifierSpec) SmoldynSolver(org.vcell.solver.smoldyn.SmoldynSolver) Simulation(cbit.vcell.solver.Simulation) Solver(cbit.vcell.solver.server.Solver) Collection(java.util.Collection) UtilCancelException(org.vcell.util.UtilCancelException) WindowEvent(java.awt.event.WindowEvent) FileNotFoundException(java.io.FileNotFoundException) SolverEvent(cbit.vcell.solver.server.SolverEvent) AsynchClientTaskFunction(cbit.vcell.client.task.AsynchClientTaskFunction) Dimension(java.awt.Dimension) List(java.util.List) ClientTaskDispatcher(cbit.vcell.client.task.ClientTaskDispatcher) VCellConfiguration(cbit.vcell.resource.VCellConfiguration) ODESolverResultSet(cbit.vcell.solver.ode.ODESolverResultSet) SimulationOwner(cbit.vcell.solver.SimulationOwner) ChildWindow(cbit.vcell.client.ChildWindowManager.ChildWindow) SimulationWorkspaceModelInfo(cbit.vcell.client.data.SimulationWorkspaceModelInfo) DataSetControllerImpl(cbit.vcell.simdata.DataSetControllerImpl) DataSetController(cbit.vcell.server.DataSetController) VtuVarInfo(org.vcell.vis.io.VtuVarInfo) LocalState(cbit.vcell.client.desktop.simulation.SimulationWindow.LocalState) SwingUtilities(javax.swing.SwingUtilities) SimDataConstants(cbit.vcell.simdata.SimDataConstants) SolverException(cbit.vcell.solver.SolverException) Hashtable(java.util.Hashtable) SimulationStatusDetailsPanel(cbit.vcell.client.desktop.simulation.SimulationStatusDetailsPanel) SimulationStatus(cbit.vcell.server.SimulationStatus) SimulationDataSetRef(cbit.vcell.client.pyvcellproxy.SimulationDataSetRef) ClientServerManager(cbit.vcell.client.server.ClientServerManager) ResourceUtil(cbit.vcell.resource.ResourceUtil) ODEDataManager(cbit.vcell.simdata.ODEDataManager) FileWriter(java.io.FileWriter) SmoldynFileWriter(org.vcell.solver.smoldyn.SmoldynFileWriter) ExpressionException(cbit.vcell.parser.ExpressionException) TokenMangler(org.vcell.util.TokenMangler) SolverDescription(cbit.vcell.solver.SolverDescription) SimulationStatusDetails(cbit.vcell.client.desktop.simulation.SimulationStatusDetails) ProgressDialogListener(org.vcell.util.ProgressDialogListener) DataManager(cbit.vcell.simdata.DataManager) InputStream(java.io.InputStream) UserCancelException(org.vcell.util.UserCancelException) LocalState(cbit.vcell.client.desktop.simulation.SimulationWindow.LocalState) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) VCSimulationIdentifier(cbit.vcell.solver.VCSimulationIdentifier) User(org.vcell.util.document.User) ArrayList(java.util.ArrayList) AsynchClientTaskFunction(cbit.vcell.client.task.AsynchClientTaskFunction) DataViewerController(cbit.vcell.client.data.DataViewerController) DataViewer(cbit.vcell.client.data.DataViewer) ExportServiceImpl(cbit.vcell.export.server.ExportServiceImpl) VCDataManager(cbit.vcell.simdata.VCDataManager) SimulationWorkspaceModelInfo(cbit.vcell.client.data.SimulationWorkspaceModelInfo) Hashtable(java.util.Hashtable) VCDataManager(cbit.vcell.simdata.VCDataManager) PDEDataManager(cbit.vcell.simdata.PDEDataManager) ODEDataManager(cbit.vcell.simdata.ODEDataManager) DataManager(cbit.vcell.simdata.DataManager) LocalVCDataIdentifier(org.vcell.util.document.LocalVCDataIdentifier) ChildWindow(cbit.vcell.client.ChildWindowManager.ChildWindow) OutputContext(cbit.vcell.simdata.OutputContext) TempSimulation(cbit.vcell.solver.TempSimulation) Simulation(cbit.vcell.solver.Simulation) PDEDataManager(cbit.vcell.simdata.PDEDataManager) SimulationWindow(cbit.vcell.client.desktop.simulation.SimulationWindow) DataSetControllerImpl(cbit.vcell.simdata.DataSetControllerImpl) ODEDataManager(cbit.vcell.simdata.ODEDataManager) File(java.io.File)

Example 3 with AsynchClientTaskFunction

use of cbit.vcell.client.task.AsynchClientTaskFunction in project vcell by virtualcell.

the class MathematicsPanel method createMathModel.

private void createMathModel(final ActionEvent e) {
    // relays an action event with this as the source
    Collection<AsynchClientTask> tasks = ClientRequestManager.updateMath(this, simulationContext, true, NetworkGenerationRequirements.ComputeFullStandardTimeout);
    tasks.add(new AsynchClientTaskFunction(ht -> refireActionPerformed(e), "creating math model", AsynchClientTask.TASKTYPE_SWING_BLOCKING));
    ClientTaskDispatcher.dispatchColl(this, new Hashtable<String, Object>(), tasks, false);
}
Also used : CardLayout(java.awt.CardLayout) ActionListener(java.awt.event.ActionListener) MultiPurposeTextPanel(cbit.gui.MultiPurposeTextPanel) MathDescPanel(cbit.vcell.math.gui.MathDescPanel) BorderLayout(java.awt.BorderLayout) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) SimulationContext(cbit.vcell.mapping.SimulationContext) Hashtable(java.util.Hashtable) BoxLayout(javax.swing.BoxLayout) ItemEvent(java.awt.event.ItemEvent) NetworkGenerationRequirements(cbit.vcell.mapping.SimulationContext.NetworkGenerationRequirements) JButton(javax.swing.JButton) Application(cbit.vcell.mapping.SimulationContext.Application) ButtonGroup(javax.swing.ButtonGroup) Font(java.awt.Font) Collection(java.util.Collection) ActionEvent(java.awt.event.ActionEvent) JRadioButton(javax.swing.JRadioButton) Box(javax.swing.Box) AsynchClientTaskFunction(cbit.vcell.client.task.AsynchClientTaskFunction) Dimension(java.awt.Dimension) MathDescEditor(cbit.vcell.math.gui.MathDescEditor) AWTEventMulticaster(java.awt.AWTEventMulticaster) PropertyChangeListener(java.beans.PropertyChangeListener) JLabel(javax.swing.JLabel) ClientTaskDispatcher(cbit.vcell.client.task.ClientTaskDispatcher) ClientRequestManager(cbit.vcell.client.ClientRequestManager) JPanel(javax.swing.JPanel) AsynchClientTaskFunction(cbit.vcell.client.task.AsynchClientTaskFunction) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask)

Aggregations

AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)3 AsynchClientTaskFunction (cbit.vcell.client.task.AsynchClientTaskFunction)3 SimulationContext (cbit.vcell.mapping.SimulationContext)3 Hashtable (java.util.Hashtable)3 BioModel (cbit.vcell.biomodel.BioModel)2 ClientTaskDispatcher (cbit.vcell.client.task.ClientTaskDispatcher)2 ExpressionException (cbit.vcell.parser.ExpressionException)2 Simulation (cbit.vcell.solver.Simulation)2 File (java.io.File)2 FileWriter (java.io.FileWriter)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 DataAccessException (org.vcell.util.DataAccessException)2 UserCancelException (org.vcell.util.UserCancelException)2 UtilCancelException (org.vcell.util.UtilCancelException)2 VCDocument (org.vcell.util.document.VCDocument)2 MultiPurposeTextPanel (cbit.gui.MultiPurposeTextPanel)1 ImageException (cbit.image.ImageException)1 VCMetaData (cbit.vcell.biomodel.meta.VCMetaData)1