Search in sources :

Example 6 with UnitDefinition

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

the class SBMLExporter method addGeometry.

private void addGeometry() throws SbmlException {
    SpatialModelPlugin mplugin = (SpatialModelPlugin) sbmlModel.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
    // Creates a geometry object via SpatialModelPlugin object.
    org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = mplugin.createGeometry();
    sbmlGeometry.setCoordinateSystem(GeometryKind.cartesian);
    sbmlGeometry.setSpatialId("vcell");
    Geometry vcGeometry = getSelectedSimContext().getGeometry();
    Model vcModel = getSelectedSimContext().getModel();
    // 
    // list of CoordinateComponents : 1 if geometry is 1-d, 2 if geometry is 2-d, 3 if geometry is 3-d
    // 
    int dimension = vcGeometry.getDimension();
    Extent vcExtent = vcGeometry.getExtent();
    Origin vcOrigin = vcGeometry.getOrigin();
    // add x coordinate component
    CoordinateComponent xComp = sbmlGeometry.createCoordinateComponent();
    xComp.setSpatialId(vcModel.getX().getName());
    xComp.setType(CoordinateKind.cartesianX);
    final UnitDefinition sbmlUnitDef_length = getOrCreateSBMLUnit(vcModel.getUnitSystem().getLengthUnit());
    xComp.setUnits(sbmlUnitDef_length);
    Boundary minX = new Boundary();
    xComp.setBoundaryMinimum(minX);
    minX.setSpatialId("Xmin");
    minX.setValue(vcOrigin.getX());
    Boundary maxX = new Boundary();
    xComp.setBoundaryMaximum(maxX);
    maxX.setSpatialId("Xmax");
    maxX.setValue(vcOrigin.getX() + (vcExtent.getX()));
    org.sbml.jsbml.Parameter pX = sbmlModel.createParameter();
    pX.setId(vcModel.getX().getName());
    pX.setValue(0.0);
    pX.setConstant(false);
    pX.setUnits(sbmlUnitDef_length);
    SpatialParameterPlugin spPluginPx = (SpatialParameterPlugin) pX.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
    SpatialSymbolReference spSymRefPx = new SpatialSymbolReference();
    spPluginPx.setParamType(spSymRefPx);
    spSymRefPx.setSpatialRef(xComp.getSpatialId());
    // add y coordinate component
    if (dimension == 2 || dimension == 3) {
        CoordinateComponent yComp = sbmlGeometry.createCoordinateComponent();
        yComp.setSpatialId(vcModel.getY().getName());
        yComp.setType(CoordinateKind.cartesianY);
        yComp.setUnits(sbmlUnitDef_length);
        Boundary minY = new Boundary();
        yComp.setBoundaryMinimum(minY);
        minY.setSpatialId("Ymin");
        minY.setValue(vcOrigin.getY());
        Boundary maxY = new Boundary();
        yComp.setBoundaryMaximum(maxY);
        maxY.setSpatialId("Ymax");
        maxY.setValue(vcOrigin.getY() + (vcExtent.getY()));
        org.sbml.jsbml.Parameter pY = sbmlModel.createParameter();
        pY.setId(vcModel.getY().getName());
        pY.setValue(0.0);
        pY.setConstant(false);
        pY.setUnits(sbmlUnitDef_length);
        SpatialParameterPlugin spPluginPy = (SpatialParameterPlugin) pY.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
        SpatialSymbolReference spSymRefPy = new SpatialSymbolReference();
        spPluginPy.setParamType(spSymRefPy);
        spSymRefPy.setSpatialRef(yComp.getSpatialId());
    }
    // add z coordinate component
    if (dimension == 3) {
        CoordinateComponent zComp = sbmlGeometry.createCoordinateComponent();
        zComp.setSpatialId(vcModel.getZ().getName());
        zComp.setType(CoordinateKind.cartesianZ);
        zComp.setUnits(sbmlUnitDef_length);
        Boundary minZ = new Boundary();
        zComp.setBoundaryMinimum(minZ);
        minZ.setSpatialId("Zmin");
        minZ.setValue(vcOrigin.getZ());
        Boundary maxZ = new Boundary();
        zComp.setBoundaryMaximum(maxZ);
        maxZ.setSpatialId("Zmax");
        maxZ.setValue(vcOrigin.getZ() + (vcExtent.getZ()));
        org.sbml.jsbml.Parameter pZ = sbmlModel.createParameter();
        pZ.setId(vcModel.getZ().getName());
        pZ.setValue(0.0);
        pZ.setConstant(false);
        pZ.setUnits(sbmlUnitDef_length);
        SpatialParameterPlugin spPluginPz = (SpatialParameterPlugin) pZ.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
        SpatialSymbolReference spSymRefPz = new SpatialSymbolReference();
        spPluginPz.setParamType(spSymRefPz);
        spSymRefPz.setSpatialRef(zComp.getSpatialId());
    }
    // 
    // list of compartmentMappings : VC structureMappings
    // 
    GeometryContext vcGeoContext = getSelectedSimContext().getGeometryContext();
    StructureMapping[] vcStrucMappings = vcGeoContext.getStructureMappings();
    for (int i = 0; i < vcStrucMappings.length; i++) {
        StructureMapping vcStructMapping = vcStrucMappings[i];
        String structName = vcStructMapping.getStructure().getName();
        Compartment comp = sbmlModel.getCompartment(TokenMangler.mangleToSName(structName));
        SpatialCompartmentPlugin cplugin = (SpatialCompartmentPlugin) comp.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
        GeometryClass gc = vcStructMapping.getGeometryClass();
        if (!goodPointer(gc, GeometryClass.class, structName)) {
            continue;
        }
        CompartmentMapping compMapping = new CompartmentMapping();
        cplugin.setCompartmentMapping(compMapping);
        String geomClassName = gc.getName();
        String id = TokenMangler.mangleToSName(geomClassName + structName);
        compMapping.setSpatialId(id);
        compMapping.setDomainType(TokenMangler.mangleToSName(DOMAIN_TYPE_PREFIX + geomClassName));
        try {
            StructureMappingParameter usp = vcStructMapping.getUnitSizeParameter();
            Expression e = usp.getExpression();
            if (goodPointer(e, Expression.class, id)) {
                compMapping.setUnitSize(e.evaluateConstant());
            }
        } catch (ExpressionException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Unable to create compartment mapping for structureMapping '" + compMapping.getId() + "' : " + e.getMessage());
        }
    }
    // 
    // list of domain types : subvolumes and surface classes from VC
    // 
    boolean bAnyAnalyticSubvolumes = false;
    boolean bAnyImageSubvolumes = false;
    boolean bAnyCSGSubvolumes = false;
    GeometryClass[] vcGeomClasses = vcGeometry.getGeometryClasses();
    int numSubVols = 0;
    for (int i = 0; i < vcGeomClasses.length; i++) {
        DomainType domainType = sbmlGeometry.createDomainType();
        domainType.setSpatialId(DOMAIN_TYPE_PREFIX + vcGeomClasses[i].getName());
        if (vcGeomClasses[i] instanceof SubVolume) {
            if (((SubVolume) vcGeomClasses[i]) instanceof AnalyticSubVolume) {
                bAnyAnalyticSubvolumes = true;
            } else if (((SubVolume) vcGeomClasses[i]) instanceof ImageSubVolume) {
                bAnyImageSubvolumes = true;
            } else if (((SubVolume) vcGeomClasses[i]) instanceof CSGObject) {
                bAnyCSGSubvolumes = true;
            }
            domainType.setSpatialDimensions(3);
            numSubVols++;
        } else if (vcGeomClasses[i] instanceof SurfaceClass) {
            domainType.setSpatialDimensions(2);
        }
    }
    // 
    // list of domains, adjacent domains : from VC geometricRegions
    // 
    GeometrySurfaceDescription vcGSD = vcGeometry.getGeometrySurfaceDescription();
    if (vcGSD.getRegionImage() == null) {
        try {
            vcGSD.updateAll();
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Unable to generate region images for geometry");
        }
    }
    GeometricRegion[] vcGeometricRegions = vcGSD.getGeometricRegions();
    ISize sampleSize = vcGSD.getVolumeSampleSize();
    int numX = sampleSize.getX();
    int numY = sampleSize.getY();
    int numZ = sampleSize.getZ();
    double ox = vcOrigin.getX();
    double oy = vcOrigin.getY();
    double oz = vcOrigin.getZ();
    RegionInfo[] regionInfos = vcGSD.getRegionImage().getRegionInfos();
    for (int i = 0; i < vcGeometricRegions.length; i++) {
        // domains
        Domain domain = sbmlGeometry.createDomain();
        domain.setSpatialId(vcGeometricRegions[i].getName());
        if (vcGeometricRegions[i] instanceof VolumeGeometricRegion) {
            domain.setDomainType(DOMAIN_TYPE_PREFIX + ((VolumeGeometricRegion) vcGeometricRegions[i]).getSubVolume().getName());
            // 
            // get a list of interior points ... should probably use the distance map to find a point
            // furthest inside (or several points associated with the morphological skeleton).
            // 
            InteriorPoint interiorPt = domain.createInteriorPoint();
            int regionID = ((VolumeGeometricRegion) vcGeometricRegions[i]).getRegionID();
            boolean bFound = false;
            int regInfoIndx = 0;
            for (int j = 0; j < regionInfos.length; j++) {
                regInfoIndx = j;
                if (regionInfos[j].getRegionIndex() == regionID) {
                    int volIndx = 0;
                    for (int z = 0; z < numZ && !bFound; z++) {
                        for (int y = 0; y < numY && !bFound; y++) {
                            for (int x = 0; x < numX && !bFound; x++) {
                                if (regionInfos[j].isIndexInRegion(volIndx)) {
                                    bFound = true;
                                    double unit_z = (numZ > 1) ? ((double) z) / (numZ - 1) : 0.5;
                                    double coordZ = oz + vcExtent.getZ() * unit_z;
                                    double unit_y = (numY > 1) ? ((double) y) / (numY - 1) : 0.5;
                                    double coordY = oy + vcExtent.getY() * unit_y;
                                    double unit_x = (numX > 1) ? ((double) x) / (numX - 1) : 0.5;
                                    double coordX = ox + vcExtent.getX() * unit_x;
                                    interiorPt.setCoord1(coordX);
                                    interiorPt.setCoord2(coordY);
                                    interiorPt.setCoord3(coordZ);
                                }
                                volIndx++;
                            }
                        // end - for x
                        }
                    // end - for y
                    }
                // end - for z
                }
            // end if
            }
            // end for regionInfos
            if (!bFound) {
                throw new RuntimeException("Unable to find interior point for region '" + regionInfos[regInfoIndx].toString());
            }
        } else if (vcGeometricRegions[i] instanceof SurfaceGeometricRegion) {
            SurfaceGeometricRegion vcSurfaceGeomReg = (SurfaceGeometricRegion) vcGeometricRegions[i];
            GeometricRegion geomRegion0 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[0];
            GeometricRegion geomRegion1 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[1];
            SurfaceClass surfaceClass = vcGSD.getSurfaceClass(((VolumeGeometricRegion) geomRegion0).getSubVolume(), ((VolumeGeometricRegion) geomRegion1).getSubVolume());
            domain.setDomainType(DOMAIN_TYPE_PREFIX + surfaceClass.getName());
            // adjacent domains : 2 adjacent domain objects for each surfaceClass in VC.
            // adjacent domain 1
            GeometricRegion adjGeomRegion0 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[0];
            GeometricRegion adjGeomRegion1 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[1];
            AdjacentDomains adjDomain = new AdjacentDomains();
            adjDomain.setSpatialId(TokenMangler.mangleToSName(vcSurfaceGeomReg.getName() + "_" + adjGeomRegion0.getName()));
            adjDomain.setDomain1(vcSurfaceGeomReg.getName());
            adjDomain.setDomain2(adjGeomRegion0.getName());
            sbmlGeometry.addAdjacentDomain(adjDomain);
            // adj domain 2
            adjDomain = new AdjacentDomains();
            adjDomain.setSpatialId(TokenMangler.mangleToSName(vcSurfaceGeomReg.getName() + "_" + adjGeomRegion1.getName()));
            adjDomain.setDomain1(vcSurfaceGeomReg.getName());
            adjDomain.setDomain2(adjGeomRegion1.getName());
            sbmlGeometry.addAdjacentDomain(adjDomain);
        }
    }
    // 
    if (bAnyAnalyticSubvolumes && !bAnyImageSubvolumes && !bAnyCSGSubvolumes) {
        AnalyticGeometry sbmlAnalyticGeomDefinition = sbmlGeometry.createAnalyticGeometry();
        sbmlAnalyticGeomDefinition.setSpatialId(TokenMangler.mangleToSName("Analytic_" + vcGeometry.getName()));
        sbmlAnalyticGeomDefinition.setIsActive(true);
        for (int i = 0; i < vcGeomClasses.length; i++) {
            if (vcGeomClasses[i] instanceof AnalyticSubVolume) {
                AnalyticVolume analyticVol = sbmlAnalyticGeomDefinition.createAnalyticVolume();
                analyticVol.setSpatialId(vcGeomClasses[i].getName());
                analyticVol.setDomainType(DOMAIN_TYPE_PREFIX + vcGeomClasses[i].getName());
                analyticVol.setFunctionType(FunctionKind.layered);
                analyticVol.setOrdinal(numSubVols - (i + 1));
                Expression expr = ((AnalyticSubVolume) vcGeomClasses[i]).getExpression();
                try {
                    String mathMLStr = ExpressionMathMLPrinter.getMathML(expr, true, MathType.BOOLEAN);
                    ASTNode mathMLNode = ASTNode.readMathMLFromString(mathMLStr);
                    analyticVol.setMath(mathMLNode);
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Error converting VC subvolume expression to mathML" + e.getMessage());
                }
            }
        }
    }
    // 
    if (!bAnyAnalyticSubvolumes && !bAnyImageSubvolumes && bAnyCSGSubvolumes) {
        CSGeometry sbmlCSGeomDefinition = new CSGeometry();
        sbmlGeometry.addGeometryDefinition(sbmlCSGeomDefinition);
        sbmlCSGeomDefinition.setSpatialId(TokenMangler.mangleToSName("CSG_" + vcGeometry.getName()));
        for (int i = 0; i < vcGeomClasses.length; i++) {
            if (vcGeomClasses[i] instanceof CSGObject) {
                CSGObject vcellCSGObject = (CSGObject) vcGeomClasses[i];
                org.sbml.jsbml.ext.spatial.CSGObject sbmlCSGObject = new org.sbml.jsbml.ext.spatial.CSGObject();
                sbmlCSGeomDefinition.addCSGObject(sbmlCSGObject);
                sbmlCSGObject.setSpatialId(vcellCSGObject.getName());
                sbmlCSGObject.setDomainType(DOMAIN_TYPE_PREFIX + vcellCSGObject.getName());
                // the ordinal should the the least for the default/background subVolume
                sbmlCSGObject.setOrdinal(numSubVols - (i + 1));
                org.sbml.jsbml.ext.spatial.CSGNode sbmlcsgNode = getSBMLCSGNode(vcellCSGObject.getRoot());
                sbmlCSGObject.setCSGNode(sbmlcsgNode);
            }
        }
    }
    // 
    // add "Segmented" and "DistanceMap" SampledField Geometries
    // 
    final boolean bVCGeometryIsImage = bAnyImageSubvolumes && !bAnyAnalyticSubvolumes && !bAnyCSGSubvolumes;
    // 55if (bAnyAnalyticSubvolumes || bAnyImageSubvolumes || bAnyCSGSubvolumes){
    if (bVCGeometryIsImage) {
        // 
        // add "Segmented" SampledFieldGeometry
        // 
        SampledFieldGeometry segmentedImageSampledFieldGeometry = sbmlGeometry.createSampledFieldGeometry();
        segmentedImageSampledFieldGeometry.setSpatialId(TokenMangler.mangleToSName("SegmentedImage_" + vcGeometry.getName()));
        segmentedImageSampledFieldGeometry.setIsActive(true);
        // 55boolean bVCGeometryIsImage = bAnyImageSubvolumes && !bAnyAnalyticSubvolumes && !bAnyCSGSubvolumes;
        Geometry vcImageGeometry = null;
        {
            if (bVCGeometryIsImage) {
                // make a resampled image;
                if (dimension == 3) {
                    try {
                        ISize imageSize = vcGeometry.getGeometrySpec().getDefaultSampledImageSize();
                        vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
                        vcImageGeometry = RayCaster.resampleGeometry(new GeometryThumbnailImageFactoryAWT(), vcGeometry, imageSize);
                    } catch (Throwable e) {
                        e.printStackTrace(System.out);
                        throw new RuntimeException("Unable to convert the original analytic or constructed solid geometry to image-based geometry : " + e.getMessage());
                    }
                } else {
                    try {
                        vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, false);
                        GeometrySpec origGeometrySpec = vcGeometry.getGeometrySpec();
                        VCImage newVCImage = origGeometrySpec.getSampledImage().getCurrentValue();
                        // 
                        // construct the new geometry with the sampled VCImage.
                        // 
                        vcImageGeometry = new Geometry(vcGeometry.getName() + "_asImage", newVCImage);
                        vcImageGeometry.getGeometrySpec().setExtent(vcGeometry.getExtent());
                        vcImageGeometry.getGeometrySpec().setOrigin(vcGeometry.getOrigin());
                        vcImageGeometry.setDescription(vcGeometry.getDescription());
                        vcImageGeometry.getGeometrySurfaceDescription().setFilterCutoffFrequency(vcGeometry.getGeometrySurfaceDescription().getFilterCutoffFrequency());
                        vcImageGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, true);
                    } catch (Exception e) {
                        e.printStackTrace(System.out);
                        throw new RuntimeException("Unable to convert the original analytic or constructed solid geometry to image-based geometry : " + e.getMessage());
                    }
                }
                GeometryClass[] vcImageGeomClasses = vcImageGeometry.getGeometryClasses();
                for (int j = 0; j < vcImageGeomClasses.length; j++) {
                    if (vcImageGeomClasses[j] instanceof ImageSubVolume) {
                        SampledVolume sampledVol = segmentedImageSampledFieldGeometry.createSampledVolume();
                        sampledVol.setSpatialId(vcGeomClasses[j].getName());
                        sampledVol.setDomainType(DOMAIN_TYPE_PREFIX + vcGeomClasses[j].getName());
                        sampledVol.setSampledValue(((ImageSubVolume) vcImageGeomClasses[j]).getPixelValue());
                    }
                }
                // add sampledField to sampledFieldGeometry
                SampledField segmentedImageSampledField = sbmlGeometry.createSampledField();
                VCImage vcImage = vcImageGeometry.getGeometrySpec().getImage();
                segmentedImageSampledField.setSpatialId("SegmentedImageSampledField");
                segmentedImageSampledField.setNumSamples1(vcImage.getNumX());
                segmentedImageSampledField.setNumSamples2(vcImage.getNumY());
                segmentedImageSampledField.setNumSamples3(vcImage.getNumZ());
                segmentedImageSampledField.setInterpolationType(InterpolationKind.nearestneighbor);
                segmentedImageSampledField.setCompression(CompressionKind.uncompressed);
                segmentedImageSampledField.setDataType(DataKind.UINT8);
                segmentedImageSampledFieldGeometry.setSampledField(segmentedImageSampledField.getId());
                try {
                    byte[] vcImagePixelsBytes = vcImage.getPixels();
                    // imageData.setCompression("");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < vcImagePixelsBytes.length; i++) {
                        int uint8_sample = ((int) vcImagePixelsBytes[i]) & 0xff;
                        sb.append(uint8_sample + " ");
                    }
                    segmentedImageSampledField.setSamplesLength(vcImage.getNumXYZ());
                    segmentedImageSampledField.setSamples(sb.toString().trim());
                } catch (ImageException e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Unable to export image from VCell to SBML : " + e.getMessage());
                }
            }
        }
    /*		
		//
		// add "DistanceMap" SampledFieldGeometry if there are exactly two subvolumes (else need more fields) and geometry is 3d.
		//
		if (numSubVols==2 && dimension == 3){
			SignedDistanceMap[] distanceMaps = null;
			try {
				distanceMaps = DistanceMapGenerator.computeDistanceMaps(vcImageGeometry, vcImageGeometry.getGeometrySpec().getImage(), false, false);
			} catch (ImageException e) {
				e.printStackTrace(System.out);
				System.err.println("Unable to export distance map sampled field from VCell to SBML : " + e.getMessage());
				// throw new RuntimeException("Unable to export distance map sampled field from VCell to SBML : " + e.getMessage());
				
				// don't want to throw an exception and stop export because distance map geometry couldn't be exported. 
				// just 'return' from method (since this is the last thing that is being done in this method).
				return;
			}
			//
			// the two distanceMaps should be redundant (one is negation of the other) ... so choose first one for field.
			//
			double[] signedDistances = distanceMaps[0].getSignedDistances();
			SampledFieldGeometry distanceMapSampledFieldGeometry = sbmlGeometry.createSampledFieldGeometry();
			distanceMapSampledFieldGeometry.setSpatialId(TokenMangler.mangleToSName("DistanceMap_"+vcGeometry.getName()));
			SampledField distanceMapSampledField = distanceMapSampledFieldGeometry.createSampledField();
			distanceMapSampledField.setSpatialId("DistanceMapSampledField");
			distanceMapSampledField.setNumSamples1(distanceMaps[0].getSamplesX().length);
			distanceMapSampledField.setNumSamples2(distanceMaps[0].getSamplesY().length);
			distanceMapSampledField.setNumSamples3(distanceMaps[0].getSamplesZ().length);
			distanceMapSampledField.setDataType("real");
System.err.println("do we need distanceMapSampleField.setDataType()?");
			distanceMapSampledField.setInterpolationType("linear");
			ImageData distanceMapImageData = distanceMapSampledField.createImageData();
			distanceMapImageData.setDataType("int16");
System.err.println("should be:\n  distanceMapImageData.setDataType(\"float32\")");
//					distanceMapImageData.setCompression("");

			double maxAbsValue = 0;
			for (int i = 0; i < signedDistances.length; i++) {
				maxAbsValue = Math.max(maxAbsValue,Math.abs(signedDistances[i]));
			}
			if (maxAbsValue==0.0){
				throw new RuntimeException("computed distance map all zeros");
			}
			double scale = (Short.MAX_VALUE-1)/maxAbsValue;
			int[] scaledIntegerDistanceMap = new int[signedDistances.length];
			for (int i = 0; i < signedDistances.length; i++) {
				scaledIntegerDistanceMap[i] = (int)(scale * signedDistances[i]);
			}
			distanceMapImageData.setSamples(scaledIntegerDistanceMap, signedDistances.length);
System.err.println("should be:\n  distanceMapImageData.setSamples((float[])signedDistances,signedDistances.length)");
			SampledVolume sampledVol = distanceMapSampledFieldGeometry.createSampledVolume();
			sampledVol.setSpatialId(distanceMaps[0].getInsideSubvolumeName());
			sampledVol.setDomainType(DOMAIN_TYPE_PREFIX+distanceMaps[0].getInsideSubvolumeName());
			sampledVol.setSampledValue(255);
			sampledVol = distanceMapSampledFieldGeometry.createSampledVolume();
			sampledVol.setSpatialId(distanceMaps[1].getInsideSubvolumeName());
			sampledVol.setDomainType(DOMAIN_TYPE_PREFIX+distanceMaps[1].getInsideSubvolumeName());
			sampledVol.setSampledValue(1);
		}
*/
    }
// 
// add "SurfaceMesh" ParametricGeometry
// 
// if (bAnyAnalyticSubvolumes || bAnyImageSubvolumes || bAnyCSGSubvolumes){
// ParametricGeometry sbmlParametricGeomDefinition = sbmlGeometry.createParametricGeometry();
// sbmlParametricGeomDefinition.setSpatialId(TokenMangler.mangleToSName("SurfaceMesh_"+vcGeometry.getName()));
// xxxx
// }
}
Also used : Origin(org.vcell.util.Origin) CompartmentMapping(org.sbml.jsbml.ext.spatial.CompartmentMapping) Compartment(org.sbml.jsbml.Compartment) SpatialParameterPlugin(org.sbml.jsbml.ext.spatial.SpatialParameterPlugin) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) ExpressionException(cbit.vcell.parser.ExpressionException) Boundary(org.sbml.jsbml.ext.spatial.Boundary) GeometrySpec(cbit.vcell.geometry.GeometrySpec) DomainType(org.sbml.jsbml.ext.spatial.DomainType) SampledVolume(org.sbml.jsbml.ext.spatial.SampledVolume) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) GeometryContext(cbit.vcell.mapping.GeometryContext) SpatialCompartmentPlugin(org.sbml.jsbml.ext.spatial.SpatialCompartmentPlugin) CoordinateComponent(org.sbml.jsbml.ext.spatial.CoordinateComponent) SimulationContext(cbit.vcell.mapping.SimulationContext) SpeciesContext(cbit.vcell.model.SpeciesContext) GeometryContext(cbit.vcell.mapping.GeometryContext) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) GeometricRegion(cbit.vcell.geometry.surface.GeometricRegion) SpatialSymbolReference(org.sbml.jsbml.ext.spatial.SpatialSymbolReference) AnalyticVolume(org.sbml.jsbml.ext.spatial.AnalyticVolume) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) SampledField(org.sbml.jsbml.ext.spatial.SampledField) Domain(org.sbml.jsbml.ext.spatial.Domain) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) GeometryClass(cbit.vcell.geometry.GeometryClass) ImageException(cbit.image.ImageException) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) Extent(org.vcell.util.Extent) SurfaceClass(cbit.vcell.geometry.SurfaceClass) ISize(org.vcell.util.ISize) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) RegionInfo(cbit.vcell.geometry.RegionImage.RegionInfo) VCImage(cbit.image.VCImage) StructureMapping(cbit.vcell.mapping.StructureMapping) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) ASTNode(org.sbml.jsbml.ASTNode) CSGObject(cbit.vcell.geometry.CSGObject) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) SpatialModelPlugin(org.sbml.jsbml.ext.spatial.SpatialModelPlugin) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) ImageException(cbit.image.ImageException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionException(cbit.vcell.parser.ExpressionException) AdjacentDomains(org.sbml.jsbml.ext.spatial.AdjacentDomains) Geometry(cbit.vcell.geometry.Geometry) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel)

Example 7 with UnitDefinition

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

the class SBMLExporter method createSBMLParamFromSpeciesParam.

/**
 * createSBMLParamFromSpeciesParam : creates an SBML parameter for each speciesContextSpecParameter (diffusion coefficient,
 * advection coeffs, boundary conditions (X,Y,Z).
 *
 * @param spContext
 * @param scsParam
 * @return
 * @throws SbmlException
 */
org.sbml.jsbml.Parameter createSBMLParamFromSpeciesParam(SpeciesContext spContext, SpeciesContextSpecParameter scsParam) throws SbmlException {
    try {
        Expression paramExpr = scsParam.getExpression();
        // if scsParam is diff, Vel X, Y, Z parameter and if its expression is null or 0.0, don't create parameter.
        int role = scsParam.getRole();
        if (((role == SpeciesContextSpec.ROLE_DiffusionRate) || (role == SpeciesContextSpec.ROLE_VelocityX) || (role == SpeciesContextSpec.ROLE_VelocityY) || (role == SpeciesContextSpec.ROLE_VelocityZ)) && ((paramExpr == null) || (paramExpr.isNumeric() && (scsParam.getConstantValue() == 0.0)))) {
            return null;
        }
        // if scsParam is a BoundaryCondition, and paramExpr is null, values are set based on boundary condition type.
        if (((role == SpeciesContextSpec.ROLE_BoundaryValueXm) || (role == SpeciesContextSpec.ROLE_BoundaryValueXp) || (role == SpeciesContextSpec.ROLE_BoundaryValueYm) || (role == SpeciesContextSpec.ROLE_BoundaryValueYp) || (role == SpeciesContextSpec.ROLE_BoundaryValueZm) || (role == SpeciesContextSpec.ROLE_BoundaryValueZp)) && (paramExpr == null)) {
            StructureMapping sm = getSelectedSimContext().getGeometryContext().getStructureMapping(spContext.getStructure());
            Expression initCondnExpr = getSelectedSimContext().getReactionContext().getSpeciesContextSpec(spContext).getInitialConditionParameter().getExpression();
            // if BC type is Neumann (flux), its value is 0.0
            if ((role == SpeciesContextSpec.ROLE_BoundaryValueXm)) {
                if (sm.getBoundaryConditionTypeXm().isDIRICHLET()) {
                    paramExpr = new Expression(initCondnExpr);
                } else if (sm.getBoundaryConditionTypeXm().isNEUMANN()) {
                    paramExpr = new Expression(0.0);
                }
            }
            if ((role == SpeciesContextSpec.ROLE_BoundaryValueXp)) {
                if (sm.getBoundaryConditionTypeXp().isDIRICHLET()) {
                    paramExpr = new Expression(initCondnExpr);
                } else if (sm.getBoundaryConditionTypeXp().isNEUMANN()) {
                    paramExpr = new Expression(0.0);
                }
            }
            if ((role == SpeciesContextSpec.ROLE_BoundaryValueYm)) {
                if (sm.getBoundaryConditionTypeYm().isDIRICHLET()) {
                    paramExpr = new Expression(initCondnExpr);
                } else if (sm.getBoundaryConditionTypeYm().isNEUMANN()) {
                    paramExpr = new Expression(0.0);
                }
            }
            if ((role == SpeciesContextSpec.ROLE_BoundaryValueYp)) {
                if (sm.getBoundaryConditionTypeYp().isDIRICHLET()) {
                    paramExpr = new Expression(initCondnExpr);
                } else if (sm.getBoundaryConditionTypeYp().isNEUMANN()) {
                    paramExpr = new Expression(0.0);
                }
            }
            if ((role == SpeciesContextSpec.ROLE_BoundaryValueZm)) {
                if (sm.getBoundaryConditionTypeZm().isDIRICHLET()) {
                    paramExpr = new Expression(initCondnExpr);
                } else if (sm.getBoundaryConditionTypeZm().isNEUMANN()) {
                    paramExpr = new Expression(0.0);
                }
            }
            if ((role == SpeciesContextSpec.ROLE_BoundaryValueZp)) {
                if (sm.getBoundaryConditionTypeZp().isDIRICHLET()) {
                    paramExpr = new Expression(initCondnExpr);
                } else if (sm.getBoundaryConditionTypeZp().isNEUMANN()) {
                    paramExpr = new Expression(0.0);
                }
            }
        }
        // create SBML parameter
        org.sbml.jsbml.Parameter param = sbmlModel.createParameter();
        param.setId(TokenMangler.mangleToSName(spContext.getName() + "_" + scsParam.getName()));
        UnitDefinition unitDefn = getOrCreateSBMLUnit(scsParam.getUnitDefinition());
        param.setUnits(unitDefn);
        param.setConstant(scsParam.isConstant());
        if (paramExpr.isNumeric()) {
            param.setValue(paramExpr.evaluateConstant());
            param.setConstant(true);
        } else {
            // we need to create a parameter and a rule for the non-numeric expr of diffParam
            param.setValue(0.0);
            param.setConstant(false);
            // now add assignment rule in SBML for the diff param
            ASTNode assgnRuleMathNode = getFormulaFromExpression(paramExpr);
            AssignmentRule assgnRule = sbmlModel.createAssignmentRule();
            assgnRule.setVariable(param.getId());
            assgnRule.setMath(assgnRuleMathNode);
        }
        return param;
    } catch (ExpressionException e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("Unable to interpret parameter '" + scsParam.getName() + "' of species : " + spContext.getName());
    }
}
Also used : Expression(cbit.vcell.parser.Expression) AssignmentRule(org.sbml.jsbml.AssignmentRule) ASTNode(org.sbml.jsbml.ASTNode) StructureMapping(cbit.vcell.mapping.StructureMapping) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 8 with UnitDefinition

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

the class SBMLImporter method createSBMLUnitSystemForVCModel.

private ModelUnitSystem createSBMLUnitSystemForVCModel() throws Exception {
    if (sbmlModel == null) {
        throw new SBMLImportException("SBML model is NULL");
    }
    ListOf listofUnitDefns = sbmlModel.getListOfUnitDefinitions();
    if (listofUnitDefns == null) {
        System.out.println("No Unit Definitions");
        // @TODO: deal with SBML level < 3.
        return ModelUnitSystem.createDefaultVCModelUnitSystem();
    }
    @SuppressWarnings("serial") VCUnitSystem tempVCUnitSystem = new VCUnitSystem() {
    };
    sbmlUnitIdentifierHash = new HashMap<String, VCUnitDefinition>();
    // add base SI unit identifiers (as defined in SBML spec) to hash
    sbmlUnitIdentifierHash.put("ampere", tempVCUnitSystem.getInstance("A"));
    sbmlUnitIdentifierHash.put("avogadro", tempVCUnitSystem.getInstance("6.02e23"));
    // sbmlUnitIdentifierHash.put("becquerel",
    // tempVCUnitSystem.getInstance("becquerel"));
    // sbmlUnitIdentifierHash.put("candela",
    // tempVCUnitSystem.getInstance("candela"));
    sbmlUnitIdentifierHash.put("coulomb", tempVCUnitSystem.getInstance("C"));
    sbmlUnitIdentifierHash.put("dimensionless", tempVCUnitSystem.getInstance("1"));
    sbmlUnitIdentifierHash.put("farad", tempVCUnitSystem.getInstance("F"));
    sbmlUnitIdentifierHash.put("gram", tempVCUnitSystem.getInstance("g"));
    // sbmlUnitIdentifierHash.put("gray",
    // tempVCUnitSystem.getInstance("gray"));
    sbmlUnitIdentifierHash.put("henry", tempVCUnitSystem.getInstance("H"));
    sbmlUnitIdentifierHash.put("hertz", tempVCUnitSystem.getInstance("Hz"));
    sbmlUnitIdentifierHash.put("item", tempVCUnitSystem.getInstance("molecules"));
    sbmlUnitIdentifierHash.put("joule", tempVCUnitSystem.getInstance("J"));
    // sbmlUnitIdentifierHash.put("katal",
    // tempVCUnitSystem.getInstance("katal"));
    sbmlUnitIdentifierHash.put("kelvin", tempVCUnitSystem.getInstance("K"));
    sbmlUnitIdentifierHash.put("kilogram", tempVCUnitSystem.getInstance("kg"));
    sbmlUnitIdentifierHash.put("litre", tempVCUnitSystem.getInstance("litre"));
    // sbmlUnitIdentifierHash.put("lumen",
    // tempVCUnitSystem.getInstance("lumen"));
    // sbmlUnitIdentifierHash.put("lux",
    // tempVCUnitSystem.getInstance("lux"));
    sbmlUnitIdentifierHash.put("metre", tempVCUnitSystem.getInstance("m"));
    sbmlUnitIdentifierHash.put("mole", tempVCUnitSystem.getInstance("mol"));
    sbmlUnitIdentifierHash.put("newton", tempVCUnitSystem.getInstance("N"));
    // sbmlUnitIdentifierHash.put("ohm",
    // tempVCUnitSystem.getInstance("ohm"));
    // sbmlUnitIdentifierHash.put("pascal",
    // tempVCUnitSystem.getInstance("pascal"));
    // sbmlUnitIdentifierHash.put("radian",
    // tempVCUnitSystem.getInstance("radian"));
    sbmlUnitIdentifierHash.put("second", tempVCUnitSystem.getInstance("s"));
    sbmlUnitIdentifierHash.put("siemens", tempVCUnitSystem.getInstance("S"));
    // sbmlUnitIdentifierHash.put("sievert",
    // tempVCUnitSystem.getInstance("sievert"));
    // sbmlUnitIdentifierHash.put("steradian",
    // tempVCUnitSystem.getInstance("steradian"));
    // sbmlUnitIdentifierHash.put("tesla",
    // tempVCUnitSystem.getInstance("tesla"));
    sbmlUnitIdentifierHash.put("volt", tempVCUnitSystem.getInstance("V"));
    sbmlUnitIdentifierHash.put("watt", tempVCUnitSystem.getInstance("W"));
    sbmlUnitIdentifierHash.put("weber", tempVCUnitSystem.getInstance("Wb"));
    long sbmlLevel = sbmlModel.getLevel();
    if (sbmlLevel < 3) {
        // SBML predefined unit identifiers
        sbmlUnitIdentifierHash.put(UnitDefinition.SUBSTANCE, tempVCUnitSystem.getInstance("mole"));
        sbmlUnitIdentifierHash.put(UnitDefinition.VOLUME, tempVCUnitSystem.getInstance("litre"));
        sbmlUnitIdentifierHash.put(UnitDefinition.AREA, tempVCUnitSystem.getInstance("m2"));
        sbmlUnitIdentifierHash.put(UnitDefinition.LENGTH, tempVCUnitSystem.getInstance("m"));
        sbmlUnitIdentifierHash.put(UnitDefinition.TIME, tempVCUnitSystem.getInstance("s"));
    }
    if (sbmlModel.isSetSubstanceUnits()) {
        UnitDefinition ud = sbmlModel.getSubstanceUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.SUBSTANCE, vcUnitDef);
    }
    if (sbmlModel.isSetVolumeUnits()) {
        UnitDefinition ud = sbmlModel.getVolumeUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.VOLUME, vcUnitDef);
    }
    if (sbmlModel.isSetAreaUnits()) {
        UnitDefinition ud = sbmlModel.getAreaUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.AREA, vcUnitDef);
    }
    if (sbmlModel.isSetLengthUnits()) {
        UnitDefinition ud = sbmlModel.getLengthUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.LENGTH, vcUnitDef);
    }
    if (sbmlModel.isSetTimeUnits()) {
        UnitDefinition ud = sbmlModel.getTimeUnitsInstance();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(UnitDefinition.TIME, vcUnitDef);
    }
    // read unit definition (identifiers) declared in SBML model
    for (int i = 0; i < sbmlModel.getNumUnitDefinitions(); i++) {
        UnitDefinition ud = (org.sbml.jsbml.UnitDefinition) listofUnitDefns.get(i);
        String unitName = ud.getId();
        VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
        sbmlUnitIdentifierHash.put(unitName, vcUnitDef);
    }
    // For SBML level 2
    // default units
    VCUnitDefinition defaultSubstanceUnit = sbmlUnitIdentifierHash.get(UnitDefinition.SUBSTANCE);
    VCUnitDefinition defaultVolumeUnit = sbmlUnitIdentifierHash.get(UnitDefinition.VOLUME);
    VCUnitDefinition defaultAreaUnit = sbmlUnitIdentifierHash.get(UnitDefinition.AREA);
    VCUnitDefinition defaultLengthUnit = sbmlUnitIdentifierHash.get(UnitDefinition.LENGTH);
    VCUnitDefinition defaultTimeUnit = sbmlUnitIdentifierHash.get(UnitDefinition.TIME);
    VCUnitDefinition modelSubstanceUnit = null;
    VCUnitDefinition modelVolumeUnit = null;
    VCUnitDefinition modelAreaUnit = null;
    VCUnitDefinition modelLengthUnit = null;
    VCUnitDefinition modelTimeUnit = null;
    // units in SBML model
    // compartments
    ListOf<Compartment> listOfCompartments = sbmlModel.getListOfCompartments();
    for (int i = 0; i < listOfCompartments.size(); i++) {
        Compartment sbmlComp = listOfCompartments.get(i);
        double dim = 3;
        if (sbmlComp.isSetSpatialDimensions()) {
            dim = sbmlComp.getSpatialDimensions();
        }
        String unitStr = sbmlComp.getUnits();
        VCUnitDefinition sbmlUnitDefinition = null;
        if (unitStr != null && unitStr.length() > 0) {
            sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
        } else {
            // applying default unit if not defined for this compartment
            if (dim == 3) {
                sbmlUnitDefinition = defaultVolumeUnit;
            } else if (dim == 2) {
                sbmlUnitDefinition = defaultAreaUnit;
            } else if (dim == 1) {
                sbmlUnitDefinition = defaultLengthUnit;
            }
        }
        if (dim == 3) {
            if (sbmlUnitDefinition == null) {
                sbmlUnitDefinition = defaultVolumeUnit;
            }
            if (modelVolumeUnit == null) {
                modelVolumeUnit = sbmlUnitDefinition;
            } else if (!sbmlUnitDefinition.isEquivalent(modelVolumeUnit)) {
                localIssueList.add(new Issue(new SBMLIssueSource(sbmlComp), issueContext, IssueCategory.Units, "unit for compartment '" + sbmlComp.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current vol unit (" + modelVolumeUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
            // logger.sendMessage(VCLogger.Priority.MediumPriority,
            // VCLogger.ErrorType.UnitError, "unit for compartment '" +
            // sbmlComp.getId() + "' (" + unitStr + ") : (" +
            // sbmlUnitDefinition.getSymbol() +
            // ") not compatible with current vol unit (" +
            // modelVolumeUnit.getSymbol() + ")");
            }
        } else if (dim == 2) {
            if (modelAreaUnit == null) {
                modelAreaUnit = sbmlUnitDefinition;
            } else if (!sbmlUnitDefinition.isEquivalent(modelAreaUnit)) {
                localIssueList.add(new Issue(new SBMLIssueSource(sbmlComp), issueContext, IssueCategory.Units, "unit for compartment '" + sbmlComp.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current area unit (" + modelAreaUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
            // logger.sendMessage(VCLogger.Priority.MediumPriority,
            // VCLogger.ErrorType.UnitError, "unit for compartment '" +
            // sbmlComp.getId() + "' (" + unitStr + ") : (" +
            // sbmlUnitDefinition.getSymbol() +
            // ") not compatible with current area unit (" +
            // modelAreaUnit.getSymbol() + ")");
            }
        }
    }
    // species
    ListOf<org.sbml.jsbml.Species> listOfSpecies = sbmlModel.getListOfSpecies();
    for (int i = 0; i < listOfSpecies.size(); i++) {
        org.sbml.jsbml.Species sbmlSpecies = listOfSpecies.get(i);
        String unitStr = sbmlSpecies.getSubstanceUnits();
        VCUnitDefinition sbmlUnitDefinition = null;
        if (unitStr != null && unitStr.length() > 0) {
            sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
        } else {
            // apply default substance unit
            sbmlUnitDefinition = defaultSubstanceUnit;
        }
        if (modelSubstanceUnit == null) {
            modelSubstanceUnit = sbmlUnitDefinition;
        } else if (!sbmlUnitDefinition.isEquivalent(modelSubstanceUnit)) {
            localIssueList.add(new Issue(new SBMLIssueSource(sbmlSpecies), issueContext, IssueCategory.Units, "unit for species '" + sbmlSpecies.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current substance unit (" + modelSubstanceUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
        // logger.sendMessage(VCLogger.Priority.MediumPriority,
        // VCLogger.ErrorType.UnitError, "unit for species '" +
        // sbmlSpecies.getId() + "' (" + unitStr + ") : (" +
        // sbmlUnitDefinition.getSymbol() +
        // ") not compatible with current substance unit (" +
        // modelSubstanceUnit.getSymbol() + ")");
        }
    }
    // reactions for SBML level 2 version < 3
    long sbmlVersion = sbmlModel.getVersion();
    if (sbmlVersion < 3) {
        ListOf<Reaction> listOfReactions = sbmlModel.getListOfReactions();
        for (int i = 0; i < listOfReactions.size(); i++) {
            Reaction sbmlReaction = listOfReactions.get(i);
            KineticLaw kineticLaw = sbmlReaction.getKineticLaw();
            if (kineticLaw != null) {
                // first check substance unit
                String unitStr = kineticLaw.getSubstanceUnits();
                VCUnitDefinition sbmlUnitDefinition = null;
                if (unitStr != null && unitStr.length() > 0) {
                    sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
                } else {
                    // apply default substance unit
                    sbmlUnitDefinition = defaultSubstanceUnit;
                }
                if (modelSubstanceUnit == null) {
                    modelSubstanceUnit = sbmlUnitDefinition;
                } else if (!sbmlUnitDefinition.isEquivalent(modelSubstanceUnit)) {
                    localIssueList.add(new Issue(new SBMLIssueSource(sbmlReaction), issueContext, IssueCategory.Units, "substance unit for reaction '" + sbmlReaction.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current substance unit (" + modelSubstanceUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
                // logger.sendMessage(VCLogger.Priority.MediumPriority,
                // VCLogger.ErrorType.UnitError,
                // "substance unit for reaction '" +
                // sbmlReaction.getId() + "' (" + unitStr + ") : (" +
                // sbmlUnitDefinition.getSymbol() +
                // ") not compatible with current substance unit (" +
                // modelSubstanceUnit.getSymbol() + ")");
                }
                // check time unit
                unitStr = kineticLaw.getTimeUnits();
                if (unitStr != null && unitStr.length() > 0) {
                    sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
                } else {
                    // apply default time unit
                    sbmlUnitDefinition = defaultTimeUnit;
                }
                if (modelTimeUnit == null) {
                    modelTimeUnit = sbmlUnitDefinition;
                } else if (!sbmlUnitDefinition.isEquivalent(modelTimeUnit)) {
                    localIssueList.add(new Issue(new SBMLIssueSource(sbmlReaction), issueContext, IssueCategory.Units, "time unit for reaction '" + sbmlReaction.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current time unit (" + modelTimeUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
                // logger.sendMessage(VCLogger.Priority.MediumPriority,
                // VCLogger.ErrorType.UnitError,
                // "time unit for reaction '" + sbmlReaction.getId() +
                // "' (" + unitStr + ") : (" +
                // sbmlUnitDefinition.getSymbol() +
                // ") not compatible with current time unit (" +
                // modelTimeUnit.getSymbol() + ")");
                }
            }
        }
    }
    if (modelSubstanceUnit == null) {
        modelSubstanceUnit = defaultSubstanceUnit;
    }
    if (modelVolumeUnit == null) {
        modelVolumeUnit = defaultVolumeUnit;
    }
    if (modelAreaUnit == null) {
        modelAreaUnit = defaultAreaUnit;
    }
    if (modelLengthUnit == null) {
        modelLengthUnit = defaultLengthUnit;
    }
    if (modelTimeUnit == null) {
        modelTimeUnit = defaultTimeUnit;
    }
    if (modelSubstanceUnit == null && modelVolumeUnit == null && modelAreaUnit == null && modelLengthUnit == null && modelTimeUnit == null) {
        // default (VC)modelUnitSystem
        return ModelUnitSystem.createDefaultVCModelUnitSystem();
    } else {
        return ModelUnitSystem.createSBMLUnitSystem(modelSubstanceUnit, modelVolumeUnit, modelAreaUnit, modelLengthUnit, modelTimeUnit);
    }
}
Also used : VCUnitSystem(cbit.vcell.units.VCUnitSystem) Issue(org.vcell.util.Issue) Compartment(org.sbml.jsbml.Compartment) Reaction(org.sbml.jsbml.Reaction) SimpleReaction(cbit.vcell.model.SimpleReaction) FluxReaction(cbit.vcell.model.FluxReaction) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) ListOf(org.sbml.jsbml.ListOf) Species(cbit.vcell.model.Species) KineticLaw(org.sbml.jsbml.KineticLaw) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition)

Example 9 with UnitDefinition

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

the class SBMLSpatialTest method test.

// @Test
public void test() throws Exception {
    // BioModel bioModel1 = BioModelTest.getExampleWithImage();
    URL vcmlURL = SBMLSpatialTest.class.getResource("Solver_Suite_6_2.vcml");
    File vcmlFile = new File(vcmlURL.toURI());
    BioModel bioModel1 = XmlHelper.XMLToBioModel(new XMLSource(vcmlFile));
    bioModel1.refreshDependencies();
    // for (int i = 0; i<bioModel1.getNumSimulationContexts(); i++){
    for (int i = 5; i == 5; i++) {
        SimulationContext sc1 = bioModel1.getSimulationContext(i);
        if (sc1.getApplicationType() != Application.NETWORK_DETERMINISTIC) {
            System.err.println(sc1.getName() + " is not a network determistic application");
            continue;
        }
        boolean isSpatial = sc1.getGeometry().getDimension() > 0;
        SBMLExporter exporter = new SBMLExporter(bioModel1, 3, 1, isSpatial);
        sc1.refreshMathDescription(null, NetworkGenerationRequirements.ComputeFullNoTimeout);
        // sc1.setMathDescription(sc1.createNewMathMapping(null, NetworkGenerationRequirements.ComputeFullNoTimeout).getMathDescription());
        exporter.setSelectedSimContext(sc1);
        VCellSBMLDoc sbmlDoc = exporter.convertToSBML();
        for (UnitDefinition unitDefn : sbmlDoc.model.getListOfUnitDefinitions()) {
            for (Unit unit : unitDefn.getListOfUnits()) {
                System.out.println(unit.getKind());
                if (!unit.isSetKind()) {
                    throw new RuntimeException("kind of unit " + unit.printUnit() + " of UnitDefn " + UnitDefinition.printUnits(unitDefn) + " is not set");
                }
            }
        }
        // sbmlDoc.document.setConsistencyChecks(CHECK_CATEGORY.UNITS_CONSISTENCY, false);
        // int numErrors = sbmlDoc.document.checkConsistency();
        // System.out.println("consistency check, num errors = "+numErrors);
        // if (numErrors>0){
        // SBMLErrorLog errorLog = sbmlDoc.document.getListOfErrors();
        // for (int err=0; err<errorLog.getErrorCount(); err++){
        // System.err.println("ERROR IN EXPORTED SBML: "+errorLog.getError(err).getMessage());
        // }
        // //Assert.fail("generated SBML document was found to be inconsistent");
        // }
        String sbmlString = sbmlDoc.xmlString;
        File tempFile = File.createTempFile("sbmlSpatialTest_SBML_", ".sbml.xml");
        FileUtils.write(tempFile, sbmlString);
        System.out.println(tempFile);
        try {
            VCLogger argVCLogger = new TLogger();
            SBMLImporter importer = new SBMLImporter(tempFile.getAbsolutePath(), argVCLogger, isSpatial);
            BioModel bioModel2 = importer.getBioModel();
            File tempFile2 = File.createTempFile("sbmlSpatialTest_Biomodel_", ".vcml.xml");
            FileUtils.write(tempFile2, XmlHelper.bioModelToXML(bioModel2));
            System.out.println(tempFile2);
            // if (true) { throw new RuntimeException("stop"); }
            bioModel2.refreshDependencies();
            SimulationContext sc2 = bioModel2.getSimulationContext(0);
            // sc2.refreshMathDescription(null, NetworkGenerationRequirements.ComputeFullNoTimeout);
            sc2.setMathDescription(sc2.createNewMathMapping(null, NetworkGenerationRequirements.ComputeFullNoTimeout).getMathDescription());
            if (!sc1.getMathDescription().isValid()) {
                throw new RuntimeException("sc1.math is not valid");
            }
            if (!sc2.getMathDescription().isValid()) {
                throw new RuntimeException("sc2.math is not valid");
            }
            MathCompareResults mathCompareResults = MathDescription.testEquivalency(SimulationSymbolTable.createMathSymbolTableFactory(), sc1.getMathDescription(), sc2.getMathDescription());
            if (!mathCompareResults.isEquivalent()) {
                System.out.println("MATH DESCRIPTION 1 <UNCHANGED>");
                System.out.println(sc1.getMathDescription().getVCML_database());
                System.out.println("MATH DESCRIPTION 2 <UNCHANGED>");
                System.out.println(sc2.getMathDescription().getVCML_database());
                // if (mathCompareResults.decision  == Decision.MathDifferent_SUBDOMAINS_DONT_MATCH){
                // BioModel bioModel1_copy = XmlHelper.XMLToBioModel(new XMLSource(vcmlFile));
                // bioModel1_copy.refreshDependencies();
                // SimulationContext sc1_copy = bioModel1_copy.getSimulationContext(i);
                // VCImage image = sc1_copy.getGeometry().getGeometrySpec().getImage();
                // if (image!=null){
                // ArrayList<VCPixelClass> pcList = new ArrayList<VCPixelClass>();
                // for (VCPixelClass pc : image.getPixelClasses()){
                // pcList.add(new VCPixelClass(pc.getKey(),SBMLExporter.DOMAIN_TYPE_PREFIX+pc.getPixelClassName(),pc.getPixel()));
                // }
                // image.setPixelClasses(pcList.toArray(new VCPixelClass[0]));
                // }
                // for (GeometryClass gc : sc1_copy.getGeometry().getGeometryClasses()){
                // System.out.println("name before "+gc.getName());
                // gc.setName(SBMLExporter.DOMAIN_TYPE_PREFIX+gc.getName());
                // System.out.println("name after "+gc.getName());
                // }
                // sc1_copy.checkValidity();
                // bioModel1_copy.refreshDependencies();
                // sc1_copy.getGeometry().precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, true);
                // sc1_copy.setMathDescription(sc1_copy.createNewMathMapping(null, NetworkGenerationRequirements.ComputeFullNoTimeout).getMathDescription());
                // MathCompareResults mathCompareResults_renamedSubdomains = MathDescription.testEquivalency(SimulationSymbolTable.createMathSymbolTableFactory(),sc1_copy.getMathDescription(), sc2.getMathDescription());
                // if (!mathCompareResults_renamedSubdomains.isEquivalent()){
                // System.out.println("MATH DESCRIPTION 1 <RENAMED>");
                // System.out.println(sc1_copy.getMathDescription().getVCML_database());
                // Assert.fail(mathCompareResults_renamedSubdomains.decision+" "+mathCompareResults_renamedSubdomains.details);
                // }
                // }else{
                System.err.println(mathCompareResults.decision + " " + mathCompareResults.details);
            // }
            } else {
                System.out.println("MATHS WERE EQUIVALENT");
            }
        } finally {
            tempFile.delete();
        }
    }
    // loop over determinstic applications
    System.out.println("done");
}
Also used : SBMLImporter(org.vcell.sbml.vcell.SBMLImporter) SBMLExporter(org.vcell.sbml.vcell.SBMLExporter) SimulationContext(cbit.vcell.mapping.SimulationContext) Unit(org.sbml.jsbml.Unit) URL(java.net.URL) BioModel(cbit.vcell.biomodel.BioModel) VCellSBMLDoc(org.vcell.sbml.vcell.SBMLExporter.VCellSBMLDoc) MathCompareResults(cbit.vcell.math.MathCompareResults) File(java.io.File) XMLSource(cbit.vcell.xml.XMLSource) UnitDefinition(org.sbml.jsbml.UnitDefinition) VCLogger(cbit.util.xml.VCLogger)

Example 10 with UnitDefinition

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

the class SBMLUnitTranslatorTest method testSBMLtoVCell.

@Test
public void testSBMLtoVCell() throws XMLStreamException, IOException, SbmlException {
    File[] sbmlFiles = getBiomodelsCuratedSBMLFiles();
    // };
    for (File sbmlFile : sbmlFiles) {
        if (sbmlFile.getName().equals("BIOMD0000000539.xml")) {
            System.err.println("skipping this model, seems like a bug in jsbml  RenderParser.processEndDocument() ... line 403 ... wrong constant for extension name");
            continue;
        }
        SBMLDocument doc = SBMLReader.read(sbmlFile);
        BioModel bioModel = new BioModel(null);
        VCUnitSystem unitSystem = bioModel.getModel().getUnitSystem();
        Model sbmlModel = doc.getModel();
        ListOf<UnitDefinition> listOfUnitDefinitions = sbmlModel.getListOfUnitDefinitions();
        for (UnitDefinition sbmlUnitDef : listOfUnitDefinitions) {
            VCUnitDefinition vcUnit = SBMLUnitTranslator.getVCUnitDefinition(sbmlUnitDef, unitSystem);
            UnitDefinition new_sbmlUnitDef = SBMLUnitTranslator.getSBMLUnitDefinition(vcUnit, 3, 1, unitSystem);
            VCUnitDefinition new_vcUnit = SBMLUnitTranslator.getVCUnitDefinition(new_sbmlUnitDef, unitSystem);
            if (!vcUnit.getSymbol().equals(new_vcUnit.getSymbol())) {
                System.err.println("orig vcUnit '" + vcUnit.getSymbol() + "' doesn't match new vcUnit '" + new_vcUnit.getSymbol() + "'");
            }
            // System.out.println("sbmlUnit = "+sbmlUnitDef.toString()+", vcUnit = "+vcUnit.getSymbol());
            System.out.println("sbmlUnit(" + sbmlUnitDef.getClass().getName() + ", builtin=" + sbmlUnitDef.isVariantOfSubstance() + ") = " + sbmlUnitDef.toString() + ", id=" + sbmlUnitDef.getId() + ",  name=" + sbmlUnitDef.getName() + ",   vcUnit = " + vcUnit.getSymbol());
            if (sbmlUnitDef.getNumUnits() > 1) {
                System.out.println("vcUnit = " + vcUnit.getSymbol());
                for (Unit unit : sbmlUnitDef.getListOfUnits()) {
                    try {
                        // VCUnitDefinition vcUnit = unitSystem.getInstance(unit.getKind().getName());
                        System.out.println("    vcUnit = " + unit);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("found bigger unit, " + sbmlUnitDef);
            }
        }
        if (sbmlFile == sbmlFiles[0]) {
            System.out.println("sbml length unit = " + sbmlModel.getLengthUnitsInstance() + ", idref=" + sbmlModel.getLengthUnits());
            System.out.println("sbml area unit = " + sbmlModel.getAreaUnitsInstance() + ", idref=" + sbmlModel.getAreaUnits());
            System.out.println("sbml volume unit = " + sbmlModel.getVolumeUnitsInstance() + ", idref=" + sbmlModel.getVolumeUnits());
            System.out.println("sbml time unit = " + sbmlModel.getTimeUnitsInstance() + ", idref=" + sbmlModel.getTimeUnits());
            System.out.println("sbml extent unit = " + sbmlModel.getExtentUnitsInstance() + ", idref=" + sbmlModel.getExtentUnits());
            System.out.println("sbml substance unit = " + sbmlModel.getSubstanceUnitsInstance() + ", idref=" + sbmlModel.getSubstanceUnits());
            for (UnitDefinition sbmlUnitDef : sbmlModel.getListOfPredefinedUnitDefinitions()) {
                if (sbmlUnitDef.getNumUnits() == 1 && sbmlUnitDef.getUnit(0).isAvogadro()) {
                    continue;
                }
                if (sbmlUnitDef.getNumUnits() == 1 && sbmlUnitDef.getUnit(0).isKatal()) {
                    continue;
                }
                VCUnitDefinition vcUnit = SBMLUnitTranslator.getVCUnitDefinition(sbmlUnitDef, unitSystem);
                // System.out.println("sbmlUnit = "+sbmlUnitDef.toString()+", vcUnit = "+vcUnit.getSymbol());
                System.out.println("sbmlUnit(" + sbmlUnitDef.getClass().getName() + ", builtin=" + sbmlUnitDef.isVariantOfSubstance() + ") = " + sbmlUnitDef.toString() + ", id=" + sbmlUnitDef.getId() + ",  name=" + sbmlUnitDef.getName() + ",   vcUnit = " + vcUnit.getSymbol());
            // for (Unit unit : sbmlUnitDef.getListOfUnits()){
            // try {
            // VCUnitDefinition vcUnit = unitSystem.getInstance(unit.getKind().getName());
            // System.out.println("    vcUnit = "+vcUnit.getSymbol());
            // }catch (Exception e){
            // e.printStackTrace();
            // }
            // }
            }
        }
    }
}
Also used : VCUnitSystem(cbit.vcell.units.VCUnitSystem) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) SBMLDocument(org.sbml.jsbml.SBMLDocument) BioModel(cbit.vcell.biomodel.BioModel) Model(org.sbml.jsbml.Model) BioModel(cbit.vcell.biomodel.BioModel) Unit(org.sbml.jsbml.Unit) File(java.io.File) UnitDefinition(org.sbml.jsbml.UnitDefinition) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) Test(org.junit.Test)

Aggregations

UnitDefinition (org.sbml.jsbml.UnitDefinition)10 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)9 InteriorPoint (org.sbml.jsbml.ext.spatial.InteriorPoint)6 BioModel (cbit.vcell.biomodel.BioModel)5 StructureMapping (cbit.vcell.mapping.StructureMapping)5 Expression (cbit.vcell.parser.Expression)5 ExpressionException (cbit.vcell.parser.ExpressionException)5 ASTNode (org.sbml.jsbml.ASTNode)5 XMLStreamException (javax.xml.stream.XMLStreamException)4 AssignmentRule (org.sbml.jsbml.AssignmentRule)4 Compartment (org.sbml.jsbml.Compartment)4 ImageException (cbit.image.ImageException)3 Model (cbit.vcell.model.Model)3 SBMLException (org.sbml.jsbml.SBMLException)3 Unit (org.sbml.jsbml.Unit)3 SbmlException (org.vcell.sbml.SbmlException)3 SimulationContext (cbit.vcell.mapping.SimulationContext)2 StructureMappingParameter (cbit.vcell.mapping.StructureMapping.StructureMappingParameter)2 SpeciesContext (cbit.vcell.model.SpeciesContext)2 VCUnitSystem (cbit.vcell.units.VCUnitSystem)2