use of cbit.vcell.geometry.SurfaceClass in project vcell by virtualcell.
the class StructureSizeSolver method updateUnitStructureSizes.
/**
* Insert the method's description here.
* Creation date: (5/17/2006 10:33:38 AM)
* @return double[]
* @param structName java.lang.String
* @param structSize double
*/
public static void updateUnitStructureSizes(SimulationContext simContext, GeometryClass geometryClass) {
if (simContext.getGeometryContext().getGeometry().getDimension() == 0) {
return;
}
StructureMapping[] myStructMappings = simContext.getGeometryContext().getStructureMappings(geometryClass);
if (myStructMappings != null && myStructMappings.length == 1) {
// if the unitSizeParameter is dimensionless, then features are mapped to SubVolumes or Membranes are mapped to surfaces (should sum to 1)
boolean bDimensionless = myStructMappings[0].getUnitSizeParameter().getUnitDefinition().isEquivalent(simContext.getModel().getUnitSystem().getInstance_DIMENSIONLESS());
if (bDimensionless) {
try {
myStructMappings[0].getUnitSizeParameter().setExpression(new Expression(1.0));
return;
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
}
}
}
if (myStructMappings != null && myStructMappings.length == 0) {
// nothing to solve, there are no mappings for this geometryClass
return;
}
StructureMapping[] structMappings = simContext.getGeometryContext().getStructureMappings();
try {
ConstraintContainerImpl ccImpl = new ConstraintContainerImpl();
Structure struct = null;
Expression totalVolExpr = new Expression(0.0);
StructureTopology structureTopology = simContext.getModel().getStructureTopology();
for (int i = 0; i < structMappings.length; i++) {
if (structMappings[i].getGeometryClass() != geometryClass) {
continue;
}
// new model with unit sizes already
if (structMappings[i].getUnitSizeParameter() != null && structMappings[i].getUnitSizeParameter().getExpression() != null) {
return;
}
if (struct == null) {
struct = structMappings[i].getStructure();
}
if (structMappings[i] instanceof MembraneMapping) {
MembraneMapping membraneMapping = (MembraneMapping) structMappings[i];
Membrane membrane = membraneMapping.getMembrane();
String membraneSizeName = TokenMangler.mangleToSName(membrane.getName() + "_size");
ccImpl.addSimpleBound(new SimpleBounds(membraneSizeName, new RealInterval(0, 100000), AbstractConstraint.PHYSICAL_LIMIT, "definition"));
Feature insideFeature = structureTopology.getInsideFeature(membrane);
String volFractName = TokenMangler.mangleToSName(insideFeature.getName() + "_volFract");
String svRatioName = TokenMangler.mangleToSName(insideFeature.getName() + "_svRatio");
StructureMapping.StructureMappingParameter volFractParameter = membraneMapping.getVolumeFractionParameter();
double volFractValue = volFractParameter.getExpression().evaluateConstant();
ccImpl.addSimpleBound(new SimpleBounds(volFractName, new RealInterval(volFractValue, volFractValue), AbstractConstraint.MODELING_ASSUMPTION, "from model"));
StructureMapping.StructureMappingParameter surfToVolParameter = membraneMapping.getSurfaceToVolumeParameter();
double svRatioValue = surfToVolParameter.getExpression().evaluateConstant();
ccImpl.addSimpleBound(new SimpleBounds(svRatioName, new RealInterval(svRatioValue, svRatioValue), AbstractConstraint.MODELING_ASSUMPTION, "from model"));
// membrane mapped to volume
if (geometryClass instanceof SubVolume) {
//
// EC eclosing cyt, which contains er and golgi
// "(cyt_size+ er_size + golgi_size) * cyt_svRatio - PM_size == 0"
//
Expression sumOfInsideVolumeExp = new Expression(0.0);
for (int j = 0; j < structMappings.length; j++) {
if (structMappings[j] instanceof FeatureMapping && structureTopology.enclosedBy(structMappings[j].getStructure(), insideFeature)) {
Feature childFeatureOfInside = ((FeatureMapping) structMappings[j]).getFeature();
if (simContext.getGeometryContext().getStructureMapping(childFeatureOfInside).getGeometryClass() == geometryClass) {
sumOfInsideVolumeExp = Expression.add(sumOfInsideVolumeExp, new Expression(TokenMangler.mangleToSName(childFeatureOfInside.getName() + "_size")));
}
}
}
Expression tempExpr = Expression.mult(sumOfInsideVolumeExp, new Expression(svRatioName));
tempExpr = Expression.add(tempExpr, new Expression("-" + membraneSizeName));
ccImpl.addGeneralConstraint(new GeneralConstraint(new Expression(tempExpr.infix() + "==0"), AbstractConstraint.MODELING_ASSUMPTION, "svRatio definition"));
//
// EC eclosing cyt, which contains er and golgi
// (EC_size + cyt_size + er_size + golgi_size) * cyt_vfRatio - (cyt_size + er_size + golgi_size) == 0
//
Feature outsideFeature = structureTopology.getOutsideFeature(membrane);
Expression sumOfParentVolumeExp = new Expression(0.0);
for (int j = 0; j < structMappings.length; j++) {
if (structMappings[j] instanceof FeatureMapping && structureTopology.enclosedBy(structMappings[j].getStructure(), outsideFeature)) {
Feature childFeatureOfParent = ((FeatureMapping) structMappings[j]).getFeature();
if (simContext.getGeometryContext().getStructureMapping(childFeatureOfParent).getGeometryClass() == geometryClass) {
sumOfParentVolumeExp = Expression.add(sumOfParentVolumeExp, new Expression(TokenMangler.mangleToSName(childFeatureOfParent.getName() + "_size")));
}
}
}
Expression exp = Expression.mult(sumOfParentVolumeExp, new Expression(volFractName));
exp = Expression.add(exp, Expression.negate(sumOfInsideVolumeExp));
ccImpl.addGeneralConstraint(new GeneralConstraint(new Expression(exp.infix() + "==0.0"), AbstractConstraint.MODELING_ASSUMPTION, "volFract definition"));
}
} else if (structMappings[i] instanceof FeatureMapping) {
FeatureMapping featureMapping = (FeatureMapping) structMappings[i];
String featureSizeName = TokenMangler.mangleToSName(featureMapping.getFeature().getName() + "_size");
totalVolExpr = Expression.add(totalVolExpr, new Expression(featureSizeName));
ccImpl.addSimpleBound(new SimpleBounds(featureSizeName, new RealInterval(0, 1), AbstractConstraint.PHYSICAL_LIMIT, "definition"));
}
}
if (geometryClass instanceof SubVolume) {
ccImpl.addGeneralConstraint(new GeneralConstraint(new Expression(totalVolExpr.infix() + "==1.0"), AbstractConstraint.MODELING_ASSUMPTION, "total volume"));
}
// ccImpl.show();
ConstraintSolver constraintSolver = new ConstraintSolver(ccImpl);
constraintSolver.resetIntervals();
int numTimesNarrowed = 0;
RealInterval[] lastSolution = null;
boolean bChanged = true;
while (constraintSolver.narrow() && bChanged && numTimesNarrowed < 125) {
numTimesNarrowed++;
bChanged = false;
RealInterval[] thisSolution = constraintSolver.getIntervals();
if (lastSolution != null) {
for (int i = 0; i < thisSolution.length; i++) {
if (!thisSolution[i].equals(lastSolution[i])) {
bChanged = true;
}
}
} else {
bChanged = true;
}
lastSolution = thisSolution;
}
System.out.println("num of times narrowed = " + numTimesNarrowed);
if (numTimesNarrowed > 0) {
String[] symbols = constraintSolver.getSymbols();
net.sourceforge.interval.ia_math.RealInterval[] solution = constraintSolver.getIntervals();
double totalArea = 0;
double totalVolume = 0;
for (int i = 0; i < symbols.length; i++) {
System.out.println("solution[" + i + "] \"" + symbols[i] + "\" = " + solution[i]);
for (int j = 0; j < structMappings.length; j++) {
if (symbols[i].equals(TokenMangler.mangleToSName(structMappings[j].getStructure().getName() + "_size"))) {
if (!Double.isInfinite(solution[i].lo()) && !Double.isInfinite(solution[i].hi())) {
double value = (solution[i].lo() + solution[i].hi()) / 2;
Expression exp = new Expression(value);
if (structMappings[j] instanceof FeatureMapping) {
FeatureMapping fm = (FeatureMapping) structMappings[j];
totalVolume += value;
if (geometryClass instanceof SubVolume) {
fm.getVolumePerUnitVolumeParameter().setExpression(exp);
} else if (geometryClass instanceof SurfaceClass) {
fm.getVolumePerUnitAreaParameter().setExpression(exp);
}
} else if (structMappings[j] instanceof MembraneMapping) {
MembraneMapping mm = (MembraneMapping) structMappings[j];
totalArea += value;
if (geometryClass instanceof SubVolume) {
mm.getAreaPerUnitVolumeParameter().setExpression(exp);
} else if (geometryClass instanceof SurfaceClass) {
mm.getAreaPerUnitAreaParameter().setExpression(exp);
}
}
}
}
}
}
//
// normalize all so that total volume is 1.0 for subVolumes or
// total area is 1.0 for surfaceClasses
//
double scaleFactor = 1;
if (geometryClass instanceof SubVolume) {
scaleFactor = totalVolume;
} else if (geometryClass instanceof SurfaceClass) {
scaleFactor = totalArea;
} else {
throw new RuntimeException("unexpected GeometryClass");
}
for (int j = 0; j < structMappings.length; j++) {
if (structMappings[j].getGeometryClass() == geometryClass) {
if (structMappings[j] instanceof FeatureMapping) {
FeatureMapping fm = (FeatureMapping) structMappings[j];
if (geometryClass instanceof SubVolume) {
fm.getVolumePerUnitVolumeParameter().setExpression(new Expression(fm.getVolumePerUnitVolumeParameter().getExpression().evaluateConstant() / scaleFactor));
} else if (geometryClass instanceof SurfaceClass) {
fm.getVolumePerUnitAreaParameter().setExpression(new Expression(fm.getVolumePerUnitAreaParameter().getExpression().evaluateConstant() / scaleFactor));
}
} else if (structMappings[j] instanceof MembraneMapping) {
MembraneMapping mm = (MembraneMapping) structMappings[j];
if (geometryClass instanceof SubVolume) {
mm.getAreaPerUnitVolumeParameter().setExpression(new Expression(mm.getAreaPerUnitVolumeParameter().getExpression().evaluateConstant() / scaleFactor));
} else if (geometryClass instanceof SurfaceClass) {
mm.getAreaPerUnitAreaParameter().setExpression(new Expression(mm.getAreaPerUnitAreaParameter().getExpression().evaluateConstant() / scaleFactor));
}
}
}
}
} else {
throw new RuntimeException("cannot solve for size");
}
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
}
}
use of cbit.vcell.geometry.SurfaceClass in project vcell by virtualcell.
the class ComsolModelBuilder method getVCCModel.
public static VCCModel getVCCModel(SimulationJob vcellSimJob) throws ExpressionException {
MathDescription vcellMathDesc = vcellSimJob.getSimulation().getMathDescription();
Geometry vcellGeometry = vcellMathDesc.getGeometry();
GeometrySpec vcellGeometrySpec = vcellGeometry.getGeometrySpec();
int vcellDim = vcellGeometrySpec.getDimension();
VCCModel model = new VCCModel("Model", vcellDim);
model.modelpath = "D:\\Developer\\eclipse\\workspace_refactor\\comsol_java\\src";
model.comments = "Untitled\n\n";
VCCModelNode comp1 = new VCCModelNode("comp1");
model.modelnodes.add(comp1);
// if (vcellDim != 2){
// throw new RuntimeException("expecting 2D simulation");
// }
//
// assume initial geometry is circle centered at 0.5, 0.5 of radius 0.3
//
// String comsolOutsideDomainName = "dif1";
// String comsolInsideDomainName = "c1";
VCCGeomSequence geom1 = new VCCGeomSequence("geom1", vcellDim);
model.geometrysequences.add(geom1);
VCCMeshSequence mesh1 = new VCCMeshSequence("mesh1", geom1);
model.meshes.add(mesh1);
VCCStudy std1 = new VCCStudy("std1");
model.study = std1;
TimeBounds timeBounds = vcellSimJob.getSimulation().getSolverTaskDescription().getTimeBounds();
TimeStep timeStep = vcellSimJob.getSimulation().getSolverTaskDescription().getTimeStep();
String beginTime = Double.toString(timeBounds.getStartingTime());
String endTime = Double.toString(timeBounds.getEndingTime());
String step = Double.toString(timeStep.getDefaultTimeStep());
VCCStudyFeature time = new VCCTransientStudyFeature("time", beginTime, step, endTime);
std1.features.add(time);
if (vcellGeometrySpec.getImage() != null) {
throw new RuntimeException("image-based geometries not yet supported by VCell's COMSOL model builder");
}
if (vcellGeometrySpec.getNumSubVolumes() == 0) {
throw new RuntimeException("no subvolumes defined in geometry");
}
if (vcellGeometrySpec.getNumAnalyticOrCSGSubVolumes() != vcellGeometrySpec.getNumSubVolumes()) {
throw new RuntimeException("only analytic and CSG subvolumes currently supported by VCell's COMSOL model builder");
}
//
// add geometry for all subvolumes
//
HashMap<String, VCCGeomFeature> subvolumeNameFeatureMap = new HashMap<String, VCCGeomFeature>();
SubVolume[] subVolumes = vcellGeometrySpec.getSubVolumes();
for (int i = 0; i < subVolumes.length; i++) {
SubVolume subvolume = subVolumes[i];
if (subvolume instanceof CSGObject) {
CSGObject vcellCSGObject = (CSGObject) subvolume;
CSGNode vcellCSGNode = vcellCSGObject.getRoot();
ArrayList<VCCGeomFeature> geomFeatureList = new ArrayList<VCCGeomFeature>();
VCCGeomFeature feature = csgVisitor(vcellCSGNode, geomFeatureList, subvolume.getName());
geom1.geomfeatures.addAll(geomFeatureList);
if (i == 0) {
// first subvolume (on top in ordinals) doesn't need any differencing
subvolumeNameFeatureMap.put(subvolume.getName(), feature);
} else {
// have to subtract union of prior subvolumes
ArrayList<VCCGeomFeature> priorFeatures = new ArrayList<VCCGeomFeature>();
for (int j = 0; j < i; j++) {
CSGObject priorCSGObject = (CSGObject) subVolumes[j];
CSGNode priorCSGNode = priorCSGObject.getRoot();
geomFeatureList.clear();
VCCGeomFeature priorFeature = csgVisitor(priorCSGNode, geomFeatureList, subvolume.getName());
priorFeatures.add(priorFeature);
geom1.geomfeatures.addAll(geomFeatureList);
}
VCCDifference diff = new VCCDifference("diff" + subvolume.getName(), Keep.off);
diff.input.add(feature);
diff.input2.addAll(priorFeatures);
geom1.geomfeatures.add(diff);
subvolumeNameFeatureMap.put(subvolume.getName(), diff);
}
} else {
throw new RuntimeException("only CSG subvolumes currently supported by VCell's COMSOL model builder");
}
}
//
// add geometry for all surfaceClasses
//
HashMap<String, VCCGeomFeature> surfaceclassNameFeatureMap = new HashMap<String, VCCGeomFeature>();
SurfaceClass[] surfaceClasses = vcellGeometry.getGeometrySurfaceDescription().getSurfaceClasses();
for (int i = 0; i < surfaceClasses.length; i++) {
SurfaceClass surfaceClass = surfaceClasses[i];
Set<SubVolume> adjacentSubvolumes = surfaceClass.getAdjacentSubvolumes();
if (adjacentSubvolumes.size() != 2) {
throw new RuntimeException("expecting two adjacent subvolumes for surface " + surfaceClass.getName() + " in COMSOL model builder");
}
// find adjacent Geometry Features (for subvolumes)
Iterator<SubVolume> svIter = adjacentSubvolumes.iterator();
SubVolume subvolume0 = svIter.next();
SubVolume subvolume1 = svIter.next();
ArrayList<VCCGeomFeature> adjacentFeatures = new ArrayList<VCCGeomFeature>();
adjacentFeatures.add(subvolumeNameFeatureMap.get(subvolume0.getName()));
adjacentFeatures.add(subvolumeNameFeatureMap.get(subvolume1.getName()));
String name = "inter_" + subvolume0.getName() + "_" + subvolume1.getName();
// surfaces are dimension N-1
int entitydim = vcellDim - 1;
VCCIntersectionSelection intersect_subvolumes = new VCCIntersectionSelection(name, entitydim);
intersect_subvolumes.input.addAll(adjacentFeatures);
geom1.geomfeatures.add(intersect_subvolumes);
surfaceclassNameFeatureMap.put(surfaceClass.getName(), intersect_subvolumes);
}
SimulationSymbolTable symbolTable = new SimulationSymbolTable(vcellSimJob.getSimulation(), vcellSimJob.getJobIndex());
//
for (SubDomain subDomain : Collections.list(vcellMathDesc.getSubDomains())) {
for (Equation equ : subDomain.getEquationCollection()) {
if (equ instanceof PdeEquation || equ instanceof OdeEquation) {
VCCGeomFeature geomFeature = null;
final int dim;
if (subDomain instanceof CompartmentSubDomain) {
geomFeature = subvolumeNameFeatureMap.get(subDomain.getName());
dim = vcellDim;
} else if (subDomain instanceof MembraneSubDomain) {
geomFeature = surfaceclassNameFeatureMap.get(subDomain.getName());
dim = vcellDim - 1;
} else {
throw new RuntimeException("subdomains of type '" + subDomain.getClass().getSimpleName() + "' not yet supported in COMSOL model builder");
}
if (geomFeature == null) {
throw new RuntimeException("cannot find COMSOL geometry feature named " + subDomain.getName() + " in COMSOL model builder");
}
VCCConvectionDiffusionEquation cdeq = new VCCConvectionDiffusionEquation("cdeq_" + equ.getVariable().getName(), geom1, geomFeature, dim);
cdeq.fieldName = equ.getVariable().getName();
cdeq.initial = MathUtilities.substituteModelParameters(equ.getInitialExpression(), symbolTable).flatten().infix();
cdeq.sourceTerm_f = MathUtilities.substituteModelParameters(equ.getRateExpression(), symbolTable).flatten().infix();
if (equ instanceof PdeEquation) {
PdeEquation pde = (PdeEquation) equ;
cdeq.diffTerm_c = MathUtilities.substituteModelParameters(pde.getDiffusionExpression(), symbolTable).flatten().infix();
if (subDomain instanceof CompartmentSubDomain) {
CompartmentSubDomain compartmentSubdomain = (CompartmentSubDomain) subDomain;
ArrayList<String> be = new ArrayList<String>();
if (pde.getVelocityX() != null) {
be.add(MathUtilities.substituteModelParameters(pde.getVelocityX(), symbolTable).flatten().infix());
} else {
be.add("0");
}
if (vcellDim >= 2) {
if (pde.getVelocityY() != null) {
be.add(MathUtilities.substituteModelParameters(pde.getVelocityY(), symbolTable).flatten().infix());
} else {
be.add("0");
}
}
if (vcellDim == 3) {
if (pde.getVelocityY() != null) {
be.add(MathUtilities.substituteModelParameters(pde.getVelocityZ(), symbolTable).flatten().infix());
} else {
be.add("0");
}
}
cdeq.advection_be = be.toArray(new String[vcellDim]);
//
// look for membrane boundary conditions for this variable
//
MembraneSubDomain[] membraneSubdomains = vcellMathDesc.getMembraneSubDomains(compartmentSubdomain);
for (MembraneSubDomain membraneSubdomain : membraneSubdomains) {
JumpCondition jumpCondition = membraneSubdomain.getJumpCondition((VolVariable) pde.getVariable());
if (jumpCondition != null) {
Expression fluxExpr = null;
if (membraneSubdomain.getInsideCompartment() == compartmentSubdomain) {
fluxExpr = jumpCondition.getInFluxExpression();
} else if (membraneSubdomain.getOutsideCompartment() == compartmentSubdomain) {
fluxExpr = jumpCondition.getOutFluxExpression();
}
String name = equ.getVariable().getName() + "_flux_" + membraneSubdomain.getName();
VCCGeomFeature selection = surfaceclassNameFeatureMap.get(membraneSubdomain.getName());
VCCFluxBoundary fluxBoundary = new VCCFluxBoundary(name, selection, vcellDim - 1);
fluxBoundary.flux_g = MathUtilities.substituteModelParameters(fluxExpr, symbolTable).flatten().infix();
cdeq.features.add(fluxBoundary);
}
}
}
}
model.physics.add(cdeq);
}
}
}
//
return model;
}
use of cbit.vcell.geometry.SurfaceClass in project vcell by virtualcell.
the class BioModelTest method getExampleWithImage.
/**
* Insert the method's description here.
* Creation date: (11/14/00 5:56:41 PM)
* @return cbit.vcell.biomodel.BioModel
*/
public static BioModel getExampleWithImage() throws Exception {
BioModel bioModel = new BioModel(null);
bioModel.setName("bioModel_" + Integer.toHexString(((new Random()).nextInt())));
//
// add SimulationContexts
//
SimulationContext sc1 = cbit.vcell.mapping.SimulationContextTest.getExample(2);
sc1.setName("simContext1_" + Integer.toHexString(((new Random()).nextInt())));
bioModel.setModel(sc1.getModel());
Model model = bioModel.getModel();
model.setName("physiology_" + Integer.toHexString(((new Random()).nextInt())));
Geometry geo = GeometryTest.getImageExample2D();
geo.setName("Image_Geometry_" + Integer.toHexString(((new Random()).nextInt())));
geo.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, false);
SimulationContext sc2 = new SimulationContext(model, geo);
GeometryContext geoContext = sc2.getGeometryContext();
Structure structure_ec = model.getStructure("extracellular");
SubVolume subVolume_cytosol = geo.getGeometrySpec().getSubVolume("cytosol");
geoContext.assignStructure(structure_ec, subVolume_cytosol);
geoContext.getStructureMapping(structure_ec).getUnitSizeParameter().setExpression(new Expression(1.0));
Structure structure_cyt = model.getStructure("cytosol");
SubVolume subVolume_er = geo.getGeometrySpec().getSubVolume("er");
geoContext.assignStructure(structure_cyt, subVolume_er);
geoContext.getStructureMapping(structure_cyt).getUnitSizeParameter().setExpression(new Expression(0.5));
Structure structure_er = model.getStructure("er");
geoContext.assignStructure(structure_er, subVolume_er);
geoContext.getStructureMapping(structure_er).getUnitSizeParameter().setExpression(new Expression(0.5));
Structure structure_pm = model.getStructure("plasmaMembrane");
SurfaceClass surfaceClass_erMem = geoContext.getGeometry().getGeometrySurfaceDescription().getSurfaceClass(subVolume_cytosol, subVolume_er);
geoContext.assignStructure(structure_pm, surfaceClass_erMem);
geoContext.getStructureMapping(structure_pm).getUnitSizeParameter().setExpression(new Expression(1.0));
Structure structure_erMem = model.getStructure("erMembrane");
geoContext.assignStructure(structure_erMem, subVolume_er);
geoContext.getStructureMapping(structure_erMem).getUnitSizeParameter().setExpression(new Expression(2.4));
bioModel.setSimulationContexts(new SimulationContext[] { /*sc1,*/
sc2 });
sc2.setName("simContext2_" + Integer.toHexString(((new Random()).nextInt())));
// sc1.setMathDescription(sc1.createNewMathMapping().getMathDescription());
sc2.setMathDescription(sc2.createNewMathMapping().getMathDescription());
//
// add simulations (must be after
//
Simulation sim1 = new Simulation(sc2.getMathDescription());
sim1.setName("sim1_" + Integer.toHexString(((new Random()).nextInt())));
Simulation sim2 = new Simulation(sc2.getMathDescription());
sim2.setName("sim2_" + Integer.toHexString(((new Random()).nextInt())));
bioModel.setSimulations(new Simulation[] { sim1, sim2 });
return bioModel;
}
use of cbit.vcell.geometry.SurfaceClass in project vcell by virtualcell.
the class ServerDocumentManager method saveBioModel.
/**
* Insert the method's description here.
* Creation date: (10/28/00 12:08:30 AM)
*/
public String saveBioModel(QueryHashtable dbc, User user, String bioModelXML, String newName, String[] independentSims) throws DataAccessException, java.sql.SQLException, java.beans.PropertyVetoException, MappingException, cbit.vcell.xml.XmlParseException {
long start = System.currentTimeMillis();
//
// this invokes "update" on the database layer
//
BioModel bioModel = XmlHelper.XMLToBioModel(new XMLSource(bioModelXML));
forceDeepDirtyIfForeign(user, bioModel);
boolean isSaveAsNew = true;
//
if (newName != null) {
try {
bioModel.setName(newName);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new DataAccessException("couldn't set new name for BioModel: " + e.getMessage());
}
} else {
isSaveAsNew = false;
}
Version oldVersion = bioModel.getVersion();
BioModel origBioModel = null;
if (oldVersion != null) {
try {
String origBioModelXML = getBioModelXML(dbc, user, oldVersion.getVersionKey(), false);
origBioModel = XmlHelper.XMLToBioModel(new XMLSource(origBioModelXML));
} catch (ObjectNotFoundException nfe) {
if (isSaveAsNew) {
User foceClearVersionUser = new User("foceClearVersionUser", new KeyValue("0"));
forceDeepDirtyIfForeign(foceClearVersionUser, bioModel);
} else {
throw new DataAccessException("Stored model has been changed or removed, please use 'Save As..'");
}
}
}
boolean bSomethingChanged = false;
//
// verify that there are no orphaned Simulations (that belonged to Applications that have null mathDescriptions ... incomplete mappings)
//
// the workspace is responsible for cleaning up Simulations
//
{
Simulation[] sims = bioModel.getSimulations();
SimulationContext[] scs = bioModel.getSimulationContexts();
for (int i = 0; sims != null && i < sims.length; i++) {
boolean bFound = false;
for (int j = 0; scs != null && j < scs.length; j++) {
if (scs[j].getMathDescription() == sims[i].getMathDescription()) {
bFound = true;
}
}
if (!bFound) {
throw new RuntimeException("Error: Simulation " + sims[i].getName() + " cannot be saved, no Application exists with same MathDescription");
}
}
}
//
// UPDATE AND SUBSTITUTE FROM BOTTOM UP
//
// Image->Geometry
// Geometry->SimContext,MathDescription
// MathDescription->Simulation,SimulationContext
// Model->BioModel
// Simulation->BioModel
// SimContext->BioModel
// VCMetaData->BioModel
//
Simulation[] simArray = bioModel.getSimulations();
SimulationContext[] scArray = bioModel.getSimulationContexts();
// Hashtable mathEquivHash = new Hashtable();
long roundtripTimer = 0;
long l1 = 0;
long l2 = 0;
//
// for each image (anywhere in document):
// save if necessary (only once) and store saved instance in hashTable
//
Hashtable<Versionable, Versionable> memoryToDatabaseHash = new Hashtable<Versionable, Versionable>();
for (int i = 0; scArray != null && i < scArray.length; i++) {
VCImage memoryImage = scArray[i].getGeometry().getGeometrySpec().getImage();
if (memoryImage != null) {
if (!memoryToDatabaseHash.containsKey(memoryImage)) {
//
// didn't evaluate this image yet.
//
// defaults to unchanged
memoryToDatabaseHash.put(memoryImage, memoryImage);
if (memoryImage.getKey() != null && memoryImage.getVersion().getName().equals(memoryImage.getName())) {
//
// if image had previously been saved, not been forced 'dirty', and name not changed
// compare with original image to see if "update" is required.
//
VCImage databaseImage = null;
if (origBioModel != null) {
for (int j = 0; j < origBioModel.getNumSimulationContexts(); j++) {
VCImage origImage = origBioModel.getSimulationContext(j).getGeometry().getGeometrySpec().getImage();
if (origImage != null && origImage.getKey().equals(memoryImage.getKey())) {
databaseImage = origImage;
}
}
}
if (databaseImage == null) {
//
// saved image not found in origBioModel (too bad), get from database.
//
l1 = System.currentTimeMillis();
databaseImage = dbServer.getDBTopLevel().getVCImage(dbc, user, memoryImage.getKey(), false);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
}
if (databaseImage != null && !databaseImage.compareEqual(memoryImage)) {
KeyValue updatedImageKey = dbServer.getDBTopLevel().updateVersionable(user, memoryImage, false, true);
l1 = System.currentTimeMillis();
VCImage updatedImage = dbServer.getDBTopLevel().getVCImage(dbc, user, updatedImageKey, false);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
memoryToDatabaseHash.put(memoryImage, updatedImage);
bSomethingChanged = true;
}
} else {
//
// Image hasn't been saved, has been renamed, or has been forced 'dirty'
// insert it with a unique name
//
int count = 0;
fixNullImageName(memoryImage);
while (dbServer.getDBTopLevel().isNameUsed(user, VersionableType.VCImage, memoryImage.getName(), true)) {
try {
memoryImage.setName(TokenMangler.getNextRandomToken(memoryImage.getName()));
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
}
if (count++ > 5) {
throw new DataAccessException("failed to find unique image name '" + memoryImage.getName() + "' is last name tried");
}
}
KeyValue updatedImageKey = dbServer.getDBTopLevel().insertVersionable(user, memoryImage, memoryImage.getName(), false, true);
l1 = System.currentTimeMillis();
VCImage updatedImage = dbServer.getDBTopLevel().getVCImage(dbc, user, updatedImageKey, false);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
memoryToDatabaseHash.put(memoryImage, updatedImage);
bSomethingChanged = true;
}
}
}
}
//
for (int i = 0; scArray != null && i < scArray.length; i++) {
Geometry memoryGeometry = scArray[i].getGeometry();
if (!memoryToDatabaseHash.containsKey(memoryGeometry)) {
//
// didn't evaluate this geometry yet.
//
// defaults to unchanged
memoryToDatabaseHash.put(memoryGeometry, memoryGeometry);
boolean bMustSaveGeometry = false;
VCImage geometryImage = memoryGeometry.getGeometrySpec().getImage();
if (geometryImage != null && memoryToDatabaseHash.get(geometryImage) != geometryImage) {
//
// image had changed and was saved, load saved image into geometry and force a save of this geometry.
//
memoryGeometry.getGeometrySpec().setImage((VCImage) memoryToDatabaseHash.get(geometryImage));
geometryImage = (VCImage) memoryToDatabaseHash.get(geometryImage);
bMustSaveGeometry = true;
}
if (memoryGeometry.getKey() != null && memoryGeometry.getVersion().getName().equals(memoryGeometry.getName())) {
if (!bMustSaveGeometry) {
//
// if geometry had previously been saved, not been forced 'dirty', and name not changed
// compare with original geometry to see if "update" is required.
//
Geometry databaseGeometry = null;
if (origBioModel != null) {
for (int j = 0; j < origBioModel.getNumSimulationContexts(); j++) {
Geometry origGeometry = origBioModel.getSimulationContext(j).getGeometry();
if (origGeometry != null && origGeometry.getKey().equals(memoryGeometry.getKey())) {
databaseGeometry = origGeometry;
}
}
}
if (databaseGeometry == null) {
//
// saved geometry not found in origBioModel (too bad), get from database.
//
l1 = System.currentTimeMillis();
databaseGeometry = dbServer.getDBTopLevel().getGeometry(dbc, user, memoryGeometry.getKey(), false);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
}
if (databaseGeometry != null && !databaseGeometry.compareEqual(memoryGeometry)) {
bMustSaveGeometry = true;
}
if (!bMustSaveGeometry && memoryGeometry.getDimension() > 0) {
GeometrySurfaceDescription geomSurfDescr = memoryGeometry.getGeometrySurfaceDescription();
SurfaceClass[] surfClassArr = geomSurfDescr.getSurfaceClasses();
for (int j = 0; surfClassArr != null && j < surfClassArr.length; j++) {
if (surfClassArr[j].getKey() == null) {
bMustSaveGeometry = true;
break;
}
}
}
}
if (bMustSaveGeometry) {
KeyValue updatedImageKey = (geometryImage != null) ? (geometryImage.getKey()) : (null);
KeyValue updatedGeometryKey = dbServer.getDBTopLevel().updateVersionable(dbc, user, memoryGeometry, updatedImageKey, false, true);
l1 = System.currentTimeMillis();
Geometry updatedGeometry = dbServer.getDBTopLevel().getGeometry(dbc, user, updatedGeometryKey, false);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
memoryToDatabaseHash.put(memoryGeometry, updatedGeometry);
bSomethingChanged = true;
}
} else {
//
// Geometry hasn't been saved, has been renamed, or has been forced 'dirty'
// insert it with a unique name
//
int count = 0;
while (dbServer.getDBTopLevel().isNameUsed(user, VersionableType.Geometry, memoryGeometry.getName(), true)) {
try {
memoryGeometry.setName(TokenMangler.getNextRandomToken(memoryGeometry.getName()));
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
}
if (count++ > 5) {
throw new DataAccessException("failed to find unique geometry name '" + memoryGeometry.getName() + "' is last name tried");
}
}
KeyValue updatedImageKey = (geometryImage != null) ? (geometryImage.getKey()) : (null);
KeyValue updatedGeometryKey = dbServer.getDBTopLevel().insertVersionable(dbc, user, memoryGeometry, updatedImageKey, memoryGeometry.getName(), false, true);
l1 = System.currentTimeMillis();
Geometry updatedGeometry = dbServer.getDBTopLevel().getGeometry(dbc, user, updatedGeometryKey, false);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
memoryToDatabaseHash.put(memoryGeometry, updatedGeometry);
bSomethingChanged = true;
}
}
}
//
// for each MathDescription in document:
// substitute saved geometry's into SimulationContext and
// save SimulationContext if necessary (only once) and store saved instance in hashtable.
//
Hashtable<MathDescription, MathCompareResults> mathEquivalencyHash = new Hashtable<MathDescription, MathCompareResults>();
for (int i = 0; scArray != null && i < scArray.length; i++) {
MathDescription memoryMathDescription = scArray[i].getMathDescription();
if (!memoryToDatabaseHash.containsKey(memoryMathDescription)) {
//
// didn't evaluate this SimulationContext yet.
//
// defaults to unchanged
memoryToDatabaseHash.put(memoryMathDescription, memoryMathDescription);
boolean bMustSaveMathDescription = false;
Geometry scGeometry = memoryMathDescription.getGeometry();
if (scGeometry != null && memoryToDatabaseHash.get(scGeometry) != scGeometry) {
//
// geometry had changed and was saved, load saved geometry into SimulationContext (and it's MathDescription) and force a save of this SimulationContext.
//
memoryMathDescription.setGeometry((Geometry) memoryToDatabaseHash.get(scGeometry));
bMustSaveMathDescription = true;
}
MathDescription databaseMathDescription = null;
if (memoryMathDescription.getKey() != null) {
//
if (origBioModel != null) {
for (int j = 0; j < origBioModel.getNumSimulationContexts(); j++) {
MathDescription math = origBioModel.getSimulationContext(j).getMathDescription();
if (math.getKey().equals(memoryMathDescription.getKey())) {
databaseMathDescription = math;
}
}
}
if (databaseMathDescription == null) {
//
// saved mathDescription not found in origBioModel (too bad), get from database.
//
l1 = System.currentTimeMillis();
databaseMathDescription = dbServer.getDBTopLevel().getMathDescription(dbc, user, memoryMathDescription.getKey());
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
}
if (databaseMathDescription != null && !databaseMathDescription.compareEqual(memoryMathDescription)) {
bMustSaveMathDescription = true;
}
} else {
bMustSaveMathDescription = true;
}
if (bMustSaveMathDescription) {
MathCompareResults mathCompareResults = null;
if (databaseMathDescription != null) {
try {
mathCompareResults = MathDescription.testEquivalency(SimulationSymbolTable.createMathSymbolTableFactory(), memoryMathDescription, databaseMathDescription);
if (mathCompareResults != null && !mathCompareResults.isEquivalent() && (mathCompareResults.decision.equals(Decision.MathDifferent_DIFFERENT_NUMBER_OF_VARIABLES) || mathCompareResults.decision.equals(Decision.MathDifferent_VARIABLE_NOT_FOUND_AS_FUNCTION))) {
//
// if there is a different number of variables or cannot find variables by name (even considering change of state variables)
// then try the VCell 4.8 generated math.
//
MathDescription mathDesc_4_8 = new MathMapping_4_8(scArray[i]).getMathDescription();
mathCompareResults = MathDescription.testEquivalency(SimulationSymbolTable.createMathSymbolTableFactory(), mathDesc_4_8, databaseMathDescription);
}
} catch (Exception e) {
e.printStackTrace(System.out);
mathCompareResults = new MathCompareResults(Decision.MathDifferent_FAILURE_UNKNOWN, "Exception: '" + e.getMessage() + "'");
System.out.println("FAILED TO COMPARE THE FOLLOWING MATH DESCRIPTIONS");
try {
System.out.println("MemoryMathDescription:\n" + ((memoryMathDescription != null) ? (memoryMathDescription.getVCML_database()) : ("null")));
System.out.println("DatabaseMathDescription:\n" + ((databaseMathDescription != null) ? (databaseMathDescription.getVCML_database()) : ("null")));
} catch (Exception e2) {
System.out.println("couldn't print math descriptions");
}
}
} else {
mathCompareResults = new MathCompareResults(Decision.MathDifferent_NOT_SAVED);
}
//
// MathDescription hasn't been saved, has been renamed, or has been forced 'dirty'
// insert it with a any name (doens't have to be unique ... mathDescription is not a top-level versionable).
//
KeyValue updatedGeometryKey = memoryMathDescription.getGeometry().getKey();
KeyValue updatedMathDescriptionKey = null;
if (memoryMathDescription.getVersion() != null && memoryMathDescription.getVersion().getName().equals(memoryMathDescription.getName())) {
updatedMathDescriptionKey = dbServer.getDBTopLevel().updateVersionable(user, memoryMathDescription, updatedGeometryKey, false, true);
} else {
updatedMathDescriptionKey = dbServer.getDBTopLevel().insertVersionable(user, memoryMathDescription, updatedGeometryKey, memoryMathDescription.getName(), false, true);
}
l1 = System.currentTimeMillis();
MathDescription updatedMathDescription = dbServer.getDBTopLevel().getMathDescription(dbc, user, updatedMathDescriptionKey);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
memoryToDatabaseHash.put(memoryMathDescription, updatedMathDescription);
mathEquivalencyHash.put(updatedMathDescription, mathCompareResults);
bSomethingChanged = true;
} else {
mathEquivalencyHash.put(memoryMathDescription, new MathCompareResults(Decision.MathEquivalent_SAME_MATHDESC_AS_IN_DB));
}
}
}
//
// update physiology
//
{
Model memoryModel = bioModel.getModel();
// preload with unchanged.
memoryToDatabaseHash.put(memoryModel, memoryModel);
if (memoryModel.getKey() != null && memoryModel.getVersion().getName().equals(memoryModel.getName())) {
//
// if Model had previously been saved, not been forced 'dirty', and name not changed
// compare with original Model to see if "update" is required.
//
Model databaseModel = null;
if (origBioModel != null) {
if (origBioModel.getModel().getKey().equals(memoryModel.getKey())) {
databaseModel = origBioModel.getModel();
}
}
if (databaseModel == null) {
//
// saved model not found in origBioModel (too bad), get from database.
//
l1 = System.currentTimeMillis();
databaseModel = dbServer.getDBTopLevel().getModel(dbc, user, memoryModel.getKey());
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
}
if (databaseModel != null && !databaseModel.compareEqual(memoryModel)) {
KeyValue updatedModelKey = dbServer.getDBTopLevel().updateVersionable(user, memoryModel, false, true);
l1 = System.currentTimeMillis();
Model updatedModel = dbServer.getDBTopLevel().getModel(dbc, user, updatedModelKey);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
memoryToDatabaseHash.put(memoryModel, updatedModel);
bSomethingChanged = true;
}
} else {
//
// Model hasn't been saved, has been renamed, or has been forced 'dirty'
// insert it with a any name (doens't have to be unique ... mathDescription is not a top-level versionable).
//
KeyValue updatedModelKey = dbServer.getDBTopLevel().insertVersionable(user, memoryModel, memoryModel.getName(), false, true);
l1 = System.currentTimeMillis();
Model updatedModel = dbServer.getDBTopLevel().getModel(dbc, user, updatedModelKey);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
memoryToDatabaseHash.put(memoryModel, updatedModel);
bSomethingChanged = true;
}
}
//
for (int i = 0; scArray != null && i < scArray.length; i++) {
SimulationContext memorySimContext = scArray[i];
if (!memoryToDatabaseHash.containsKey(memorySimContext)) {
//
// didn't evaluate this SimulationContext yet.
//
// defaults to unchanged
memoryToDatabaseHash.put(memorySimContext, memorySimContext);
boolean bMustSaveSimContext = false;
Geometry scGeometry = memorySimContext.getGeometry();
if (scGeometry != null && memoryToDatabaseHash.get(scGeometry) != scGeometry) {
//
// geometry had changed and was saved, load saved geometry into SimulationContext (and force a save)
//
memorySimContext.setGeometry((Geometry) memoryToDatabaseHash.get(scGeometry));
bMustSaveSimContext = true;
}
MathDescription scMathDescription = memorySimContext.getMathDescription();
if (scMathDescription != null && memoryToDatabaseHash.get(scMathDescription) != scMathDescription) {
//
// mathDescription had changed and was saved, load saved mathDescription into SimulationContext (and force a save)
//
memorySimContext.setMathDescription((MathDescription) memoryToDatabaseHash.get(scMathDescription));
bMustSaveSimContext = true;
}
Model scModel = memorySimContext.getModel();
if (scModel != null && memoryToDatabaseHash.get(scModel) != scModel) {
//
// model had changed and was saved, load saved model into SimulationContext (and force a save)
//
memorySimContext.setModel((Model) memoryToDatabaseHash.get(scModel));
bMustSaveSimContext = true;
}
if (memorySimContext.getKey() != null && memorySimContext.getVersion().getName().equals(memorySimContext.getName())) {
if (!bMustSaveSimContext) {
//
// if SimulationContext had previously been saved, not been forced 'dirty', and name not changed
// compare with original SimulationContext to see if "update" is required.
//
SimulationContext databaseSimContext = null;
if (origBioModel != null) {
for (int j = 0; j < origBioModel.getNumSimulationContexts(); j++) {
if (origBioModel.getSimulationContext(j).getKey().equals(memorySimContext.getKey())) {
databaseSimContext = origBioModel.getSimulationContext(j);
}
}
}
if (databaseSimContext == null) {
//
// saved geometry not found in origBioModel (too bad), get from database.
//
l1 = System.currentTimeMillis();
databaseSimContext = dbServer.getDBTopLevel().getSimulationContext(dbc, user, memorySimContext.getKey());
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
}
if (databaseSimContext != null && !databaseSimContext.compareEqual(memorySimContext)) {
bMustSaveSimContext = true;
}
}
if (bMustSaveSimContext) {
KeyValue updatedGeometryKey = memorySimContext.getGeometry().getKey();
KeyValue updatedMathDescriptionKey = memorySimContext.getMathDescription().getKey();
Model updatedModel = memorySimContext.getModel();
KeyValue updatedSimContextKey = dbServer.getDBTopLevel().updateVersionable(user, memorySimContext, updatedMathDescriptionKey, updatedModel, updatedGeometryKey, false, true);
l1 = System.currentTimeMillis();
SimulationContext updatedSimContext = dbServer.getDBTopLevel().getSimulationContext(dbc, user, updatedSimContextKey);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
//
// make sure mathDescription is a single reference (for this app and all of it's Simulations).
//
updatedSimContext.setMathDescription((MathDescription) memorySimContext.getMathDescription());
memoryToDatabaseHash.put(memorySimContext, updatedSimContext);
bSomethingChanged = true;
}
} else {
//
// SimulationContext hasn't been saved, has been renamed, or has been forced 'dirty'
//
KeyValue updatedGeometryKey = memorySimContext.getGeometry().getKey();
KeyValue updatedMathDescriptionKey = memorySimContext.getMathDescription().getKey();
Model updatedModel = memorySimContext.getModel();
KeyValue updatedSimContextKey = dbServer.getDBTopLevel().insertVersionable(user, memorySimContext, updatedMathDescriptionKey, updatedModel, updatedGeometryKey, memorySimContext.getName(), false, true);
l1 = System.currentTimeMillis();
SimulationContext updatedSimContext = dbServer.getDBTopLevel().getSimulationContext(dbc, user, updatedSimContextKey);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
//
// make sure mathDescription is a single reference (for this app and all of it's Simulations).
//
updatedSimContext.setMathDescription((MathDescription) memorySimContext.getMathDescription());
memoryToDatabaseHash.put(memorySimContext, updatedSimContext);
bSomethingChanged = true;
}
}
}
//
for (int i = 0; simArray != null && i < simArray.length; i++) {
Simulation memorySimulation = simArray[i];
if (!memoryToDatabaseHash.containsKey(memorySimulation)) {
//
// didn't evaluate this Simulation yet.
//
// defaults to unchanged
memoryToDatabaseHash.put(memorySimulation, memorySimulation);
boolean bMustSaveSimulation = false;
MathDescription simMathDescription = memorySimulation.getMathDescription();
if (simMathDescription != null && memoryToDatabaseHash.get(simMathDescription) != simMathDescription) {
if (memoryToDatabaseHash.get(simMathDescription) != null) {
// make sure mathDescription hasn't already propagated (newer math won't be in hashtable)
//
// mathDescription had changed and was saved, load saved mathDescription into Simulation (and force a save)
//
memorySimulation.setMathDescription((MathDescription) memoryToDatabaseHash.get(simMathDescription));
bMustSaveSimulation = true;
}
}
Simulation databaseSimulation = null;
//
if (memorySimulation.getKey() != null) {
if (origBioModel != null) {
for (int j = 0; j < origBioModel.getNumSimulations(); j++) {
if (origBioModel.getSimulation(j).getKey().equals(memorySimulation.getKey())) {
databaseSimulation = origBioModel.getSimulation(j);
}
}
}
if (databaseSimulation == null) {
//
// saved simulation not found in origBioModel (too bad), get from database.
//
l1 = System.currentTimeMillis();
databaseSimulation = dbServer.getDBTopLevel().getSimulation(dbc, user, memorySimulation.getKey());
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
}
if (databaseSimulation != null) {
if (!memorySimulation.compareEqual(databaseSimulation)) {
bMustSaveSimulation = true;
}
}
if (!memorySimulation.getVersion().getName().equals(memorySimulation.getName())) {
// name was changed.
bMustSaveSimulation = true;
}
} else {
// never been saved.
bMustSaveSimulation = true;
}
if (bMustSaveSimulation) {
boolean bMathematicallyEquivalent = false;
if (databaseSimulation != null) {
//
// if to be forced "independent", then set equivalent to false
//
boolean bForceIndependent = false;
for (int j = 0; independentSims != null && j < independentSims.length; j++) {
if (independentSims[j].equals(memorySimulation.getName())) {
bForceIndependent = true;
}
}
//
// check for math equivalency first
//
MathCompareResults mathCompareResults = mathEquivalencyHash.get(memorySimulation.getMathDescription());
bMathematicallyEquivalent = !bForceIndependent && Simulation.testEquivalency(memorySimulation, databaseSimulation, mathCompareResults);
//
if (bMathematicallyEquivalent) {
VCSimulationIdentifier vcSimulationIdentifier = databaseSimulation.getSimulationInfo().getAuthoritativeVCSimulationIdentifier();
SimulationStatusPersistent simStatus = dbServer.getSimulationStatus(vcSimulationIdentifier.getSimulationKey());
if (simStatus == null || !simStatus.getHasData()) {
bMathematicallyEquivalent = false;
}
}
}
KeyValue updatedMathDescriptionKey = memorySimulation.getMathDescription().getKey();
KeyValue updatedSimulationKey = null;
if (memorySimulation.getKey() != null && memorySimulation.getVersion().getName().equals(memorySimulation.getName())) {
// name not changed, update simulation (but pass in database Simulation to check for parent-equivalence)
updatedSimulationKey = dbServer.getDBTopLevel().updateVersionable(user, memorySimulation, updatedMathDescriptionKey, false, bMathematicallyEquivalent, true);
} else {
// name changed, insert simulation (but pass in database Simulation to check for parent-equivalence)
updatedSimulationKey = dbServer.getDBTopLevel().insertVersionable(user, memorySimulation, updatedMathDescriptionKey, memorySimulation.getName(), false, bMathematicallyEquivalent, true);
}
l1 = System.currentTimeMillis();
Simulation updatedSimulation = dbServer.getDBTopLevel().getSimulation(dbc, user, updatedSimulationKey);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
//
// make sure mathDescription is a single reference (for an app and all of it's Simulations).
//
updatedSimulation.setMathDescription((MathDescription) memorySimulation.getMathDescription());
memoryToDatabaseHash.put(memorySimulation, updatedSimulation);
bSomethingChanged = true;
}
}
}
boolean bMustSaveVCMetaData = false;
if (origBioModel != null) {
//
// for the VCMetaData in the document:
// save VCMetaData if necessary (only once) and store saved instance in hashtable.
//
// The persisted VCMetaData doesn't have any foreign keys
// (when annotating a simulation ... we don't point to the simulation,
// we use the text-based VCID that is stored in URIBindingList in the XML serialization
//
// Therefore, there are no additional dependencies that we have to update during the
// incremental save and force propagation to save the VCMetaData.
//
VCMetaData memoryVCMetaData = bioModel.getVCMetaData();
VCMetaData databaseVCMetaData = origBioModel.getVCMetaData();
//
if (databaseVCMetaData == null || !databaseVCMetaData.compareEquals(memoryVCMetaData)) {
bMustSaveVCMetaData = true;
bSomethingChanged = true;
}
}
if (bSomethingChanged || origBioModel == null || !bioModel.compareEqual(origBioModel)) {
//
// create new BioModelMetaData and save to server
//
KeyValue modelKey = ((Model) memoryToDatabaseHash.get(bioModel.getModel())).getKey();
KeyValue[] scKeys = new KeyValue[bioModel.getNumSimulationContexts()];
for (int i = 0; i < bioModel.getNumSimulationContexts(); i++) {
scKeys[i] = ((SimulationContext) memoryToDatabaseHash.get(bioModel.getSimulationContext(i))).getKey();
}
KeyValue[] simKeys = new KeyValue[bioModel.getNumSimulations()];
for (int i = 0; i < bioModel.getNumSimulations(); i++) {
simKeys[i] = ((Simulation) memoryToDatabaseHash.get(bioModel.getSimulation(i))).getKey();
}
// @TODO Add VC_METADATA table ... pointed to by VC_BIOMODEL (metadataref on delete cascade)
// @TODO Write script to populate VC_METADATA from VC_MIRIAM
// @TODO save VCMetaData from this BioModel into VC_METADATA .. stick in memoryToDatabaseHash
//
BioModelMetaData bioModelMetaData = null;
String vcMetaDataXML = XmlHelper.vcMetaDataToXML(bioModel.getVCMetaData(), bioModel);
if (oldVersion == null) {
bioModelMetaData = new BioModelMetaData(modelKey, scKeys, simKeys, vcMetaDataXML, bioModel.getName(), bioModel.getDescription());
} else {
bioModelMetaData = new BioModelMetaData(oldVersion, modelKey, scKeys, simKeys, vcMetaDataXML);
if (!bioModel.getDescription().equals(oldVersion.getAnnot())) {
try {
bioModelMetaData.setDescription(bioModel.getDescription());
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
}
}
}
// bioModelMetaData.setMIRIAMAnnotation(bioModel.getMIRIAMAnnotation());
BioModelMetaData updatedBioModelMetaData = null;
if (bioModel.getVersion() == null || !bioModel.getVersion().getName().equals(bioModel.getName())) {
KeyValue updatedBioModelKey = dbServer.getDBTopLevel().insertVersionable(user, bioModelMetaData, null, /*hack*/
bioModel.getName(), false, true);
l1 = System.currentTimeMillis();
updatedBioModelMetaData = dbServer.getDBTopLevel().getBioModelMetaData(dbc, user, updatedBioModelKey);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
} else {
KeyValue updatedBioModelKey = dbServer.getDBTopLevel().updateVersionable(user, bioModelMetaData, null, /*hack*/
false, true);
l1 = System.currentTimeMillis();
updatedBioModelMetaData = dbServer.getDBTopLevel().getBioModelMetaData(dbc, user, updatedBioModelKey);
l2 = System.currentTimeMillis();
roundtripTimer += l2 - l1;
}
//
// (THIS IS THE REALLY SCAREY PART...NOT GETTING A FRESH VIEW OF EVERYTING FROM THE DATABASE FOR CREATING THE XML)
//
// bioModelXML = getBioModelXML(user,updatedBioModelMetaData.getVersion().getVersionKey());
BioModel updatedBioModel = new BioModel(updatedBioModelMetaData.getVersion());
// updatedBioModel.setMIRIAMAnnotation(updatedBioModelMetaData.getMIRIAMAnnotation());
updatedBioModel.setModel((Model) memoryToDatabaseHash.get(bioModel.getModel()));
for (int i = 0; i < bioModel.getNumSimulationContexts(); i++) {
updatedBioModel.addSimulationContext((SimulationContext) memoryToDatabaseHash.get(bioModel.getSimulationContext(i)));
}
for (int i = 0; i < bioModel.getNumSimulations(); i++) {
updatedBioModel.addSimulation((Simulation) memoryToDatabaseHash.get(bioModel.getSimulation(i)));
}
updatedBioModel.setVCMetaData(XmlHelper.xmlToVCMetaData(updatedBioModel.getVCMetaData(), updatedBioModel, vcMetaDataXML));
// TODO must replace this with proper persistance.
updatedBioModel.getPathwayModel().merge(bioModel.getPathwayModel());
updatedBioModel.getRelationshipModel().merge(bioModel.getRelationshipModel());
bioModelXML = cbit.vcell.xml.XmlHelper.bioModelToXML(updatedBioModel);
dbServer.insertVersionableChildSummary(user, VersionableType.BioModelMetaData, updatedBioModel.getVersion().getVersionKey(), updatedBioModel.createBioModelChildSummary().toDatabaseSerialization());
dbServer.insertVersionableXML(user, VersionableType.BioModelMetaData, updatedBioModel.getVersion().getVersionKey(), bioModelXML);
System.out.println("------------------------------> Total time: " + ((double) (System.currentTimeMillis() - start)) / 1000);
System.out.println("------------------------------> Time spent on roundtrip: " + ((double) roundtripTimer) / 1000);
return bioModelXML;
} else {
System.out.println("------------------------------> Total time: " + ((double) (System.currentTimeMillis() - start)) / 1000);
System.out.println("------------------------------> Time spent on roundtrip: " + ((double) roundtripTimer) / 1000);
return bioModelXML;
}
}
use of cbit.vcell.geometry.SurfaceClass in project vcell by virtualcell.
the class StructureMappingTable method getSQLValueList.
/**
* This method was created in VisualAge.
* @return java.lang.String
* @param key KeyValue
* @param modelName java.lang.String
*/
public String getSQLValueList(InsertHashtable hash, KeyValue Key, KeyValue simContextKey, StructureMapping structureMapping) throws DataAccessException {
GeometryClass geometryClass = structureMapping.getGeometryClass();
KeyValue geometryClassKey = (geometryClass == null ? null : hash.getDatabaseKey(geometryClass));
if (geometryClass != null && geometryClassKey == null) {
geometryClassKey = geometryClass.getKey();
if (geometryClassKey == null) {
throw new DataAccessException("no key for GeometryClass '" + geometryClass.getName() + "' " + geometryClass.getClass().getName());
}
}
KeyValue structureKey = hash.getDatabaseKey(structureMapping.getStructure());
if (structureKey == null) {
structureKey = structureMapping.getStructure().getKey();
if (structureKey == null) {
throw new DataAccessException("no key for structure " + structureMapping.getStructure());
}
}
StringBuffer buffer = new StringBuffer();
buffer.append("(");
buffer.append(Key + ",");
buffer.append((geometryClass instanceof SubVolume ? geometryClassKey : null) + ",");
buffer.append(structureKey + ",");
buffer.append(simContextKey + ",");
buffer.append((/*isResolved*/
false ? 1 : 0) + ",");
if (structureMapping instanceof FeatureMapping) {
FeatureMapping fm = (FeatureMapping) structureMapping;
buffer.append("null" + ",");
buffer.append("null" + ",");
buffer.append("'" + fm.getBoundaryConditionTypeXm().boundaryTypeStringValue() + "',");
buffer.append("'" + fm.getBoundaryConditionTypeXp().boundaryTypeStringValue() + "',");
buffer.append("'" + fm.getBoundaryConditionTypeYm().boundaryTypeStringValue() + "',");
buffer.append("'" + fm.getBoundaryConditionTypeYp().boundaryTypeStringValue() + "',");
buffer.append("'" + fm.getBoundaryConditionTypeZm().boundaryTypeStringValue() + "',");
buffer.append("'" + fm.getBoundaryConditionTypeZp().boundaryTypeStringValue() + "',");
buffer.append("null" + ",");
buffer.append("null" + ",");
buffer.append("null" + ",");
} else if (structureMapping instanceof MembraneMapping) {
MembraneMapping mm = (MembraneMapping) structureMapping;
// amended Sept. 17th, 2007
if (mm.getSurfaceToVolumeParameter().getExpression() != null) {
buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getSurfaceToVolumeParameter().getExpression().infix()) + "',");
} else {
buffer.append("null" + ",");
}
if (mm.getVolumeFractionParameter().getExpression() != null) {
buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getVolumeFractionParameter().getExpression().infix()) + "',");
} else {
buffer.append("null" + ",");
}
buffer.append("null" + ",");
buffer.append("null" + ",");
buffer.append("null" + ",");
buffer.append("null" + ",");
buffer.append("null" + ",");
buffer.append("null" + ",");
buffer.append((mm.getCalculateVoltage() ? 1 : 0) + ",");
try {
buffer.append(mm.getSpecificCapacitanceParameter().getExpression().evaluateConstant() + ",");
} catch (cbit.vcell.parser.ExpressionException e) {
e.printStackTrace(System.out);
throw new DataAccessException("specific capacitance for " + mm.getMembrane().getName() + " not constant: (" + e.getMessage() + ")");
}
buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getInitialVoltageParameter().getExpression().infix()) + "',");
}
if (structureMapping.getSizeParameter().getExpression() != null)
buffer.append("'" + TokenMangler.getSQLEscapedString(structureMapping.getSizeParameter().getExpression().infix()) + "',");
else
buffer.append("'',");
if (structureMapping instanceof FeatureMapping) {
FeatureMapping fm = (FeatureMapping) structureMapping;
if (fm.getVolumePerUnitAreaParameter().getExpression() != null) {
buffer.append("'" + TokenMangler.getSQLEscapedString(fm.getVolumePerUnitAreaParameter().getExpression().infix()) + "',");
} else {
buffer.append("null" + ",");
}
if (fm.getVolumePerUnitVolumeParameter().getExpression() != null) {
buffer.append("'" + TokenMangler.getSQLEscapedString(fm.getVolumePerUnitVolumeParameter().getExpression().infix()) + "',");
} else {
buffer.append("null" + ",");
}
// if structureMapping is a featureMapping, 'areaPerUnitArea' and 'areaPerUnitVol' params are null, so fill those in here
buffer.append("null,null");
} else if (structureMapping instanceof MembraneMapping) {
// if structureMapping is a featureMapping, 'volPerUnitArea' and 'volPerUnitVol' params are null, so fill those in here; then memMapping params
buffer.append("null,null,");
MembraneMapping mm = (MembraneMapping) structureMapping;
if (mm.getAreaPerUnitAreaParameter().getExpression() != null) {
buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getAreaPerUnitAreaParameter().getExpression().infix()) + "',");
} else {
buffer.append("null" + ",");
}
if (mm.getAreaPerUnitVolumeParameter().getExpression() != null) {
buffer.append("'" + TokenMangler.getSQLEscapedString(mm.getAreaPerUnitVolumeParameter().getExpression().infix()) + "'");
} else {
buffer.append("null");
}
}
buffer.append("," + (geometryClass instanceof SurfaceClass ? geometryClassKey : null));
buffer.append(")");
return buffer.toString();
}
Aggregations