use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.
the class SmoldynFileWriter method writeCompartments.
private void writeCompartments() throws ImageException, PropertyVetoException, GeometryException, ExpressionException {
MeshSpecification meshSpecification = simulation.getMeshSpecification();
ISize sampleSize = meshSpecification.getSamplingSize();
int numX = sampleSize.getX();
int numY = dimension < 2 ? 1 : sampleSize.getY();
int numZ = dimension < 3 ? 1 : sampleSize.getZ();
int numXY = numX * numY;
boolean bCellCentered = simulation.hasCellCenteredMesh();
double dx = meshSpecification.getDx(bCellCentered);
double dy = meshSpecification.getDy(bCellCentered);
double dz = meshSpecification.getDz(bCellCentered);
Origin origin = resampledGeometry.getGeometrySpec().getOrigin();
printWriter.println("# compartments");
resampledGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
for (SubVolume subVolume : resampledGeometry.getGeometrySpec().getSubVolumes()) {
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.start_compartment + " " + subVolume.getName());
for (SurfaceClass sc : resampledGeometry.getGeometrySurfaceDescription().getSurfaceClasses()) {
if (sc.getAdjacentSubvolumes().contains(subVolume)) {
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.surface + " " + sc.getName());
}
}
if (boundaryXSubVolumes.contains(subVolume)) {
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.surface + " " + VCellSmoldynKeyword.bounding_wall_surface_X);
}
if (dimension > 1) {
if (boundaryYSubVolumes.contains(subVolume)) {
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.surface + " " + VCellSmoldynKeyword.bounding_wall_surface_Y);
}
if (dimension > 2) {
if (boundaryZSubVolumes.contains(subVolume)) {
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.surface + " " + VCellSmoldynKeyword.bounding_wall_surface_Z);
}
}
}
// if (DEBUG) {
// tmppw.println("points" + pointsCount + "=[");
// pointsCount ++;
// }
// gather all the points in all the regions
Geometry interiorPointGeometry = RayCaster.resampleGeometry(new GeometryThumbnailImageFactoryAWT(), resampledGeometry, resampledGeometry.getGeometrySurfaceDescription().getVolumeSampleSize());
SubVolume interiorPointSubVolume = interiorPointGeometry.getGeometrySpec().getSubVolume(subVolume.getName());
GeometricRegion[] geometricRegions = interiorPointGeometry.getGeometrySurfaceDescription().getGeometricRegions(interiorPointSubVolume);
RegionInfo[] regionInfos = interiorPointGeometry.getGeometrySurfaceDescription().getRegionImage().getRegionInfos();
for (GeometricRegion geometricRegion : geometricRegions) {
VolumeGeometricRegion volumeGeometricRegion = (VolumeGeometricRegion) geometricRegion;
ArrayList<SelectPoint> selectPointList = new ArrayList<SelectPoint>();
for (RegionInfo regionInfo : regionInfos) {
if (regionInfo.getRegionIndex() != volumeGeometricRegion.getRegionID()) {
continue;
}
int volIndex = 0;
for (int k = 0; k < numZ; k++) {
for (int j = 0; j < numY; j++) {
int starti = -1;
int endi = 0;
for (int i = 0; i < numX; i++, volIndex++) {
boolean bInRegion = false;
if (regionInfo.isIndexInRegion(volIndex)) {
bInRegion = true;
if (starti == -1) {
starti = i;
endi = i;
} else {
endi++;
}
}
if ((!bInRegion || i == numX - 1) && starti != -1) {
int midi = (endi + starti) / 2;
int midVolIndex = k * numXY + j * numX + midi;
boolean bOnBoundary = false;
int[] neighbors = { j == 0 ? -1 : midVolIndex - numX, j == numY - 1 ? -1 : midVolIndex + numX, k == 0 ? -1 : midVolIndex - numXY, k == numZ - 1 ? -1 : midVolIndex + numXY };
for (int n = 0; n < 2 * (dimension - 1); n++) {
if (neighbors[n] == -1 || !regionInfo.isIndexInRegion(neighbors[n])) {
bOnBoundary = true;
break;
}
}
if (!bOnBoundary) {
selectPointList.add(new SelectPoint(starti, endi, j, k));
}
starti = -1;
}
}
// end i
}
// end j
}
// end k
}
for (int m = 0; m < selectPointList.size(); m++) {
SelectPoint thisPoint = selectPointList.get(m);
boolean bPrint = true;
for (int n = 0; n < selectPointList.size(); n++) {
if (n == m) {
continue;
}
SelectPoint point = selectPointList.get(n);
if (thisPoint.k == point.k && Math.abs(thisPoint.j - point.j) == 1 || thisPoint.j == point.j && Math.abs(thisPoint.k - point.k) == 1) {
if (point.same(thisPoint) && m < n) {
// found same one later, print the later one
bPrint = false;
break;
}
if (point.contains(thisPoint) && point.length() < 2 * thisPoint.length()) {
// found a longer one, but not too much longer
bPrint = false;
break;
}
}
}
if (bPrint) {
int midi = (thisPoint.starti + thisPoint.endi) / 2;
double coordX = origin.getX() + dx * midi;
printWriter.print(SmoldynVCellMapper.SmoldynKeyword.point + " " + coordX);
if (dimension > 1) {
double coordY = origin.getY() + dy * thisPoint.j;
printWriter.print(" " + coordY);
if (dimension > 2) {
double coordZ = origin.getZ() + dz * thisPoint.k;
printWriter.print(" " + coordZ);
}
}
printWriter.println();
}
}
}
// end for (GeometricRegion
printWriter.println(SmoldynVCellMapper.SmoldynKeyword.end_compartment);
printWriter.println();
}
// end for (SubVolume
}
use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.
the class SmoldynFileWriter method init.
private void init() throws SolverException {
simulation = simTask.getSimulation();
mathDesc = simulation.getMathDescription();
simulationSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
particleVariableList = new ArrayList<ParticleVariable>();
Variable[] variables = simulationSymbolTable.getVariables();
for (Variable variable : variables) {
if (variable instanceof ParticleVariable) {
if (variable.getDomain() == null) {
throw new SolverException("Particle Variables are required to be defined in a subdomain using syntax Subdomain::Variable.");
}
particleVariableList.add((ParticleVariable) variable);
}
}
// write geometry
Geometry geometry = mathDesc.getGeometry();
dimension = geometry.getDimension();
try {
// clone and resample geometry
resampledGeometry = (Geometry) BeanUtils.cloneSerializable(geometry);
GeometrySurfaceDescription geoSurfaceDesc = resampledGeometry.getGeometrySurfaceDescription();
ISize newSize = simulation.getMeshSpecification().getSamplingSize();
geoSurfaceDesc.setVolumeSampleSize(newSize);
geoSurfaceDesc.updateAll();
bHasNoSurface = geoSurfaceDesc.getSurfaceClasses() == null || geoSurfaceDesc.getSurfaceClasses().length == 0;
} catch (Exception e) {
e.printStackTrace();
throw new SolverException(e.getMessage());
}
if (!bGraphicOpenGL) {
writeMeshFile();
}
colors = ColorUtil.generateAutoColor(particleVariableList.size() + resampledGeometry.getGeometrySurfaceDescription().getSurfaceClasses().length, bg, new Integer(5));
}
use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.
the class SBMLImporter method getBioModel.
// /**
// * @ TODO: This method doesn't take care of adjusting species in nested
// parameter rules with the species_concetration_factor.
// * @param kinetics
// * @param paramExpr
// * @throws ExpressionException
// */
// private void substituteOtherGlobalParams(Kinetics kinetics, Expression
// paramExpr) throws ExpressionException, PropertyVetoException {
// String[] exprSymbols = paramExpr.getSymbols();
// if (exprSymbols == null || exprSymbols.length == 0) {
// return;
// }
// Model vcModel = vcBioModel.getSimulationContext(0).getModel();
// for (int kk = 0; kk < exprSymbols.length; kk++) {
// ModelParameter mp = vcModel.getModelParameter(exprSymbols[kk]);
// if (mp != null) {
// Expression expr = mp.getExpression();
// if (expr != null) {
// Expression newExpr = new Expression(expr);
// substituteGlobalParamRulesInPlace(newExpr, false);
// // param has constant value, add it as a kinetic parameter if it is not
// already in the kinetics
// kinetics.setParameterValue(exprSymbols[kk], newExpr.infix());
// kinetics.getKineticsParameter(exprSymbols[kk]).setUnitDefinition(getSBMLUnit(sbmlModel.getParameter(exprSymbols[kk]).getUnits(),
// null));
// if (newExpr.getSymbols() != null) {
// substituteOtherGlobalParams(kinetics, newExpr);
// }
// }
// }
// }
// }
/**
* parse SBML file into biomodel logs errors to log4j if present in source
* document
*
* @return new Biomodel
* @throws IOException
* @throws XMLStreamException
*/
public BioModel getBioModel() throws XMLStreamException, IOException {
SBMLDocument document;
String output = "didn't check";
try {
if (sbmlFileName != null) {
// Read SBML model into libSBML SBMLDocument and create an SBML model
SBMLReader reader = new SBMLReader();
document = reader.readSBML(sbmlFileName);
// document.checkConsistencyOffline();
// long numProblems = document.getNumErrors();
//
// System.out.println("\n\nSBML Import Error Report");
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// PrintStream ps = new PrintStream(os);
// document.printErrors(ps);
// String output = os.toString();
// if (numProblems > 0 && lg.isEnabledFor(Level.WARN)) {
// lg.warn("Num problems in original SBML document : " + numProblems);
// lg.warn(output);
// }
sbmlModel = document.getModel();
if (sbmlModel == null) {
throw new SBMLImportException("Unable to read SBML file : \n" + output);
}
} else {
if (sbmlModel == null) {
throw new IllegalStateException("Expected non-null SBML model");
}
document = sbmlModel.getSBMLDocument();
}
// Convert SBML Model to VCell model
// An SBML model will correspond to a simcontext - which needs a
// Model and a Geometry
// SBML handles only nonspatial geometries at this time, hence
// creating a non-spatial default geometry
String modelName = sbmlModel.getId();
if (modelName == null || modelName.trim().equals("")) {
modelName = sbmlModel.getName();
}
// name, say 'newModel'
if (modelName == null || modelName.trim().equals("")) {
modelName = "newModel";
}
// get namespace based on SBML model level and version to use in
// SBMLAnnotationUtil
this.level = sbmlModel.getLevel();
// this.version = sbmlModel.getVersion();
String ns = document.getNamespace();
try {
// create SBML unit system for the model and create the bioModel.
ModelUnitSystem modelUnitSystem;
try {
modelUnitSystem = createSBMLUnitSystemForVCModel();
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Inconsistent unit system. Cannot import SBML model into VCell", Category.INCONSISTENT_UNIT, e);
}
Geometry geometry = new Geometry(BioModelChildSummary.COMPARTMENTAL_GEO_STR, 0);
vcBioModel = new BioModel(null, modelUnitSystem);
SimulationContext simulationContext = new SimulationContext(vcBioModel.getModel(), geometry, null, null, Application.NETWORK_DETERMINISTIC);
vcBioModel.addSimulationContext(simulationContext);
simulationContext.setName(vcBioModel.getSimulationContext(0).getModel().getName());
// vcBioModel.getSimulationContext(0).setName(vcBioModel.getSimulationContext(0).getModel().getName()+"_"+vcBioModel.getSimulationContext(0).getGeometry().getName());
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Could not create simulation context corresponding to the input SBML model", e);
}
// SBML annotation
sbmlAnnotationUtil = new SBMLAnnotationUtil(vcBioModel.getVCMetaData(), vcBioModel, ns);
translateSBMLModel();
try {
// **** TEMPORARY BLOCK - to name the biomodel with proper name,
// rather than model id
String biomodelName = sbmlModel.getName();
// if name is not set, use id
if ((biomodelName == null) || biomodelName.trim().equals("")) {
biomodelName = sbmlModel.getId();
}
// if id is not set, use a default, say, 'newModel'
if ((biomodelName == null) || biomodelName.trim().equals("")) {
biomodelName = "newBioModel";
}
vcBioModel.setName(biomodelName);
// **** end - TEMPORARY BLOCK
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Could not create Biomodel", e);
}
sbmlAnnotationUtil.readAnnotation(vcBioModel, sbmlModel);
sbmlAnnotationUtil.readNotes(vcBioModel, sbmlModel);
vcBioModel.refreshDependencies();
Issue[] warningIssues = localIssueList.toArray(new Issue[localIssueList.size()]);
if (warningIssues != null && warningIssues.length > 0) {
StringBuffer messageBuffer = new StringBuffer("Issues encountered during SBML Import:\n");
int issueCount = 0;
for (int i = 0; i < warningIssues.length; i++) {
if (warningIssues[i].getSeverity() == Issue.SEVERITY_WARNING || warningIssues[i].getSeverity() == Issue.SEVERITY_INFO) {
messageBuffer.append(warningIssues[i].getCategory() + " " + warningIssues[i].getSeverityName() + " : " + warningIssues[i].getMessage() + "\n");
issueCount++;
}
}
if (issueCount > 0) {
try {
logger.sendMessage(VCLogger.Priority.MediumPriority, VCLogger.ErrorType.OverallWarning, messageBuffer.toString());
} catch (Exception e) {
e.printStackTrace(System.out);
}
// PopupGenerator.showWarningDialog(requester,messageBuffer.toString(),new
// String[] { "OK" }, "OK");
}
}
} catch (Exception e) {
throw new SBMLImportException("Unable to read SBML file : \n" + output, e);
}
return vcBioModel;
}
use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.
the class SBMLImporter method addGeometry.
protected void addGeometry() {
// get a Geometry object via SpatialModelPlugin object.
org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = getSbmlGeometry();
if (sbmlGeometry == null) {
return;
}
int dimension = 0;
Origin vcOrigin = null;
Extent vcExtent = null;
{
// local code block
// get a CoordComponent object via the Geometry object.
ListOf<CoordinateComponent> listOfCoordComps = sbmlGeometry.getListOfCoordinateComponents();
if (listOfCoordComps == null) {
throw new RuntimeException("Cannot have 0 coordinate compartments in geometry");
}
// coord component
double ox = 0.0;
double oy = 0.0;
double oz = 0.0;
double ex = 1.0;
double ey = 1.0;
double ez = 1.0;
for (CoordinateComponent coordComponent : listOfCoordComps) {
double minValue = coordComponent.getBoundaryMinimum().getValue();
double maxValue = coordComponent.getBoundaryMaximum().getValue();
switch(coordComponent.getType()) {
case cartesianX:
{
ox = minValue;
ex = maxValue - minValue;
break;
}
case cartesianY:
{
oy = minValue;
ey = maxValue - minValue;
break;
}
case cartesianZ:
{
oz = minValue;
ez = maxValue - minValue;
break;
}
}
dimension++;
}
vcOrigin = new Origin(ox, oy, oz);
vcExtent = new Extent(ex, ey, ez);
}
// from geometry definition, find out which type of geometry : image or
// analytic or CSG
AnalyticGeometry analyticGeometryDefinition = null;
CSGeometry csGeometry = null;
SampledFieldGeometry segmentedSampledFieldGeometry = null;
SampledFieldGeometry distanceMapSampledFieldGeometry = null;
ParametricGeometry parametricGeometry = null;
for (int i = 0; i < sbmlGeometry.getListOfGeometryDefinitions().size(); i++) {
GeometryDefinition gd_temp = sbmlGeometry.getListOfGeometryDefinitions().get(i);
if (!gd_temp.isSetIsActive()) {
continue;
}
if (gd_temp instanceof AnalyticGeometry) {
analyticGeometryDefinition = (AnalyticGeometry) gd_temp;
} else if (gd_temp instanceof SampledFieldGeometry) {
SampledFieldGeometry sfg = (SampledFieldGeometry) gd_temp;
String sfn = sfg.getSampledField();
ListOf<SampledField> sampledFields = sbmlGeometry.getListOfSampledFields();
if (sampledFields.size() > 1) {
throw new RuntimeException("only one sampled field supported");
}
InterpolationKind ik = sampledFields.get(0).getInterpolationType();
switch(ik) {
case linear:
distanceMapSampledFieldGeometry = sfg;
break;
case nearestneighbor:
segmentedSampledFieldGeometry = sfg;
break;
default:
lg.warn("Unsupported " + sampledFields.get(0).getName() + " interpolation type " + ik);
}
} else if (gd_temp instanceof CSGeometry) {
csGeometry = (CSGeometry) gd_temp;
} else if (gd_temp instanceof ParametricGeometry) {
parametricGeometry = (ParametricGeometry) gd_temp;
} else {
throw new RuntimeException("unsupported geometry definition type " + gd_temp.getClass().getSimpleName());
}
}
if (analyticGeometryDefinition == null && segmentedSampledFieldGeometry == null && distanceMapSampledFieldGeometry == null && csGeometry == null) {
throw new SBMLImportException("VCell supports only Analytic, Image based (segmentd or distance map) or Constructed Solid Geometry at this time.");
}
GeometryDefinition selectedGeometryDefinition = null;
if (csGeometry != null) {
selectedGeometryDefinition = csGeometry;
} else if (analyticGeometryDefinition != null) {
selectedGeometryDefinition = analyticGeometryDefinition;
} else if (segmentedSampledFieldGeometry != null) {
selectedGeometryDefinition = segmentedSampledFieldGeometry;
} else if (distanceMapSampledFieldGeometry != null) {
selectedGeometryDefinition = distanceMapSampledFieldGeometry;
} else if (parametricGeometry != null) {
selectedGeometryDefinition = parametricGeometry;
} else {
throw new SBMLImportException("no geometry definition found");
}
Geometry vcGeometry = null;
if (selectedGeometryDefinition == analyticGeometryDefinition || selectedGeometryDefinition == csGeometry) {
vcGeometry = new Geometry("spatialGeom", dimension);
} else if (selectedGeometryDefinition == distanceMapSampledFieldGeometry || selectedGeometryDefinition == segmentedSampledFieldGeometry) {
SampledFieldGeometry sfg = (SampledFieldGeometry) selectedGeometryDefinition;
// get image from sampledFieldGeometry
// get a sampledVol object via the listOfSampledVol (from
// SampledGeometry) object.
// gcw gcw gcw
String sfn = sfg.getSampledField();
SampledField sf = null;
for (SampledField sampledField : sbmlGeometry.getListOfSampledFields()) {
if (sampledField.getSpatialId().equals(sfn)) {
sf = sampledField;
}
}
int numX = sf.getNumSamples1();
int numY = sf.getNumSamples2();
int numZ = sf.getNumSamples3();
int[] samples = new int[sf.getSamplesLength()];
StringTokenizer tokens = new StringTokenizer(sf.getSamples(), " ");
int count = 0;
while (tokens.hasMoreTokens()) {
int sample = Integer.parseInt(tokens.nextToken());
samples[count++] = sample;
}
byte[] imageInBytes = new byte[samples.length];
if (selectedGeometryDefinition == distanceMapSampledFieldGeometry) {
//
for (int i = 0; i < imageInBytes.length; i++) {
// if (interpolation(samples[i])<0){
if (samples[i] < 0) {
imageInBytes[i] = -1;
} else {
imageInBytes[i] = 1;
}
}
} else {
for (int i = 0; i < imageInBytes.length; i++) {
imageInBytes[i] = (byte) samples[i];
}
}
try {
// System.out.println("ident " + sf.getId() + " " + sf.getName());
VCImage vcImage = null;
CompressionKind ck = sf.getCompression();
DataKind dk = sf.getDataType();
if (ck == CompressionKind.deflated) {
vcImage = new VCImageCompressed(null, imageInBytes, vcExtent, numX, numY, numZ);
} else {
switch(dk) {
case UINT8:
case UINT16:
case UINT32:
vcImage = new VCImageUncompressed(null, imageInBytes, vcExtent, numX, numY, numZ);
default:
}
}
if (vcImage == null) {
throw new SbmlException("Unsupported type combination " + ck + ", " + dk + " for sampled field " + sf.getName());
}
vcImage.setName(sf.getId());
ListOf<SampledVolume> sampledVolumes = sfg.getListOfSampledVolumes();
final int numSampledVols = sampledVolumes.size();
if (numSampledVols == 0) {
throw new RuntimeException("Cannot have 0 sampled volumes in sampledField (image_based) geometry");
}
// check to see if values are uniquely integer , add set up scaling if necessary
double scaleFactor = checkPixelScaling(sampledVolumes, 1);
if (scaleFactor != 1) {
double checkScaleFactor = checkPixelScaling(sampledVolumes, scaleFactor);
VCAssert.assertTrue(checkScaleFactor != scaleFactor, "Scale factor check failed");
}
VCPixelClass[] vcpixelClasses = new VCPixelClass[numSampledVols];
// get pixel classes for geometry
for (int i = 0; i < numSampledVols; i++) {
SampledVolume sVol = sampledVolumes.get(i);
// from subVolume, get pixelClass?
final int scaled = (int) (scaleFactor * sVol.getSampledValue());
vcpixelClasses[i] = new VCPixelClass(null, sVol.getDomainType(), scaled);
}
vcImage.setPixelClasses(vcpixelClasses);
// now create image geometry
vcGeometry = new Geometry("spatialGeom", vcImage);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to create image from SampledFieldGeometry : " + e.getMessage());
}
}
GeometrySpec vcGeometrySpec = vcGeometry.getGeometrySpec();
vcGeometrySpec.setOrigin(vcOrigin);
try {
vcGeometrySpec.setExtent(vcExtent);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Unable to set extent on VC geometry : " + e.getMessage(), e);
}
// get listOfDomainTypes via the Geometry object.
ListOf<DomainType> listOfDomainTypes = sbmlGeometry.getListOfDomainTypes();
if (listOfDomainTypes == null || listOfDomainTypes.size() < 1) {
throw new SBMLImportException("Cannot have 0 domainTypes in geometry");
}
// get a listOfDomains via the Geometry object.
ListOf<Domain> listOfDomains = sbmlGeometry.getListOfDomains();
if (listOfDomains == null || listOfDomains.size() < 1) {
throw new SBMLImportException("Cannot have 0 domains in geometry");
}
// ListOfGeometryDefinitions listOfGeomDefns =
// sbmlGeometry.getListOfGeometryDefinitions();
// if ((listOfGeomDefns == null) ||
// (sbmlGeometry.getNumGeometryDefinitions() > 1)) {
// throw new
// RuntimeException("Can have only 1 geometry definition in geometry");
// }
// use the boolean bAnalytic to create the right kind of subvolume.
// First match the somVol=domainTypes for spDim=3. Deal witl spDim=2
// afterwards.
GeometrySurfaceDescription vcGsd = vcGeometry.getGeometrySurfaceDescription();
Vector<DomainType> surfaceClassDomainTypesVector = new Vector<DomainType>();
try {
for (DomainType dt : listOfDomainTypes) {
if (dt.getSpatialDimensions() == 3) {
// subvolume
if (selectedGeometryDefinition == analyticGeometryDefinition) {
// will set expression later - when reading in Analytic
// Volumes in GeometryDefinition
vcGeometrySpec.addSubVolume(new AnalyticSubVolume(dt.getId(), new Expression(1.0)));
} else {
// add SubVolumes later for CSG and Image-based
}
} else if (dt.getSpatialDimensions() == 2) {
surfaceClassDomainTypesVector.add(dt);
}
}
// analytic vol is needed to get the expression for subVols
if (selectedGeometryDefinition == analyticGeometryDefinition) {
// get an analyticVol object via the listOfAnalyticVol (from
// AnalyticGeometry) object.
ListOf<AnalyticVolume> aVolumes = analyticGeometryDefinition.getListOfAnalyticVolumes();
if (aVolumes.size() < 1) {
throw new SBMLImportException("Cannot have 0 Analytic volumes in analytic geometry");
}
for (AnalyticVolume analyticVol : aVolumes) {
// get subVol from VC geometry using analyticVol spatialId;
// set its expr using analyticVol's math.
SubVolume vcSubvolume = vcGeometrySpec.getSubVolume(analyticVol.getDomainType());
CastInfo<AnalyticSubVolume> ci = BeanUtils.attemptCast(AnalyticSubVolume.class, vcSubvolume);
if (!ci.isGood()) {
throw new RuntimeException("analytic volume '" + analyticVol.getId() + "' does not map to any VC subvolume.");
}
AnalyticSubVolume asv = ci.get();
try {
Expression subVolExpr = getExpressionFromFormula(analyticVol.getMath());
asv.setExpression(subVolExpr);
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Unable to set expression on subVolume '" + asv.getName() + "'. " + e.getMessage(), e);
}
}
}
SampledFieldGeometry sfg = BeanUtils.downcast(SampledFieldGeometry.class, selectedGeometryDefinition);
if (sfg != null) {
ListOf<SampledVolume> sampledVolumes = sfg.getListOfSampledVolumes();
int numSampledVols = sampledVolumes.size();
if (numSampledVols == 0) {
throw new SBMLImportException("Cannot have 0 sampled volumes in sampledField (image_based) geometry");
}
VCPixelClass[] vcpixelClasses = new VCPixelClass[numSampledVols];
ImageSubVolume[] vcImageSubVols = new ImageSubVolume[numSampledVols];
// get pixel classes for geometry
int idx = 0;
for (SampledVolume sVol : sampledVolumes) {
// from subVolume, get pixelClass?
final String name = sVol.getDomainType();
final int pixelValue = SBMLUtils.ignoreZeroFraction(sVol.getSampledValue());
VCPixelClass pc = new VCPixelClass(null, name, pixelValue);
vcpixelClasses[idx] = pc;
// Create the new Image SubVolume - use index of this for
// loop as 'handle' for ImageSubVol?
ImageSubVolume isv = new ImageSubVolume(null, pc, idx);
isv.setName(name);
vcImageSubVols[idx++] = isv;
}
vcGeometry.getGeometrySpec().setSubVolumes(vcImageSubVols);
}
if (selectedGeometryDefinition == csGeometry) {
ListOf<org.sbml.jsbml.ext.spatial.CSGObject> listOfcsgObjs = csGeometry.getListOfCSGObjects();
ArrayList<org.sbml.jsbml.ext.spatial.CSGObject> sbmlCSGs = new ArrayList<org.sbml.jsbml.ext.spatial.CSGObject>(listOfcsgObjs);
// we want the CSGObj with highest ordinal to be the first
// element in the CSG subvols array.
Collections.sort(sbmlCSGs, new Comparator<org.sbml.jsbml.ext.spatial.CSGObject>() {
@Override
public int compare(org.sbml.jsbml.ext.spatial.CSGObject lhs, org.sbml.jsbml.ext.spatial.CSGObject rhs) {
// minus one to reverse sort
return -1 * Integer.compare(lhs.getOrdinal(), rhs.getOrdinal());
}
});
int n = sbmlCSGs.size();
CSGObject[] vcCSGSubVolumes = new CSGObject[n];
for (int i = 0; i < n; i++) {
org.sbml.jsbml.ext.spatial.CSGObject sbmlCSGObject = sbmlCSGs.get(i);
CSGObject vcellCSGObject = new CSGObject(null, sbmlCSGObject.getDomainType(), i);
vcellCSGObject.setRoot(getVCellCSGNode(sbmlCSGObject.getCSGNode()));
}
vcGeometry.getGeometrySpec().setSubVolumes(vcCSGSubVolumes);
}
// Call geom.geomSurfDesc.updateAll() to automatically generate
// surface classes.
// vcGsd.updateAll();
vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, true);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Unable to create VC subVolumes from SBML domainTypes : " + e.getMessage(), e);
}
// should now map each SBML domain to right VC geometric region.
GeometricRegion[] vcGeomRegions = vcGsd.getGeometricRegions();
ISize sampleSize = vcGsd.getVolumeSampleSize();
RegionInfo[] regionInfos = vcGsd.getRegionImage().getRegionInfos();
int numX = sampleSize.getX();
int numY = sampleSize.getY();
int numZ = sampleSize.getZ();
double ox = vcOrigin.getX();
double oy = vcOrigin.getY();
double oz = vcOrigin.getZ();
for (Domain domain : listOfDomains) {
String domainType = domain.getDomainType();
InteriorPoint interiorPt = domain.getListOfInteriorPoints().get(0);
if (interiorPt == null) {
DomainType currDomainType = null;
for (DomainType dt : sbmlGeometry.getListOfDomainTypes()) {
if (dt.getSpatialId().equals(domainType)) {
currDomainType = dt;
}
}
if (currDomainType.getSpatialDimensions() == 2) {
continue;
}
}
Coordinate sbmlInteriorPtCoord = new Coordinate(interiorPt.getCoord1(), interiorPt.getCoord2(), interiorPt.getCoord3());
for (int j = 0; j < vcGeomRegions.length; j++) {
if (vcGeomRegions[j] instanceof VolumeGeometricRegion) {
int regionID = ((VolumeGeometricRegion) vcGeomRegions[j]).getRegionID();
for (int k = 0; k < regionInfos.length; k++) {
// (using gemoRegion regionID).
if (regionInfos[k].getRegionIndex() == regionID) {
int volIndx = 0;
Coordinate nearestPtCoord = null;
double minDistance = Double.MAX_VALUE;
// represented by SBML 'domain[i]'.
for (int z = 0; z < numZ; z++) {
for (int y = 0; y < numY; y++) {
for (int x = 0; x < numX; x++) {
if (regionInfos[k].isIndexInRegion(volIndx)) {
double unit_z = (numZ > 1) ? ((double) z) / (numZ - 1) : 0.5;
double coordZ = oz + vcExtent.getZ() * unit_z;
double unit_y = (numY > 1) ? ((double) y) / (numY - 1) : 0.5;
double coordY = oy + vcExtent.getY() * unit_y;
double unit_x = (numX > 1) ? ((double) x) / (numX - 1) : 0.5;
double coordX = ox + vcExtent.getX() * unit_x;
// for now, find the shortest dist
// coord. Can refine algo later.
Coordinate vcCoord = new Coordinate(coordX, coordY, coordZ);
double distance = sbmlInteriorPtCoord.distanceTo(vcCoord);
if (distance < minDistance) {
minDistance = distance;
nearestPtCoord = vcCoord;
}
}
volIndx++;
}
// end - for x
}
// end - for y
}
// with domain name
if (nearestPtCoord != null) {
GeometryClass geomClassSBML = vcGeometry.getGeometryClass(domainType);
// we know vcGeometryReg[j] is a VolGeomRegion
GeometryClass geomClassVC = ((VolumeGeometricRegion) vcGeomRegions[j]).getSubVolume();
if (geomClassSBML.compareEqual(geomClassVC)) {
vcGeomRegions[j].setName(domain.getId());
}
}
}
// end if (regInfoIndx = regId)
}
// end - for regInfo
}
}
// end for - vcGeomRegions
}
// deal with surfaceClass:spDim2-domainTypes
for (int i = 0; i < surfaceClassDomainTypesVector.size(); i++) {
DomainType surfaceClassDomainType = surfaceClassDomainTypesVector.elementAt(i);
// 'surfaceClassDomainType'
for (Domain d : listOfDomains) {
if (d.getDomainType().equals(surfaceClassDomainType.getId())) {
// get the adjacent domains of this 'surface' domain
// (surface domain + its 2 adj vol domains)
Set<Domain> adjacentDomainsSet = getAssociatedAdjacentDomains(sbmlGeometry, d);
// get the domain types of the adjacent domains in SBML and
// store the corresponding subVol counterparts from VC for
// adj vol domains
Vector<SubVolume> adjacentSubVolumesVector = new Vector<SubVolume>();
Vector<VolumeGeometricRegion> adjVolGeomRegionsVector = new Vector<VolumeGeometricRegion>();
Iterator<Domain> iterator = adjacentDomainsSet.iterator();
while (iterator.hasNext()) {
Domain dom = iterator.next();
DomainType dt = getBySpatialID(sbmlGeometry.getListOfDomainTypes(), dom.getDomainType());
if (dt.getSpatialDimensions() == 3) {
// for domain type with sp. dim = 3, get
// correspoinding subVol from VC geometry.
GeometryClass gc = vcGeometry.getGeometryClass(dt.getId());
adjacentSubVolumesVector.add((SubVolume) gc);
// store volGeomRegions corresponding to this (vol)
// geomClass in adjVolGeomRegionsVector : this
// should return ONLY 1 region for subVol.
GeometricRegion[] geomRegion = vcGsd.getGeometricRegions(gc);
adjVolGeomRegionsVector.add((VolumeGeometricRegion) geomRegion[0]);
}
}
// there should be only 2 subVols in this vector
if (adjacentSubVolumesVector.size() != 2) {
throw new RuntimeException("Cannot have more or less than 2 subvolumes that are adjacent to surface (membrane) '" + d.getId() + "'");
}
// get the surface class with these 2 adj subVols. Set its
// name to that of 'surfaceClassDomainType'
SurfaceClass surfacClass = vcGsd.getSurfaceClass(adjacentSubVolumesVector.get(0), adjacentSubVolumesVector.get(1));
surfacClass.setName(surfaceClassDomainType.getSpatialId());
// get surfaceGeometricRegion that has adjVolGeomRegions as
// its adjacent vol geom regions and set its name from
// domain 'd'
SurfaceGeometricRegion surfaceGeomRegion = getAssociatedSurfaceGeometricRegion(vcGsd, adjVolGeomRegionsVector);
if (surfaceGeomRegion != null) {
surfaceGeomRegion.setName(d.getId());
}
}
// end if - domain.domainType == surfaceClassDomainType
}
// end for - numDomains
}
// structureMappings in VC from compartmentMappings in SBML
try {
// set geometry first and then set structureMappings?
vcBioModel.getSimulationContext(0).setGeometry(vcGeometry);
// update simContextName ...
vcBioModel.getSimulationContext(0).setName(vcBioModel.getSimulationContext(0).getName() + "_" + vcGeometry.getName());
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
ModelUnitSystem vcModelUnitSystem = vcModel.getUnitSystem();
Vector<StructureMapping> structMappingsVector = new Vector<StructureMapping>();
SpatialCompartmentPlugin cplugin = null;
for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
Compartment c = sbmlModel.getCompartment(i);
String cname = c.getName();
cplugin = (SpatialCompartmentPlugin) c.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
CompartmentMapping compMapping = cplugin.getCompartmentMapping();
if (compMapping != null) {
// final String id = compMapping.getId();
// final String name = compMapping.getName();
CastInfo<Structure> ci = SBMLHelper.getTypedStructure(Structure.class, vcModel, cname);
if (ci.isGood()) {
Structure struct = ci.get();
String domainType = compMapping.getDomainType();
GeometryClass geometryClass = vcGeometry.getGeometryClass(domainType);
double unitSize = compMapping.getUnitSize();
Feature feat = BeanUtils.downcast(Feature.class, struct);
if (feat != null) {
FeatureMapping featureMapping = new FeatureMapping(feat, vcBioModel.getSimulationContext(0), vcModelUnitSystem);
featureMapping.setGeometryClass(geometryClass);
if (geometryClass instanceof SubVolume) {
featureMapping.getVolumePerUnitVolumeParameter().setExpression(new Expression(unitSize));
} else if (geometryClass instanceof SurfaceClass) {
featureMapping.getVolumePerUnitAreaParameter().setExpression(new Expression(unitSize));
}
structMappingsVector.add(featureMapping);
} else if (struct instanceof Membrane) {
MembraneMapping membraneMapping = new MembraneMapping((Membrane) struct, vcBioModel.getSimulationContext(0), vcModelUnitSystem);
membraneMapping.setGeometryClass(geometryClass);
if (geometryClass instanceof SubVolume) {
membraneMapping.getAreaPerUnitVolumeParameter().setExpression(new Expression(unitSize));
} else if (geometryClass instanceof SurfaceClass) {
membraneMapping.getAreaPerUnitAreaParameter().setExpression(new Expression(unitSize));
}
structMappingsVector.add(membraneMapping);
}
}
}
}
StructureMapping[] structMappings = structMappingsVector.toArray(new StructureMapping[0]);
vcBioModel.getSimulationContext(0).getGeometryContext().setStructureMappings(structMappings);
// if type from SBML parameter Boundary Condn is not the same as the
// boundary type of the
// structureMapping of structure of paramSpContext, set the boundary
// condn type of the structureMapping
// to the value of 'type' from SBML parameter Boundary Condn.
ListOf<Parameter> listOfGlobalParams = sbmlModel.getListOfParameters();
for (Parameter sbmlGlobalParam : sbmlModel.getListOfParameters()) {
SpatialParameterPlugin spplugin = (SpatialParameterPlugin) sbmlGlobalParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
ParameterType paramType = spplugin.getParamType();
if (!(paramType instanceof BoundaryCondition)) {
continue;
}
BoundaryCondition bCondn = (BoundaryCondition) paramType;
if (bCondn.isSetVariable()) {
// get the var of boundaryCondn; find appropriate spContext
// in vcell;
SpeciesContext paramSpContext = vcBioModel.getSimulationContext(0).getModel().getSpeciesContext(bCondn.getVariable());
if (paramSpContext != null) {
Structure s = paramSpContext.getStructure();
StructureMapping sm = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(s);
if (sm != null) {
BoundaryConditionType bct = null;
switch(bCondn.getType()) {
case Dirichlet:
{
bct = BoundaryConditionType.DIRICHLET;
break;
}
case Neumann:
{
bct = BoundaryConditionType.NEUMANN;
break;
}
case Robin_inwardNormalGradientCoefficient:
case Robin_sum:
case Robin_valueCoefficient:
default:
throw new RuntimeException("boundary condition type " + bCondn.getType().name() + " not supported");
}
for (CoordinateComponent coordComp : getSbmlGeometry().getListOfCoordinateComponents()) {
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMinimum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
sm.setBoundaryConditionTypeXm(bct);
}
case cartesianY:
{
sm.setBoundaryConditionTypeYm(bct);
}
case cartesianZ:
{
sm.setBoundaryConditionTypeZm(bct);
}
}
}
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMaximum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
sm.setBoundaryConditionTypeXm(bct);
}
case cartesianY:
{
sm.setBoundaryConditionTypeYm(bct);
}
case cartesianZ:
{
sm.setBoundaryConditionTypeZm(bct);
}
}
}
}
} else // sm != null
{
logger.sendMessage(VCLogger.Priority.MediumPriority, VCLogger.ErrorType.OverallWarning, "No structure " + s.getName() + " requested by species context " + paramSpContext.getName());
}
}
// end if (paramSpContext != null)
}
// end if (bCondn.isSetVar())
}
// end for (sbmlModel.numParams)
vcBioModel.getSimulationContext(0).getGeometryContext().refreshStructureMappings();
vcBioModel.getSimulationContext(0).refreshSpatialObjects();
} catch (Exception e) {
e.printStackTrace(System.out);
throw new SBMLImportException("Unable to create VC structureMappings from SBML compartment mappings : " + e.getMessage(), e);
}
}
use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.
the class ClientRequestManager method newDocument.
/**
* Insert the method's description here.
* Creation date: (5/21/2004 4:20:47 AM)
* @param documentType int
*/
public AsynchClientTask[] newDocument(TopLevelWindowManager requester, final VCDocument.DocumentCreationInfo documentCreationInfo) {
// gcwtodo
AsynchClientTask createNewDocumentTask = new AsynchClientTask("Creating New Document", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
VCDocument doc = (VCDocument) hashTable.get("doc");
DocumentWindowManager windowManager = createDocumentWindowManager(doc);
DocumentWindow dw = getMdiManager().createNewDocumentWindow(windowManager);
if (windowManager != null) {
hashTable.put("windowManager", windowManager);
}
setFinalWindow(hashTable, dw);
}
};
if (documentCreationInfo.getDocumentType() == VCDocumentType.MATHMODEL_DOC && documentCreationInfo.getOption() == VCDocument.MATH_OPTION_SPATIAL_NEW) {
final AsynchClientTask createSpatialMathModelTask = new AsynchClientTask("creating mathmodel", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
Geometry geometry = null;
geometry = (Geometry) hashTable.get("doc");
MathModel mathModel = createMathModel("Untitled", geometry);
mathModel.setName("MathModel" + (getMdiManager().getNumCreatedDocumentWindows() + 1));
hashTable.put("doc", mathModel);
}
};
requester.createGeometry(null, new AsynchClientTask[] { createSpatialMathModelTask, createNewDocumentTask }, "Choose geometry type to start MathModel creation", "Create MathModel", null);
return null;
}
/* asynchronous and not blocking any window */
AsynchClientTask[] taskArray = null;
if (documentCreationInfo.getPreCreatedDocument() == null) {
AsynchClientTask[] taskArray1 = createNewDocument(requester, documentCreationInfo);
taskArray = new AsynchClientTask[taskArray1.length + 1];
System.arraycopy(taskArray1, 0, taskArray, 0, taskArray1.length);
} else {
taskArray = new AsynchClientTask[2];
taskArray[0] = new AsynchClientTask("Setting document...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
hashTable.put("doc", documentCreationInfo.getPreCreatedDocument());
}
};
}
taskArray[taskArray.length - 1] = createNewDocumentTask;
return taskArray;
}
Aggregations