Search in sources :

Example 1 with CompFlatteningConverter

use of org.sbml.jsbml.ext.comp.util.CompFlatteningConverter 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 {
    if (sbmlFileName == null && sbmlModel == null) {
        throw new IllegalStateException("Expected non-null SBML model");
    }
    SBMLDocument document;
    String defaultErrorPrefix = "Unable to read SBML file";
    if (sbmlFileName != null) {
        try {
            // Read SBML model into libSBML SBMLDocument and create an SBML model
            List<String> readLines = FileUtils.readLines(new File(sbmlFileName), Charset.defaultCharset());
            StringBuffer sb = new StringBuffer();
            // throws NPE when "<sbml ... xmlns:render... " is defined in input document
            for (String line : readLines) {
                String str = "xmlns:render=\"http://www.sbml.org/sbml/level3/version1/render/version1\"";
                int indexOf = line.indexOf(str);
                if (indexOf != -1) {
                    line = line.substring(0, indexOf - 1) + line.substring(indexOf + str.length());
                }
                str = "render:required=\"false\"";
                indexOf = line.indexOf(str);
                if (indexOf != -1) {
                    line = line.substring(0, indexOf - 1) + line.substring(indexOf + str.length());
                }
                sb.append(line + "\n");
            }
            SBMLReader reader = new SBMLReader();
            document = reader.readSBMLFromString(sb.toString());
            // check for VCell origin
            String topNotes = document.getNotesString();
            if (topNotes != null && topNotes.contains("VCell")) {
                isFromVCell = true;
            }
            // 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();
        } catch (Exception e) {
            throw new SBMLImportException(defaultErrorPrefix + ": \n" + sbmlFileName, e);
        }
        if (sbmlModel == null) {
            throw new SBMLImportException(defaultErrorPrefix + ": \n" + sbmlFileName);
        }
    } else {
        // sbmlModel != null
        try {
            document = sbmlModel.getSBMLDocument();
        } catch (Exception e) {
            throw new SBMLImportException(defaultErrorPrefix + ".\n", e);
        }
    }
    if (document == null) {
        throw new SBMLImportException(defaultErrorPrefix + ".\n");
    }
    int numPackages = 0;
    String msgPackages = "";
    try {
        boolean b = document.getPackageRequired("comp");
        if (document.isPackageEnabled("comp")) {
            numPackages++;
            msgPackages += "'comp', ";
            CompSBMLDocumentPlugin cdp = null;
            CompModelPlugin cmp = null;
            CompSBasePlugin csp = null;
            CompFlatteningConverter ccc = null;
        }
        if (document.isPackageEnabled("fbc")) {
            numPackages++;
            msgPackages += "'fbc', ";
        }
        if (document.isPackageEnabled("multi")) {
            numPackages++;
            msgPackages += "'multi', ";
        }
        if (document.isPackageEnabled("qual")) {
            numPackages++;
            msgPackages += "'qual', ";
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Unable to check the SBML file package requirements.");
    }
    String ext = "extension";
    String is = "is";
    String has = "has";
    if (numPackages > 0) {
        if (numPackages > 1) {
            ext += "s";
            is = "are";
        }
        msgPackages = msgPackages.substring(0, msgPackages.length() - 1);
        msgPackages = "The model includes elements of SBML " + ext + " " + msgPackages + " which " + is + " required for simulating the model but " + is + " not supported.";
        throw new SBMLImportException("Unable to import the SBML file.\n" + msgPackages);
    }
    try {
        if (document.isPackageEnabled("groups")) {
            numPackages++;
            msgPackages += "'groups', ";
        }
        if (document.isPackageEnabled("layout")) {
            numPackages++;
            msgPackages += "'layout', ";
        }
        if (document.isPackageEnabled("render")) {
            numPackages++;
            msgPackages += "'render', ";
        }
    } catch (Exception e) {
        // we're going to ignore these packages anyway
        e.printStackTrace(System.out);
    }
    if (numPackages > 0) {
        if (numPackages > 1) {
            ext += "s";
            is = "are";
            has = "have";
        }
        msgPackages = "The model includes elements of SBML " + ext + " " + msgPackages + " which " + is + " not required for simulating the model and " + has + " been ignored.";
        localIssueList.add(new Issue(vcBioModel, issueContext, IssueCategory.SBMLImport_UnsupportedFeature, msgPackages, Issue.Severity.WARNING));
    }
    // 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
    // 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();
    // 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);
    }
    try {
        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 (Exception e) {
        // PropertyVetoException
        e.printStackTrace(System.out);
        throw new SBMLImportException("Could not create simulation context corresponding to the input SBML model.\n", e);
    }
    try {
        String biomodelName = sbmlModel.getName();
        if ((biomodelName == null) || biomodelName.trim().equals("")) {
            biomodelName = sbmlModel.getId();
        }
        if ((biomodelName == null) || biomodelName.trim().equals("")) {
            biomodelName = "newBioModel";
        }
        vcBioModel.setName(biomodelName);
        sbmlAnnotationUtil = new SBMLAnnotationUtil(vcBioModel.getVCMetaData(), vcBioModel, ns);
        sbmlAnnotationUtil.readAnnotation(vcBioModel, sbmlModel);
        sbmlAnnotationUtil.readNotes(vcBioModel, sbmlModel);
        // vcBioModel.getVCMetaData().printRdfPretty();
        // vcBioModel.getVCMetaData().printRdfStatements();
        translateSBMLModel();
        vcBioModel.refreshDependencies();
        ReactionStep[] reax = vcBioModel.getModel().getReactionSteps();
        for (int i = 0; i < reax.length; i++) {
            if (reax[i].getKinetics().getKineticsDescription().isLumped()) {
                DistributedKinetics.toDistributedKinetics((LumpedKinetics) reax[i].getKinetics());
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Could not create Biomodel corresponding to the input SBML model.\n", e);
    }
    Issue[] warnings = localIssueList.toArray(new Issue[localIssueList.size()]);
    if (warnings != null && warnings.length > 0) {
        StringBuffer messageBuffer = new StringBuffer("Issues encountered during SBML Import:\n");
        int issueCount = 0;
        for (int i = 0; i < warnings.length; i++) {
            if (warnings[i].getSeverity() == Issue.Severity.WARNING || warnings[i].getSeverity() == Issue.Severity.INFO) {
                // messageBuffer.append("- " + warnings[i].getMessage() + " (" + warnings[i].getCategory() + ", " + warnings[i].getSeverity().name() + ")\n");
                messageBuffer.append("- " + warnings[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);
            }
        }
    }
    // if called from GUI application convert if VCell origin, otherwise ask user
    if (isFromVCell) {
        ModelUnitSystem vcUnitSystem = ModelUnitSystem.createDefaultVCModelUnitSystem();
        try {
            BioModel convertedBioModel = ModelUnitConverter.createBioModelWithNewUnitSystem(vcBioModel, vcUnitSystem);
            return convertedBioModel;
        } catch (ExpressionException | XmlParseException e) {
            // TODO maybe alert user? for now fail silently...
            e.printStackTrace();
            return vcBioModel;
        }
    }
    return vcBioModel;
}
Also used : Issue(org.vcell.util.Issue) SBMLDocument(org.sbml.jsbml.SBMLDocument) CompFlatteningConverter(org.sbml.jsbml.ext.comp.util.CompFlatteningConverter) ExpressionException(cbit.vcell.parser.ExpressionException) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SBMLReader(org.sbml.jsbml.SBMLReader) XmlParseException(cbit.vcell.xml.XmlParseException) SimulationContext(cbit.vcell.mapping.SimulationContext) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) 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) BioModel(cbit.vcell.biomodel.BioModel) ReactionStep(cbit.vcell.model.ReactionStep) File(java.io.File)

Aggregations

BioModel (cbit.vcell.biomodel.BioModel)1 Geometry (cbit.vcell.geometry.Geometry)1 SimulationContext (cbit.vcell.mapping.SimulationContext)1 ModelPropertyVetoException (cbit.vcell.model.ModelPropertyVetoException)1 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)1 ReactionStep (cbit.vcell.model.ReactionStep)1 DivideByZeroException (cbit.vcell.parser.DivideByZeroException)1 ExpressionBindingException (cbit.vcell.parser.ExpressionBindingException)1 ExpressionException (cbit.vcell.parser.ExpressionException)1 XmlParseException (cbit.vcell.xml.XmlParseException)1 PropertyVetoException (java.beans.PropertyVetoException)1 File (java.io.File)1 IOException (java.io.IOException)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 SBMLDocument (org.sbml.jsbml.SBMLDocument)1 SBMLException (org.sbml.jsbml.SBMLException)1 SBMLReader (org.sbml.jsbml.SBMLReader)1 CompFlatteningConverter (org.sbml.jsbml.ext.comp.util.CompFlatteningConverter)1 AnalyticGeometry (org.sbml.jsbml.ext.spatial.AnalyticGeometry)1 CSGeometry (org.sbml.jsbml.ext.spatial.CSGeometry)1