Search in sources :

Example 1 with SBMLReader

use of org.sbml.jsbml.SBMLReader 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 2 with SBMLReader

use of org.sbml.jsbml.SBMLReader in project vcell by virtualcell.

the class ProjectService method load.

public Task<Project, String> load(File root) {
    final Task<Project, String> task = new Task<Project, String>() {

        @Override
        protected Project doInBackground() throws Exception {
            Project project = new Project(root.getName());
            String rootPath = root.getAbsolutePath();
            File[] dataFiles = Paths.get(rootPath, "data").toFile().listFiles();
            File[] geometryFiles = Paths.get(rootPath, "geometry").toFile().listFiles();
            File[] modelDirectories = Paths.get(rootPath, "models").toFile().listFiles();
            File[] resultsFiles = Paths.get(rootPath, "results").toFile().listFiles();
            int numFiles = dataFiles.length + geometryFiles.length + modelDirectories.length + resultsFiles.length;
            int numLoaded = 0;
            if (dataFiles != null) {
                for (File dataFile : dataFiles) {
                    try {
                        setSubtask(dataFile.getName());
                        Dataset data = datasetIOService.open(dataFile.getAbsolutePath());
                        project.getData().add(data);
                        numLoaded++;
                        setProgress(numLoaded * 100 / numFiles);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (geometryFiles != null) {
                for (File geometryFile : geometryFiles) {
                    try {
                        setSubtask(geometryFile.getName());
                        Dataset geometry = datasetIOService.open(geometryFile.getAbsolutePath());
                        // Geometry datasets are saved as 8-bit images so we must convert back to 1-bit
                        if (geometry.firstElement() instanceof UnsignedByteType) {
                            @SuppressWarnings("unchecked") Img<UnsignedByteType> img = (Img<UnsignedByteType>) geometry.getImgPlus().getImg();
                            Img<BitType> converted = opService.convert().bit(img);
                            ImgPlus<BitType> convertedImgPlus = new ImgPlus<>(converted, geometry.getName());
                            geometry.setImgPlus(convertedImgPlus);
                        }
                        project.getGeometry().add(geometry);
                        numLoaded++;
                        setProgress(numLoaded * 100 / numFiles);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (modelDirectories != null) {
                for (File modelDirectory : modelDirectories) {
                    setSubtask(modelDirectory.getName());
                    SBMLDocument sbmlDocument = null;
                    BufferedImage image = null;
                    File[] modelFiles = modelDirectory.listFiles();
                    System.out.println(modelFiles.length);
                    // Invalid model directory
                    if (modelFiles.length > 2)
                        continue;
                    for (File modelFile : modelFiles) {
                        System.out.println(modelFile.getName());
                        if (FilenameUtils.getExtension(modelFile.getName()).equals("xml")) {
                            sbmlDocument = new SBMLReader().readSBML(modelFile);
                            System.out.println("Loaded sbml");
                        } else if (FilenameUtils.getExtension(modelFile.getName()).equals("png")) {
                            image = ImageIO.read(modelFile);
                            System.out.println("Loaded image");
                        }
                    }
                    if (sbmlDocument != null) {
                        VCellModel vCellModel = new VCellModel(modelDirectory.getName(), null, sbmlDocument);
                        vCellModel.setImage(image);
                        project.getModels().add(vCellModel);
                        System.out.println("Added model");
                    }
                    numLoaded++;
                    setProgress(numLoaded * 100 / numFiles);
                }
            }
            if (resultsFiles != null) {
                for (File resultsFile : resultsFiles) {
                    try {
                        setSubtask(resultsFile.getName());
                        Dataset results = datasetIOService.open(resultsFile.getAbsolutePath());
                        // Loading 1-dimensional tif images adds a dimension
                        // so must crop out empty dimensions
                        @SuppressWarnings("unchecked") ImgPlus<T> imgPlus = (ImgPlus<T>) results.getImgPlus();
                        int numDimensions = imgPlus.numDimensions();
                        long[] dimensions = new long[2 * imgPlus.numDimensions()];
                        for (int i = 0; i < numDimensions; i++) {
                            dimensions[i] = 0;
                            dimensions[i + numDimensions] = imgPlus.dimension(i) - 1;
                        }
                        FinalInterval interval = Intervals.createMinMax(dimensions);
                        ImgPlus<T> cropped = opService.transform().crop(imgPlus, interval, true);
                        results.setImgPlus(cropped);
                        project.getResults().add(results);
                        numLoaded++;
                        setProgress(numLoaded * 100 / numFiles);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            currentProjectRoot = root;
            return project;
        }
    };
    return task;
}
Also used : Task(org.vcell.imagej.common.gui.Task) SBMLDocument(org.sbml.jsbml.SBMLDocument) UnsignedByteType(net.imglib2.type.numeric.integer.UnsignedByteType) BufferedImage(java.awt.image.BufferedImage) BitType(net.imglib2.type.logic.BitType) Img(net.imglib2.img.Img) SBMLReader(org.sbml.jsbml.SBMLReader) ImgPlus(net.imagej.ImgPlus) Dataset(net.imagej.Dataset) IOException(java.io.IOException) VCellModel(org.vcell.imagej.common.vcell.VCellModel) FinalInterval(net.imglib2.FinalInterval) File(java.io.File)

Aggregations

IOException (java.io.IOException)2 SBMLDocument (org.sbml.jsbml.SBMLDocument)2 SBMLReader (org.sbml.jsbml.SBMLReader)2 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 ExpressionException (cbit.vcell.parser.ExpressionException)1 BufferedImage (java.awt.image.BufferedImage)1 PropertyVetoException (java.beans.PropertyVetoException)1 File (java.io.File)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 Dataset (net.imagej.Dataset)1 ImgPlus (net.imagej.ImgPlus)1 FinalInterval (net.imglib2.FinalInterval)1 Img (net.imglib2.img.Img)1 BitType (net.imglib2.type.logic.BitType)1 UnsignedByteType (net.imglib2.type.numeric.integer.UnsignedByteType)1 SBMLException (org.sbml.jsbml.SBMLException)1