Search in sources :

Example 41 with GeometryClass

use of cbit.vcell.geometry.GeometryClass 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 42 with GeometryClass

use of cbit.vcell.geometry.GeometryClass in project vcell by virtualcell.

the class SimulationContextDbDriver method assignStructureMappingsSQL.

/**
 * This method was created in VisualAge.
 * @param simContext cbit.vcell.mapping.SimulationContext
 */
private void assignStructureMappingsSQL(QueryHashtable dbc, Connection con, KeyValue simContextKey, SimulationContext simContext) throws SQLException, DataAccessException {
    String sql;
    sql = " SELECT " + "*" + " FROM " + structureMappingTable.getTableName() + " WHERE " + structureMappingTable.simContextRef + " = " + simContextKey;
    Statement stmt = con.createStatement();
    try {
        // log.print(sql);
        ResultSet rset = stmt.executeQuery(sql);
        while (rset.next()) {
            BigDecimal subvolumeRefBigDecimal = rset.getBigDecimal(structureMappingTable.subVolumeRef.toString());
            KeyValue subVolumeRef = (subvolumeRefBigDecimal == null ? null : new KeyValue(subvolumeRefBigDecimal));
            BigDecimal surfaceClassRefBigDecimal = rset.getBigDecimal(structureMappingTable.surfaceClassRef.toString());
            KeyValue surfaceClassRef = (surfaceClassRefBigDecimal == null ? null : new KeyValue(surfaceClassRefBigDecimal));
            KeyValue structureRef = new KeyValue(rset.getBigDecimal(structureMappingTable.structRef.toString()));
            // 
            // lookup structure and subVolume from SimulationContext by their keys
            // 
            // DBCache will not always give same instance consistently (usually this is
            // fixed up later in the ReferenceResolver at the Client).
            // 
            Structure theStructure = null;
            Structure[] structureArray = simContext.getModel().getStructures();
            for (int i = 0; i < structureArray.length; i++) {
                Structure structure = structureArray[i];
                if (structure.getKey().compareEqual(structureRef)) {
                    theStructure = structure;
                    break;
                }
            }
            if (theStructure == null) {
                throw new DataAccessException("Can't match structure and subvolume");
            }
            GeometryClass theGeometryClass = null;
            KeyValue geometryClassKey = (subVolumeRef == null ? surfaceClassRef : subVolumeRef);
            if (geometryClassKey != null) {
                GeometryClass[] geometryClasses = simContext.getGeometry().getGeometryClasses();
                for (int i = 0; i < geometryClasses.length; i++) {
                    if (geometryClasses[i].getKey().compareEqual(geometryClassKey)) {
                        theGeometryClass = geometryClasses[i];
                        break;
                    }
                }
                if (theGeometryClass == null) {
                    throw new DataAccessException("Can't find Geometryclass");
                }
            }
            Expression sizeExpression = null;
            String sizeExpressionS = rset.getString(StructureMappingTable.table.sizeExp.getUnqualifiedColName());
            if (!rset.wasNull() && sizeExpressionS != null && sizeExpressionS.length() > 0) {
                try {
                    sizeExpressionS = TokenMangler.getSQLRestoredString(sizeExpressionS);
                    sizeExpression = new Expression(sizeExpressionS);
                } catch (ExpressionException e) {
                    e.printStackTrace();
                    throw new DataAccessException("SimulationContextDbDriver.assignStructureMappingSQL : Couldn't parse non-null size expression for Structure " + theStructure.getName());
                }
            }
            StructureMapping sm = simContext.getGeometryContext().getStructureMapping(theStructure);
            try {
                sm.getSizeParameter().setExpression(sizeExpression);
            } catch (Exception e1) {
                throw new DataAccessException("SimulationContextDbDriver.assignStructureMappingSQL : Couldn't set size expression '" + sizeExpressionS + "'for Structure " + theStructure.getName());
            }
            try {
                sm.setGeometryClass(theGeometryClass);
            } catch (PropertyVetoException e) {
                lg.error(e.getMessage(), e);
                throw new DataAccessException(e.getMessage());
            }
            if (sm instanceof FeatureMapping) {
                FeatureMapping fm = (FeatureMapping) sm;
                String boundaryTypeXmString = rset.getString(structureMappingTable.boundaryTypeXm.toString());
                if (!rset.wasNull()) {
                    fm.setBoundaryConditionTypeXm(new BoundaryConditionType(boundaryTypeXmString));
                }
                String boundaryTypeXpString = rset.getString(structureMappingTable.boundaryTypeXp.toString());
                if (!rset.wasNull()) {
                    fm.setBoundaryConditionTypeXp(new BoundaryConditionType(boundaryTypeXpString));
                }
                String boundaryTypeYmString = rset.getString(structureMappingTable.boundaryTypeYm.toString());
                if (!rset.wasNull()) {
                    fm.setBoundaryConditionTypeYm(new BoundaryConditionType(boundaryTypeYmString));
                }
                String boundaryTypeYpString = rset.getString(structureMappingTable.boundaryTypeYp.toString());
                if (!rset.wasNull()) {
                    fm.setBoundaryConditionTypeYp(new BoundaryConditionType(boundaryTypeYpString));
                }
                String boundaryTypeZmString = rset.getString(structureMappingTable.boundaryTypeZm.toString());
                if (!rset.wasNull()) {
                    fm.setBoundaryConditionTypeZm(new BoundaryConditionType(boundaryTypeZmString));
                }
                String boundaryTypeZpString = rset.getString(structureMappingTable.boundaryTypeZp.toString());
                if (!rset.wasNull()) {
                    fm.setBoundaryConditionTypeZp(new BoundaryConditionType(boundaryTypeZpString));
                }
                String volPerUnitArea = rset.getString(structureMappingTable.volPerUnitAreaExp.toString());
                if (!rset.wasNull()) {
                    try {
                        fm.getVolumePerUnitAreaParameter().setExpression(new Expression(TokenMangler.getSQLRestoredString(volPerUnitArea)));
                    } catch (ExpressionException e) {
                        e.printStackTrace(System.out);
                        throw new DataAccessException("parse error in surfaceToVol expression: " + e.getMessage());
                    }
                }
                String volPerUnitVol = rset.getString(structureMappingTable.volPerUnitVolExp.toString());
                if (!rset.wasNull()) {
                    try {
                        fm.getVolumePerUnitVolumeParameter().setExpression(new Expression(TokenMangler.getSQLRestoredString(volPerUnitVol)));
                    } catch (ExpressionException e) {
                        e.printStackTrace(System.out);
                        throw new DataAccessException("parse error in surfaceToVol expression: " + e.getMessage());
                    }
                }
            } else if (sm instanceof MembraneMapping) {
                MembraneMapping mm = (MembraneMapping) sm;
                String surfToVolString = rset.getString(structureMappingTable.surfToVolExp.toString());
                if (!rset.wasNull()) {
                    try {
                        mm.getSurfaceToVolumeParameter().setExpression(new Expression(TokenMangler.getSQLRestoredString(surfToVolString)));
                    } catch (ExpressionException e) {
                        e.printStackTrace(System.out);
                        throw new DataAccessException("parse error in surfaceToVol expression: " + e.getMessage());
                    }
                }
                String volFractString = rset.getString(structureMappingTable.volFractExp.toString());
                if (!rset.wasNull()) {
                    try {
                        mm.getVolumeFractionParameter().setExpression(new Expression(TokenMangler.getSQLRestoredString(volFractString)));
                    } catch (ExpressionException e) {
                        e.printStackTrace(System.out);
                        throw new DataAccessException("parse error in volFract expression: " + e.getMessage());
                    }
                }
                boolean bCalculateVoltage = rset.getBoolean(structureMappingTable.bCalculateVoltage.toString());
                if (!rset.wasNull()) {
                    mm.setCalculateVoltage(bCalculateVoltage);
                }
                java.math.BigDecimal specificCapacitance = rset.getBigDecimal(structureMappingTable.specificCap.toString());
                if (!rset.wasNull()) {
                    try {
                        mm.getSpecificCapacitanceParameter().setExpression(new Expression(specificCapacitance.doubleValue()));
                    } catch (ExpressionBindingException e) {
                        e.printStackTrace(System.out);
                        throw new DataAccessException("error setting membrane specific capacitance: " + e.getMessage());
                    }
                }
                String initialVoltageString = rset.getString(structureMappingTable.initialVoltage.toString());
                if (!rset.wasNull()) {
                    try {
                        mm.getInitialVoltageParameter().setExpression(new Expression(TokenMangler.getSQLRestoredString(initialVoltageString)));
                    } catch (ExpressionException e) {
                        e.printStackTrace(System.out);
                        throw new DataAccessException("database parse error in initial membrane voltage: " + e.getMessage());
                    }
                }
                String areaPerUnitArea = rset.getString(structureMappingTable.areaPerUnitAreaExp.toString());
                if (!rset.wasNull()) {
                    try {
                        mm.getAreaPerUnitAreaParameter().setExpression(new Expression(TokenMangler.getSQLRestoredString(areaPerUnitArea)));
                    } catch (ExpressionException e) {
                        e.printStackTrace(System.out);
                        throw new DataAccessException("parse error in surfaceToVol expression: " + e.getMessage());
                    }
                }
                String areaPerUnitVol = rset.getString(structureMappingTable.areaPerUnitVolExp.toString());
                if (!rset.wasNull()) {
                    try {
                        mm.getAreaPerUnitVolumeParameter().setExpression(new Expression(TokenMangler.getSQLRestoredString(areaPerUnitVol)));
                    } catch (ExpressionException e) {
                        e.printStackTrace(System.out);
                        throw new DataAccessException("parse error in surfaceToVol expression: " + e.getMessage());
                    }
                }
            } else {
                throw new DataAccessException("unknown structureMapping type");
            }
        // System.out.println("Structure Key = " + theStructure + " - " + "SubVolume Key " + theSubVolume.getKey());
        }
    } finally {
        stmt.close();
    }
}
Also used : GeometryClass(cbit.vcell.geometry.GeometryClass) MembraneMapping(cbit.vcell.mapping.MembraneMapping) KeyValue(org.vcell.util.document.KeyValue) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) BoundaryConditionType(cbit.vcell.math.BoundaryConditionType) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) StructureMapping(cbit.vcell.mapping.StructureMapping) BigDecimal(java.math.BigDecimal) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) DependencyException(org.vcell.util.DependencyException) RecordChangedException(cbit.sql.RecordChangedException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) PermissionException(org.vcell.util.PermissionException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) IllegalMappingException(cbit.vcell.mapping.IllegalMappingException) SQLException(java.sql.SQLException) DataAccessException(org.vcell.util.DataAccessException) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MathException(cbit.vcell.math.MathException) PropertyVetoException(java.beans.PropertyVetoException) FeatureMapping(cbit.vcell.mapping.FeatureMapping) Expression(cbit.vcell.parser.Expression) ResultSet(java.sql.ResultSet) Structure(cbit.vcell.model.Structure) DataAccessException(org.vcell.util.DataAccessException)

Example 43 with GeometryClass

use of cbit.vcell.geometry.GeometryClass in project vcell by virtualcell.

the class StructureMappingTable method getSQLValueList.

/**
 * This method was created in VisualAge.
 * @return java.lang.String
 * @param key KeyValue
 * @param modelName java.lang.String
 */
public String getSQLValueList(InsertHashtable hash, KeyValue Key, KeyValue simContextKey, StructureMapping structureMapping) throws DataAccessException {
    GeometryClass geometryClass = structureMapping.getGeometryClass();
    KeyValue geometryClassKey = (geometryClass == null ? null : hash.getDatabaseKey(geometryClass));
    if (geometryClass != null && geometryClassKey == null) {
        geometryClassKey = geometryClass.getKey();
        if (geometryClassKey == null) {
            throw new DataAccessException("no key for GeometryClass '" + geometryClass.getName() + "' " + geometryClass.getClass().getName());
        }
    }
    KeyValue structureKey = hash.getDatabaseKey(structureMapping.getStructure());
    if (structureKey == null) {
        structureKey = structureMapping.getStructure().getKey();
        if (structureKey == null) {
            throw new DataAccessException("no key for structure " + structureMapping.getStructure());
        }
    }
    StringBuffer buffer = new StringBuffer();
    buffer.append("(");
    buffer.append(Key + ",");
    buffer.append((geometryClass instanceof SubVolume ? geometryClassKey : null) + ",");
    buffer.append(structureKey + ",");
    buffer.append(simContextKey + ",");
    buffer.append((/*isResolved*/
    false ? 1 : 0) + ",");
    if (structureMapping instanceof FeatureMapping) {
        FeatureMapping fm = (FeatureMapping) structureMapping;
        buffer.append("null" + ",");
        buffer.append("null" + ",");
        buffer.append("'" + fm.getBoundaryConditionTypeXm().boundaryTypeStringValue() + "',");
        buffer.append("'" + fm.getBoundaryConditionTypeXp().boundaryTypeStringValue() + "',");
        buffer.append("'" + fm.getBoundaryConditionTypeYm().boundaryTypeStringValue() + "',");
        buffer.append("'" + fm.getBoundaryConditionTypeYp().boundaryTypeStringValue() + "',");
        buffer.append("'" + fm.getBoundaryConditionTypeZm().boundaryTypeStringValue() + "',");
        buffer.append("'" + fm.getBoundaryConditionTypeZp().boundaryTypeStringValue() + "',");
        buffer.append("null" + ",");
        buffer.append("null" + ",");
        buffer.append("null" + ",");
    } else if (structureMapping instanceof MembraneMapping) {
        MembraneMapping mm = (MembraneMapping) structureMapping;
        // amended Sept. 17th, 2007
        if (mm.getSurfaceToVolumeParameter().getExpression() != null) {
            buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getSurfaceToVolumeParameter().getExpression().infix()) + "',");
        } else {
            buffer.append("null" + ",");
        }
        if (mm.getVolumeFractionParameter().getExpression() != null) {
            buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getVolumeFractionParameter().getExpression().infix()) + "',");
        } else {
            buffer.append("null" + ",");
        }
        buffer.append("null" + ",");
        buffer.append("null" + ",");
        buffer.append("null" + ",");
        buffer.append("null" + ",");
        buffer.append("null" + ",");
        buffer.append("null" + ",");
        buffer.append((mm.getCalculateVoltage() ? 1 : 0) + ",");
        try {
            buffer.append(mm.getSpecificCapacitanceParameter().getExpression().evaluateConstant() + ",");
        } catch (cbit.vcell.parser.ExpressionException e) {
            e.printStackTrace(System.out);
            throw new DataAccessException("specific capacitance for " + mm.getMembrane().getName() + " not constant: (" + e.getMessage() + ")");
        }
        buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getInitialVoltageParameter().getExpression().infix()) + "',");
    }
    if (structureMapping.getSizeParameter().getExpression() != null)
        buffer.append("'" + TokenMangler.getSQLEscapedString(structureMapping.getSizeParameter().getExpression().infix()) + "',");
    else
        buffer.append("'',");
    if (structureMapping instanceof FeatureMapping) {
        FeatureMapping fm = (FeatureMapping) structureMapping;
        if (fm.getVolumePerUnitAreaParameter().getExpression() != null) {
            buffer.append("'" + TokenMangler.getSQLEscapedString(fm.getVolumePerUnitAreaParameter().getExpression().infix()) + "',");
        } else {
            buffer.append("null" + ",");
        }
        if (fm.getVolumePerUnitVolumeParameter().getExpression() != null) {
            buffer.append("'" + TokenMangler.getSQLEscapedString(fm.getVolumePerUnitVolumeParameter().getExpression().infix()) + "',");
        } else {
            buffer.append("null" + ",");
        }
        // if structureMapping is a featureMapping, 'areaPerUnitArea' and 'areaPerUnitVol' params are null, so fill those in here
        buffer.append("null,null");
    } else if (structureMapping instanceof MembraneMapping) {
        // if structureMapping is a featureMapping, 'volPerUnitArea' and 'volPerUnitVol' params are null, so fill those in here; then memMapping params
        buffer.append("null,null,");
        MembraneMapping mm = (MembraneMapping) structureMapping;
        if (mm.getAreaPerUnitAreaParameter().getExpression() != null) {
            buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getAreaPerUnitAreaParameter().getExpression().infix()) + "',");
        } else {
            buffer.append("null" + ",");
        }
        if (mm.getAreaPerUnitVolumeParameter().getExpression() != null) {
            buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getAreaPerUnitVolumeParameter().getExpression().infix()) + "'");
        } else {
            buffer.append("null");
        }
    }
    buffer.append("," + (geometryClass instanceof SurfaceClass ? geometryClassKey : null));
    buffer.append(")");
    return buffer.toString();
}
Also used : GeometryClass(cbit.vcell.geometry.GeometryClass) MembraneMapping(cbit.vcell.mapping.MembraneMapping) KeyValue(org.vcell.util.document.KeyValue) FeatureMapping(cbit.vcell.mapping.FeatureMapping) SurfaceClass(cbit.vcell.geometry.SurfaceClass) SubVolume(cbit.vcell.geometry.SubVolume) DataAccessException(org.vcell.util.DataAccessException)

Aggregations

GeometryClass (cbit.vcell.geometry.GeometryClass)43 SubVolume (cbit.vcell.geometry.SubVolume)21 SurfaceClass (cbit.vcell.geometry.SurfaceClass)19 Expression (cbit.vcell.parser.Expression)18 ExpressionException (cbit.vcell.parser.ExpressionException)14 PropertyVetoException (java.beans.PropertyVetoException)13 Structure (cbit.vcell.model.Structure)12 StructureMapping (cbit.vcell.mapping.StructureMapping)8 MathDescription (cbit.vcell.math.MathDescription)7 MathException (cbit.vcell.math.MathException)7 Variable (cbit.vcell.math.Variable)7 SpeciesContext (cbit.vcell.model.SpeciesContext)7 ExpressionBindingException (cbit.vcell.parser.ExpressionBindingException)7 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)7 MappingException (cbit.vcell.mapping.MappingException)6 Domain (cbit.vcell.math.Variable.Domain)6 ModelException (cbit.vcell.model.ModelException)6 Parameter (cbit.vcell.model.Parameter)6 ArrayList (java.util.ArrayList)6 Geometry (cbit.vcell.geometry.Geometry)5