use of org.sbml.jsbml.Compartment in project vcell by virtualcell.
the class SBMLExporter method addSpecies.
/**
* addSpecies comment.
* @throws XMLStreamException
* @throws SbmlException
*/
protected void addSpecies() throws XMLStreamException, SbmlException {
Model vcModel = vcBioModel.getModel();
SpeciesContext[] vcSpeciesContexts = vcModel.getSpeciesContexts();
for (int i = 0; i < vcSpeciesContexts.length; i++) {
org.sbml.jsbml.Species sbmlSpecies = sbmlModel.createSpecies();
sbmlSpecies.setId(vcSpeciesContexts[i].getName());
// Assuming that at this point, the compartment(s) for the model are already filled in.
Compartment compartment = sbmlModel.getCompartment(TokenMangler.mangleToSName(vcSpeciesContexts[i].getStructure().getName()));
if (compartment != null) {
sbmlSpecies.setCompartment(compartment.getId());
}
// 'hasSubstanceOnly' field will be 'false', since VC deals only with initial concentrations and not initial amounts.
sbmlSpecies.setHasOnlySubstanceUnits(false);
// Get (and set) the initial concentration value
if (getSelectedSimContext() == null) {
throw new RuntimeException("No simcontext (application) specified; Cannot proceed.");
}
// Get the speciesContextSpec in the simContext corresponding to the 'speciesContext'; and extract its initial concentration value.
SpeciesContextSpec vcSpeciesContextsSpec = getSelectedSimContext().getReactionContext().getSpeciesContextSpec(vcSpeciesContexts[i]);
// we need to convert concentration from uM -> molecules/um3; this can be achieved by dividing by KMOLE.
try {
sbmlSpecies.setInitialConcentration(vcSpeciesContextsSpec.getInitialConditionParameter().getExpression().evaluateConstant());
} catch (cbit.vcell.parser.ExpressionException e) {
// If exporting to L2V3, if species concentration is not an expr with x, y, z or other species, add as InitialAssignment, else complain.
if (vcSpeciesContextsSpec.getInitialConditionParameter().getExpression() != null) {
Expression initConcExpr = vcSpeciesContextsSpec.getInitialConditionParameter().getExpression();
if ((sbmlLevel == 2 && sbmlVersion >= 3) || (sbmlLevel > 2)) {
// L2V3 and above - add expression as init assignment
ASTNode initAssgnMathNode = getFormulaFromExpression(initConcExpr);
InitialAssignment initAssignment = sbmlModel.createInitialAssignment();
initAssignment.setSymbol(vcSpeciesContexts[i].getName());
initAssignment.setMath(initAssgnMathNode);
} else {
// L2V1 (or L1V2 also??)
// L2V1 (and L1V2?) and species is 'fixed' (constant), and not fn of x,y,z, other sp, add expr as assgn rule
ASTNode assgnRuleMathNode = getFormulaFromExpression(initConcExpr);
AssignmentRule assgnRule = sbmlModel.createAssignmentRule();
assgnRule.setVariable(vcSpeciesContexts[i].getName());
assgnRule.setMath(assgnRuleMathNode);
}
}
}
// Get (and set) the boundary condition value
boolean bBoundaryCondition = getBoundaryCondition(vcSpeciesContexts[i]);
sbmlSpecies.setBoundaryCondition(bBoundaryCondition);
// mandatory for L3, optional for L2
sbmlSpecies.setConstant(false);
// set species substance units as 'molecules' - same as defined in the model; irrespective of it is in surface or volume.
UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlExportSpec.getSubstanceUnits());
sbmlSpecies.setSubstanceUnits(unitDefn);
// need to do the following if exporting to SBML spatial
if (bSpatial) {
// Required for setting BoundaryConditions : structureMapping for vcSpeciesContext[i] & sbmlGeometry.coordinateComponents
StructureMapping sm = getSelectedSimContext().getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure());
SpatialModelPlugin mplugin = (SpatialModelPlugin) sbmlModel.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = mplugin.getGeometry();
CoordinateComponent ccX = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getX().getName());
CoordinateComponent ccY = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getY().getName());
CoordinateComponent ccZ = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getZ().getName());
// add diffusion, advection, boundary condition parameters for species, if they exist
Parameter[] scsParams = vcSpeciesContextsSpec.getParameters();
if (scsParams != null) {
for (int j = 0; j < scsParams.length; j++) {
if (scsParams[j] != null) {
SpeciesContextSpecParameter scsParam = (SpeciesContextSpecParameter) scsParams[j];
// no need to add parameters in SBML for init conc or init count
int role = scsParam.getRole();
switch(role) {
case SpeciesContextSpec.ROLE_BoundaryValueXm:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueXp:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueYm:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueYp:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueZm:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueZp:
{
break;
}
case SpeciesContextSpec.ROLE_DiffusionRate:
{
break;
}
case SpeciesContextSpec.ROLE_InitialConcentration:
{
// done elsewhere??
continue;
// break;
}
case SpeciesContextSpec.ROLE_InitialCount:
{
// done elsewhere??
continue;
// break;
}
case SpeciesContextSpec.ROLE_VelocityX:
{
break;
}
case SpeciesContextSpec.ROLE_VelocityY:
{
break;
}
case SpeciesContextSpec.ROLE_VelocityZ:
{
break;
}
default:
{
throw new RuntimeException("SpeciesContext Specification parameter with role " + SpeciesContextSpec.RoleNames[role] + " not yet supported for SBML export");
}
}
// if diffusion is 0 && vel terms are not specified, boundary condition not present
if (vcSpeciesContextsSpec.isAdvecting() || vcSpeciesContextsSpec.isDiffusing()) {
Expression diffExpr = vcSpeciesContextsSpec.getDiffusionParameter().getExpression();
boolean bDiffExprNull = (diffExpr == null);
boolean bDiffExprIsZero = false;
if (!bDiffExprNull && diffExpr.isNumeric()) {
try {
bDiffExprIsZero = (diffExpr.evaluateConstant() == 0.0);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to evalute numeric value of diffusion parameter for speciesContext '" + vcSpeciesContexts[i] + "'.");
}
}
boolean bDiffusionZero = (bDiffExprNull || bDiffExprIsZero);
Expression velX_Expr = vcSpeciesContextsSpec.getVelocityXParameter().getExpression();
SpatialQuantity[] velX_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.X);
boolean bVelX_ExprIsNull = (velX_Expr == null && velX_Quantities.length == 0);
Expression velY_Expr = vcSpeciesContextsSpec.getVelocityYParameter().getExpression();
SpatialQuantity[] velY_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Y);
boolean bVelY_ExprIsNull = (velY_Expr == null && velY_Quantities.length == 0);
Expression velZ_Expr = vcSpeciesContextsSpec.getVelocityZParameter().getExpression();
SpatialQuantity[] velZ_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Z);
boolean bVelZ_ExprIsNull = (velZ_Expr == null && velZ_Quantities.length == 0);
boolean bAdvectionNull = (bVelX_ExprIsNull && bVelY_ExprIsNull && bVelZ_ExprIsNull);
if (bDiffusionZero && bAdvectionNull) {
continue;
}
}
// for example, if scsParam is BC_Zm and if coordinateComponent 'ccZ' is null, no SBML parameter should be created for BC_Zm
if ((((role == SpeciesContextSpec.ROLE_BoundaryValueXm) || (role == SpeciesContextSpec.ROLE_BoundaryValueXp)) && (ccX == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueYm) || (role == SpeciesContextSpec.ROLE_BoundaryValueYp)) && (ccY == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueZm) || (role == SpeciesContextSpec.ROLE_BoundaryValueZp)) && (ccZ == null))) {
continue;
}
org.sbml.jsbml.Parameter sbmlParam = createSBMLParamFromSpeciesParam(vcSpeciesContexts[i], (SpeciesContextSpecParameter) scsParams[j]);
if (sbmlParam != null) {
BoundaryConditionType vcBCType_Xm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXm();
BoundaryConditionType vcBCType_Xp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXp();
BoundaryConditionType vcBCType_Ym = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYm();
BoundaryConditionType vcBCType_Yp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYp();
BoundaryConditionType vcBCType_Zm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZm();
BoundaryConditionType vcBCType_Zp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZp();
SpatialParameterPlugin spplugin = (SpatialParameterPlugin) sbmlParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
if (role == SpeciesContextSpec.ROLE_DiffusionRate) {
// set diffusionCoefficient element in SpatialParameterPlugin for param
DiffusionCoefficient sbmlDiffCoeff = new DiffusionCoefficient();
sbmlDiffCoeff.setVariable(vcSpeciesContexts[i].getName());
sbmlDiffCoeff.setDiffusionKind(DiffusionKind.isotropic);
sbmlDiffCoeff.setSpeciesRef(vcSpeciesContexts[i].getName());
spplugin.setParamType(sbmlDiffCoeff);
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueXm) && (ccX != null)) {
// set BoundaryCondn Xm element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCXm = new BoundaryCondition();
spplugin.setParamType(sbmlBCXm);
sbmlBCXm.setType(getBoundaryConditionKind(vcBCType_Xm));
sbmlBCXm.setVariable(vcSpeciesContexts[i].getName());
sbmlBCXm.setCoordinateBoundary(ccX.getBoundaryMinimum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueXp) && (ccX != null)) {
// set BoundaryCondn Xp element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCXp = new BoundaryCondition();
spplugin.setParamType(sbmlBCXp);
sbmlBCXp.setType(getBoundaryConditionKind(vcBCType_Xp));
sbmlBCXp.setVariable(vcSpeciesContexts[i].getName());
sbmlBCXp.setType(sm.getBoundaryConditionTypeXp().boundaryTypeStringValue());
sbmlBCXp.setCoordinateBoundary(ccX.getBoundaryMaximum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueYm) && (ccY != null)) {
// set BoundaryCondn Ym element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCYm = new BoundaryCondition();
spplugin.setParamType(sbmlBCYm);
sbmlBCYm.setType(getBoundaryConditionKind(vcBCType_Yp));
sbmlBCYm.setVariable(vcSpeciesContexts[i].getName());
sbmlBCYm.setType(sm.getBoundaryConditionTypeYm().boundaryTypeStringValue());
sbmlBCYm.setCoordinateBoundary(ccY.getBoundaryMinimum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueYp) && (ccY != null)) {
// set BoundaryCondn Yp element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCYp = new BoundaryCondition();
spplugin.setParamType(sbmlBCYp);
sbmlBCYp.setType(getBoundaryConditionKind(vcBCType_Yp));
sbmlBCYp.setVariable(vcSpeciesContexts[i].getName());
sbmlBCYp.setType(sm.getBoundaryConditionTypeYp().boundaryTypeStringValue());
sbmlBCYp.setCoordinateBoundary(ccY.getBoundaryMaximum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueZm) && (ccZ != null)) {
// set BoundaryCondn Zm element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCZm = new BoundaryCondition();
spplugin.setParamType(sbmlBCZm);
sbmlBCZm.setType(getBoundaryConditionKind(vcBCType_Zm));
sbmlBCZm.setVariable(vcSpeciesContexts[i].getName());
sbmlBCZm.setType(sm.getBoundaryConditionTypeZm().boundaryTypeStringValue());
sbmlBCZm.setCoordinateBoundary(ccZ.getBoundaryMinimum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueZp) && (ccZ != null)) {
// set BoundaryCondn Zp element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCZp = new BoundaryCondition();
spplugin.setParamType(sbmlBCZp);
sbmlBCZp.setType(getBoundaryConditionKind(vcBCType_Zp));
sbmlBCZp.setVariable(vcSpeciesContexts[i].getName());
sbmlBCZp.setType(sm.getBoundaryConditionTypeZp().boundaryTypeStringValue());
sbmlBCZp.setCoordinateBoundary(ccZ.getBoundaryMaximum().getId());
}
if (role == SpeciesContextSpec.ROLE_VelocityX) {
// set advectionCoeff X element in SpatialParameterPlugin for param
AdvectionCoefficient sbmlAdvCoeffX = new AdvectionCoefficient();
spplugin.setParamType(sbmlAdvCoeffX);
sbmlAdvCoeffX.setVariable(vcSpeciesContexts[i].getName());
sbmlAdvCoeffX.setCoordinate(CoordinateKind.cartesianX);
}
if (role == SpeciesContextSpec.ROLE_VelocityY) {
// set advectionCoeff Y element in SpatialParameterPlugin for param
AdvectionCoefficient sbmlAdvCoeffY = new AdvectionCoefficient();
spplugin.setParamType(sbmlAdvCoeffY);
sbmlAdvCoeffY.setVariable(vcSpeciesContexts[i].getName());
sbmlAdvCoeffY.setCoordinate(CoordinateKind.cartesianY);
}
if (role == SpeciesContextSpec.ROLE_VelocityZ) {
// set advectionCoeff Z element in SpatialParameterPlugin for param
AdvectionCoefficient sbmlAdvCoeffZ = new AdvectionCoefficient();
spplugin.setParamType(sbmlAdvCoeffZ);
sbmlAdvCoeffZ.setVariable(vcSpeciesContexts[i].getName());
sbmlAdvCoeffZ.setCoordinate(CoordinateKind.cartesianZ);
}
}
// if sbmlParam != null
}
// if scsParams[j] != null
}
// end for scsParams
}
// end scsParams != null
}
// end if (bSpatial)
// Add the common name of species to annotation, and add an annotation element to the species.
// This is required later while trying to read in fluxes ...
// new Element(XMLTags.VCellRelatedInfoTag, sbml_vcml_ns);
Element sbmlImportRelatedElement = null;
// Element speciesElement = new Element(XMLTags.SpeciesTag, sbml_vcml_ns);
// speciesElement.setAttribute(XMLTags.NameAttrTag, TokenMangler.mangleToSName(vcSpeciesContexts[i].getSpecies().getCommonName()));
// sbmlImportRelatedElement.addContent(speciesElement);
// Get RDF annotation for species from SBMLAnnotationUtils
sbmlAnnotationUtil.writeAnnotation(vcSpeciesContexts[i].getSpecies(), sbmlSpecies, sbmlImportRelatedElement);
// Now set notes,
sbmlAnnotationUtil.writeNotes(vcSpeciesContexts[i].getSpecies(), sbmlSpecies);
}
}
use of org.sbml.jsbml.Compartment 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
// }
}
use of org.sbml.jsbml.Compartment in project vcell by virtualcell.
the class SBMLImporter method addSpecies.
protected void addSpecies(VCMetaData metaData) {
if (sbmlModel == null) {
throw new SBMLImportException("SBML model is NULL");
}
ListOf listOfSpecies = sbmlModel.getListOfSpecies();
if (listOfSpecies == null) {
System.out.println("No Spcecies");
return;
}
HashMap<String, Species> vcSpeciesHash = new HashMap<String, Species>();
HashMap<Species, org.sbml.jsbml.Species> vc_sbmlSpeciesHash = new HashMap<Species, org.sbml.jsbml.Species>();
SpeciesContext[] vcSpeciesContexts = new SpeciesContext[(int) sbmlModel.getNumSpecies()];
// Get species from SBMLmodel; Add/get speciesContext
try {
// First pass - add the speciesContexts
for (int i = 0; i < sbmlModel.getNumSpecies(); i++) {
org.sbml.jsbml.Species sbmlSpecies = (org.sbml.jsbml.Species) listOfSpecies.get(i);
// Sometimes, the species name can be null or a blank string; in
// that case, use species id as the name.
String speciesName = sbmlSpecies.getId();
Species vcSpecies = null;
// create a species with speciesName as commonName. If it is
// different in the annotation, can change it later
Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlSpecies);
if (sbmlImportRelatedElement != null) {
Element embeddedElement = getEmbeddedElementInAnnotation(sbmlImportRelatedElement, SPECIES_NAME);
if (embeddedElement != null) {
// species.
if (embeddedElement.getName().equals(XMLTags.SpeciesTag)) {
String vcSpeciesName = embeddedElement.getAttributeValue(XMLTags.NameAttrTag);
vcSpecies = vcSpeciesHash.get(vcSpeciesName);
if (vcSpecies == null) {
vcSpecies = new Species(vcSpeciesName, vcSpeciesName);
vcSpeciesHash.put(vcSpeciesName, vcSpecies);
}
}
// if embedded element is not speciesTag, do I have to
// do something?
} else {
// Annotation element is present, but doesn't contain
// the species element.
vcSpecies = new Species(speciesName, speciesName);
vcSpeciesHash.put(speciesName, vcSpecies);
}
} else {
vcSpecies = new Species(speciesName, speciesName);
vcSpeciesHash.put(speciesName, vcSpecies);
}
// store vc & sbml species in hash to read in annotation later
vc_sbmlSpeciesHash.put(vcSpecies, sbmlSpecies);
// Get matching compartment name (of sbmlSpecies[i]) from
// feature list
String compartmentId = sbmlSpecies.getCompartment();
Structure spStructure = vcBioModel.getSimulationContext(0).getModel().getStructure(compartmentId);
vcSpeciesContexts[i] = new SpeciesContext(vcSpecies, spStructure);
vcSpeciesContexts[i].setName(speciesName);
// Adjust units of species, convert to VC units.
// Units in SBML, compute this using some of the attributes of
// sbmlSpecies
Compartment sbmlCompartment = sbmlModel.getCompartment(sbmlSpecies.getCompartment());
int dimension = 3;
if (sbmlCompartment.isSetSpatialDimensions()) {
dimension = (int) sbmlCompartment.getSpatialDimensions();
}
if (dimension == 0 || dimension == 1) {
logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.UnitError, dimension + " dimensional compartment " + compartmentId + " not supported");
}
}
// end - for sbmlSpecies
// set the species & speciesContexts on model
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
vcModel.setSpecies(vcSpeciesHash.values().toArray(new Species[0]));
vcModel.setSpeciesContexts(vcSpeciesContexts);
// Set annotations and notes from SBML to VCMetadata
Species[] vcSpeciesArray = vc_sbmlSpeciesHash.keySet().toArray(new Species[0]);
for (Species vcSpecies : vcSpeciesArray) {
org.sbml.jsbml.Species sbmlSpecies = vc_sbmlSpeciesHash.get(vcSpecies);
sbmlAnnotationUtil.readAnnotation(vcSpecies, sbmlSpecies);
sbmlAnnotationUtil.readNotes(vcSpecies, sbmlSpecies);
}
} catch (ModelPropertyVetoException e) {
throw new SBMLImportException("Error adding species context; " + e.getMessage(), e);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Error adding species context; " + e.getMessage(), e);
}
}
use of org.sbml.jsbml.Compartment in project vcell by virtualcell.
the class SBMLImporter method getReactionStructure.
/**
* getReactionStructure :
*/
private Structure getReactionStructure(org.sbml.jsbml.Reaction sbmlRxn, SpeciesContext[] speciesContexts, Element sbmlImportElement) throws Exception {
Structure struct = null;
String structName = null;
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
// return structure from vcmodel, if present.
if (bSpatial) {
structName = sbmlRxn.getCompartment();
if (structName != null && structName.length() > 0) {
struct = vcModel.getStructure(structName);
if (struct != null) {
return struct;
}
}
}
// If annotation has structure name, return the corresponding structure.
if (sbmlImportElement != null) {
// Get the embedded element in the annotation str (fluxStep or
// simpleReaction), and the structure attribute from the element.
Element embeddedElement = getEmbeddedElementInAnnotation(sbmlImportElement, REACTION);
if (embeddedElement != null) {
structName = embeddedElement.getAttributeValue(XMLTags.StructureAttrTag);
// Using the structName, get the structure from the structures
// (compartments) list.
struct = vcModel.getStructure(structName);
return struct;
}
}
if (sbmlRxn.isSetKineticLaw()) {
// String rxnName = sbmlRxn.getId();
KineticLaw kLaw = sbmlRxn.getKineticLaw();
Expression kRateExp = getExpressionFromFormula(kLaw.getMath());
String[] symbols = kRateExp.getSymbols();
if (symbols != null) {
for (String symbol : symbols) {
Compartment sbmlCompartment = sbmlModel.getCompartment(symbol);
if (sbmlCompartment != null) {
return vcBioModel.getSimulationContext(0).getModel().getStructure(sbmlCompartment.getId());
}
}
}
}
HashSet<String> refSpeciesNameHash = new HashSet<String>();
getReferencedSpecies(sbmlRxn, refSpeciesNameHash);
java.util.Iterator<String> refSpIterator = refSpeciesNameHash.iterator();
HashSet<String> compartmentNamesHash = new HashSet<String>();
while (refSpIterator.hasNext()) {
String spName = refSpIterator.next();
String rxnCompartmentName = sbmlModel.getSpecies(spName).getCompartment();
compartmentNamesHash.add(rxnCompartmentName);
}
if (compartmentNamesHash.size() == 1) {
struct = vcModel.getStructure(compartmentNamesHash.iterator().next());
return struct;
} else if (compartmentNamesHash.size() == 0) {
struct = vcModel.getStructures()[0];
return struct;
} else {
// more than one structure in reaction participants, try to figure
// out which one to choose
HashMap<String, Integer> structureFrequencyHash = new HashMap<String, Integer>();
for (String structureName : compartmentNamesHash) {
if (structureFrequencyHash.containsKey(structureName)) {
structureFrequencyHash.put(structureName, structureFrequencyHash.get(structName) + 1);
} else {
structureFrequencyHash.put(structureName, 1);
}
}
Iterator<Entry<String, Integer>> iterator = structureFrequencyHash.entrySet().iterator();
Entry<String, Integer> mostUsedStructureEntry = iterator.next();
while (iterator.hasNext()) {
Entry<String, Integer> currentStructureEntry = iterator.next();
if (currentStructureEntry.getValue() > mostUsedStructureEntry.getValue()) {
mostUsedStructureEntry = currentStructureEntry;
}
}
String mostUsedStructureName = mostUsedStructureEntry.getKey();
struct = vcModel.getStructure(mostUsedStructureName);
return struct;
}
}
use of org.sbml.jsbml.Compartment in project vcell by virtualcell.
the class SBMLImporter method createSBMLUnitSystemForVCModel.
private ModelUnitSystem createSBMLUnitSystemForVCModel() throws Exception {
if (sbmlModel == null) {
throw new SBMLImportException("SBML model is NULL");
}
ListOf listofUnitDefns = sbmlModel.getListOfUnitDefinitions();
if (listofUnitDefns == null) {
System.out.println("No Unit Definitions");
// @TODO: deal with SBML level < 3.
return ModelUnitSystem.createDefaultVCModelUnitSystem();
}
@SuppressWarnings("serial") VCUnitSystem tempVCUnitSystem = new VCUnitSystem() {
};
sbmlUnitIdentifierHash = new HashMap<String, VCUnitDefinition>();
// add base SI unit identifiers (as defined in SBML spec) to hash
sbmlUnitIdentifierHash.put("ampere", tempVCUnitSystem.getInstance("A"));
sbmlUnitIdentifierHash.put("avogadro", tempVCUnitSystem.getInstance("6.02e23"));
// sbmlUnitIdentifierHash.put("becquerel",
// tempVCUnitSystem.getInstance("becquerel"));
// sbmlUnitIdentifierHash.put("candela",
// tempVCUnitSystem.getInstance("candela"));
sbmlUnitIdentifierHash.put("coulomb", tempVCUnitSystem.getInstance("C"));
sbmlUnitIdentifierHash.put("dimensionless", tempVCUnitSystem.getInstance("1"));
sbmlUnitIdentifierHash.put("farad", tempVCUnitSystem.getInstance("F"));
sbmlUnitIdentifierHash.put("gram", tempVCUnitSystem.getInstance("g"));
// sbmlUnitIdentifierHash.put("gray",
// tempVCUnitSystem.getInstance("gray"));
sbmlUnitIdentifierHash.put("henry", tempVCUnitSystem.getInstance("H"));
sbmlUnitIdentifierHash.put("hertz", tempVCUnitSystem.getInstance("Hz"));
sbmlUnitIdentifierHash.put("item", tempVCUnitSystem.getInstance("molecules"));
sbmlUnitIdentifierHash.put("joule", tempVCUnitSystem.getInstance("J"));
// sbmlUnitIdentifierHash.put("katal",
// tempVCUnitSystem.getInstance("katal"));
sbmlUnitIdentifierHash.put("kelvin", tempVCUnitSystem.getInstance("K"));
sbmlUnitIdentifierHash.put("kilogram", tempVCUnitSystem.getInstance("kg"));
sbmlUnitIdentifierHash.put("litre", tempVCUnitSystem.getInstance("litre"));
// sbmlUnitIdentifierHash.put("lumen",
// tempVCUnitSystem.getInstance("lumen"));
// sbmlUnitIdentifierHash.put("lux",
// tempVCUnitSystem.getInstance("lux"));
sbmlUnitIdentifierHash.put("metre", tempVCUnitSystem.getInstance("m"));
sbmlUnitIdentifierHash.put("mole", tempVCUnitSystem.getInstance("mol"));
sbmlUnitIdentifierHash.put("newton", tempVCUnitSystem.getInstance("N"));
// sbmlUnitIdentifierHash.put("ohm",
// tempVCUnitSystem.getInstance("ohm"));
// sbmlUnitIdentifierHash.put("pascal",
// tempVCUnitSystem.getInstance("pascal"));
// sbmlUnitIdentifierHash.put("radian",
// tempVCUnitSystem.getInstance("radian"));
sbmlUnitIdentifierHash.put("second", tempVCUnitSystem.getInstance("s"));
sbmlUnitIdentifierHash.put("siemens", tempVCUnitSystem.getInstance("S"));
// sbmlUnitIdentifierHash.put("sievert",
// tempVCUnitSystem.getInstance("sievert"));
// sbmlUnitIdentifierHash.put("steradian",
// tempVCUnitSystem.getInstance("steradian"));
// sbmlUnitIdentifierHash.put("tesla",
// tempVCUnitSystem.getInstance("tesla"));
sbmlUnitIdentifierHash.put("volt", tempVCUnitSystem.getInstance("V"));
sbmlUnitIdentifierHash.put("watt", tempVCUnitSystem.getInstance("W"));
sbmlUnitIdentifierHash.put("weber", tempVCUnitSystem.getInstance("Wb"));
long sbmlLevel = sbmlModel.getLevel();
if (sbmlLevel < 3) {
// SBML predefined unit identifiers
sbmlUnitIdentifierHash.put(UnitDefinition.SUBSTANCE, tempVCUnitSystem.getInstance("mole"));
sbmlUnitIdentifierHash.put(UnitDefinition.VOLUME, tempVCUnitSystem.getInstance("litre"));
sbmlUnitIdentifierHash.put(UnitDefinition.AREA, tempVCUnitSystem.getInstance("m2"));
sbmlUnitIdentifierHash.put(UnitDefinition.LENGTH, tempVCUnitSystem.getInstance("m"));
sbmlUnitIdentifierHash.put(UnitDefinition.TIME, tempVCUnitSystem.getInstance("s"));
}
if (sbmlModel.isSetSubstanceUnits()) {
UnitDefinition ud = sbmlModel.getSubstanceUnitsInstance();
VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
sbmlUnitIdentifierHash.put(UnitDefinition.SUBSTANCE, vcUnitDef);
}
if (sbmlModel.isSetVolumeUnits()) {
UnitDefinition ud = sbmlModel.getVolumeUnitsInstance();
VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
sbmlUnitIdentifierHash.put(UnitDefinition.VOLUME, vcUnitDef);
}
if (sbmlModel.isSetAreaUnits()) {
UnitDefinition ud = sbmlModel.getAreaUnitsInstance();
VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
sbmlUnitIdentifierHash.put(UnitDefinition.AREA, vcUnitDef);
}
if (sbmlModel.isSetLengthUnits()) {
UnitDefinition ud = sbmlModel.getLengthUnitsInstance();
VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
sbmlUnitIdentifierHash.put(UnitDefinition.LENGTH, vcUnitDef);
}
if (sbmlModel.isSetTimeUnits()) {
UnitDefinition ud = sbmlModel.getTimeUnitsInstance();
VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
sbmlUnitIdentifierHash.put(UnitDefinition.TIME, vcUnitDef);
}
// read unit definition (identifiers) declared in SBML model
for (int i = 0; i < sbmlModel.getNumUnitDefinitions(); i++) {
UnitDefinition ud = (org.sbml.jsbml.UnitDefinition) listofUnitDefns.get(i);
String unitName = ud.getId();
VCUnitDefinition vcUnitDef = SBMLUnitTranslator.getVCUnitDefinition(ud, tempVCUnitSystem);
sbmlUnitIdentifierHash.put(unitName, vcUnitDef);
}
// For SBML level 2
// default units
VCUnitDefinition defaultSubstanceUnit = sbmlUnitIdentifierHash.get(UnitDefinition.SUBSTANCE);
VCUnitDefinition defaultVolumeUnit = sbmlUnitIdentifierHash.get(UnitDefinition.VOLUME);
VCUnitDefinition defaultAreaUnit = sbmlUnitIdentifierHash.get(UnitDefinition.AREA);
VCUnitDefinition defaultLengthUnit = sbmlUnitIdentifierHash.get(UnitDefinition.LENGTH);
VCUnitDefinition defaultTimeUnit = sbmlUnitIdentifierHash.get(UnitDefinition.TIME);
VCUnitDefinition modelSubstanceUnit = null;
VCUnitDefinition modelVolumeUnit = null;
VCUnitDefinition modelAreaUnit = null;
VCUnitDefinition modelLengthUnit = null;
VCUnitDefinition modelTimeUnit = null;
// units in SBML model
// compartments
ListOf<Compartment> listOfCompartments = sbmlModel.getListOfCompartments();
for (int i = 0; i < listOfCompartments.size(); i++) {
Compartment sbmlComp = listOfCompartments.get(i);
double dim = 3;
if (sbmlComp.isSetSpatialDimensions()) {
dim = sbmlComp.getSpatialDimensions();
}
String unitStr = sbmlComp.getUnits();
VCUnitDefinition sbmlUnitDefinition = null;
if (unitStr != null && unitStr.length() > 0) {
sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
} else {
// applying default unit if not defined for this compartment
if (dim == 3) {
sbmlUnitDefinition = defaultVolumeUnit;
} else if (dim == 2) {
sbmlUnitDefinition = defaultAreaUnit;
} else if (dim == 1) {
sbmlUnitDefinition = defaultLengthUnit;
}
}
if (dim == 3) {
if (sbmlUnitDefinition == null) {
sbmlUnitDefinition = defaultVolumeUnit;
}
if (modelVolumeUnit == null) {
modelVolumeUnit = sbmlUnitDefinition;
} else if (!sbmlUnitDefinition.isEquivalent(modelVolumeUnit)) {
localIssueList.add(new Issue(new SBMLIssueSource(sbmlComp), issueContext, IssueCategory.Units, "unit for compartment '" + sbmlComp.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current vol unit (" + modelVolumeUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.ErrorType.UnitError, "unit for compartment '" +
// sbmlComp.getId() + "' (" + unitStr + ") : (" +
// sbmlUnitDefinition.getSymbol() +
// ") not compatible with current vol unit (" +
// modelVolumeUnit.getSymbol() + ")");
}
} else if (dim == 2) {
if (modelAreaUnit == null) {
modelAreaUnit = sbmlUnitDefinition;
} else if (!sbmlUnitDefinition.isEquivalent(modelAreaUnit)) {
localIssueList.add(new Issue(new SBMLIssueSource(sbmlComp), issueContext, IssueCategory.Units, "unit for compartment '" + sbmlComp.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current area unit (" + modelAreaUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.ErrorType.UnitError, "unit for compartment '" +
// sbmlComp.getId() + "' (" + unitStr + ") : (" +
// sbmlUnitDefinition.getSymbol() +
// ") not compatible with current area unit (" +
// modelAreaUnit.getSymbol() + ")");
}
}
}
// species
ListOf<org.sbml.jsbml.Species> listOfSpecies = sbmlModel.getListOfSpecies();
for (int i = 0; i < listOfSpecies.size(); i++) {
org.sbml.jsbml.Species sbmlSpecies = listOfSpecies.get(i);
String unitStr = sbmlSpecies.getSubstanceUnits();
VCUnitDefinition sbmlUnitDefinition = null;
if (unitStr != null && unitStr.length() > 0) {
sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
} else {
// apply default substance unit
sbmlUnitDefinition = defaultSubstanceUnit;
}
if (modelSubstanceUnit == null) {
modelSubstanceUnit = sbmlUnitDefinition;
} else if (!sbmlUnitDefinition.isEquivalent(modelSubstanceUnit)) {
localIssueList.add(new Issue(new SBMLIssueSource(sbmlSpecies), issueContext, IssueCategory.Units, "unit for species '" + sbmlSpecies.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current substance unit (" + modelSubstanceUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.ErrorType.UnitError, "unit for species '" +
// sbmlSpecies.getId() + "' (" + unitStr + ") : (" +
// sbmlUnitDefinition.getSymbol() +
// ") not compatible with current substance unit (" +
// modelSubstanceUnit.getSymbol() + ")");
}
}
// reactions for SBML level 2 version < 3
long sbmlVersion = sbmlModel.getVersion();
if (sbmlVersion < 3) {
ListOf<Reaction> listOfReactions = sbmlModel.getListOfReactions();
for (int i = 0; i < listOfReactions.size(); i++) {
Reaction sbmlReaction = listOfReactions.get(i);
KineticLaw kineticLaw = sbmlReaction.getKineticLaw();
if (kineticLaw != null) {
// first check substance unit
String unitStr = kineticLaw.getSubstanceUnits();
VCUnitDefinition sbmlUnitDefinition = null;
if (unitStr != null && unitStr.length() > 0) {
sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
} else {
// apply default substance unit
sbmlUnitDefinition = defaultSubstanceUnit;
}
if (modelSubstanceUnit == null) {
modelSubstanceUnit = sbmlUnitDefinition;
} else if (!sbmlUnitDefinition.isEquivalent(modelSubstanceUnit)) {
localIssueList.add(new Issue(new SBMLIssueSource(sbmlReaction), issueContext, IssueCategory.Units, "substance unit for reaction '" + sbmlReaction.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current substance unit (" + modelSubstanceUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.ErrorType.UnitError,
// "substance unit for reaction '" +
// sbmlReaction.getId() + "' (" + unitStr + ") : (" +
// sbmlUnitDefinition.getSymbol() +
// ") not compatible with current substance unit (" +
// modelSubstanceUnit.getSymbol() + ")");
}
// check time unit
unitStr = kineticLaw.getTimeUnits();
if (unitStr != null && unitStr.length() > 0) {
sbmlUnitDefinition = sbmlUnitIdentifierHash.get(unitStr);
} else {
// apply default time unit
sbmlUnitDefinition = defaultTimeUnit;
}
if (modelTimeUnit == null) {
modelTimeUnit = sbmlUnitDefinition;
} else if (!sbmlUnitDefinition.isEquivalent(modelTimeUnit)) {
localIssueList.add(new Issue(new SBMLIssueSource(sbmlReaction), issueContext, IssueCategory.Units, "time unit for reaction '" + sbmlReaction.getId() + "' (" + unitStr + ") : (" + sbmlUnitDefinition.getSymbol() + ") not compatible with current time unit (" + modelTimeUnit.getSymbol() + ")", Issue.SEVERITY_WARNING));
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.ErrorType.UnitError,
// "time unit for reaction '" + sbmlReaction.getId() +
// "' (" + unitStr + ") : (" +
// sbmlUnitDefinition.getSymbol() +
// ") not compatible with current time unit (" +
// modelTimeUnit.getSymbol() + ")");
}
}
}
}
if (modelSubstanceUnit == null) {
modelSubstanceUnit = defaultSubstanceUnit;
}
if (modelVolumeUnit == null) {
modelVolumeUnit = defaultVolumeUnit;
}
if (modelAreaUnit == null) {
modelAreaUnit = defaultAreaUnit;
}
if (modelLengthUnit == null) {
modelLengthUnit = defaultLengthUnit;
}
if (modelTimeUnit == null) {
modelTimeUnit = defaultTimeUnit;
}
if (modelSubstanceUnit == null && modelVolumeUnit == null && modelAreaUnit == null && modelLengthUnit == null && modelTimeUnit == null) {
// default (VC)modelUnitSystem
return ModelUnitSystem.createDefaultVCModelUnitSystem();
} else {
return ModelUnitSystem.createSBMLUnitSystem(modelSubstanceUnit, modelVolumeUnit, modelAreaUnit, modelLengthUnit, modelTimeUnit);
}
}
Aggregations