use of org.sbml.jsbml.ext.spatial.SpatialSymbolReference in project vcell by virtualcell.
the class SBMLImporter method addParameters.
/**
* addParameters : Adds global parameters from SBML model to VCell model. If
* expression for global parameter contains species, creates a conc_factor
* parameter (conversion from SBML - VCell conc units) and adds this factor
* to VC global params list, and replaces occurances of 'sp' with
* 'sp*concFactor' in original param expression.
*
* @throws PropertyVetoException
*/
protected void addParameters() throws Exception {
ListOf listofGlobalParams = sbmlModel.getListOfParameters();
if (listofGlobalParams == null) {
System.out.println("No Global Parameters");
return;
}
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
ArrayList<ModelParameter> vcModelParamsList = new ArrayList<Model.ModelParameter>();
// create a hash of reserved symbols so that if there is any reserved
// symbol occurring as a global parameter in the SBML model,
// the hash can be used to check for reserved symbols, so that it will
// not be added as a global parameter in VCell,
// since reserved symbols cannot be used as other variables (species,
// structureSize, parameters, reactions, etc.).
HashSet<String> reservedSymbolHash = new HashSet<String>();
for (ReservedSymbol rs : vcModel.getReservedSymbols()) {
reservedSymbolHash.add(rs.getName());
}
ModelUnitSystem modelUnitSystem = vcModel.getUnitSystem();
for (int i = 0; i < sbmlModel.getNumParameters(); i++) {
Parameter sbmlGlobalParam = (Parameter) listofGlobalParams.get(i);
String paramName = sbmlGlobalParam.getId();
SpatialParameterPlugin spplugin = null;
if (bSpatial) {
// check if parameter id is x/y/z : if so, check if its
// 'spatialSymbolRef' child's spatial id and type are non-empty.
// If so, the parameter represents a spatial element.
// If not, throw an exception, since a parameter that does not
// represent a spatial element cannot have an id of x/y/z
spplugin = (SpatialParameterPlugin) sbmlGlobalParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
if (paramName.equals("x") || paramName.equals("y") || paramName.equals("z")) {
boolean bSpatialParam = (spplugin != null && spplugin.getParamType() instanceof SpatialSymbolReference);
// if (a) and (b) are true, continue with the next parameter
if (!bSpatialParam) {
throw new RuntimeException("Parameter '" + paramName + "' is not a spatial parameter : Cannot have a variable in VCell named '" + paramName + "' unless it is a spatial variable.");
} else {
// parameter to the list of vcell parameters.
continue;
}
}
}
//
// Get param value if set or get its expression from rule
//
// Check if param is defined by an assignment rule or initial
// assignment. If so, that value overrides the value existing in the
// param element.
// assignment rule, first
Expression valueExpr = getValueFromAssignmentRule(paramName);
if (valueExpr == null) {
if (sbmlGlobalParam.isSetValue()) {
double value = sbmlGlobalParam.getValue();
valueExpr = new Expression(value);
} else {
// if value for global param is not set and param has a rate
// rule, need to set an init value for param (else, there
// will be a problem in reaction which uses this parameter).
// use a 'default' initial value of '0'
valueExpr = new Expression(0.0);
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.Priority.LowPriority,
// "Parameter did not have an initial value, but has a rate rule specified. Using a default value of 0.0.");
}
}
if (valueExpr != null) {
// valueExpr will be changed
valueExpr = adjustExpression(valueExpr, vcModel);
}
// extension
if (bSpatial) {
VCAssert.assertTrue(spplugin != null, "invalid initialization logic");
ParameterType sbmlParamType = spplugin.getParamType();
SpeciesContext paramSpContext = null;
SpeciesContextSpec vcSpContextsSpec = null;
// Check for diffusion coefficient(s)
if (sbmlParamType instanceof DiffusionCoefficient) {
DiffusionCoefficient diffCoeff = (DiffusionCoefficient) sbmlParamType;
if (diffCoeff != null && diffCoeff.isSetVariable()) {
// get the var of diffCoeff; find appropriate spContext
// in vcell; set its diff param to param value.
paramSpContext = vcModel.getSpeciesContext(diffCoeff.getVariable());
if (paramSpContext != null) {
vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
vcSpContextsSpec.getDiffusionParameter().setExpression(valueExpr);
}
// coeff parameter to the list of vcell parameters.
continue;
}
}
// Check for advection coefficient(s)
if (sbmlParamType instanceof AdvectionCoefficient) {
AdvectionCoefficient advCoeff = (AdvectionCoefficient) sbmlParamType;
if (advCoeff != null && advCoeff.isSetVariable()) {
// get the var of advCoeff; find appropriate spContext
// in vcell; set its adv param to param value.
paramSpContext = vcModel.getSpeciesContext(advCoeff.getVariable());
if (paramSpContext != null) {
vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
CoordinateKind coordKind = advCoeff.getCoordinate();
SpeciesContextSpecParameter param = null;
switch(coordKind) {
case cartesianX:
{
param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityX);
break;
}
case cartesianY:
{
param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityY);
break;
}
case cartesianZ:
{
param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityZ);
break;
}
}
param.setExpression(valueExpr);
}
// coeff parameter to the list of vcell parameters.
continue;
}
}
// Check for Boundary condition(s)
if (sbmlParamType instanceof BoundaryCondition) {
BoundaryCondition bCondn = (BoundaryCondition) sbmlParamType;
if (bCondn != null && bCondn.isSetVariable()) {
// get the var of boundaryCondn; find appropriate
// spContext in vcell;
// set the BC param of its speciesContextSpec to param
// value.
paramSpContext = vcModel.getSpeciesContext(bCondn.getVariable());
if (paramSpContext == null) {
throw new RuntimeException("unable to process boundary condition for variable " + bCondn.getVariable());
}
StructureMapping sm = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(paramSpContext.getStructure());
vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
for (CoordinateComponent coordComp : getSbmlGeometry().getListOfCoordinateComponents()) {
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMinimum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
vcSpContextsSpec.getBoundaryXmParameter().setExpression(valueExpr);
}
case cartesianY:
{
vcSpContextsSpec.getBoundaryYmParameter().setExpression(valueExpr);
}
case cartesianZ:
{
vcSpContextsSpec.getBoundaryZmParameter().setExpression(valueExpr);
}
}
}
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMaximum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
vcSpContextsSpec.getBoundaryXpParameter().setExpression(valueExpr);
}
case cartesianY:
{
vcSpContextsSpec.getBoundaryYpParameter().setExpression(valueExpr);
}
case cartesianZ:
{
vcSpContextsSpec.getBoundaryZpParameter().setExpression(valueExpr);
}
}
}
}
continue;
}
}
// Check for Boundary condition(s)
if (sbmlParamType instanceof SpatialSymbolReference) {
SpatialSymbolReference spatialSymbolRef = (SpatialSymbolReference) sbmlParamType;
throw new RuntimeException("generic Spatial Symbol References not yet supported, unresolved spatial reference '" + spatialSymbolRef.getSpatialRef() + "'");
}
}
// doesn't exist.
if (vcModel.getModelParameter(paramName) == null) {
VCUnitDefinition glParamUnitDefn = sbmlUnitIdentifierHash.get(sbmlGlobalParam.getUnits());
// set it to TBD or check if it was dimensionless.
if (glParamUnitDefn == null) {
glParamUnitDefn = modelUnitSystem.getInstance_TBD();
}
// VCell : cannot add reserved symbol to model params.
if (!reservedSymbolHash.contains(paramName)) {
ModelParameter vcGlobalParam = vcModel.new ModelParameter(paramName, valueExpr, Model.ROLE_UserDefined, glParamUnitDefn);
if (paramName.length() > 64) {
// record global parameter name in annotation if it is
// longer than 64 characeters
vcGlobalParam.setDescription("Parameter Name : " + paramName);
}
vcModelParamsList.add(vcGlobalParam);
}
}
}
// end for - sbmlModel.parameters
vcModel.setModelParameters(vcModelParamsList.toArray(new ModelParameter[0]));
}
use of org.sbml.jsbml.ext.spatial.SpatialSymbolReference in project vcell by virtualcell.
the class SBMLImporter method addParameters.
/**
* addParameters : Adds global parameters from SBML model to VCell model. If
* expression for global parameter contains species, creates a conc_factor
* parameter (conversion from SBML - VCell conc units) and adds this factor
* to VC global params list, and replaces occurances of 'sp' with
* 'sp*concFactor' in original param expression.
*
* @throws PropertyVetoException
*/
protected void addParameters(Map<String, String> vcToSbmlNameMap, Map<String, String> sbmlToVcNameMap) throws Exception {
ListOf listofGlobalParams = sbmlModel.getListOfParameters();
if (listofGlobalParams == null) {
System.out.println("No Global Parameters");
return;
}
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
ArrayList<ModelParameter> vcModelParamsList = new ArrayList<Model.ModelParameter>();
// create a hash of reserved symbols so that if there is any reserved
// symbol occurring as a global parameter in the SBML model,
// the hash can be used to check for reserved symbols, so that it will
// not be added as a global parameter in VCell,
// since reserved symbols cannot be used as other variables (species,
// structureSize, parameters, reactions, etc.).
HashSet<String> reservedSymbolHash = new HashSet<String>();
for (ReservedSymbol rs : vcModel.getReservedSymbols()) {
reservedSymbolHash.add(rs.getName());
}
ModelUnitSystem modelUnitSystem = vcModel.getUnitSystem();
for (int i = 0; i < sbmlModel.getNumParameters(); i++) {
Parameter sbmlGlobalParam = (Parameter) listofGlobalParams.get(i);
String paramName = sbmlGlobalParam.getId();
String sbmlParamName = sbmlGlobalParam.getName();
SpatialParameterPlugin spplugin = null;
if (bSpatial) {
// check if parameter id is x/y/z : if so, check if its
// 'spatialSymbolRef' child's spatial id and type are non-empty.
// If so, the parameter represents a spatial element.
// If not, throw an exception, since a parameter that does not
// represent a spatial element cannot have an id of x/y/z
spplugin = (SpatialParameterPlugin) sbmlGlobalParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
if (paramName.equals("x") || paramName.equals("y") || paramName.equals("z")) {
boolean bSpatialParam = (spplugin != null && spplugin.getParamType() instanceof SpatialSymbolReference);
// if (a) and (b) are true, continue with the next parameter
if (!bSpatialParam) {
throw new RuntimeException("Parameter '" + paramName + "' is not a spatial parameter : Cannot have a variable in VCell named '" + paramName + "' unless it is a spatial variable.");
} else {
// parameter to the list of vcell parameters.
continue;
}
}
}
//
// Get param value if set or get its expression from rule
//
// Check if param is defined by an assignment rule or initial
// assignment. If so, that value overrides the value existing in the
// param element.
// assignment rule, first
Expression valueExpr = getValueFromAssignmentRule(paramName);
if (valueExpr == null) {
if (sbmlGlobalParam.isSetValue()) {
double value = sbmlGlobalParam.getValue();
valueExpr = new Expression(value);
} else {
// if value for global param is not set and param has a rate
// rule, need to set an init value for param (else, there
// will be a problem in reaction which uses this parameter).
// use a 'default' initial value of '0'
valueExpr = new Expression(0.0);
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.Priority.LowPriority,
// "Parameter did not have an initial value, but has a rate rule specified. Using a default value of 0.0.");
}
}
if (valueExpr != null) {
// valueExpr will be changed
valueExpr = adjustExpression(valueExpr, vcModel);
}
// extension
if (bSpatial) {
VCAssert.assertTrue(spplugin != null, "invalid initialization logic");
ParameterType sbmlParamType = spplugin.getParamType();
SpeciesContext paramSpContext = null;
SpeciesContextSpec vcSpContextsSpec = null;
// Check for diffusion coefficient(s)
if (sbmlParamType instanceof DiffusionCoefficient) {
DiffusionCoefficient diffCoeff = (DiffusionCoefficient) sbmlParamType;
if (diffCoeff != null && diffCoeff.isSetVariable()) {
// get the var of diffCoeff; find appropriate spContext
// in vcell; set its diff param to param value.
paramSpContext = vcModel.getSpeciesContext(diffCoeff.getVariable());
if (paramSpContext != null) {
vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
vcSpContextsSpec.getDiffusionParameter().setExpression(valueExpr);
}
// coeff parameter to the list of vcell parameters.
continue;
}
}
// Check for advection coefficient(s)
if (sbmlParamType instanceof AdvectionCoefficient) {
AdvectionCoefficient advCoeff = (AdvectionCoefficient) sbmlParamType;
if (advCoeff != null && advCoeff.isSetVariable()) {
// get the var of advCoeff; find appropriate spContext
// in vcell; set its adv param to param value.
paramSpContext = vcModel.getSpeciesContext(advCoeff.getVariable());
if (paramSpContext != null) {
vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
CoordinateKind coordKind = advCoeff.getCoordinate();
SpeciesContextSpecParameter param = null;
switch(coordKind) {
case cartesianX:
{
param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityX);
break;
}
case cartesianY:
{
param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityY);
break;
}
case cartesianZ:
{
param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityZ);
break;
}
}
param.setExpression(valueExpr);
}
// coeff parameter to the list of vcell parameters.
continue;
}
}
// Check for Boundary condition(s)
if (sbmlParamType instanceof BoundaryCondition) {
BoundaryCondition bCondn = (BoundaryCondition) sbmlParamType;
if (bCondn != null && bCondn.isSetVariable()) {
// get the var of boundaryCondn; find appropriate
// spContext in vcell;
// set the BC param of its speciesContextSpec to param
// value.
paramSpContext = vcModel.getSpeciesContext(bCondn.getVariable());
if (paramSpContext == null) {
throw new RuntimeException("unable to process boundary condition for variable " + bCondn.getVariable());
}
StructureMapping sm = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(paramSpContext.getStructure());
vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
for (CoordinateComponent coordComp : getSbmlGeometry().getListOfCoordinateComponents()) {
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMinimum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
vcSpContextsSpec.getBoundaryXmParameter().setExpression(valueExpr);
}
case cartesianY:
{
vcSpContextsSpec.getBoundaryYmParameter().setExpression(valueExpr);
}
case cartesianZ:
{
vcSpContextsSpec.getBoundaryZmParameter().setExpression(valueExpr);
}
}
}
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMaximum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
vcSpContextsSpec.getBoundaryXpParameter().setExpression(valueExpr);
}
case cartesianY:
{
vcSpContextsSpec.getBoundaryYpParameter().setExpression(valueExpr);
}
case cartesianZ:
{
vcSpContextsSpec.getBoundaryZpParameter().setExpression(valueExpr);
}
}
}
}
continue;
}
}
// Check for Boundary condition(s)
if (sbmlParamType instanceof SpatialSymbolReference) {
SpatialSymbolReference spatialSymbolRef = (SpatialSymbolReference) sbmlParamType;
throw new RuntimeException("generic Spatial Symbol References not yet supported, unresolved spatial reference '" + spatialSymbolRef.getSpatialRef() + "'");
}
}
// doesn't exist.
if (vcModel.getModelParameter(paramName) == null) {
VCUnitDefinition glParamUnitDefn = sbmlUnitIdentifierHash.get(sbmlGlobalParam.getUnits());
// set it to TBD or check if it was dimensionless.
if (glParamUnitDefn == null) {
glParamUnitDefn = modelUnitSystem.getInstance_TBD();
}
// special treatment for x,y,z
if (isRestrictedXYZT(paramName)) {
String vcSpeciesId = "s_" + paramName;
vcToSbmlNameMap.put(vcSpeciesId, paramName);
sbmlToVcNameMap.put(paramName, vcSpeciesId);
ModelParameter vcGlobalParam = vcModel.new ModelParameter(vcSpeciesId, valueExpr, Model.ROLE_UserDefined, glParamUnitDefn);
if (vcSpeciesId.length() > 64) {
vcGlobalParam.setDescription("Parameter Name : " + vcSpeciesId);
}
if (sbmlParamName != null && !sbmlParamName.isEmpty()) {
vcGlobalParam.setSbmlName(sbmlParamName);
}
vcModelParamsList.add(vcGlobalParam);
} else if (!reservedSymbolHash.contains(paramName)) {
// Also check if the SBML global param is a reserved symbol in
// VCell : cannot add reserved symbol to model params.
// we dealt with x,y,z above
ModelParameter vcGlobalParam = vcModel.new ModelParameter(paramName, valueExpr, Model.ROLE_UserDefined, glParamUnitDefn);
if (paramName.length() > 64) {
// record global parameter name in annotation if it is
// longer than 64 characeters
vcGlobalParam.setDescription("Parameter Name : " + paramName);
}
if (sbmlParamName != null && !sbmlParamName.isEmpty()) {
vcGlobalParam.setSbmlName(sbmlParamName);
}
vcModelParamsList.add(vcGlobalParam);
}
}
}
// end for - sbmlModel.parameters
vcModel.setModelParameters(vcModelParamsList.toArray(new ModelParameter[0]));
}
use of org.sbml.jsbml.ext.spatial.SpatialSymbolReference in project vcell by virtualcell.
the class MathModel_SBMLExporter method addGeometry.
private static void addGeometry(Model sbmlModel, MathModel vcMathModel) {
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.getGeometry();
sbmlGeometry.setCoordinateSystem(GeometryKind.cartesian);
Geometry vcGeometry = vcMathModel.getGeometry();
//
// 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 coordCompX = sbmlGeometry.createCoordinateComponent();
coordCompX.setSpatialId("CoordCompX");
coordCompX.setType(CoordinateKind.cartesianX);
Boundary minX = coordCompX.getBoundaryMaximum();
minX.setSpatialId("Xmin");
minX.setValue(vcOrigin.getX());
Boundary maxX = coordCompX.getBoundaryMaximum();
maxX.setSpatialId("Xmax");
maxX.setValue(vcOrigin.getX() + (vcExtent.getX()));
Parameter parameterX = sbmlModel.createParameter();
// note for exporting BioModels rather than MathModels, get ReservedSymbol from Model with Role of ReservedSymbolRole.X
parameterX.setId(ReservedVariable.X.getName());
SpatialSymbolReference coordXSpatialRef = new SpatialSymbolReference();
coordXSpatialRef.setSpatialRef(coordCompX.getSpatialId());
SpatialParameterPlugin parameterXSpatialPlugin = (SpatialParameterPlugin) parameterX.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
parameterXSpatialPlugin.setParamType(coordXSpatialRef);
// add y coordinate component
if (dimension == 2 || dimension == 3) {
CoordinateComponent coordCompY = sbmlGeometry.createCoordinateComponent();
coordCompY.setSpatialId("CoordCompY");
coordCompY.setType(CoordinateKind.cartesianY);
Boundary minY = coordCompY.getBoundaryMinimum();
minY.setId("Ymin");
minY.setValue(vcOrigin.getY());
Boundary maxY = coordCompY.getBoundaryMaximum();
maxY.setId("Ymax");
maxY.setValue(vcOrigin.getY() + (vcExtent.getY()));
Parameter parameterY = sbmlModel.createParameter();
// note for exporting BioModels rather than MathModels, get ReservedSymbol from Model with Role of ReservedSymbolRole.Y
parameterY.setId(ReservedVariable.Y.getName());
SpatialSymbolReference coordYSpatialRef = new SpatialSymbolReference();
coordYSpatialRef.setSpatialRef(coordCompY.getSpatialId());
SpatialParameterPlugin parameterYSpatialPlugin = (SpatialParameterPlugin) parameterY.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
parameterYSpatialPlugin.setParamType(coordYSpatialRef);
}
// add z coordinate component
if (dimension == 3) {
CoordinateComponent coordCompZ = sbmlGeometry.createCoordinateComponent();
coordCompZ.setSpatialId("CoordCompZ");
coordCompZ.setType(CoordinateKind.cartesianZ);
Boundary minZ = coordCompZ.getBoundaryMinimum();
minZ.setId("Zmin");
minZ.setValue(vcOrigin.getZ());
Boundary maxZ = coordCompZ.getBoundaryMaximum();
maxZ.setId("Zmax");
maxZ.setValue(vcOrigin.getZ() + (vcExtent.getZ()));
Parameter parameterZ = sbmlModel.createParameter();
// note for exporting BioModels rather than MathModels, get ReservedSymbol from Model with Role of ReservedSymbolRole.Y
parameterZ.setId(ReservedVariable.Z.getName());
SpatialSymbolReference coordZSpatialRef = new SpatialSymbolReference();
coordZSpatialRef.setSpatialRef(coordCompZ.getSpatialId());
SpatialParameterPlugin parameterZSpatialPlugin = (SpatialParameterPlugin) parameterZ.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
parameterZSpatialPlugin.setParamType(coordZSpatialRef);
}
//
// list of domain types : subvolumes and surface classes from VC
// Also create compartments - one compartment for each geometryClass. set id and spatialDimension based on type of geometryClass.
//
boolean bAnalyticGeom = false;
boolean bImageGeom = false;
GeometryClass[] vcGeomClasses = vcGeometry.getGeometryClasses();
int numVCGeomClasses = vcGeomClasses.length;
for (int i = 0; i < numVCGeomClasses; i++) {
DomainType domainType = sbmlGeometry.createDomainType();
domainType.setId(vcGeomClasses[i].getName());
if (vcGeomClasses[i] instanceof SubVolume) {
if (((SubVolume) vcGeomClasses[i]) instanceof AnalyticSubVolume) {
bAnalyticGeom = true;
} else if (((SubVolume) vcGeomClasses[i]) instanceof ImageSubVolume) {
bImageGeom = true;
}
domainType.setSpatialDimensions(3);
} 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();
Compartment compartment = null;
for (int i = 0; i < vcGeometricRegions.length; i++) {
// domains
Domain domain = sbmlGeometry.createDomain();
domain.setId(vcGeometricRegions[i].getName());
compartment = sbmlModel.createCompartment();
compartment.setId("compartment" + i);
if (vcGeometricRegions[i] instanceof VolumeGeometricRegion) {
domain.setDomainType(((VolumeGeometricRegion) vcGeometricRegions[i]).getSubVolume().getName());
// domain.setImplicit(false);
compartment.setSpatialDimensions(3);
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(surfaceClass.getName());
// domain.setImplicit(true);
compartment.setSpatialDimensions(2);
// adjacent domains : 2 adjacent domain objects for each surfaceClass in VC.
// adjacent domain 1
AdjacentDomains adjDomain = sbmlGeometry.createAdjacentDomain();
adjDomain.setId(TokenMangler.mangleToSName(vcSurfaceGeomReg.getName() + "_" + geomRegion0.getName()));
adjDomain.setDomain1(vcSurfaceGeomReg.getName());
adjDomain.setDomain2(geomRegion0.getName());
// adjacent domain 2
adjDomain = sbmlGeometry.createAdjacentDomain();
adjDomain.setId(TokenMangler.mangleToSName(vcSurfaceGeomReg.getName() + "_" + geomRegion1.getName()));
adjDomain.setDomain1(vcSurfaceGeomReg.getName());
adjDomain.setDomain2(geomRegion1.getName());
}
//
// Mathmodel does not have structureMapping, hence creating compartmentMapping while creating domains.
// @TODO : how to assign unitSize for compartmentMapping?
//
SpatialCompartmentPlugin cplugin = (SpatialCompartmentPlugin) compartment.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
CompartmentMapping compMapping = cplugin.getCompartmentMapping();
String compMappingId = TokenMangler.mangleToSName(domain.getDomainType() + "_" + compartment.getId());
compMapping.setId(compMappingId);
compMapping.setDomainType(TokenMangler.mangleToSName(domain.getDomainType()));
// try {
// compMapping.setUnitSize(1.0);
// } catch (ExpressionException e) {
// e.printStackTrace(System.out);
// throw new RuntimeException("Unable to create compartment mapping for structureMapping '" + compMapping.getId() +"' : " + e.getMessage());
// }
}
AnalyticGeometry sbmlAnalyticGeom = null;
SampledFieldGeometry sbmlSFGeom = null;
// both image and analytic subvolumes?? == not handled in SBML at this time.
if (bAnalyticGeom && !bImageGeom) {
sbmlAnalyticGeom = sbmlGeometry.createAnalyticGeometry();
sbmlAnalyticGeom.setId(TokenMangler.mangleToSName(vcGeometry.getName()));
} else if (bImageGeom && !bAnalyticGeom) {
// assuming image based geometry if not analytic geometry
sbmlSFGeom = sbmlGeometry.createSampledFieldGeometry();
sbmlSFGeom.setId(TokenMangler.mangleToSName(vcGeometry.getName()));
} else if (bAnalyticGeom && bImageGeom) {
throw new RuntimeException("Export to SBML of a combination of Image-based and Analytic geometries is not supported yet.");
} else if (!bAnalyticGeom && !bImageGeom) {
throw new RuntimeException("Unknown geometry type.");
}
//
for (int i = 0; i < vcGeomClasses.length; i++) {
if (vcGeomClasses[i] instanceof AnalyticSubVolume) {
// add analytiVols to sbmlAnalyticGeometry
if (sbmlAnalyticGeom != null) {
AnalyticVolume analyticVol = sbmlAnalyticGeom.createAnalyticVolume();
analyticVol.setId(vcGeomClasses[i].getName());
analyticVol.setDomainType(vcGeomClasses[i].getName());
analyticVol.setFunctionType(FunctionKind.layered);
analyticVol.setOrdinal(i);
Expression expr = ((AnalyticSubVolume) vcGeomClasses[i]).getExpression();
try {
String mathMLStr = ExpressionMathMLPrinter.getMathML(expr, true);
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());
}
} else {
throw new RuntimeException("SBML AnalyticGeometry is null.");
}
} else if (vcGeomClasses[i] instanceof ImageSubVolume) {
// add sampledVols to sbmlSFGeometry
if (sbmlSFGeom != null) {
SampledVolume sampledVol = sbmlSFGeom.createSampledVolume();
sampledVol.setId(vcGeomClasses[i].getName());
sampledVol.setDomainType(vcGeomClasses[i].getName());
sampledVol.setSampledValue(((ImageSubVolume) vcGeomClasses[i]).getPixelValue());
} else {
throw new RuntimeException("SBML SampledFieldGeometry is null.");
}
}
}
if (sbmlSFGeom != null) {
// add sampledField to sampledFieldGeometry
SampledField sampledField = sbmlGeometry.createSampledField();
VCImage vcImage = vcGeometry.getGeometrySpec().getImage();
sampledField.setId(vcImage.getName());
sampledField.setNumSamples1(vcImage.getNumX());
if (vcImage.getNumY() > 1) {
sampledField.setNumSamples2(vcImage.getNumY());
}
if (vcImage.getNumZ() > 1) {
sampledField.setNumSamples3(vcImage.getNumZ());
}
sampledField.setInterpolationType(InterpolationKind.nearestNeighbor);
sampledField.setDataType(DataKind.UINT8);
// add image from vcGeometrySpec to sampledField.
try {
StringBuffer sb = new StringBuffer();
byte[] imagePixelsBytes = vcImage.getPixelsCompressed();
for (int i = 0; i < imagePixelsBytes.length; i++) {
int uint8_sample = ((int) imagePixelsBytes[i]) & 0xff;
sb.append(uint8_sample + " ");
}
sampledField.setSamplesLength(vcImage.getNumXYZ());
sampledField.setSamples(sb.toString().trim());
} catch (ImageException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to export image from VCell to SBML : " + e.getMessage());
}
}
}
use of org.sbml.jsbml.ext.spatial.SpatialSymbolReference 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
// }
}
Aggregations