use of org.vcell.util.ISize in project vcell by virtualcell.
the class SBMLImporter method addGeometry.
protected void addGeometry() {
// get a Geometry object via SpatialModelPlugin object.
org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = getSbmlGeometry();
if (sbmlGeometry == null) {
return;
}
int dimension = 0;
Origin vcOrigin = null;
Extent vcExtent = null;
{
// local code block
// get a CoordComponent object via the Geometry object.
ListOf<CoordinateComponent> listOfCoordComps = sbmlGeometry.getListOfCoordinateComponents();
if (listOfCoordComps == null) {
throw new RuntimeException("Cannot have 0 coordinate compartments in geometry");
}
// coord component
double ox = 0.0;
double oy = 0.0;
double oz = 0.0;
double ex = 1.0;
double ey = 1.0;
double ez = 1.0;
for (CoordinateComponent coordComponent : listOfCoordComps) {
double minValue = coordComponent.getBoundaryMinimum().getValue();
double maxValue = coordComponent.getBoundaryMaximum().getValue();
switch(coordComponent.getType()) {
case cartesianX:
{
ox = minValue;
ex = maxValue - minValue;
break;
}
case cartesianY:
{
oy = minValue;
ey = maxValue - minValue;
break;
}
case cartesianZ:
{
oz = minValue;
ez = maxValue - minValue;
break;
}
}
dimension++;
}
vcOrigin = new Origin(ox, oy, oz);
vcExtent = new Extent(ex, ey, ez);
}
// from geometry definition, find out which type of geometry : image or
// analytic or CSG
AnalyticGeometry analyticGeometryDefinition = null;
CSGeometry csGeometry = null;
SampledFieldGeometry segmentedSampledFieldGeometry = null;
SampledFieldGeometry distanceMapSampledFieldGeometry = null;
ParametricGeometry parametricGeometry = null;
for (int i = 0; i < sbmlGeometry.getListOfGeometryDefinitions().size(); i++) {
GeometryDefinition gd_temp = sbmlGeometry.getListOfGeometryDefinitions().get(i);
if (!gd_temp.isSetIsActive()) {
continue;
}
if (gd_temp instanceof AnalyticGeometry) {
analyticGeometryDefinition = (AnalyticGeometry) gd_temp;
} else if (gd_temp instanceof SampledFieldGeometry) {
SampledFieldGeometry sfg = (SampledFieldGeometry) gd_temp;
String sfn = sfg.getSampledField();
ListOf<SampledField> sampledFields = sbmlGeometry.getListOfSampledFields();
if (sampledFields.size() > 1) {
throw new RuntimeException("only one sampled field supported");
}
InterpolationKind ik = sampledFields.get(0).getInterpolationType();
switch(ik) {
case linear:
distanceMapSampledFieldGeometry = sfg;
break;
case nearestneighbor:
segmentedSampledFieldGeometry = sfg;
break;
default:
lg.warn("Unsupported " + sampledFields.get(0).getName() + " interpolation type " + ik);
}
} else if (gd_temp instanceof CSGeometry) {
csGeometry = (CSGeometry) gd_temp;
} else if (gd_temp instanceof ParametricGeometry) {
parametricGeometry = (ParametricGeometry) gd_temp;
} else {
throw new RuntimeException("unsupported geometry definition type " + gd_temp.getClass().getSimpleName());
}
}
if (analyticGeometryDefinition == null && segmentedSampledFieldGeometry == null && distanceMapSampledFieldGeometry == null && csGeometry == null) {
throw new SBMLImportException("VCell supports only Analytic, Image based (segmentd or distance map) or Constructed Solid Geometry at this time.");
}
GeometryDefinition selectedGeometryDefinition = null;
if (csGeometry != null) {
selectedGeometryDefinition = csGeometry;
} else if (analyticGeometryDefinition != null) {
selectedGeometryDefinition = analyticGeometryDefinition;
} else if (segmentedSampledFieldGeometry != null) {
selectedGeometryDefinition = segmentedSampledFieldGeometry;
} else if (distanceMapSampledFieldGeometry != null) {
selectedGeometryDefinition = distanceMapSampledFieldGeometry;
} else if (parametricGeometry != null) {
selectedGeometryDefinition = parametricGeometry;
} else {
throw new SBMLImportException("no geometry definition found");
}
Geometry vcGeometry = null;
if (selectedGeometryDefinition == analyticGeometryDefinition || selectedGeometryDefinition == csGeometry) {
vcGeometry = new Geometry("spatialGeom", dimension);
} else if (selectedGeometryDefinition == distanceMapSampledFieldGeometry || selectedGeometryDefinition == segmentedSampledFieldGeometry) {
SampledFieldGeometry sfg = (SampledFieldGeometry) selectedGeometryDefinition;
// get image from sampledFieldGeometry
// get a sampledVol object via the listOfSampledVol (from
// SampledGeometry) object.
// gcw gcw gcw
String sfn = sfg.getSampledField();
SampledField sf = null;
for (SampledField sampledField : sbmlGeometry.getListOfSampledFields()) {
if (sampledField.getSpatialId().equals(sfn)) {
sf = sampledField;
}
}
int numX = sf.getNumSamples1();
int numY = sf.getNumSamples2();
int numZ = sf.getNumSamples3();
int[] samples = new int[sf.getSamplesLength()];
StringTokenizer tokens = new StringTokenizer(sf.getSamples(), " ");
int count = 0;
while (tokens.hasMoreTokens()) {
int sample = Integer.parseInt(tokens.nextToken());
samples[count++] = sample;
}
byte[] imageInBytes = new byte[samples.length];
if (selectedGeometryDefinition == distanceMapSampledFieldGeometry) {
//
for (int i = 0; i < imageInBytes.length; i++) {
// if (interpolation(samples[i])<0){
if (samples[i] < 0) {
imageInBytes[i] = -1;
} else {
imageInBytes[i] = 1;
}
}
} else {
for (int i = 0; i < imageInBytes.length; i++) {
imageInBytes[i] = (byte) samples[i];
}
}
try {
// System.out.println("ident " + sf.getId() + " " + sf.getName());
VCImage vcImage = null;
CompressionKind ck = sf.getCompression();
DataKind dk = sf.getDataType();
if (ck == CompressionKind.deflated) {
vcImage = new VCImageCompressed(null, imageInBytes, vcExtent, numX, numY, numZ);
} else {
switch(dk) {
case UINT8:
case UINT16:
case UINT32:
vcImage = new VCImageUncompressed(null, imageInBytes, vcExtent, numX, numY, numZ);
default:
}
}
if (vcImage == null) {
throw new SbmlException("Unsupported type combination " + ck + ", " + dk + " for sampled field " + sf.getName());
}
vcImage.setName(sf.getId());
ListOf<SampledVolume> sampledVolumes = sfg.getListOfSampledVolumes();
final int numSampledVols = sampledVolumes.size();
if (numSampledVols == 0) {
throw new RuntimeException("Cannot have 0 sampled volumes in sampledField (image_based) geometry");
}
// check to see if values are uniquely integer , add set up scaling if necessary
double scaleFactor = checkPixelScaling(sampledVolumes, 1);
if (scaleFactor != 1) {
double checkScaleFactor = checkPixelScaling(sampledVolumes, scaleFactor);
VCAssert.assertTrue(checkScaleFactor != scaleFactor, "Scale factor check failed");
}
VCPixelClass[] vcpixelClasses = new VCPixelClass[numSampledVols];
// get pixel classes for geometry
for (int i = 0; i < numSampledVols; i++) {
SampledVolume sVol = sampledVolumes.get(i);
// from subVolume, get pixelClass?
final int scaled = (int) (scaleFactor * sVol.getSampledValue());
vcpixelClasses[i] = new VCPixelClass(null, sVol.getDomainType(), scaled);
}
vcImage.setPixelClasses(vcpixelClasses);
// now create image geometry
vcGeometry = new Geometry("spatialGeom", vcImage);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to create image from SampledFieldGeometry : " + e.getMessage());
}
}
GeometrySpec vcGeometrySpec = vcGeometry.getGeometrySpec();
vcGeometrySpec.setOrigin(vcOrigin);
try {
vcGeometrySpec.setExtent(vcExtent);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Unable to set extent on VC geometry : " + e.getMessage(), e);
}
// get listOfDomainTypes via the Geometry object.
ListOf<DomainType> listOfDomainTypes = sbmlGeometry.getListOfDomainTypes();
if (listOfDomainTypes == null || listOfDomainTypes.size() < 1) {
throw new SBMLImportException("Cannot have 0 domainTypes in geometry");
}
// get a listOfDomains via the Geometry object.
ListOf<Domain> listOfDomains = sbmlGeometry.getListOfDomains();
if (listOfDomains == null || listOfDomains.size() < 1) {
throw new SBMLImportException("Cannot have 0 domains in geometry");
}
// ListOfGeometryDefinitions listOfGeomDefns =
// sbmlGeometry.getListOfGeometryDefinitions();
// if ((listOfGeomDefns == null) ||
// (sbmlGeometry.getNumGeometryDefinitions() > 1)) {
// throw new
// RuntimeException("Can have only 1 geometry definition in geometry");
// }
// use the boolean bAnalytic to create the right kind of subvolume.
// First match the somVol=domainTypes for spDim=3. Deal witl spDim=2
// afterwards.
GeometrySurfaceDescription vcGsd = vcGeometry.getGeometrySurfaceDescription();
Vector<DomainType> surfaceClassDomainTypesVector = new Vector<DomainType>();
try {
for (DomainType dt : listOfDomainTypes) {
if (dt.getSpatialDimensions() == 3) {
// subvolume
if (selectedGeometryDefinition == analyticGeometryDefinition) {
// will set expression later - when reading in Analytic
// Volumes in GeometryDefinition
vcGeometrySpec.addSubVolume(new AnalyticSubVolume(dt.getId(), new Expression(1.0)));
} else {
// add SubVolumes later for CSG and Image-based
}
} else if (dt.getSpatialDimensions() == 2) {
surfaceClassDomainTypesVector.add(dt);
}
}
// analytic vol is needed to get the expression for subVols
if (selectedGeometryDefinition == analyticGeometryDefinition) {
// get an analyticVol object via the listOfAnalyticVol (from
// AnalyticGeometry) object.
ListOf<AnalyticVolume> aVolumes = analyticGeometryDefinition.getListOfAnalyticVolumes();
if (aVolumes.size() < 1) {
throw new SBMLImportException("Cannot have 0 Analytic volumes in analytic geometry");
}
for (AnalyticVolume analyticVol : aVolumes) {
// get subVol from VC geometry using analyticVol spatialId;
// set its expr using analyticVol's math.
SubVolume vcSubvolume = vcGeometrySpec.getSubVolume(analyticVol.getDomainType());
CastInfo<AnalyticSubVolume> ci = BeanUtils.attemptCast(AnalyticSubVolume.class, vcSubvolume);
if (!ci.isGood()) {
throw new RuntimeException("analytic volume '" + analyticVol.getId() + "' does not map to any VC subvolume.");
}
AnalyticSubVolume asv = ci.get();
try {
Expression subVolExpr = getExpressionFromFormula(analyticVol.getMath());
asv.setExpression(subVolExpr);
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Unable to set expression on subVolume '" + asv.getName() + "'. " + e.getMessage(), e);
}
}
}
SampledFieldGeometry sfg = BeanUtils.downcast(SampledFieldGeometry.class, selectedGeometryDefinition);
if (sfg != null) {
ListOf<SampledVolume> sampledVolumes = sfg.getListOfSampledVolumes();
int numSampledVols = sampledVolumes.size();
if (numSampledVols == 0) {
throw new SBMLImportException("Cannot have 0 sampled volumes in sampledField (image_based) geometry");
}
VCPixelClass[] vcpixelClasses = new VCPixelClass[numSampledVols];
ImageSubVolume[] vcImageSubVols = new ImageSubVolume[numSampledVols];
// get pixel classes for geometry
int idx = 0;
for (SampledVolume sVol : sampledVolumes) {
// from subVolume, get pixelClass?
final String name = sVol.getDomainType();
final int pixelValue = SBMLUtils.ignoreZeroFraction(sVol.getSampledValue());
VCPixelClass pc = new VCPixelClass(null, name, pixelValue);
vcpixelClasses[idx] = pc;
// Create the new Image SubVolume - use index of this for
// loop as 'handle' for ImageSubVol?
ImageSubVolume isv = new ImageSubVolume(null, pc, idx);
isv.setName(name);
vcImageSubVols[idx++] = isv;
}
vcGeometry.getGeometrySpec().setSubVolumes(vcImageSubVols);
}
if (selectedGeometryDefinition == csGeometry) {
ListOf<org.sbml.jsbml.ext.spatial.CSGObject> listOfcsgObjs = csGeometry.getListOfCSGObjects();
ArrayList<org.sbml.jsbml.ext.spatial.CSGObject> sbmlCSGs = new ArrayList<org.sbml.jsbml.ext.spatial.CSGObject>(listOfcsgObjs);
// we want the CSGObj with highest ordinal to be the first
// element in the CSG subvols array.
Collections.sort(sbmlCSGs, new Comparator<org.sbml.jsbml.ext.spatial.CSGObject>() {
@Override
public int compare(org.sbml.jsbml.ext.spatial.CSGObject lhs, org.sbml.jsbml.ext.spatial.CSGObject rhs) {
// minus one to reverse sort
return -1 * Integer.compare(lhs.getOrdinal(), rhs.getOrdinal());
}
});
int n = sbmlCSGs.size();
CSGObject[] vcCSGSubVolumes = new CSGObject[n];
for (int i = 0; i < n; i++) {
org.sbml.jsbml.ext.spatial.CSGObject sbmlCSGObject = sbmlCSGs.get(i);
CSGObject vcellCSGObject = new CSGObject(null, sbmlCSGObject.getDomainType(), i);
vcellCSGObject.setRoot(getVCellCSGNode(sbmlCSGObject.getCSGNode()));
}
vcGeometry.getGeometrySpec().setSubVolumes(vcCSGSubVolumes);
}
// Call geom.geomSurfDesc.updateAll() to automatically generate
// surface classes.
// vcGsd.updateAll();
vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, true);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Unable to create VC subVolumes from SBML domainTypes : " + e.getMessage(), e);
}
// should now map each SBML domain to right VC geometric region.
GeometricRegion[] vcGeomRegions = vcGsd.getGeometricRegions();
ISize sampleSize = vcGsd.getVolumeSampleSize();
RegionInfo[] regionInfos = vcGsd.getRegionImage().getRegionInfos();
int numX = sampleSize.getX();
int numY = sampleSize.getY();
int numZ = sampleSize.getZ();
double ox = vcOrigin.getX();
double oy = vcOrigin.getY();
double oz = vcOrigin.getZ();
for (Domain domain : listOfDomains) {
String domainType = domain.getDomainType();
InteriorPoint interiorPt = domain.getListOfInteriorPoints().get(0);
if (interiorPt == null) {
DomainType currDomainType = null;
for (DomainType dt : sbmlGeometry.getListOfDomainTypes()) {
if (dt.getSpatialId().equals(domainType)) {
currDomainType = dt;
}
}
if (currDomainType.getSpatialDimensions() == 2) {
continue;
}
}
Coordinate sbmlInteriorPtCoord = new Coordinate(interiorPt.getCoord1(), interiorPt.getCoord2(), interiorPt.getCoord3());
for (int j = 0; j < vcGeomRegions.length; j++) {
if (vcGeomRegions[j] instanceof VolumeGeometricRegion) {
int regionID = ((VolumeGeometricRegion) vcGeomRegions[j]).getRegionID();
for (int k = 0; k < regionInfos.length; k++) {
// (using gemoRegion regionID).
if (regionInfos[k].getRegionIndex() == regionID) {
int volIndx = 0;
Coordinate nearestPtCoord = null;
double minDistance = Double.MAX_VALUE;
// represented by SBML 'domain[i]'.
for (int z = 0; z < numZ; z++) {
for (int y = 0; y < numY; y++) {
for (int x = 0; x < numX; x++) {
if (regionInfos[k].isIndexInRegion(volIndx)) {
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;
// for now, find the shortest dist
// coord. Can refine algo later.
Coordinate vcCoord = new Coordinate(coordX, coordY, coordZ);
double distance = sbmlInteriorPtCoord.distanceTo(vcCoord);
if (distance < minDistance) {
minDistance = distance;
nearestPtCoord = vcCoord;
}
}
volIndx++;
}
// end - for x
}
// end - for y
}
// with domain name
if (nearestPtCoord != null) {
GeometryClass geomClassSBML = vcGeometry.getGeometryClass(domainType);
// we know vcGeometryReg[j] is a VolGeomRegion
GeometryClass geomClassVC = ((VolumeGeometricRegion) vcGeomRegions[j]).getSubVolume();
if (geomClassSBML.compareEqual(geomClassVC)) {
vcGeomRegions[j].setName(domain.getId());
}
}
}
// end if (regInfoIndx = regId)
}
// end - for regInfo
}
}
// end for - vcGeomRegions
}
// deal with surfaceClass:spDim2-domainTypes
for (int i = 0; i < surfaceClassDomainTypesVector.size(); i++) {
DomainType surfaceClassDomainType = surfaceClassDomainTypesVector.elementAt(i);
// 'surfaceClassDomainType'
for (Domain d : listOfDomains) {
if (d.getDomainType().equals(surfaceClassDomainType.getId())) {
// get the adjacent domains of this 'surface' domain
// (surface domain + its 2 adj vol domains)
Set<Domain> adjacentDomainsSet = getAssociatedAdjacentDomains(sbmlGeometry, d);
// get the domain types of the adjacent domains in SBML and
// store the corresponding subVol counterparts from VC for
// adj vol domains
Vector<SubVolume> adjacentSubVolumesVector = new Vector<SubVolume>();
Vector<VolumeGeometricRegion> adjVolGeomRegionsVector = new Vector<VolumeGeometricRegion>();
Iterator<Domain> iterator = adjacentDomainsSet.iterator();
while (iterator.hasNext()) {
Domain dom = iterator.next();
DomainType dt = getBySpatialID(sbmlGeometry.getListOfDomainTypes(), dom.getDomainType());
if (dt.getSpatialDimensions() == 3) {
// for domain type with sp. dim = 3, get
// correspoinding subVol from VC geometry.
GeometryClass gc = vcGeometry.getGeometryClass(dt.getId());
adjacentSubVolumesVector.add((SubVolume) gc);
// store volGeomRegions corresponding to this (vol)
// geomClass in adjVolGeomRegionsVector : this
// should return ONLY 1 region for subVol.
GeometricRegion[] geomRegion = vcGsd.getGeometricRegions(gc);
adjVolGeomRegionsVector.add((VolumeGeometricRegion) geomRegion[0]);
}
}
// there should be only 2 subVols in this vector
if (adjacentSubVolumesVector.size() != 2) {
throw new RuntimeException("Cannot have more or less than 2 subvolumes that are adjacent to surface (membrane) '" + d.getId() + "'");
}
// get the surface class with these 2 adj subVols. Set its
// name to that of 'surfaceClassDomainType'
SurfaceClass surfacClass = vcGsd.getSurfaceClass(adjacentSubVolumesVector.get(0), adjacentSubVolumesVector.get(1));
surfacClass.setName(surfaceClassDomainType.getSpatialId());
// get surfaceGeometricRegion that has adjVolGeomRegions as
// its adjacent vol geom regions and set its name from
// domain 'd'
SurfaceGeometricRegion surfaceGeomRegion = getAssociatedSurfaceGeometricRegion(vcGsd, adjVolGeomRegionsVector);
if (surfaceGeomRegion != null) {
surfaceGeomRegion.setName(d.getId());
}
}
// end if - domain.domainType == surfaceClassDomainType
}
// end for - numDomains
}
// structureMappings in VC from compartmentMappings in SBML
try {
// set geometry first and then set structureMappings?
vcBioModel.getSimulationContext(0).setGeometry(vcGeometry);
// update simContextName ...
vcBioModel.getSimulationContext(0).setName(vcBioModel.getSimulationContext(0).getName() + "_" + vcGeometry.getName());
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
ModelUnitSystem vcModelUnitSystem = vcModel.getUnitSystem();
Vector<StructureMapping> structMappingsVector = new Vector<StructureMapping>();
SpatialCompartmentPlugin cplugin = null;
for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
Compartment c = sbmlModel.getCompartment(i);
String cname = c.getName();
cplugin = (SpatialCompartmentPlugin) c.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
CompartmentMapping compMapping = cplugin.getCompartmentMapping();
if (compMapping != null) {
// final String id = compMapping.getId();
// final String name = compMapping.getName();
CastInfo<Structure> ci = SBMLHelper.getTypedStructure(Structure.class, vcModel, cname);
if (ci.isGood()) {
Structure struct = ci.get();
String domainType = compMapping.getDomainType();
GeometryClass geometryClass = vcGeometry.getGeometryClass(domainType);
double unitSize = compMapping.getUnitSize();
Feature feat = BeanUtils.downcast(Feature.class, struct);
if (feat != null) {
FeatureMapping featureMapping = new FeatureMapping(feat, vcBioModel.getSimulationContext(0), vcModelUnitSystem);
featureMapping.setGeometryClass(geometryClass);
if (geometryClass instanceof SubVolume) {
featureMapping.getVolumePerUnitVolumeParameter().setExpression(new Expression(unitSize));
} else if (geometryClass instanceof SurfaceClass) {
featureMapping.getVolumePerUnitAreaParameter().setExpression(new Expression(unitSize));
}
structMappingsVector.add(featureMapping);
} else if (struct instanceof Membrane) {
MembraneMapping membraneMapping = new MembraneMapping((Membrane) struct, vcBioModel.getSimulationContext(0), vcModelUnitSystem);
membraneMapping.setGeometryClass(geometryClass);
if (geometryClass instanceof SubVolume) {
membraneMapping.getAreaPerUnitVolumeParameter().setExpression(new Expression(unitSize));
} else if (geometryClass instanceof SurfaceClass) {
membraneMapping.getAreaPerUnitAreaParameter().setExpression(new Expression(unitSize));
}
structMappingsVector.add(membraneMapping);
}
}
}
}
StructureMapping[] structMappings = structMappingsVector.toArray(new StructureMapping[0]);
vcBioModel.getSimulationContext(0).getGeometryContext().setStructureMappings(structMappings);
// if type from SBML parameter Boundary Condn is not the same as the
// boundary type of the
// structureMapping of structure of paramSpContext, set the boundary
// condn type of the structureMapping
// to the value of 'type' from SBML parameter Boundary Condn.
ListOf<Parameter> listOfGlobalParams = sbmlModel.getListOfParameters();
for (Parameter sbmlGlobalParam : sbmlModel.getListOfParameters()) {
SpatialParameterPlugin spplugin = (SpatialParameterPlugin) sbmlGlobalParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
ParameterType paramType = spplugin.getParamType();
if (!(paramType instanceof BoundaryCondition)) {
continue;
}
BoundaryCondition bCondn = (BoundaryCondition) paramType;
if (bCondn.isSetVariable()) {
// get the var of boundaryCondn; find appropriate spContext
// in vcell;
SpeciesContext paramSpContext = vcBioModel.getSimulationContext(0).getModel().getSpeciesContext(bCondn.getVariable());
if (paramSpContext != null) {
Structure s = paramSpContext.getStructure();
StructureMapping sm = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(s);
if (sm != null) {
BoundaryConditionType bct = null;
switch(bCondn.getType()) {
case Dirichlet:
{
bct = BoundaryConditionType.DIRICHLET;
break;
}
case Neumann:
{
bct = BoundaryConditionType.NEUMANN;
break;
}
case Robin_inwardNormalGradientCoefficient:
case Robin_sum:
case Robin_valueCoefficient:
default:
throw new RuntimeException("boundary condition type " + bCondn.getType().name() + " not supported");
}
for (CoordinateComponent coordComp : getSbmlGeometry().getListOfCoordinateComponents()) {
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMinimum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
sm.setBoundaryConditionTypeXm(bct);
}
case cartesianY:
{
sm.setBoundaryConditionTypeYm(bct);
}
case cartesianZ:
{
sm.setBoundaryConditionTypeZm(bct);
}
}
}
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMaximum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
sm.setBoundaryConditionTypeXm(bct);
}
case cartesianY:
{
sm.setBoundaryConditionTypeYm(bct);
}
case cartesianZ:
{
sm.setBoundaryConditionTypeZm(bct);
}
}
}
}
} else // sm != null
{
logger.sendMessage(VCLogger.Priority.MediumPriority, VCLogger.ErrorType.OverallWarning, "No structure " + s.getName() + " requested by species context " + paramSpContext.getName());
}
}
// end if (paramSpContext != null)
}
// end if (bCondn.isSetVar())
}
// end for (sbmlModel.numParams)
vcBioModel.getSimulationContext(0).getGeometryContext().refreshStructureMappings();
vcBioModel.getSimulationContext(0).refreshSpatialObjects();
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Unable to create VC structureMappings from SBML compartment mappings : " + e.getMessage(), e);
}
}
use of org.vcell.util.ISize in project vcell by virtualcell.
the class CartesianMeshFileReader method readCartesianMesh.
private CartesianMesh readCartesianMesh(CommentStringTokenizer tokens, final MembraneMeshMetrics membraneMeshMetrics, final SubdomainInfo subdomainInfo) throws MathException {
//
// clear previous contents
//
MembraneElement[] membraneElements = null;
String version = null;
MeshRegionInfo meshRegionInfo = null;
ISize size = null;
Vect3D extent = null;
Vect3D origin = null;
ContourElement[] contourElements = null;
//
// read new stuff
//
String token = null;
token = tokens.nextToken();
if (token.equalsIgnoreCase(VCML.Version)) {
//
// read version number
//
token = tokens.nextToken();
version = token;
token = tokens.nextToken();
}
if (token.equalsIgnoreCase(VCML.CartesianMesh)) {
token = tokens.nextToken();
} else {
throw new MathFormatException("unexpected token " + token + " expecting " + VCML.CartesianMesh);
}
//
// only Version 1.1 and later supports membrane connectivity (as of 8/30/2000)
//
boolean bConnectivity = false;
if (version.equals(VERSION_1_1) || version.equals(VERSION_1_2)) {
bConnectivity = true;
}
//
// only Version 1.2 and later supports Regions
//
boolean bRegions = false;
if (version.equals(VERSION_1_2)) {
bRegions = true;
meshRegionInfo = new MeshRegionInfo();
}
if (!token.equalsIgnoreCase(VCML.BeginBlock)) {
throw new MathFormatException("unexpected token " + token + " expecting " + VCML.BeginBlock);
}
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
if (token.equalsIgnoreCase(VCML.EndBlock)) {
break;
}
if (token.equalsIgnoreCase(VCML.Size)) {
int sx, sy, sz;
try {
token = tokens.nextToken();
sx = Integer.valueOf(token).intValue();
token = tokens.nextToken();
sy = Integer.valueOf(token).intValue();
token = tokens.nextToken();
sz = Integer.valueOf(token).intValue();
} catch (NumberFormatException e) {
throw new MathFormatException("expected: " + VCML.Size + " # # #");
}
size = new ISize(sx, sy, sz);
continue;
}
if (token.equalsIgnoreCase(VCML.Extent)) {
double ex, ey, ez;
try {
token = tokens.nextToken();
ex = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
ey = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
ez = Double.valueOf(token).doubleValue();
} catch (NumberFormatException e) {
throw new MathFormatException("expected: " + VCML.Extent + " # # #");
}
extent = new Vect3D(ex, ey, ez);
continue;
}
if (token.equalsIgnoreCase(VCML.Origin)) {
double ox, oy, oz;
try {
token = tokens.nextToken();
ox = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
oy = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
oz = Double.valueOf(token).doubleValue();
} catch (NumberFormatException e) {
throw new MathFormatException("expected: " + VCML.Origin + " # # #");
}
origin = new Vect3D(ox, oy, oz);
continue;
}
//
if (token.equalsIgnoreCase(VCML.VolumeRegionsMapSubvolume)) {
token = tokens.nextToken();
if (!token.equalsIgnoreCase(VCML.BeginBlock)) {
throw new MathFormatException("unexpected token " + token + " expecting " + VCML.BeginBlock);
}
token = tokens.nextToken();
int numVolumeRegions = 0;
try {
numVolumeRegions = Integer.valueOf(token).intValue();
} catch (NumberFormatException e) {
throw new MathFormatException("unexpected token " + token + " expecting the VolumeRegionsMapSubvolume list length");
}
int checkCount = 0;
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
if (token.equalsIgnoreCase(VCML.EndBlock)) {
break;
}
try {
int volRegionID = Integer.valueOf(token).intValue();
token = tokens.nextToken();
int subvolumeID = Integer.valueOf(token).intValue();
token = tokens.nextToken();
double volume = Double.valueOf(token).doubleValue();
String subdomainName = null;
if (subdomainInfo != null) {
subdomainName = subdomainInfo.getCompartmentSubdomainName(subvolumeID);
}
meshRegionInfo.mapVolumeRegionToSubvolume(volRegionID, subvolumeID, volume, subdomainName);
} catch (NumberFormatException e) {
throw new MathFormatException("expected: # # #");
}
checkCount += 1;
}
if (checkCount != numVolumeRegions) {
throw new MathFormatException("CartesianMesh.read->VolumeRegionsMapSubvolume: read " + checkCount + " VolRegions but was expecting " + numVolumeRegions);
}
continue;
}
if (token.equalsIgnoreCase(VCML.MembraneRegionsMapVolumeRegion)) {
token = tokens.nextToken();
if (!token.equalsIgnoreCase(VCML.BeginBlock)) {
throw new MathFormatException("unexpected token " + token + " expecting " + VCML.BeginBlock);
}
token = tokens.nextToken();
int numMembraneRegions = 0;
try {
numMembraneRegions = Integer.valueOf(token).intValue();
} catch (NumberFormatException e) {
throw new MathFormatException("unexpected token " + token + " expecting the MembraneRegionsMapVolumeRegion list length");
}
int checkCount = 0;
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
if (token.equalsIgnoreCase(VCML.EndBlock)) {
break;
}
try {
int memRegionID = Integer.valueOf(token).intValue();
token = tokens.nextToken();
int volRegionIn = Integer.valueOf(token).intValue();
token = tokens.nextToken();
int volRegionOut = Integer.valueOf(token).intValue();
token = tokens.nextToken();
double surface = Double.valueOf(token).doubleValue();
meshRegionInfo.mapMembraneRegionToVolumeRegion(memRegionID, volRegionIn, volRegionOut, surface);
} catch (NumberFormatException e) {
throw new MathFormatException("expected: # # #");
}
checkCount += 1;
}
if (checkCount != numMembraneRegions) {
throw new MathFormatException("CartesianMesh.read->MembraneRegionsMapVolumeRegion: read " + checkCount + " MembraneRegions but was expecting " + numMembraneRegions);
}
continue;
}
if (token.equalsIgnoreCase(VCML.VolumeElementsMapVolumeRegion)) {
token = tokens.nextToken();
if (!token.equalsIgnoreCase(VCML.BeginBlock)) {
throw new MathFormatException("unexpected token " + token + " expecting " + VCML.BeginBlock);
}
token = tokens.nextToken();
int numVolumeElements = 0;
try {
numVolumeElements = Integer.valueOf(token).intValue();
} catch (NumberFormatException e) {
throw new MathFormatException("unexpected token " + token + " expecting the VolumeElementsMapVolumeRegion list length");
}
token = tokens.nextToken();
boolean bCompressed = token.equalsIgnoreCase("Compressed");
if (!bCompressed) {
if (!token.equalsIgnoreCase("UnCompressed")) {
throw new MathFormatException("unexpected token " + token + " expecting Compress or UnCompress");
}
}
byte[] volumeElementMap = new byte[numVolumeElements];
int checkCount = 0;
if (bCompressed) {
// Get HEX encoded bytes of the compressed VolumeElements-RegionID Map
StringBuffer hexOfCompressed = new StringBuffer();
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
if (token.equalsIgnoreCase(VCML.EndBlock)) {
break;
}
hexOfCompressed.append(token);
}
// Un-HEX the compressed data
byte[] compressedData = Hex.toBytes(hexOfCompressed.toString());
try {
meshRegionInfo.setCompressedVolumeElementMapVolumeRegion(compressedData, numVolumeElements);
} catch (IOException e) {
throw new MathFormatException("CartesianMesh.read->VolumeElementsMapVolumeRegion " + e.toString());
}
checkCount = meshRegionInfo.getUncompressedVolumeElementMapVolumeRegionLength();
} else {
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
if (token.equalsIgnoreCase(VCML.EndBlock)) {
break;
}
try {
int volumeRegionID = Integer.valueOf(token).intValue();
volumeElementMap[checkCount] = (byte) volumeRegionID;
} catch (NumberFormatException e) {
throw new MathFormatException("expected: # # #");
}
checkCount += 1;
}
}
if (checkCount != numVolumeElements && checkCount != 2 * numVolumeElements) {
throw new MathFormatException("CartesianMesh.read->VolumeElementsMapVolumeRegion: read " + checkCount + " VolumeElements but was expecting " + numVolumeElements);
}
continue;
}
//
//
//
HashMap<Integer, Integer> volumeRegionMapSubvolume = getVolumeRegionMapSubvolume(meshRegionInfo);
if (token.equalsIgnoreCase(VCML.MembraneElements)) {
//
// read '{'
//
token = tokens.nextToken();
if (!token.equalsIgnoreCase(VCML.BeginBlock)) {
throw new MathFormatException("unexpected token " + token + " expecting " + VCML.BeginBlock);
}
token = tokens.nextToken();
int numMemElements = 0;
try {
numMemElements = Integer.valueOf(token).intValue();
} catch (NumberFormatException e) {
throw new MathFormatException("unexpected token " + token + " expecting the membraneElement list length");
}
//
// read list of the following format:
//
// memIndex insideVolIndex outsideVolIndex
//
membraneElements = new MembraneElement[numMemElements];
int index = 0;
int[] membraneElementMapMembraneRegion = null;
if (bRegions) {
membraneElementMapMembraneRegion = new int[numMemElements];
meshRegionInfo.mapMembraneElementsToMembraneRegions(membraneElementMapMembraneRegion);
}
//
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
if (token.equalsIgnoreCase(VCML.EndBlock)) {
break;
}
int memIndex = -1;
int insideIndex = -1;
int outsideIndex = -1;
try {
//
// read first three tokens of a membrane element
//
// membraneIndex insideIndex outsideIndex
//
memIndex = Integer.valueOf(token).intValue();
token = tokens.nextToken();
insideIndex = Integer.valueOf(token).intValue();
token = tokens.nextToken();
outsideIndex = Integer.valueOf(token).intValue();
if (subdomainInfo != null) {
int insideRegionIndex = meshRegionInfo.getVolumeElementMapVolumeRegion(insideIndex);
int outsideRegionIndex = meshRegionInfo.getVolumeElementMapVolumeRegion(outsideIndex);
int insideSubVolumeHandle = volumeRegionMapSubvolume.get(insideRegionIndex);
int outsideSubVolumeHandle = volumeRegionMapSubvolume.get(outsideRegionIndex);
int realInsideSubVolumeHandle = subdomainInfo.getInside(insideSubVolumeHandle, outsideSubVolumeHandle);
if (realInsideSubVolumeHandle != insideSubVolumeHandle) {
int temp = insideIndex;
insideIndex = outsideIndex;
outsideIndex = temp;
}
}
} catch (NumberFormatException e) {
throw new MathFormatException("expected: # # #");
}
MembraneElement me = null;
//
if (bConnectivity) {
try {
token = tokens.nextToken();
int neighbor1 = Integer.valueOf(token).intValue();
token = tokens.nextToken();
int neighbor2 = Integer.valueOf(token).intValue();
token = tokens.nextToken();
int neighbor3 = Integer.valueOf(token).intValue();
token = tokens.nextToken();
int neighbor4 = Integer.valueOf(token).intValue();
//
if (bRegions) {
token = tokens.nextToken();
int regionID = Integer.valueOf(token).intValue();
membraneElementMapMembraneRegion[memIndex] = regionID;
}
if (membraneMeshMetrics == null) {
me = new MembraneElement(memIndex, insideIndex, outsideIndex, neighbor1, neighbor2, neighbor3, neighbor4, MembraneElement.AREA_UNDEFINED, 0, 0, 0, 0, 0, 0);
} else {
me = new MembraneElement(memIndex, insideIndex, outsideIndex, neighbor1, neighbor2, neighbor3, neighbor4, membraneMeshMetrics.areas[memIndex], membraneMeshMetrics.normals[memIndex][0], membraneMeshMetrics.normals[memIndex][1], membraneMeshMetrics.normals[memIndex][2], membraneMeshMetrics.centroids[memIndex][0], membraneMeshMetrics.centroids[memIndex][1], membraneMeshMetrics.centroids[memIndex][2]);
}
} catch (NumberFormatException e) {
throw new MathFormatException("expected: # # # # # # #");
}
} else {
me = new MembraneElement(memIndex, insideIndex, outsideIndex);
}
membraneElements[index] = me;
index++;
}
continue;
}
if (token.equalsIgnoreCase(VCML.ContourElements)) {
//
// read '{'
//
token = tokens.nextToken();
if (!token.equalsIgnoreCase(VCML.BeginBlock)) {
throw new MathFormatException("unexpected token " + token + " expecting " + VCML.BeginBlock);
}
token = tokens.nextToken();
int numContourElements = 0;
try {
numContourElements = Integer.valueOf(token).intValue();
} catch (NumberFormatException e) {
throw new MathFormatException("unexpected token " + token + " expecting the contourElement list length");
}
//
// read list of the following format:
//
// contourIndex volumeIndex beginCoord endCoord prevIndex nextIndex
//
contourElements = new ContourElement[numContourElements];
int index = 0;
//
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
if (token.equalsIgnoreCase(VCML.EndBlock)) {
break;
}
ContourElement ce = null;
try {
//
// read first two tokens of a contour element
//
// contourIndex volumeIndex
//
int contourIndex = Integer.valueOf(token).intValue();
token = tokens.nextToken();
int volumeIndex = Integer.valueOf(token).intValue();
token = tokens.nextToken();
//
// read beginCoord endCoord
//
double beginX = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
double beginY = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
double beginZ = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
double endX = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
double endY = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
double endZ = Double.valueOf(token).doubleValue();
token = tokens.nextToken();
Coordinate begin = new Coordinate(beginX, beginY, beginZ);
Coordinate end = new Coordinate(endX, endY, endZ);
//
// read last two tokens of a contour element
//
// prevContourIndex nextContourIndex
//
int prevContourIndex = Integer.valueOf(token).intValue();
token = tokens.nextToken();
int nextContourIndex = Integer.valueOf(token).intValue();
ce = new ContourElement(contourIndex, volumeIndex, begin, end, prevContourIndex, nextContourIndex);
} catch (NumberFormatException e) {
throw new MathFormatException("expected: %d %d %f %f %f %f %f %f %d %d");
}
contourElements[index] = ce;
index++;
}
continue;
}
throw new MathFormatException("unexpected identifier " + token);
}
int dimension = getGeometryDimension(size);
switch(dimension) {
case 1:
{
if (extent.y != 1 || extent.z != 1) {
System.out.println("Extent " + extent.toString() + " for a 1-D mesh truncated to 1 for y and z");
extent = new Vect3D(extent.x, 1.0, 1.0);
}
break;
}
case 2:
{
if (extent.z != 1) {
System.out.println("Extent " + extent.toString() + " for a 2-D mesh truncated to 1 for z");
extent = new Vect3D(extent.x, extent.y, 1.0);
}
break;
}
}
CartesianMesh mesh = new CartesianMesh(version, subdomainInfo, membraneElements, contourElements, meshRegionInfo, size, extent, origin, dimension);
return mesh;
}
use of org.vcell.util.ISize in project vcell by virtualcell.
the class CartesianMeshMapping method fromMesh3DMembrane.
private VisMesh fromMesh3DMembrane(CartesianMesh cartesianMesh, String domainName) {
ISize size = cartesianMesh.getSize();
int numX = size.getX();
int numY = size.getY();
int dimension = 3;
Vect3D origin = new Vect3D(cartesianMesh.getOrigin().x, cartesianMesh.getOrigin().y, cartesianMesh.getOrigin().z);
Vect3D extent = new Vect3D(cartesianMesh.getExtent().x, cartesianMesh.getExtent().y, cartesianMesh.getExtent().z);
// invoke VisMesh() constructor
VisMesh visMesh = new VisMesh(dimension, origin, extent);
int currPointIndex = 0;
HashMap<String, Integer> pointDict = new HashMap<String, Integer>();
List<MembraneElement> membraneElements = cartesianMesh.getMembraneElements(domainName);
for (MembraneElement membraneElement : membraneElements) {
// inside
int insideVolumeIndex = membraneElement.getInsideVolumeIndex();
int insideI = insideVolumeIndex % numX;
int insideJ = (insideVolumeIndex % (numX * numY)) / numX;
int insideK = insideVolumeIndex / (numX * numY);
Box3D insideBox = cartesianMesh.getVolumeElementBox(insideI, insideJ, insideK);
// outside
int outsideVolumeIndex = membraneElement.getOutsideVolumeIndex();
int outsideI = outsideVolumeIndex % numX;
int outsideJ = (outsideVolumeIndex % (numX * numY)) / numX;
int outsideK = outsideVolumeIndex / (numX * numY);
VisPoint p1Coord;
VisPoint p2Coord;
VisPoint p3Coord;
VisPoint p4Coord;
if (insideI == outsideI + 1) {
// x- z cross y
double x = insideBox.x_lo;
p1Coord = new VisPoint(x, insideBox.y_lo, insideBox.z_lo);
p2Coord = new VisPoint(x, insideBox.y_lo, insideBox.z_hi);
p3Coord = new VisPoint(x, insideBox.y_hi, insideBox.z_hi);
p4Coord = new VisPoint(x, insideBox.y_hi, insideBox.z_lo);
} else if (outsideI == insideI + 1) {
// x+ y cross z
double x = insideBox.x_hi;
p1Coord = new VisPoint(x, insideBox.y_lo, insideBox.z_lo);
p2Coord = new VisPoint(x, insideBox.y_hi, insideBox.z_lo);
p3Coord = new VisPoint(x, insideBox.y_hi, insideBox.z_hi);
p4Coord = new VisPoint(x, insideBox.y_lo, insideBox.z_hi);
} else if (insideJ == outsideJ + 1) {
// y- x cross z
double y = insideBox.y_lo;
p1Coord = new VisPoint(insideBox.x_lo, y, insideBox.z_lo);
p2Coord = new VisPoint(insideBox.x_hi, y, insideBox.z_lo);
p3Coord = new VisPoint(insideBox.x_hi, y, insideBox.z_hi);
p4Coord = new VisPoint(insideBox.x_lo, y, insideBox.z_hi);
} else if (outsideJ == insideJ + 1) {
// y+ z cross x
double y = insideBox.y_hi;
p1Coord = new VisPoint(insideBox.x_lo, y, insideBox.z_lo);
p2Coord = new VisPoint(insideBox.x_lo, y, insideBox.z_hi);
p3Coord = new VisPoint(insideBox.x_hi, y, insideBox.z_hi);
p4Coord = new VisPoint(insideBox.x_hi, y, insideBox.z_lo);
} else if (insideK == outsideK + 1) {
// z- y cross x
double z = insideBox.z_lo;
p1Coord = new VisPoint(insideBox.x_lo, insideBox.y_lo, z);
p2Coord = new VisPoint(insideBox.x_lo, insideBox.y_hi, z);
p3Coord = new VisPoint(insideBox.x_hi, insideBox.y_hi, z);
p4Coord = new VisPoint(insideBox.x_hi, insideBox.y_lo, z);
} else if (outsideK == insideK + 1) {
// z+ x cross y
double z = insideBox.z_hi;
p1Coord = new VisPoint(insideBox.x_lo, insideBox.y_lo, z);
p2Coord = new VisPoint(insideBox.x_hi, insideBox.y_lo, z);
p3Coord = new VisPoint(insideBox.x_hi, insideBox.y_hi, z);
p4Coord = new VisPoint(insideBox.x_lo, insideBox.y_hi, z);
} else {
throw new RuntimeException("inside/outside volume indices not reconciled in membraneElement " + membraneElement.getMembraneIndex() + " in domain " + domainName);
}
//
// make sure vertices are added to model without duplicates and get the assigned identifier.
//
String p1Key = toStringKey(p1Coord);
Integer i1 = pointDict.get(p1Key);
if (i1 == null) {
pointDict.put(p1Key, currPointIndex);
i1 = currPointIndex;
visMesh.addToPoints(p1Coord);
currPointIndex++;
}
String p2Key = toStringKey(p2Coord);
Integer i2 = pointDict.get(p2Key);
if (i2 == null) {
pointDict.put(p2Key, currPointIndex);
i2 = currPointIndex;
visMesh.addToPoints(p2Coord);
currPointIndex++;
}
String p3Key = toStringKey(p3Coord);
Integer i3 = pointDict.get(p3Key);
if (i3 == null) {
pointDict.put(p3Key, currPointIndex);
i3 = currPointIndex;
visMesh.addToPoints(p3Coord);
currPointIndex++;
}
String p4Key = toStringKey(p4Coord);
Integer i4 = pointDict.get(p4Key);
if (i4 == null) {
pointDict.put(p4Key, currPointIndex);
i4 = currPointIndex;
visMesh.addToPoints(p4Coord);
currPointIndex++;
}
VisPolygon quad = new VisPolygon(Arrays.asList(new Integer[] { i1, i2, i3, i4 }));
quad.setFiniteVolumeIndex(new FiniteVolumeIndex(membraneElement.getMembraneIndex(), cartesianMesh.getMembraneRegionIndex(membraneElement.getMembraneIndex())));
// print('adding a cell at level '+str(currLevel.getLevel())+" from "+str(p1Coord)+" to "+str(p3Coord))
visMesh.addToPolygons(quad);
}
return visMesh;
}
use of org.vcell.util.ISize in project vcell by virtualcell.
the class ChomboXmlWriter method write.
public static void write(ChomboMeshData chomboMeshData, String filename) throws IOException {
Element rootNode = new Element("root");
Element meshNode = new Element("mesh");
meshNode.setAttribute("dimension", Integer.toString(chomboMeshData.getMesh().getDimension()));
rootNode.addContent(meshNode);
Element levelListNode = new Element("levelList");
meshNode.addContent(levelListNode);
for (ChomboLevel chomboLevel : chomboMeshData.getMesh().getLevels()) {
Element levelNode = new Element("level");
levelNode.setAttribute("info", "level=" + Integer.toString(chomboLevel.getLevel()));
levelListNode.addContent(levelNode);
Element boxListNode = new Element("boxList");
levelNode.addContent(boxListNode);
for (ChomboBox chomboBox : chomboLevel.getBoxes()) {
int minZ = 0;
int maxZ = 0;
Element boxNode = new Element("box");
boxNode.setAttribute("info", "(" + chomboBox.getMinX() + "," + chomboBox.getMinY() + "," + minZ + ") (" + chomboBox.getMaxX() + "," + chomboBox.getMaxY() + "," + maxZ + ")");
boxListNode.addContent(boxNode);
}
Element coveringNode = new Element("covering");
levelNode.addContent(coveringNode);
Covering covering = chomboLevel.getCovering();
int[] levelMap = covering.getLevelMap();
int[] boxNumberMap = covering.getBoxNumberMap();
int[] boxIndexMap = covering.getBoxIndexMap();
ISize size = chomboLevel.getSize();
int numX = size.getX();
int numY = size.getY();
{
Element levelMapNode = new Element("levelMap");
levelMapNode.setAttribute("info", "level=" + chomboLevel.getLevel());
StringBuffer levelMapText = new StringBuffer("\n");
for (int j = 0; j < numY; j++) {
levelMapText.append("[");
for (int i = 0; i < numX; i++) {
levelMapText.append(levelMap[i + j * numX] + " ");
}
levelMapText.append("]\n");
}
levelMapNode.setText(levelMapText.toString());
coveringNode.addContent(levelMapNode);
}
{
Element boxNumberMapNode = new Element("boxNumberMap");
boxNumberMapNode.setAttribute("info", "level=" + chomboLevel.getLevel());
StringBuffer boxNumberMapText = new StringBuffer("\n");
for (int j = 0; j < numY; j++) {
boxNumberMapText.append("[");
for (int i = 0; i < numX; i++) {
boxNumberMapText.append(boxNumberMap[i + j * numX] + " ");
}
boxNumberMapText.append("]\n");
}
boxNumberMapNode.setText(boxNumberMapText.toString());
coveringNode.addContent(boxNumberMapNode);
}
{
Element boxIndexMapNode = new Element("boxIndexMap");
boxIndexMapNode.setAttribute("info", "level=" + chomboLevel.getLevel());
StringBuffer boxIndexMapText = new StringBuffer("\n");
for (int j = 0; j < numY; j++) {
boxIndexMapText.append("[");
for (int i = 0; i < numX; i++) {
boxIndexMapText.append(boxIndexMap[i + j * numX] + " ");
}
boxIndexMapText.append("]\n");
}
boxIndexMapNode.setText(boxIndexMapText.toString());
coveringNode.addContent(boxIndexMapNode);
}
}
String xmlString = XmlUtil.xmlToString(rootNode, true);
XmlUtil.writeXMLStringToFile(xmlString, filename, true);
}
use of org.vcell.util.ISize in project vcell by virtualcell.
the class ClientRequestManager method resizeImage.
private static void resizeImage(FieldDataFileOperationSpec fdfos, ISize newImagesISize, int imageType) throws Exception {
final int ORIG_XYSIZE = fdfos.isize.getX() * fdfos.isize.getY();
try {
int xsize = newImagesISize.getX();
int ysize = newImagesISize.getY();
double scaleFactor = (double) newImagesISize.getX() / (double) fdfos.isize.getX();
if (xsize != fdfos.isize.getX() || ysize != fdfos.isize.getY()) {
// this normally contains different variables but is used for channels here
int numChannels = fdfos.shortSpecData[0].length;
// resize each z section to xsize,ysize
AffineTransform scaleAffineTransform = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
AffineTransformOp scaleAffineTransformOp = new AffineTransformOp(scaleAffineTransform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
short[][][] resizeData = new short[1][numChannels][fdfos.isize.getZ() * xsize * ysize];
for (int c = 0; c < numChannels; c++) {
BufferedImage originalImage = new BufferedImage(fdfos.isize.getX(), fdfos.isize.getY(), BufferedImage.TYPE_USHORT_GRAY);
BufferedImage scaledImage = new BufferedImage(xsize, ysize, BufferedImage.TYPE_USHORT_GRAY);
for (int z = 0; z < fdfos.isize.getZ(); z++) {
short[] originalImageBuffer = ((DataBufferUShort) (originalImage.getRaster().getDataBuffer())).getData();
System.arraycopy(fdfos.shortSpecData[0][c], z * ORIG_XYSIZE, originalImageBuffer, 0, ORIG_XYSIZE);
scaleAffineTransformOp.filter(originalImage, scaledImage);
short[] scaledImageBuffer = ((DataBufferUShort) (scaledImage.getRaster().getDataBuffer())).getData();
System.arraycopy(scaledImageBuffer, 0, resizeData[0][c], z * xsize * ysize, xsize * ysize);
}
}
fdfos.isize = new ISize(xsize, ysize, fdfos.isize.getZ());
fdfos.shortSpecData = resizeData;
}
} catch (Exception e) {
throw new Exception("Error scaling imported image:\n" + e.getMessage());
}
}
Aggregations