Search in sources :

Example 1 with Issue

use of org.vcell.util.Issue in project vcell by virtualcell.

the class ParameterEstimationRunTaskPanel method solve.

private void solve() throws NumberFormatException {
    CopasiOptimizationMethod com = optimizationMethodParameterTableModel.copasiOptimizationMethod;
    OptimizationSolverSpec optSolverSpec = new OptimizationSolverSpec(com);
    // get num runs for stochstic opt mehtods before starting solving...
    if (com.getType().isStochasticMethod()) {
        int numRuns = Integer.parseInt(((String) numberOfRunComboBox.getSelectedItem()));
        optSolverSpec.setNumOfRuns(numRuns);
    }
    parameterEstimationTask.setOptimizationSolverSpec(optSolverSpec);
    parameterEstimationTask.getModelOptimizationSpec().setComputeProfileDistributions(computeProfileDistributionsCheckBox.isSelected());
    optSolverCallbacks.reset();
    Double endValue = com.getEndValue();
    optSolverCallbacks.setEvaluation(0, Double.POSITIVE_INFINITY, 0, endValue, 0);
    // (endValue != null);
    getRunStatusDialog().showProgressBar(com);
    Collection<AsynchClientTask> taskList = ClientRequestManager.updateMath(this, parameterEstimationTask.getSimulationContext(), false, NetworkGenerationRequirements.ComputeFullStandardTimeout);
    AsynchClientTask task1 = new AsynchClientTask("checking issues", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            StringBuffer issueText = new StringBuffer();
            java.util.Vector<Issue> issueList = new java.util.Vector<Issue>();
            IssueContext issueContext = new IssueContext();
            parameterEstimationTask.gatherIssues(issueContext, issueList);
            boolean bFailed = false;
            for (int i = 0; i < issueList.size(); i++) {
                Issue issue = (Issue) issueList.elementAt(i);
                issueText.append(issue.getMessage() + "\n");
                if (issue.getSeverity() == Issue.SEVERITY_ERROR) {
                    bFailed = true;
                    break;
                }
            }
            if (bFailed) {
                throw new OptimizationException(issueText.toString());
            }
            parameterEstimationTask.refreshMappings();
        }
    };
    taskList.add(task1);
    AsynchClientTask task2 = new AsynchClientTask("solving", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            MathMappingCallback mathMappingCallback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
            // OptimizationResultSet optResultSet = CopasiOptimizationSolver.solveLocalPython(new ParameterEstimationTaskSimulatorIDA(),parameterEstimationTask,optSolverCallbacks,mathMappingCallback);
            OptimizationResultSet optResultSet = CopasiOptimizationSolver.solveRemoteApi(new ParameterEstimationTaskSimulatorIDA(), parameterEstimationTask, optSolverCallbacks, mathMappingCallback);
            hashTable.put(ORS_KEY, optResultSet);
        }
    };
    taskList.add(task2);
    AsynchClientTask setResultTask = new AsynchClientTask("set results", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            OptimizationResultSet optResultSet = (OptimizationResultSet) hashTable.get(ORS_KEY);
            parameterEstimationTask.setOptimizationResultSet(optResultSet);
        }
    };
    taskList.add(setResultTask);
    ClientTaskDispatcher.dispatch(this, new Hashtable<String, Object>(), taskList.toArray(new AsynchClientTask[taskList.size()]), getRunStatusDialog(), true, true, true, null, false);
}
Also used : OptimizationException(cbit.vcell.opt.OptimizationException) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Issue(org.vcell.util.Issue) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) Hashtable(java.util.Hashtable) OptimizationResultSet(cbit.vcell.opt.OptimizationResultSet) CopasiOptimizationMethod(cbit.vcell.opt.CopasiOptimizationMethod) IssueContext(org.vcell.util.IssueContext) OptimizationSolverSpec(cbit.vcell.opt.OptimizationSolverSpec) EventObject(java.util.EventObject) ParameterEstimationTaskSimulatorIDA(org.vcell.optimization.ParameterEstimationTaskSimulatorIDA)

Example 2 with Issue

use of org.vcell.util.Issue in project vcell by virtualcell.

the class SBMLImporter method addReactions.

/**
 * addReactions:
 */
protected void addReactions(VCMetaData metaData) {
    if (sbmlModel == null) {
        throw new SBMLImportException("SBML model is NULL");
    }
    ListOf<Reaction> reactions = sbmlModel.getListOfReactions();
    final int numReactions = reactions.size();
    if (numReactions == 0) {
        lg.info("No Reactions");
        return;
    }
    // all reactions
    ArrayList<ReactionStep> vcReactionList = new ArrayList<>();
    // just the fast ones
    ArrayList<ReactionStep> fastReactionList = new ArrayList<>();
    Model vcModel = vcBioModel.getSimulationContext(0).getModel();
    ModelUnitSystem vcModelUnitSystem = vcModel.getUnitSystem();
    SpeciesContext[] vcSpeciesContexts = vcModel.getSpeciesContexts();
    try {
        for (Reaction sbmlRxn : reactions) {
            ReactionStep vcReaction = null;
            String rxnName = sbmlRxn.getId();
            boolean bReversible = true;
            if (sbmlRxn.isSetReversible()) {
                bReversible = sbmlRxn.getReversible();
            }
            // Check of reaction annotation is present; if so, does it have
            // an embedded element (flux or simpleRxn).
            // Create a fluxReaction or simpleReaction accordingly.
            Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlRxn);
            Structure reactionStructure = getReactionStructure(sbmlRxn, vcSpeciesContexts, sbmlImportRelatedElement);
            if (sbmlImportRelatedElement != null) {
                Element embeddedRxnElement = getEmbeddedElementInAnnotation(sbmlImportRelatedElement, REACTION);
                if (embeddedRxnElement != null) {
                    if (embeddedRxnElement.getName().equals(XMLTags.FluxStepTag)) {
                        // If embedded element is a flux reaction, set flux
                        // reaction's strucure, flux carrier, physicsOption
                        // from the element attributes.
                        String structName = embeddedRxnElement.getAttributeValue(XMLTags.StructureAttrTag);
                        CastInfo<Membrane> ci = SBMLHelper.getTypedStructure(Membrane.class, vcModel, structName);
                        if (!ci.isGood()) {
                            throw new SBMLImportException("Appears that the flux reaction is occuring on " + ci.actualName() + ", not a membrane.");
                        }
                        vcReaction = new FluxReaction(vcModel, ci.get(), null, rxnName, bReversible);
                        vcReaction.setModel(vcModel);
                        // Set the fluxOption on the flux reaction based on
                        // whether it is molecular, molecular & electrical,
                        // electrical.
                        String fluxOptionStr = embeddedRxnElement.getAttributeValue(XMLTags.FluxOptionAttrTag);
                        if (fluxOptionStr.equals(XMLTags.FluxOptionMolecularOnly)) {
                            ((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_MOLECULAR_ONLY);
                        } else if (fluxOptionStr.equals(XMLTags.FluxOptionMolecularAndElectrical)) {
                            ((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_MOLECULAR_AND_ELECTRICAL);
                        } else if (fluxOptionStr.equals(XMLTags.FluxOptionElectricalOnly)) {
                            ((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_ELECTRICAL_ONLY);
                        } else {
                            localIssueList.add(new Issue(vcReaction, issueContext, IssueCategory.SBMLImport_Reaction, "Unknown FluxOption : " + fluxOptionStr + " for SBML reaction : " + rxnName, Issue.SEVERITY_WARNING));
                        // logger.sendMessage(VCLogger.Priority.MediumPriority,
                        // VCLogger.ErrorType.ReactionError,
                        // "Unknown FluxOption : " + fluxOptionStr +
                        // " for SBML reaction : " + rxnName);
                        }
                    } else if (embeddedRxnElement.getName().equals(XMLTags.SimpleReactionTag)) {
                        // if embedded element is a simple reaction, set
                        // simple reaction's structure from element
                        // attributes
                        vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
                    }
                } else {
                    vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
                }
            } else {
                vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
            }
            // set annotations and notes on vcReactions[i]
            sbmlAnnotationUtil.readAnnotation(vcReaction, sbmlRxn);
            sbmlAnnotationUtil.readNotes(vcReaction, sbmlRxn);
            // the limit on the reactionName length.
            if (rxnName.length() > 64) {
                String freeTextAnnotation = metaData.getFreeTextAnnotation(vcReaction);
                if (freeTextAnnotation == null) {
                    freeTextAnnotation = "";
                }
                StringBuffer oldRxnAnnotation = new StringBuffer(freeTextAnnotation);
                oldRxnAnnotation.append("\n\n" + rxnName);
                metaData.setFreeTextAnnotation(vcReaction, oldRxnAnnotation.toString());
            }
            // Now add the reactants, products, modifiers as specified by
            // the sbmlRxn
            addReactionParticipants(sbmlRxn, vcReaction);
            KineticLaw kLaw = sbmlRxn.getKineticLaw();
            Kinetics kinetics = null;
            if (kLaw != null) {
                // Convert the formula from kineticLaw into MathML and then
                // to an expression (infix) to be used in VCell kinetics
                ASTNode sbmlRateMath = kLaw.getMath();
                Expression kLawRateExpr = getExpressionFromFormula(sbmlRateMath);
                Expression vcRateExpression = new Expression(kLawRateExpr);
                // modifier (catalyst) to the reaction.
                for (int k = 0; k < vcSpeciesContexts.length; k++) {
                    if (vcRateExpression.hasSymbol(vcSpeciesContexts[k].getName())) {
                        if ((vcReaction.getReactant(vcSpeciesContexts[k].getName()) == null) && (vcReaction.getProduct(vcSpeciesContexts[k].getName()) == null) && (vcReaction.getCatalyst(vcSpeciesContexts[k].getName()) == null)) {
                            // This means that the speciesContext is not a
                            // reactant, product or modifier : it has to be
                            // added to the VC Rxn as a catalyst
                            vcReaction.addCatalyst(vcSpeciesContexts[k]);
                        }
                    }
                }
                // set kinetics on VCell reaction
                if (bSpatial) {
                    // if spatial SBML ('isSpatial' attribute set), create
                    // DistributedKinetics)
                    SpatialReactionPlugin ssrplugin = (SpatialReactionPlugin) sbmlRxn.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
                    // 'spatial'
                    if (ssrplugin != null && ssrplugin.getIsLocal()) {
                        kinetics = new GeneralKinetics(vcReaction);
                    } else {
                        kinetics = new GeneralLumpedKinetics(vcReaction);
                    }
                } else {
                    kinetics = new GeneralLumpedKinetics(vcReaction);
                }
                // set kinetics on vcReaction
                vcReaction.setKinetics(kinetics);
                // If the name of the rate parameter has been changed by
                // user, or matches with global/local param,
                // it has to be changed.
                resolveRxnParameterNameConflicts(sbmlRxn, kinetics, sbmlImportRelatedElement);
                /**
                 * Now, based on the kinetic law expression, see if the rate
                 * is expressed in concentration/time or substance/time : If
                 * the compartment_id of the compartment corresponding to
                 * the structure in which the reaction takes place occurs in
                 * the rate law expression, it is in concentration/time;
                 * divide it by the compartment size and bring in the rate
                 * law as 'Distributed' kinetics. If not, the rate law is in
                 * substance/time; bring it in (as is) as 'Lumped' kinetics.
                 */
                ListOf<LocalParameter> localParameters = kLaw.getListOfLocalParameters();
                for (LocalParameter p : localParameters) {
                    String paramName = p.getId();
                    KineticsParameter kineticsParameter = kinetics.getKineticsParameter(paramName);
                    if (kineticsParameter == null) {
                        // add unresolved for now to prevent errors in kinetics.setParameterValue(kp,vcRateExpression) below
                        kinetics.addUnresolvedParameter(paramName);
                    }
                }
                KineticsParameter kp = kinetics.getAuthoritativeParameter();
                if (lg.isDebugEnabled()) {
                    lg.debug("Setting " + kp.getName() + ":  " + vcRateExpression.infix());
                }
                kinetics.setParameterValue(kp, vcRateExpression);
                // If there are any global parameters used in the kinetics,
                // and if they have species,
                // check if the species are already reactionParticipants in
                // the reaction. If not, add them as catalysts.
                KineticsProxyParameter[] kpps = kinetics.getProxyParameters();
                for (int j = 0; j < kpps.length; j++) {
                    if (kpps[j].getTarget() instanceof ModelParameter) {
                        ModelParameter mp = (ModelParameter) kpps[j].getTarget();
                        HashSet<String> refSpeciesNameHash = new HashSet<String>();
                        getReferencedSpeciesInExpr(mp.getExpression(), refSpeciesNameHash);
                        java.util.Iterator<String> refSpIterator = refSpeciesNameHash.iterator();
                        while (refSpIterator.hasNext()) {
                            String spName = refSpIterator.next();
                            org.sbml.jsbml.Species sp = sbmlModel.getSpecies(spName);
                            ArrayList<ReactionParticipant> rpArray = getVCReactionParticipantsFromSymbol(vcReaction, sp.getId());
                            if (rpArray == null || rpArray.size() == 0) {
                                // This means that the speciesContext is not
                                // a reactant, product or modifier : it has
                                // to be added as a catalyst
                                vcReaction.addCatalyst(vcModel.getSpeciesContext(sp.getId()));
                            }
                        }
                    }
                }
                // model - local params cannot be defined by rules.
                for (LocalParameter param : localParameters) {
                    String paramName = param.getId();
                    Expression exp = new Expression(param.getValue());
                    String unitString = param.getUnits();
                    VCUnitDefinition paramUnit = sbmlUnitIdentifierHash.get(unitString);
                    if (paramUnit == null) {
                        paramUnit = vcModelUnitSystem.getInstance_TBD();
                    }
                    // check if sbml local param is in kinetic params list;
                    // if so, add its value.
                    boolean lpSet = false;
                    KineticsParameter kineticsParameter = kinetics.getKineticsParameter(paramName);
                    if (kineticsParameter != null) {
                        if (lg.isDebugEnabled()) {
                            lg.debug("Setting local " + kineticsParameter.getName() + ":  " + exp.infix());
                        }
                        kineticsParameter.setExpression(exp);
                        kineticsParameter.setUnitDefinition(paramUnit);
                        lpSet = true;
                    } else {
                        UnresolvedParameter ur = kinetics.getUnresolvedParameter(paramName);
                        if (ur != null) {
                            kinetics.addUserDefinedKineticsParameter(paramName, exp, paramUnit);
                            lpSet = true;
                        }
                    }
                    if (!lpSet) {
                        // check if it is a proxy parameter (specifically,
                        // speciesContext or model parameter (structureSize
                        // too)).
                        KineticsProxyParameter kpp = kinetics.getProxyParameter(paramName);
                        // and units to local param values
                        if (kpp != null && kpp.getTarget() instanceof ModelParameter) {
                            kinetics.convertParameterType(kpp, false);
                            kineticsParameter = kinetics.getKineticsParameter(paramName);
                            kinetics.setParameterValue(kineticsParameter, exp);
                            kineticsParameter.setUnitDefinition(paramUnit);
                        }
                    }
                }
            } else {
                // sbmlKLaw was null, so creating a GeneralKinetics with 0.0
                // as rate.
                kinetics = new GeneralKinetics(vcReaction);
            }
            // end - if-else KLaw != null
            // set the reaction kinetics, and add reaction to the vcell
            // model.
            kinetics.resolveUndefinedUnits();
            // System.out.println("ADDED SBML REACTION : \"" + rxnName +
            // "\" to VCModel");
            vcReactionList.add(vcReaction);
            if (sbmlRxn.isSetFast() && sbmlRxn.getFast()) {
                fastReactionList.add(vcReaction);
            }
        }
        // end - for vcReactions
        ReactionStep[] array = vcReactionList.toArray(new ReactionStep[vcReactionList.size()]);
        vcModel.setReactionSteps(array);
        final ReactionContext rc = vcBioModel.getSimulationContext(0).getReactionContext();
        for (ReactionStep frs : fastReactionList) {
            final ReactionSpec rs = rc.getReactionSpec(frs);
            rs.setReactionMapping(ReactionSpec.FAST);
        }
    } catch (ModelPropertyVetoException mpve) {
        throw new SBMLImportException(mpve.getMessage(), mpve);
    } catch (Exception e1) {
        e1.printStackTrace(System.out);
        throw new SBMLImportException(e1.getMessage(), e1);
    }
}
Also used : Issue(org.vcell.util.Issue) ArrayList(java.util.ArrayList) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) GeneralKinetics(cbit.vcell.model.GeneralKinetics) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ReactionContext(cbit.vcell.mapping.ReactionContext) HashSet(java.util.HashSet) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) ReactionSpec(cbit.vcell.mapping.ReactionSpec) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ModelParameter(cbit.vcell.model.Model.ModelParameter) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) ReactionStep(cbit.vcell.model.ReactionStep) Kinetics(cbit.vcell.model.Kinetics) GeneralKinetics(cbit.vcell.model.GeneralKinetics) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) KineticLaw(org.sbml.jsbml.KineticLaw) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Element(org.jdom.Element) UnresolvedParameter(cbit.vcell.model.Kinetics.UnresolvedParameter) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) ASTNode(org.sbml.jsbml.ASTNode) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SpatialReactionPlugin(org.sbml.jsbml.ext.spatial.SpatialReactionPlugin) SimpleReaction(cbit.vcell.model.SimpleReaction) Reaction(org.sbml.jsbml.Reaction) SimpleReaction(cbit.vcell.model.SimpleReaction) FluxReaction(cbit.vcell.model.FluxReaction) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) SBMLException(org.sbml.jsbml.SBMLException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) LocalParameter(org.sbml.jsbml.LocalParameter) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel)

Example 3 with Issue

use of org.vcell.util.Issue in project vcell by virtualcell.

the class SBMLImporter method getBioModel.

// /**
// * @ TODO: This method doesn't take care of adjusting species in nested
// parameter rules with the species_concetration_factor.
// * @param kinetics
// * @param paramExpr
// * @throws ExpressionException
// */
// private void substituteOtherGlobalParams(Kinetics kinetics, Expression
// paramExpr) throws ExpressionException, PropertyVetoException {
// String[] exprSymbols = paramExpr.getSymbols();
// if (exprSymbols == null || exprSymbols.length == 0) {
// return;
// }
// Model vcModel = vcBioModel.getSimulationContext(0).getModel();
// for (int kk = 0; kk < exprSymbols.length; kk++) {
// ModelParameter mp = vcModel.getModelParameter(exprSymbols[kk]);
// if (mp != null) {
// Expression expr = mp.getExpression();
// if (expr != null) {
// Expression newExpr = new Expression(expr);
// substituteGlobalParamRulesInPlace(newExpr, false);
// // param has constant value, add it as a kinetic parameter if it is not
// already in the kinetics
// kinetics.setParameterValue(exprSymbols[kk], newExpr.infix());
// kinetics.getKineticsParameter(exprSymbols[kk]).setUnitDefinition(getSBMLUnit(sbmlModel.getParameter(exprSymbols[kk]).getUnits(),
// null));
// if (newExpr.getSymbols() != null) {
// substituteOtherGlobalParams(kinetics, newExpr);
// }
// }
// }
// }
// }
/**
 * parse SBML file into biomodel logs errors to log4j if present in source
 * document
 *
 * @return new Biomodel
 * @throws IOException
 * @throws XMLStreamException
 */
public BioModel getBioModel() throws XMLStreamException, IOException {
    SBMLDocument document;
    String output = "didn't check";
    try {
        if (sbmlFileName != null) {
            // Read SBML model into libSBML SBMLDocument and create an SBML model
            SBMLReader reader = new SBMLReader();
            document = reader.readSBML(sbmlFileName);
            // document.checkConsistencyOffline();
            // long numProblems = document.getNumErrors();
            // 
            // System.out.println("\n\nSBML Import Error Report");
            // ByteArrayOutputStream os = new ByteArrayOutputStream();
            // PrintStream ps = new PrintStream(os);
            // document.printErrors(ps);
            // String output = os.toString();
            // if (numProblems > 0 && lg.isEnabledFor(Level.WARN)) {
            // lg.warn("Num problems in original SBML document : " + numProblems);
            // lg.warn(output);
            // }
            sbmlModel = document.getModel();
            if (sbmlModel == null) {
                throw new SBMLImportException("Unable to read SBML file : \n" + output);
            }
        } else {
            if (sbmlModel == null) {
                throw new IllegalStateException("Expected non-null SBML model");
            }
            document = sbmlModel.getSBMLDocument();
        }
        // Convert SBML Model to VCell model
        // An SBML model will correspond to a simcontext - which needs a
        // Model and a Geometry
        // SBML handles only nonspatial geometries at this time, hence
        // creating a non-spatial default geometry
        String modelName = sbmlModel.getId();
        if (modelName == null || modelName.trim().equals("")) {
            modelName = sbmlModel.getName();
        }
        // name, say 'newModel'
        if (modelName == null || modelName.trim().equals("")) {
            modelName = "newModel";
        }
        // get namespace based on SBML model level and version to use in
        // SBMLAnnotationUtil
        this.level = sbmlModel.getLevel();
        // this.version = sbmlModel.getVersion();
        String ns = document.getNamespace();
        try {
            // create SBML unit system for the model and create the bioModel.
            ModelUnitSystem modelUnitSystem;
            try {
                modelUnitSystem = createSBMLUnitSystemForVCModel();
            } catch (Exception e) {
                e.printStackTrace(System.out);
                throw new SBMLImportException("Inconsistent unit system. Cannot import SBML model into VCell", Category.INCONSISTENT_UNIT, e);
            }
            Geometry geometry = new Geometry(BioModelChildSummary.COMPARTMENTAL_GEO_STR, 0);
            vcBioModel = new BioModel(null, modelUnitSystem);
            SimulationContext simulationContext = new SimulationContext(vcBioModel.getModel(), geometry, null, null, Application.NETWORK_DETERMINISTIC);
            vcBioModel.addSimulationContext(simulationContext);
            simulationContext.setName(vcBioModel.getSimulationContext(0).getModel().getName());
        // vcBioModel.getSimulationContext(0).setName(vcBioModel.getSimulationContext(0).getModel().getName()+"_"+vcBioModel.getSimulationContext(0).getGeometry().getName());
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new SBMLImportException("Could not create simulation context corresponding to the input SBML model", e);
        }
        // SBML annotation
        sbmlAnnotationUtil = new SBMLAnnotationUtil(vcBioModel.getVCMetaData(), vcBioModel, ns);
        translateSBMLModel();
        try {
            // **** TEMPORARY BLOCK - to name the biomodel with proper name,
            // rather than model id
            String biomodelName = sbmlModel.getName();
            // if name is not set, use id
            if ((biomodelName == null) || biomodelName.trim().equals("")) {
                biomodelName = sbmlModel.getId();
            }
            // if id is not set, use a default, say, 'newModel'
            if ((biomodelName == null) || biomodelName.trim().equals("")) {
                biomodelName = "newBioModel";
            }
            vcBioModel.setName(biomodelName);
        // **** end - TEMPORARY BLOCK
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new SBMLImportException("Could not create Biomodel", e);
        }
        sbmlAnnotationUtil.readAnnotation(vcBioModel, sbmlModel);
        sbmlAnnotationUtil.readNotes(vcBioModel, sbmlModel);
        vcBioModel.refreshDependencies();
        Issue[] warningIssues = localIssueList.toArray(new Issue[localIssueList.size()]);
        if (warningIssues != null && warningIssues.length > 0) {
            StringBuffer messageBuffer = new StringBuffer("Issues encountered during SBML Import:\n");
            int issueCount = 0;
            for (int i = 0; i < warningIssues.length; i++) {
                if (warningIssues[i].getSeverity() == Issue.SEVERITY_WARNING || warningIssues[i].getSeverity() == Issue.SEVERITY_INFO) {
                    messageBuffer.append(warningIssues[i].getCategory() + " " + warningIssues[i].getSeverityName() + " : " + warningIssues[i].getMessage() + "\n");
                    issueCount++;
                }
            }
            if (issueCount > 0) {
                try {
                    logger.sendMessage(VCLogger.Priority.MediumPriority, VCLogger.ErrorType.OverallWarning, messageBuffer.toString());
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                }
            // PopupGenerator.showWarningDialog(requester,messageBuffer.toString(),new
            // String[] { "OK" }, "OK");
            }
        }
    } catch (Exception e) {
        throw new SBMLImportException("Unable to read SBML file : \n" + output, e);
    }
    return vcBioModel;
}
Also used : SBMLReader(org.sbml.jsbml.SBMLReader) Issue(org.vcell.util.Issue) SBMLDocument(org.sbml.jsbml.SBMLDocument) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) SBMLException(org.sbml.jsbml.SBMLException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) Geometry(cbit.vcell.geometry.Geometry) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) ParametricGeometry(org.sbml.jsbml.ext.spatial.ParametricGeometry) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) PropertyVetoException(java.beans.PropertyVetoException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) BioModel(cbit.vcell.biomodel.BioModel) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 4 with Issue

use of org.vcell.util.Issue in project vcell by virtualcell.

the class SBMLImporter method getSbmlGeometry.

/**
 * extract SBML geometry issue warning if not defined
 *
 * @return null if not defined
 * @throws IllegalArgumentException
 *             if plugin or geometry not found
 */
private org.sbml.jsbml.ext.spatial.Geometry getSbmlGeometry() {
    // Get a SpatialModelPlugin object plugged in the model object.
    // 
    // The type of the returned value of SBase::getPlugin() function is
    // SBasePlugin*, and thus the value needs to be cast for the
    // corresponding derived class.
    // 
    SpatialModelPlugin mplugin = (SpatialModelPlugin) sbmlModel.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
    if (mplugin == null) {
        throw new IllegalArgumentException("SpatialModelPlugin not found");
    }
    // get a Geometry object via SpatialModelPlugin object.
    org.sbml.jsbml.ext.spatial.Geometry geometry = mplugin.getGeometry();
    if (geometry == null) {
        throw new IllegalArgumentException("SBML Geometry not found");
    }
    if (geometry.getListOfGeometryDefinitions().size() < 1) {
        // (2/15/2013) For now, allow model to be imported even without
        // geometry defined. Issue a warning.
        localIssueList.add(new Issue(new SBMLIssueSource(sbmlModel), issueContext, IssueCategory.SBMLImport_UnsupportedAttributeOrElement, "Geometry not defined in spatial model.", Issue.SEVERITY_WARNING));
        return null;
    // throw new
    // RuntimeException("SBML model does not have any geometryDefinition. Cannot proceed with import.");
    }
    return geometry;
}
Also used : Issue(org.vcell.util.Issue) SpatialModelPlugin(org.sbml.jsbml.ext.spatial.SpatialModelPlugin)

Example 5 with Issue

use of org.vcell.util.Issue in project vcell by virtualcell.

the class DocumentValidUtil method checkIssuesForErrors.

public static void checkIssuesForErrors(Vector<Issue> issueList) {
    final int MaxCounter = 5;
    String errMsg = "Unable to perform operation. Errors found: \n\n";
    boolean bErrorFound = false;
    int counter = 0;
    for (int i = 0; i < issueList.size(); i++) {
        Issue issue = issueList.elementAt(i);
        if (issue.getSeverity() == Issue.Severity.ERROR) {
            bErrorFound = true;
            Object issueSource = issue.getSource();
            if (!(issueSource instanceof OutputFunctionIssueSource)) {
                if (counter >= MaxCounter) {
                    // We display MaxCounter error issues
                    errMsg += "\n...and more.\n";
                    break;
                }
                errMsg += issue.getMessage() + "\n";
                counter++;
            }
        }
    }
    for (int i = 0; i < issueList.size(); i++) {
        Issue issue = issueList.elementAt(i);
        if (issue.getSeverity() == Issue.Severity.ERROR) {
            bErrorFound = true;
            Object issueSource = issue.getSource();
            if (issueSource instanceof OutputFunctionIssueSource) {
                SimulationOwner simulationOwner = ((OutputFunctionIssueSource) issueSource).getOutputFunctionContext().getSimulationOwner();
                String funcName = ((OutputFunctionIssueSource) issueSource).getAnnotatedFunction().getDisplayName();
                if (simulationOwner instanceof SimulationContext) {
                    String opErrMsg = "Output Function '" + funcName + "' in application '" + simulationOwner.getName() + "' ";
                    if (issue.getCategory().equals(IssueCategory.OUTPUTFUNCTIONCONTEXT_FUNCTION_EXPBINDING)) {
                        opErrMsg += "refers to an unknown variable. Either the model changed or this version of VCell generates variable names differently.\n";
                    }
                    errMsg += opErrMsg;
                }
                errMsg += issue.getMessage() + "\n";
                // we display no more than 1 issue of this type because it may get very verbose
                break;
            }
        }
    }
    if (bErrorFound) {
        errMsg += "\n See the Problems panel for a full list of errors and detailed error information.";
        throw new RuntimeException(errMsg);
    }
}
Also used : SimulationOwner(cbit.vcell.solver.SimulationOwner) Issue(org.vcell.util.Issue) OutputFunctionIssueSource(cbit.vcell.solver.OutputFunctionContext.OutputFunctionIssueSource) SimulationContext(cbit.vcell.mapping.SimulationContext)

Aggregations

Issue (org.vcell.util.Issue)88 ArrayList (java.util.ArrayList)18 IssueContext (org.vcell.util.IssueContext)14 Expression (cbit.vcell.parser.Expression)13 ExpressionException (cbit.vcell.parser.ExpressionException)13 PropertyVetoException (java.beans.PropertyVetoException)9 MolecularType (org.vcell.model.rbm.MolecularType)9 Structure (cbit.vcell.model.Structure)8 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)8 SymbolTableEntry (cbit.vcell.parser.SymbolTableEntry)7 MolecularComponentPattern (org.vcell.model.rbm.MolecularComponentPattern)7 Model (cbit.vcell.model.Model)6 ModelParameter (cbit.vcell.model.Model.ModelParameter)6 ExpressionBindingException (cbit.vcell.parser.ExpressionBindingException)6 BioModel (cbit.vcell.biomodel.BioModel)5 ModelException (cbit.vcell.model.ModelException)5 Product (cbit.vcell.model.Product)5 Reactant (cbit.vcell.model.Reactant)5 ReactionParticipant (cbit.vcell.model.ReactionParticipant)5 InteriorPoint (org.sbml.jsbml.ext.spatial.InteriorPoint)5