use of cbit.vcell.model.ModelUnitSystem in project vcell by virtualcell.
the class SEDMLExporter method translateBioModelToSedML.
private void translateBioModelToSedML(String savePath) {
sbmlFilePathStrAbsoluteList.clear();
// models
try {
SimulationContext[] simContexts = vcBioModel.getSimulationContexts();
cbit.vcell.model.Model vcModel = vcBioModel.getModel();
// "urn:sedml:language:sbml";
String sbmlLanguageURN = SUPPORTED_LANGUAGE.SBML_GENERIC.getURN();
String bioModelName = TokenMangler.mangleToSName(vcBioModel.getName());
// String usrHomeDirPath = ResourceUtil.getUserHomeDir().getAbsolutePath();
// to get Xpath string for variables.
SBMLSupport sbmlSupport = new SBMLSupport();
// for model count, task subcount
int simContextCnt = 0;
// for dtaGenerator count.
int varCount = 0;
boolean bSpeciesAddedAsDataGens = false;
String sedmlNotesStr = "";
for (SimulationContext simContext : simContexts) {
String simContextName = simContext.getName();
// export all applications that are not spatial stochastic
if (!(simContext.getGeometry().getDimension() > 0 && simContext.isStoch())) {
// to compute and set the sizes of the remaining structures.
if (!simContext.getGeometryContext().isAllSizeSpecifiedPositive()) {
Structure structure = simContext.getModel().getStructure(0);
double structureSize = 1.0;
StructureMapping structMapping = simContext.getGeometryContext().getStructureMapping(structure);
StructureSizeSolver.updateAbsoluteStructureSizes(simContext, structure, structureSize, structMapping.getSizeParameter().getUnitDefinition());
}
// Export the application itself to SBML, with default overrides
String sbmlString = null;
int level = 2;
int version = 4;
boolean isSpatial = simContext.getGeometry().getDimension() > 0 ? true : false;
SimulationJob simJob = null;
// if (simContext.getGeometry().getDimension() > 0) {
// sbmlString = XmlHelper.exportSBML(vcBioModel, 2, 4, 0, true, simContext, null);
// } else {
// sbmlString = XmlHelper.exportSBML(vcBioModel, 2, 4, 0, false, simContext, null);
// }
//
// TODO: we need to salvage from the SBMLExporter info about the fate of local parameters
// some of them may stay as locals, some others may become globals
// Any of these, if used in a repeated task or change or whatever, needs to be used in a consistent way,
// that is, if a param becomes a global in SBML, we need to refer at it in SEDML as the same global
//
// We'll use:
// Map<Pair <String reaction, String param>, String global> - if local converted to global
// Set<Pair <String reaction, String param>> (if needed?) - if local stays local
//
// local to global translation map
Map<Pair<String, String>, String> l2gMap = null;
if (vcBioModel instanceof BioModel) {
try {
// check if model to be exported to SBML has units compatible with SBML default units (default units in SBML can be assumed only until SBML Level2)
ModelUnitSystem forcedModelUnitSystem = simContext.getModel().getUnitSystem();
if (level < 3 && !ModelUnitSystem.isCompatibleWithDefaultSBMLLevel2Units(forcedModelUnitSystem)) {
forcedModelUnitSystem = ModelUnitSystem.createDefaultSBMLLevel2Units();
}
// create new Biomodel with new (SBML compatible) unit system
BioModel modifiedBiomodel = ModelUnitConverter.createBioModelWithNewUnitSystem(simContext.getBioModel(), forcedModelUnitSystem);
// extract the simContext from new Biomodel. Apply overrides to *this* modified simContext
SimulationContext simContextFromModifiedBioModel = modifiedBiomodel.getSimulationContext(simContext.getName());
SBMLExporter sbmlExporter = new SBMLExporter(modifiedBiomodel, level, version, isSpatial);
sbmlExporter.setSelectedSimContext(simContextFromModifiedBioModel);
// no sim job
sbmlExporter.setSelectedSimulationJob(null);
sbmlString = sbmlExporter.getSBMLFile();
l2gMap = sbmlExporter.getLocalToGlobalTranslationMap();
} catch (ExpressionException | SbmlException e) {
e.printStackTrace(System.out);
throw new XmlParseException(e);
}
} else {
throw new RuntimeException("unsupported Document Type " + vcBioModel.getClass().getName() + " for SBML export");
}
String sbmlFilePathStrAbsolute = savePath + FileUtils.WINDOWS_SEPARATOR + bioModelName + "_" + simContextName + ".xml";
String sbmlFilePathStrRelative = bioModelName + "_" + simContextName + ".xml";
XmlUtil.writeXMLStringToFile(sbmlString, sbmlFilePathStrAbsolute, true);
sbmlFilePathStrAbsoluteList.add(sbmlFilePathStrRelative);
String simContextId = TokenMangler.mangleToSName(simContextName);
sedmlModel.addModel(new Model(simContextId, simContextName, sbmlLanguageURN, sbmlFilePathStrRelative));
// required for mathOverrides, if any
MathMapping mathMapping = simContext.createNewMathMapping();
MathSymbolMapping mathSymbolMapping = mathMapping.getMathSymbolMapping();
// create sedml simulation objects and tasks (mapping each sim with current simContext)
int simCount = 0;
String taskRef = null;
int overrideCount = 0;
for (Simulation vcSimulation : simContext.getSimulations()) {
List<DataGenerator> dataGeneratorsOfSim = new ArrayList<DataGenerator>();
// if simContext is non-spatial stochastic, check if sim is histogram
SolverTaskDescription simTaskDesc = vcSimulation.getSolverTaskDescription();
if (simContext.getGeometry().getDimension() == 0 && simContext.isStoch()) {
long numOfTrials = simTaskDesc.getStochOpt().getNumOfTrials();
if (numOfTrials > 1) {
String msg = "\n\t" + simContextName + " ( " + vcSimulation.getName() + " ) : export of non-spatial stochastic simulation with histogram option to SEDML not supported at this time.";
sedmlNotesStr += msg;
continue;
}
}
// create Algorithm and sedmlSimulation (UniformtimeCourse)
SolverDescription vcSolverDesc = simTaskDesc.getSolverDescription();
// String kiSAOIdStr = getKiSAOIdFromSimulation(vcSolverDesc); // old way of doing it, going directly to the web site
String kiSAOIdStr = vcSolverDesc.getKisao();
Algorithm sedmlAlgorithm = new Algorithm(kiSAOIdStr);
TimeBounds vcSimTimeBounds = simTaskDesc.getTimeBounds();
double startingTime = vcSimTimeBounds.getStartingTime();
String simName = vcSimulation.getName();
UniformTimeCourse utcSim = new UniformTimeCourse(TokenMangler.mangleToSName(simName), simName, startingTime, startingTime, vcSimTimeBounds.getEndingTime(), (int) simTaskDesc.getExpectedNumTimePoints(), sedmlAlgorithm);
// if solver is not CVODE, add a note to utcSim to indicate actual solver name
if (!vcSolverDesc.equals(SolverDescription.CVODE)) {
String simNotesStr = "Actual Solver Name : '" + vcSolverDesc.getDisplayLabel() + "'.";
utcSim.addNote(createNotesElement(simNotesStr));
}
sedmlModel.addSimulation(utcSim);
// add SEDML tasks (map simulation to model:simContext)
// repeated tasks
MathOverrides mathOverrides = vcSimulation.getMathOverrides();
if (mathOverrides != null && mathOverrides.hasOverrides()) {
String[] overridenConstantNames = mathOverrides.getOverridenConstantNames();
String[] scannedConstantsNames = mathOverrides.getScannedConstantNames();
HashMap<String, String> scannedParamHash = new HashMap<String, String>();
HashMap<String, String> unscannedParamHash = new HashMap<String, String>();
for (String name : scannedConstantsNames) {
scannedParamHash.put(name, name);
}
for (String name : overridenConstantNames) {
if (!scannedParamHash.containsKey(name)) {
unscannedParamHash.put(name, name);
}
}
if (!unscannedParamHash.isEmpty() && scannedParamHash.isEmpty()) {
// only parameters with simple overrides (numeric/expression) no scans
// create new model with change for each parameter that has override; add simple task
String overriddenSimContextId = simContextId + "_" + overrideCount;
String overriddenSimContextName = simContextName + " modified";
Model sedModel = new Model(overriddenSimContextId, overriddenSimContextName, sbmlLanguageURN, simContextId);
overrideCount++;
for (String unscannedParamName : unscannedParamHash.values()) {
SymbolTableEntry ste = getSymbolTableEntryForModelEntity(mathSymbolMapping, unscannedParamName);
Expression unscannedParamExpr = mathOverrides.getActualExpression(unscannedParamName, 0);
if (unscannedParamExpr.isNumeric()) {
// if expression is numeric, add ChangeAttribute to model created above
XPathTarget targetXpath = getTargetAttributeXPath(ste, l2gMap);
ChangeAttribute changeAttribute = new ChangeAttribute(targetXpath, unscannedParamExpr.infix());
sedModel.addChange(changeAttribute);
} else {
// non-numeric expression : add 'computeChange' to modified model
ASTNode math = Libsedml.parseFormulaString(unscannedParamExpr.infix());
XPathTarget targetXpath = getTargetXPath(ste, l2gMap);
ComputeChange computeChange = new ComputeChange(targetXpath, math);
String[] exprSymbols = unscannedParamExpr.getSymbols();
for (String symbol : exprSymbols) {
String symbolName = TokenMangler.mangleToSName(symbol);
SymbolTableEntry ste1 = vcModel.getEntry(symbol);
if (ste != null) {
if (ste1 instanceof SpeciesContext || ste1 instanceof Structure || ste1 instanceof ModelParameter) {
XPathTarget ste1_XPath = getTargetXPath(ste1, l2gMap);
org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(symbolName, symbolName, taskRef, ste1_XPath.getTargetAsString());
computeChange.addVariable(sedmlVar);
} else {
double doubleValue = 0.0;
if (ste1 instanceof ReservedSymbol) {
doubleValue = getReservedSymbolValue(ste1);
}
Parameter sedmlParameter = new Parameter(symbolName, symbolName, doubleValue);
computeChange.addParameter(sedmlParameter);
}
} else {
throw new RuntimeException("Symbol '" + symbol + "' used in expression for '" + unscannedParamName + "' not found in model.");
}
}
sedModel.addChange(computeChange);
}
}
sedmlModel.addModel(sedModel);
String taskId = "tsk_" + simContextCnt + "_" + simCount;
Task sedmlTask = new Task(taskId, taskId, sedModel.getId(), utcSim.getId());
sedmlModel.addTask(sedmlTask);
// to be used later to add dataGenerators : one set of DGs per model (simContext).
taskRef = taskId;
} else if (!scannedParamHash.isEmpty() && unscannedParamHash.isEmpty()) {
// only parameters with scans : only add 1 Task and 1 RepeatedTask
String taskId = "tsk_" + simContextCnt + "_" + simCount;
Task sedmlTask = new Task(taskId, taskId, simContextId, utcSim.getId());
sedmlModel.addTask(sedmlTask);
String repeatedTaskId = "repTsk_" + simContextCnt + "_" + simCount;
// TODO: temporary solution - we use as range here the first range
String scn = scannedConstantsNames[0];
String rId = "range_" + simContextCnt + "_" + simCount + "_" + scn;
RepeatedTask rt = new RepeatedTask(repeatedTaskId, repeatedTaskId, true, rId);
// to be used later to add dataGenerators - in our case it has to be the repeated task
taskRef = repeatedTaskId;
SubTask subTask = new SubTask("0", taskId);
rt.addSubtask(subTask);
for (String scannedConstName : scannedConstantsNames) {
ConstantArraySpec constantArraySpec = mathOverrides.getConstantArraySpec(scannedConstName);
String rangeId = "range_" + simContextCnt + "_" + simCount + "_" + scannedConstName;
// list of Ranges, if sim is parameter scan.
if (constantArraySpec != null) {
Range r = null;
System.out.println(" " + constantArraySpec.toString());
if (constantArraySpec.getType() == ConstantArraySpec.TYPE_INTERVAL) {
// ------ Uniform Range
r = new UniformRange(rangeId, constantArraySpec.getMinValue(), constantArraySpec.getMaxValue(), constantArraySpec.getNumValues());
rt.addRange(r);
} else {
// ----- Vector Range
cbit.vcell.math.Constant[] cs = constantArraySpec.getConstants();
ArrayList<Double> values = new ArrayList<Double>();
for (int i = 0; i < cs.length; i++) {
String value = cs[i].getExpression().infix();
values.add(Double.parseDouble(value));
}
r = new VectorRange(rangeId, values);
rt.addRange(r);
}
// list of Changes
SymbolTableEntry ste = getSymbolTableEntryForModelEntity(mathSymbolMapping, scannedConstName);
XPathTarget target = getTargetXPath(ste, l2gMap);
// ASTNode math1 = new ASTCi(r.getId()); // was scannedConstName
ASTNode math1 = Libsedml.parseFormulaString(r.getId());
SetValue setValue = new SetValue(target, r.getId(), simContextId);
setValue.setMath(math1);
rt.addChange(setValue);
} else {
throw new RuntimeException("No scan ranges found for scanned parameter : '" + scannedConstName + "'.");
}
}
sedmlModel.addTask(rt);
} else {
// both scanned and simple parameters : create new model with change for each simple override; add RepeatedTask
// create new model with change for each unscanned parameter that has override
String overriddenSimContextId = simContextId + "_" + overrideCount;
String overriddenSimContextName = simContextName + " modified";
Model sedModel = new Model(overriddenSimContextId, overriddenSimContextName, sbmlLanguageURN, simContextId);
overrideCount++;
String taskId = "tsk_" + simContextCnt + "_" + simCount;
Task sedmlTask = new Task(taskId, taskId, overriddenSimContextId, utcSim.getId());
sedmlModel.addTask(sedmlTask);
// scanned parameters
String repeatedTaskId = "repTsk_" + simContextCnt + "_" + simCount;
// TODO: temporary solution - we use as range here the first range
String scn = scannedConstantsNames[0];
String rId = "range_" + simContextCnt + "_" + simCount + "_" + scn;
RepeatedTask rt = new RepeatedTask(repeatedTaskId, repeatedTaskId, true, rId);
// to be used later to add dataGenerators - in our case it has to be the repeated task
taskRef = repeatedTaskId;
SubTask subTask = new SubTask("0", taskId);
rt.addSubtask(subTask);
for (String scannedConstName : scannedConstantsNames) {
ConstantArraySpec constantArraySpec = mathOverrides.getConstantArraySpec(scannedConstName);
String rangeId = "range_" + simContextCnt + "_" + simCount + "_" + scannedConstName;
// list of Ranges, if sim is parameter scan.
if (constantArraySpec != null) {
Range r = null;
System.out.println(" " + constantArraySpec.toString());
if (constantArraySpec.getType() == ConstantArraySpec.TYPE_INTERVAL) {
// ------ Uniform Range
r = new UniformRange(rangeId, constantArraySpec.getMinValue(), constantArraySpec.getMaxValue(), constantArraySpec.getNumValues());
rt.addRange(r);
} else {
// ----- Vector Range
cbit.vcell.math.Constant[] cs = constantArraySpec.getConstants();
ArrayList<Double> values = new ArrayList<Double>();
for (int i = 0; i < cs.length; i++) {
String value = cs[i].getExpression().infix() + ", ";
values.add(Double.parseDouble(value));
}
r = new VectorRange(rangeId, values);
rt.addRange(r);
}
// use scannedParamHash to store rangeId for that param, since it might be needed if unscanned param has a scanned param in expr.
if (scannedParamHash.get(scannedConstName).equals(scannedConstName)) {
// the hash was originally populated as <scannedParamName, scannedParamName>. Replace 'value' with rangeId for scannedParam
scannedParamHash.put(scannedConstName, r.getId());
}
// create setValue for scannedConstName
SymbolTableEntry ste2 = getSymbolTableEntryForModelEntity(mathSymbolMapping, scannedConstName);
XPathTarget target1 = getTargetXPath(ste2, l2gMap);
ASTNode math1 = new ASTCi(scannedConstName);
SetValue setValue1 = new SetValue(target1, r.getId(), sedModel.getId());
setValue1.setMath(math1);
rt.addChange(setValue1);
} else {
throw new RuntimeException("No scan ranges found for scanned parameter : '" + scannedConstName + "'.");
}
}
// for unscanned parameter overrides
for (String unscannedParamName : unscannedParamHash.values()) {
SymbolTableEntry ste = getSymbolTableEntryForModelEntity(mathSymbolMapping, unscannedParamName);
Expression unscannedParamExpr = mathOverrides.getActualExpression(unscannedParamName, 0);
if (unscannedParamExpr.isNumeric()) {
// if expression is numeric, add ChangeAttribute to model created above
XPathTarget targetXpath = getTargetAttributeXPath(ste, l2gMap);
ChangeAttribute changeAttribute = new ChangeAttribute(targetXpath, unscannedParamExpr.infix());
sedModel.addChange(changeAttribute);
} else {
// check for any scanned parameter in unscanned parameter expression
ASTNode math = Libsedml.parseFormulaString(unscannedParamExpr.infix());
String[] exprSymbols = unscannedParamExpr.getSymbols();
boolean bHasScannedParameter = false;
String scannedParamNameInUnscannedParamExp = null;
for (String symbol : exprSymbols) {
if (scannedParamHash.get(symbol) != null) {
bHasScannedParameter = true;
scannedParamNameInUnscannedParamExp = new String(symbol);
// @TODO check for multiple scannedParameters in expression.
break;
}
}
// (scanned parameter in expr) ? (add setValue for unscanned param in repeatedTask) : (add computeChange to modifiedModel)
if (bHasScannedParameter && scannedParamNameInUnscannedParamExp != null) {
// create setValue for unscannedParamName (which contains a scanned param in its expression)
SymbolTableEntry entry = getSymbolTableEntryForModelEntity(mathSymbolMapping, unscannedParamName);
XPathTarget target = getTargetXPath(entry, l2gMap);
String rangeId = scannedParamHash.get(scannedParamNameInUnscannedParamExp);
// @TODO: we have no range??
SetValue setValue = new SetValue(target, rangeId, sedModel.getId());
setValue.setMath(math);
rt.addChange(setValue);
} else {
// non-numeric expression : add 'computeChange' to modified model
XPathTarget targetXpath = getTargetXPath(ste, l2gMap);
ComputeChange computeChange = new ComputeChange(targetXpath, math);
for (String symbol : exprSymbols) {
String symbolName = TokenMangler.mangleToSName(symbol);
SymbolTableEntry ste1 = vcModel.getEntry(symbol);
// ste1 could be a math parameter, hence the above could return null
if (ste1 == null) {
ste1 = simContext.getMathDescription().getEntry(symbol);
}
if (ste1 != null) {
if (ste1 instanceof SpeciesContext || ste1 instanceof Structure || ste1 instanceof ModelParameter) {
XPathTarget ste1_XPath = getTargetXPath(ste1, l2gMap);
org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(symbolName, symbolName, taskRef, ste1_XPath.getTargetAsString());
computeChange.addVariable(sedmlVar);
} else {
double doubleValue = 0.0;
if (ste1 instanceof ReservedSymbol) {
doubleValue = getReservedSymbolValue(ste1);
} else if (ste instanceof Function) {
try {
doubleValue = ste.getExpression().evaluateConstant();
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to evaluate function '" + ste.getName() + "' used in '" + unscannedParamName + "' expression : ", e);
}
} else {
doubleValue = ste.getConstantValue();
}
// TODO: shouldn't be s1_init_uM which is a math symbol, should be s0 (so use the ste-something from above)
// TODO: revert to Variable, not Parameter
Parameter sedmlParameter = new Parameter(symbolName, symbolName, doubleValue);
computeChange.addParameter(sedmlParameter);
}
} else {
throw new RuntimeException("Symbol '" + symbol + "' used in expression for '" + unscannedParamName + "' not found in model.");
}
}
sedModel.addChange(computeChange);
}
}
}
sedmlModel.addModel(sedModel);
sedmlModel.addTask(rt);
}
} else {
// no math overrides, add basic task.
String taskId = "tsk_" + simContextCnt + "_" + simCount;
Task sedmlTask = new Task(taskId, taskId, simContextId, utcSim.getId());
sedmlModel.addTask(sedmlTask);
// to be used later to add dataGenerators : one set of DGs per model (simContext).
taskRef = taskId;
}
// add one dataGenerator for 'time' for entire SEDML model.
// (using the id of the first task in model for 'taskRef' field of var since
String timeDataGenPrefix = DATAGENERATOR_TIME_NAME + "_" + taskRef;
DataGenerator timeDataGen = sedmlModel.getDataGeneratorWithId(timeDataGenPrefix);
if (timeDataGen == null) {
// org.jlibsedml.Variable timeVar = new org.jlibsedml.Variable(DATAGENERATOR_TIME_SYMBOL, DATAGENERATOR_TIME_SYMBOL, sedmlModel.getTasks().get(0).getId(), VariableSymbol.TIME);
org.jlibsedml.Variable timeVar = new org.jlibsedml.Variable(DATAGENERATOR_TIME_SYMBOL, DATAGENERATOR_TIME_SYMBOL, taskRef, VariableSymbol.TIME);
ASTNode math = Libsedml.parseFormulaString(DATAGENERATOR_TIME_SYMBOL);
timeDataGen = new DataGenerator(timeDataGenPrefix, timeDataGenPrefix, math);
timeDataGen.addVariable(timeVar);
sedmlModel.addDataGenerator(timeDataGen);
dataGeneratorsOfSim.add(timeDataGen);
}
// add dataGenerators for species
// get species list from SBML model.
String dataGenIdPrefix = "dataGen_" + taskRef;
String[] varNamesList = SimSpec.fromSBML(sbmlString).getVarsList();
for (String varName : varNamesList) {
org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(varName, varName, taskRef, sbmlSupport.getXPathForSpecies(varName));
ASTNode varMath = Libsedml.parseFormulaString(varName);
// "dataGen_" + varCount; - old code
String dataGenId = dataGenIdPrefix + "_" + TokenMangler.mangleToSName(varName);
DataGenerator dataGen = new DataGenerator(dataGenId, dataGenId, varMath);
dataGen.addVariable(sedmlVar);
sedmlModel.addDataGenerator(dataGen);
dataGeneratorsOfSim.add(dataGen);
varCount++;
}
// add DataGenerators for output functions here
ArrayList<AnnotatedFunction> outputFunctions = simContext.getOutputFunctionContext().getOutputFunctionsList();
for (AnnotatedFunction annotatedFunction : outputFunctions) {
Expression functionExpr = annotatedFunction.getExpression();
ASTNode funcMath = Libsedml.parseFormulaString(functionExpr.infix());
// "dataGen_" + varCount; - old code
String dataGenId = dataGenIdPrefix + "_" + TokenMangler.mangleToSName(annotatedFunction.getName());
DataGenerator dataGen = new DataGenerator(dataGenId, dataGenId, funcMath);
String[] functionSymbols = functionExpr.getSymbols();
for (String symbol : functionSymbols) {
String symbolName = TokenMangler.mangleToSName(symbol);
// try to get symbol from model, if null, try simContext.mathDesc
SymbolTableEntry ste = vcModel.getEntry(symbol);
if (ste == null) {
ste = simContext.getMathDescription().getEntry(symbol);
}
if (ste instanceof SpeciesContext || ste instanceof Structure || ste instanceof ModelParameter) {
XPathTarget targetXPath = getTargetXPath(ste, l2gMap);
org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(symbolName, symbolName, taskRef, targetXPath.getTargetAsString());
dataGen.addVariable(sedmlVar);
} else {
double value = 0.0;
if (ste instanceof Function) {
try {
value = ste.getExpression().evaluateConstant();
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to evaluate function '" + ste.getName() + "' for output function '" + annotatedFunction.getName() + "'.", e);
}
} else {
value = ste.getConstantValue();
}
Parameter sedmlParameter = new Parameter(symbolName, symbolName, value);
dataGen.addParameter(sedmlParameter);
}
}
sedmlModel.addDataGenerator(dataGen);
dataGeneratorsOfSim.add(dataGen);
varCount++;
}
simCount++;
// ignoring output for spatial deterministic (spatial stochastic is not exported to SEDML) and non-spatial stochastic applications with histogram
if (!(simContext.getGeometry().getDimension() > 0)) {
// ignore Output (Plot2d) for non-spatial stochastic simulation with histogram.
boolean bSimHasHistogram = false;
if (simContext.isStoch()) {
long numOfTrials = simTaskDesc.getStochOpt().getNumOfTrials();
if (numOfTrials > 1) {
// not histogram {
bSimHasHistogram = true;
}
}
if (!bSimHasHistogram) {
String plot2dId = "plot2d_" + TokenMangler.mangleToSName(vcSimulation.getName());
Plot2D sedmlPlot2d = new Plot2D(plot2dId, simContext.getName() + "plots");
sedmlPlot2d.addNote(createNotesElement("Plot of all variables and output functions from application '" + simContext.getName() + "' ; simulation '" + vcSimulation.getName() + "' in VCell model"));
List<DataGenerator> dataGenerators = sedmlModel.getDataGenerators();
String xDataRef = sedmlModel.getDataGeneratorWithId(DATAGENERATOR_TIME_NAME + "_" + taskRef).getId();
// add a curve for each dataGenerator in SEDML model
int curveCnt = 0;
for (DataGenerator dataGenerator : dataGeneratorsOfSim) {
// no curve for time, since time is xDateReference
if (dataGenerator.getId().equals(xDataRef)) {
continue;
}
String curveId = "curve_" + curveCnt++;
Curve curve = new Curve(curveId, curveId, false, false, xDataRef, dataGenerator.getId());
sedmlPlot2d.addCurve(curve);
}
sedmlModel.addOutput(sedmlPlot2d);
}
}
}
// end - for 'sims'
} else {
// end if (!(simContext.getGeometry().getDimension() > 0 && simContext.isStoch()))
String msg = "\n\t" + simContextName + " : export of spatial stochastic (Smoldyn solver) applications to SEDML not supported at this time.";
sedmlNotesStr += msg;
}
// end : if-else simContext is not spatial stochastic
simContextCnt++;
}
// if sedmlNotesStr is not null, there were some applications that could not be exported to SEDML (eg., spatial stochastic). Create a notes element and add it to sedml Model.
if (sedmlNotesStr.length() > 0) {
sedmlNotesStr = "\n\tThe following applications in the VCell model were not exported to VCell : " + sedmlNotesStr;
sedmlModel.addNote(createNotesElement(sedmlNotesStr));
}
// error check : if there are no non-spatial deterministic applications (=> no models in SEDML document), complain.
if (sedmlModel.getModels().isEmpty()) {
throw new RuntimeException("No applications in biomodel to export to Sedml.");
}
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error adding model to SEDML document : " + e.getMessage());
}
}
use of cbit.vcell.model.ModelUnitSystem in project vcell by virtualcell.
the class SBMLImporter method addParameters.
/**
* addParameters : Adds global parameters from SBML model to VCell model. If
* expression for global parameter contains species, creates a conc_factor
* parameter (conversion from SBML - VCell conc units) and adds this factor
* to VC global params list, and replaces occurances of 'sp' with
* 'sp*concFactor' in original param expression.
*
* @throws PropertyVetoException
*/
protected void addParameters() throws Exception {
ListOf listofGlobalParams = sbmlModel.getListOfParameters();
if (listofGlobalParams == null) {
System.out.println("No Global Parameters");
return;
}
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
ArrayList<ModelParameter> vcModelParamsList = new ArrayList<Model.ModelParameter>();
// create a hash of reserved symbols so that if there is any reserved
// symbol occurring as a global parameter in the SBML model,
// the hash can be used to check for reserved symbols, so that it will
// not be added as a global parameter in VCell,
// since reserved symbols cannot be used as other variables (species,
// structureSize, parameters, reactions, etc.).
HashSet<String> reservedSymbolHash = new HashSet<String>();
for (ReservedSymbol rs : vcModel.getReservedSymbols()) {
reservedSymbolHash.add(rs.getName());
}
ModelUnitSystem modelUnitSystem = vcModel.getUnitSystem();
for (int i = 0; i < sbmlModel.getNumParameters(); i++) {
Parameter sbmlGlobalParam = (Parameter) listofGlobalParams.get(i);
String paramName = sbmlGlobalParam.getId();
SpatialParameterPlugin spplugin = null;
if (bSpatial) {
// check if parameter id is x/y/z : if so, check if its
// 'spatialSymbolRef' child's spatial id and type are non-empty.
// If so, the parameter represents a spatial element.
// If not, throw an exception, since a parameter that does not
// represent a spatial element cannot have an id of x/y/z
spplugin = (SpatialParameterPlugin) sbmlGlobalParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
if (paramName.equals("x") || paramName.equals("y") || paramName.equals("z")) {
boolean bSpatialParam = (spplugin != null && spplugin.getParamType() instanceof SpatialSymbolReference);
// if (a) and (b) are true, continue with the next parameter
if (!bSpatialParam) {
throw new RuntimeException("Parameter '" + paramName + "' is not a spatial parameter : Cannot have a variable in VCell named '" + paramName + "' unless it is a spatial variable.");
} else {
// parameter to the list of vcell parameters.
continue;
}
}
}
//
// Get param value if set or get its expression from rule
//
// Check if param is defined by an assignment rule or initial
// assignment. If so, that value overrides the value existing in the
// param element.
// assignment rule, first
Expression valueExpr = getValueFromAssignmentRule(paramName);
if (valueExpr == null) {
if (sbmlGlobalParam.isSetValue()) {
double value = sbmlGlobalParam.getValue();
valueExpr = new Expression(value);
} else {
// if value for global param is not set and param has a rate
// rule, need to set an init value for param (else, there
// will be a problem in reaction which uses this parameter).
// use a 'default' initial value of '0'
valueExpr = new Expression(0.0);
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.Priority.LowPriority,
// "Parameter did not have an initial value, but has a rate rule specified. Using a default value of 0.0.");
}
}
if (valueExpr != null) {
// valueExpr will be changed
valueExpr = adjustExpression(valueExpr, vcModel);
}
// extension
if (bSpatial) {
VCAssert.assertTrue(spplugin != null, "invalid initialization logic");
ParameterType sbmlParamType = spplugin.getParamType();
SpeciesContext paramSpContext = null;
SpeciesContextSpec vcSpContextsSpec = null;
// Check for diffusion coefficient(s)
if (sbmlParamType instanceof DiffusionCoefficient) {
DiffusionCoefficient diffCoeff = (DiffusionCoefficient) sbmlParamType;
if (diffCoeff != null && diffCoeff.isSetVariable()) {
// get the var of diffCoeff; find appropriate spContext
// in vcell; set its diff param to param value.
paramSpContext = vcModel.getSpeciesContext(diffCoeff.getVariable());
if (paramSpContext != null) {
vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
vcSpContextsSpec.getDiffusionParameter().setExpression(valueExpr);
}
// coeff parameter to the list of vcell parameters.
continue;
}
}
// Check for advection coefficient(s)
if (sbmlParamType instanceof AdvectionCoefficient) {
AdvectionCoefficient advCoeff = (AdvectionCoefficient) sbmlParamType;
if (advCoeff != null && advCoeff.isSetVariable()) {
// get the var of advCoeff; find appropriate spContext
// in vcell; set its adv param to param value.
paramSpContext = vcModel.getSpeciesContext(advCoeff.getVariable());
if (paramSpContext != null) {
vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
CoordinateKind coordKind = advCoeff.getCoordinate();
SpeciesContextSpecParameter param = null;
switch(coordKind) {
case cartesianX:
{
param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityX);
break;
}
case cartesianY:
{
param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityY);
break;
}
case cartesianZ:
{
param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityZ);
break;
}
}
param.setExpression(valueExpr);
}
// coeff parameter to the list of vcell parameters.
continue;
}
}
// Check for Boundary condition(s)
if (sbmlParamType instanceof BoundaryCondition) {
BoundaryCondition bCondn = (BoundaryCondition) sbmlParamType;
if (bCondn != null && bCondn.isSetVariable()) {
// get the var of boundaryCondn; find appropriate
// spContext in vcell;
// set the BC param of its speciesContextSpec to param
// value.
paramSpContext = vcModel.getSpeciesContext(bCondn.getVariable());
if (paramSpContext == null) {
throw new RuntimeException("unable to process boundary condition for variable " + bCondn.getVariable());
}
StructureMapping sm = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(paramSpContext.getStructure());
vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
for (CoordinateComponent coordComp : getSbmlGeometry().getListOfCoordinateComponents()) {
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMinimum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
vcSpContextsSpec.getBoundaryXmParameter().setExpression(valueExpr);
}
case cartesianY:
{
vcSpContextsSpec.getBoundaryYmParameter().setExpression(valueExpr);
}
case cartesianZ:
{
vcSpContextsSpec.getBoundaryZmParameter().setExpression(valueExpr);
}
}
}
if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMaximum().getSpatialId())) {
switch(coordComp.getType()) {
case cartesianX:
{
vcSpContextsSpec.getBoundaryXpParameter().setExpression(valueExpr);
}
case cartesianY:
{
vcSpContextsSpec.getBoundaryYpParameter().setExpression(valueExpr);
}
case cartesianZ:
{
vcSpContextsSpec.getBoundaryZpParameter().setExpression(valueExpr);
}
}
}
}
continue;
}
}
// Check for Boundary condition(s)
if (sbmlParamType instanceof SpatialSymbolReference) {
SpatialSymbolReference spatialSymbolRef = (SpatialSymbolReference) sbmlParamType;
throw new RuntimeException("generic Spatial Symbol References not yet supported, unresolved spatial reference '" + spatialSymbolRef.getSpatialRef() + "'");
}
}
// doesn't exist.
if (vcModel.getModelParameter(paramName) == null) {
VCUnitDefinition glParamUnitDefn = sbmlUnitIdentifierHash.get(sbmlGlobalParam.getUnits());
// set it to TBD or check if it was dimensionless.
if (glParamUnitDefn == null) {
glParamUnitDefn = modelUnitSystem.getInstance_TBD();
}
// VCell : cannot add reserved symbol to model params.
if (!reservedSymbolHash.contains(paramName)) {
ModelParameter vcGlobalParam = vcModel.new ModelParameter(paramName, valueExpr, Model.ROLE_UserDefined, glParamUnitDefn);
if (paramName.length() > 64) {
// record global parameter name in annotation if it is
// longer than 64 characeters
vcGlobalParam.setDescription("Parameter Name : " + paramName);
}
vcModelParamsList.add(vcGlobalParam);
}
}
}
// end for - sbmlModel.parameters
vcModel.setModelParameters(vcModelParamsList.toArray(new ModelParameter[0]));
}
use of cbit.vcell.model.ModelUnitSystem in project vcell by virtualcell.
the class SBMLImporter method addReactions.
/**
* addReactions:
*/
protected void addReactions(VCMetaData metaData) {
if (sbmlModel == null) {
throw new SBMLImportException("SBML model is NULL");
}
ListOf<Reaction> reactions = sbmlModel.getListOfReactions();
final int numReactions = reactions.size();
if (numReactions == 0) {
lg.info("No Reactions");
return;
}
// all reactions
ArrayList<ReactionStep> vcReactionList = new ArrayList<>();
// just the fast ones
ArrayList<ReactionStep> fastReactionList = new ArrayList<>();
Model vcModel = vcBioModel.getSimulationContext(0).getModel();
ModelUnitSystem vcModelUnitSystem = vcModel.getUnitSystem();
SpeciesContext[] vcSpeciesContexts = vcModel.getSpeciesContexts();
try {
for (Reaction sbmlRxn : reactions) {
ReactionStep vcReaction = null;
String rxnName = sbmlRxn.getId();
boolean bReversible = true;
if (sbmlRxn.isSetReversible()) {
bReversible = sbmlRxn.getReversible();
}
// Check of reaction annotation is present; if so, does it have
// an embedded element (flux or simpleRxn).
// Create a fluxReaction or simpleReaction accordingly.
Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlRxn);
Structure reactionStructure = getReactionStructure(sbmlRxn, vcSpeciesContexts, sbmlImportRelatedElement);
if (sbmlImportRelatedElement != null) {
Element embeddedRxnElement = getEmbeddedElementInAnnotation(sbmlImportRelatedElement, REACTION);
if (embeddedRxnElement != null) {
if (embeddedRxnElement.getName().equals(XMLTags.FluxStepTag)) {
// If embedded element is a flux reaction, set flux
// reaction's strucure, flux carrier, physicsOption
// from the element attributes.
String structName = embeddedRxnElement.getAttributeValue(XMLTags.StructureAttrTag);
CastInfo<Membrane> ci = SBMLHelper.getTypedStructure(Membrane.class, vcModel, structName);
if (!ci.isGood()) {
throw new SBMLImportException("Appears that the flux reaction is occuring on " + ci.actualName() + ", not a membrane.");
}
vcReaction = new FluxReaction(vcModel, ci.get(), null, rxnName, bReversible);
vcReaction.setModel(vcModel);
// Set the fluxOption on the flux reaction based on
// whether it is molecular, molecular & electrical,
// electrical.
String fluxOptionStr = embeddedRxnElement.getAttributeValue(XMLTags.FluxOptionAttrTag);
if (fluxOptionStr.equals(XMLTags.FluxOptionMolecularOnly)) {
((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_MOLECULAR_ONLY);
} else if (fluxOptionStr.equals(XMLTags.FluxOptionMolecularAndElectrical)) {
((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_MOLECULAR_AND_ELECTRICAL);
} else if (fluxOptionStr.equals(XMLTags.FluxOptionElectricalOnly)) {
((FluxReaction) vcReaction).setPhysicsOptions(ReactionStep.PHYSICS_ELECTRICAL_ONLY);
} else {
localIssueList.add(new Issue(vcReaction, issueContext, IssueCategory.SBMLImport_Reaction, "Unknown FluxOption : " + fluxOptionStr + " for SBML reaction : " + rxnName, Issue.SEVERITY_WARNING));
// logger.sendMessage(VCLogger.Priority.MediumPriority,
// VCLogger.ErrorType.ReactionError,
// "Unknown FluxOption : " + fluxOptionStr +
// " for SBML reaction : " + rxnName);
}
} else if (embeddedRxnElement.getName().equals(XMLTags.SimpleReactionTag)) {
// if embedded element is a simple reaction, set
// simple reaction's structure from element
// attributes
vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
}
} else {
vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
}
} else {
vcReaction = new SimpleReaction(vcModel, reactionStructure, rxnName, bReversible);
}
// set annotations and notes on vcReactions[i]
sbmlAnnotationUtil.readAnnotation(vcReaction, sbmlRxn);
sbmlAnnotationUtil.readNotes(vcReaction, sbmlRxn);
// the limit on the reactionName length.
if (rxnName.length() > 64) {
String freeTextAnnotation = metaData.getFreeTextAnnotation(vcReaction);
if (freeTextAnnotation == null) {
freeTextAnnotation = "";
}
StringBuffer oldRxnAnnotation = new StringBuffer(freeTextAnnotation);
oldRxnAnnotation.append("\n\n" + rxnName);
metaData.setFreeTextAnnotation(vcReaction, oldRxnAnnotation.toString());
}
// Now add the reactants, products, modifiers as specified by
// the sbmlRxn
addReactionParticipants(sbmlRxn, vcReaction);
KineticLaw kLaw = sbmlRxn.getKineticLaw();
Kinetics kinetics = null;
if (kLaw != null) {
// Convert the formula from kineticLaw into MathML and then
// to an expression (infix) to be used in VCell kinetics
ASTNode sbmlRateMath = kLaw.getMath();
Expression kLawRateExpr = getExpressionFromFormula(sbmlRateMath);
Expression vcRateExpression = new Expression(kLawRateExpr);
// modifier (catalyst) to the reaction.
for (int k = 0; k < vcSpeciesContexts.length; k++) {
if (vcRateExpression.hasSymbol(vcSpeciesContexts[k].getName())) {
if ((vcReaction.getReactant(vcSpeciesContexts[k].getName()) == null) && (vcReaction.getProduct(vcSpeciesContexts[k].getName()) == null) && (vcReaction.getCatalyst(vcSpeciesContexts[k].getName()) == null)) {
// This means that the speciesContext is not a
// reactant, product or modifier : it has to be
// added to the VC Rxn as a catalyst
vcReaction.addCatalyst(vcSpeciesContexts[k]);
}
}
}
// set kinetics on VCell reaction
if (bSpatial) {
// if spatial SBML ('isSpatial' attribute set), create
// DistributedKinetics)
SpatialReactionPlugin ssrplugin = (SpatialReactionPlugin) sbmlRxn.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
// 'spatial'
if (ssrplugin != null && ssrplugin.getIsLocal()) {
kinetics = new GeneralKinetics(vcReaction);
} else {
kinetics = new GeneralLumpedKinetics(vcReaction);
}
} else {
kinetics = new GeneralLumpedKinetics(vcReaction);
}
// set kinetics on vcReaction
vcReaction.setKinetics(kinetics);
// If the name of the rate parameter has been changed by
// user, or matches with global/local param,
// it has to be changed.
resolveRxnParameterNameConflicts(sbmlRxn, kinetics, sbmlImportRelatedElement);
/**
* Now, based on the kinetic law expression, see if the rate
* is expressed in concentration/time or substance/time : If
* the compartment_id of the compartment corresponding to
* the structure in which the reaction takes place occurs in
* the rate law expression, it is in concentration/time;
* divide it by the compartment size and bring in the rate
* law as 'Distributed' kinetics. If not, the rate law is in
* substance/time; bring it in (as is) as 'Lumped' kinetics.
*/
ListOf<LocalParameter> localParameters = kLaw.getListOfLocalParameters();
for (LocalParameter p : localParameters) {
String paramName = p.getId();
KineticsParameter kineticsParameter = kinetics.getKineticsParameter(paramName);
if (kineticsParameter == null) {
// add unresolved for now to prevent errors in kinetics.setParameterValue(kp,vcRateExpression) below
kinetics.addUnresolvedParameter(paramName);
}
}
KineticsParameter kp = kinetics.getAuthoritativeParameter();
if (lg.isDebugEnabled()) {
lg.debug("Setting " + kp.getName() + ": " + vcRateExpression.infix());
}
kinetics.setParameterValue(kp, vcRateExpression);
// If there are any global parameters used in the kinetics,
// and if they have species,
// check if the species are already reactionParticipants in
// the reaction. If not, add them as catalysts.
KineticsProxyParameter[] kpps = kinetics.getProxyParameters();
for (int j = 0; j < kpps.length; j++) {
if (kpps[j].getTarget() instanceof ModelParameter) {
ModelParameter mp = (ModelParameter) kpps[j].getTarget();
HashSet<String> refSpeciesNameHash = new HashSet<String>();
getReferencedSpeciesInExpr(mp.getExpression(), refSpeciesNameHash);
java.util.Iterator<String> refSpIterator = refSpeciesNameHash.iterator();
while (refSpIterator.hasNext()) {
String spName = refSpIterator.next();
org.sbml.jsbml.Species sp = sbmlModel.getSpecies(spName);
ArrayList<ReactionParticipant> rpArray = getVCReactionParticipantsFromSymbol(vcReaction, sp.getId());
if (rpArray == null || rpArray.size() == 0) {
// This means that the speciesContext is not
// a reactant, product or modifier : it has
// to be added as a catalyst
vcReaction.addCatalyst(vcModel.getSpeciesContext(sp.getId()));
}
}
}
}
// model - local params cannot be defined by rules.
for (LocalParameter param : localParameters) {
String paramName = param.getId();
Expression exp = new Expression(param.getValue());
String unitString = param.getUnits();
VCUnitDefinition paramUnit = sbmlUnitIdentifierHash.get(unitString);
if (paramUnit == null) {
paramUnit = vcModelUnitSystem.getInstance_TBD();
}
// check if sbml local param is in kinetic params list;
// if so, add its value.
boolean lpSet = false;
KineticsParameter kineticsParameter = kinetics.getKineticsParameter(paramName);
if (kineticsParameter != null) {
if (lg.isDebugEnabled()) {
lg.debug("Setting local " + kineticsParameter.getName() + ": " + exp.infix());
}
kineticsParameter.setExpression(exp);
kineticsParameter.setUnitDefinition(paramUnit);
lpSet = true;
} else {
UnresolvedParameter ur = kinetics.getUnresolvedParameter(paramName);
if (ur != null) {
kinetics.addUserDefinedKineticsParameter(paramName, exp, paramUnit);
lpSet = true;
}
}
if (!lpSet) {
// check if it is a proxy parameter (specifically,
// speciesContext or model parameter (structureSize
// too)).
KineticsProxyParameter kpp = kinetics.getProxyParameter(paramName);
// and units to local param values
if (kpp != null && kpp.getTarget() instanceof ModelParameter) {
kinetics.convertParameterType(kpp, false);
kineticsParameter = kinetics.getKineticsParameter(paramName);
kinetics.setParameterValue(kineticsParameter, exp);
kineticsParameter.setUnitDefinition(paramUnit);
}
}
}
} else {
// sbmlKLaw was null, so creating a GeneralKinetics with 0.0
// as rate.
kinetics = new GeneralKinetics(vcReaction);
}
// end - if-else KLaw != null
// set the reaction kinetics, and add reaction to the vcell
// model.
kinetics.resolveUndefinedUnits();
// System.out.println("ADDED SBML REACTION : \"" + rxnName +
// "\" to VCModel");
vcReactionList.add(vcReaction);
if (sbmlRxn.isSetFast() && sbmlRxn.getFast()) {
fastReactionList.add(vcReaction);
}
}
// end - for vcReactions
ReactionStep[] array = vcReactionList.toArray(new ReactionStep[vcReactionList.size()]);
vcModel.setReactionSteps(array);
final ReactionContext rc = vcBioModel.getSimulationContext(0).getReactionContext();
for (ReactionStep frs : fastReactionList) {
final ReactionSpec rs = rc.getReactionSpec(frs);
rs.setReactionMapping(ReactionSpec.FAST);
}
} catch (ModelPropertyVetoException mpve) {
throw new SBMLImportException(mpve.getMessage(), mpve);
} catch (Exception e1) {
e1.printStackTrace(System.out);
throw new SBMLImportException(e1.getMessage(), e1);
}
}
use of cbit.vcell.model.ModelUnitSystem 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.model.ModelUnitSystem 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);
}
}
Aggregations