use of cbit.vcell.mapping.StructureMapping 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.mapping.StructureMapping 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.mapping.StructureMapping in project vcell by virtualcell.
the class ElectricalMembraneMappingTableModel method setGeometryContext.
/**
* Sets the geometryContext property (cbit.vcell.mapping.GeometryContext) value.
* @param geometryContext The new value for the property.
* @see #getGeometryContext
*/
public void setGeometryContext(GeometryContext geometryContext) {
GeometryContext oldValue = fieldGeometryContext;
if (oldValue != null) {
oldValue.removePropertyChangeListener(this);
StructureMapping[] oldStructureMappings = oldValue.getStructureMappings();
for (int i = 0; i < oldStructureMappings.length; i++) {
if (oldStructureMappings[i] instanceof MembraneMapping) {
oldStructureMappings[i].removePropertyChangeListener(this);
}
}
}
fieldGeometryContext = geometryContext;
if (geometryContext != null) {
geometryContext.addPropertyChangeListener(this);
StructureMapping[] newStructureMappings = geometryContext.getStructureMappings();
for (int i = 0; i < newStructureMappings.length; i++) {
if (newStructureMappings[i] instanceof MembraneMapping) {
newStructureMappings[i].addPropertyChangeListener(this);
}
}
}
refreshData();
}
use of cbit.vcell.mapping.StructureMapping in project vcell by virtualcell.
the class StructureMappingTableRenderer method getTableCellRendererComponent.
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setIcon(null);
if (table.getModel() instanceof StructureMappingTableModel) {
StructureMappingTableModel structureMappingTableModel = (StructureMappingTableModel) table.getModel();
String toolTip = structureMappingTableModel.getToolTip(row, column);
if (value instanceof Structure) {
Structure structure = (Structure) value;
setText(structure.getName());
} else if (value instanceof Double && structureMappingTableModel.isNewSizeColumn(column)) {
StructureMapping structureMapping = structureMappingTableModel.getStructureMapping(row);
if (structureMappingTableModel.isNonSpatial()) {
VCUnitDefinition unitDefinition = structureMapping.getStructure().getStructureSize().getUnitDefinition();
TextIcon sizeIcon = unitIconHash.get(unitDefinition.getSymbol());
if (sizeIcon == null) {
sizeIcon = new TextIcon("[ " + unitDefinition.getSymbolUnicode() + " ]");
unitIconHash.put(unitDefinition.getSymbol(), sizeIcon);
}
setIcon(sizeIcon);
} else {
// spatial
if (structureMapping.getUnitSizeParameter() != null) {
VCUnitDefinition unitDefinition = structureMapping.getUnitSizeParameter().getUnitDefinition();
TextIcon sizeIcon = unitIconHash.get(unitDefinition.getSymbol());
if (sizeIcon == null) {
sizeIcon = new TextIcon("[ " + unitDefinition.getSymbolUnicode() + " ]");
unitIconHash.put(unitDefinition.getSymbol(), sizeIcon);
}
setIcon(sizeIcon);
}
}
}
if (structureMappingTableModel.isSubdomainColumn(column)) {
// can be null
if (value == null) {
setText("Unmapped");
setForeground(Color.red);
setIcon(null);
} else {
if (value instanceof GeometryClass) {
setText(((GeometryClass) value).getName());
if (value instanceof SubVolume) {
SubVolume subVolume = (SubVolume) value;
java.awt.Color handleColor = new java.awt.Color(colormap[subVolume.getHandle()]);
// small square icon with subdomain color
Icon icon = new ColorIcon(10, 10, handleColor, true);
setHorizontalTextPosition(SwingConstants.RIGHT);
setIcon(icon);
} else if (value instanceof SurfaceClass) {
SurfaceClass sc = (SurfaceClass) value;
Set<SubVolume> sv = sc.getAdjacentSubvolumes();
Iterator<SubVolume> iterator = sv.iterator();
SubVolume sv1 = iterator.next();
SubVolume sv2 = iterator.next();
java.awt.Color c1 = new java.awt.Color(colormap[sv2.getHandle()]);
java.awt.Color c2 = new java.awt.Color(colormap[sv1.getHandle()]);
Icon icon = new ColorIconEx(10, 10, c1, c2);
setIcon(icon);
setHorizontalTextPosition(SwingConstants.RIGHT);
}
} else {
setText(value.toString());
setIcon(null);
}
}
}
if (value instanceof BoundaryConditionType) {
// we get here only for spatial
Object candidate = structureMappingTableModel.getValueAt(row, StructureMappingTableModel.SPATIAL_COLUMN_SUBDOMAIN);
if (candidate instanceof SurfaceClass) {
SurfaceClass surfaceClass = (SurfaceClass) candidate;
cbit.vcell.model.Model model = structureMappingTableModel.getGeometryContext().getModel();
SimulationContext simContext = structureMappingTableModel.getGeometryContext().getSimulationContext();
Pair<SubVolume, SubVolume> ret = DiffEquMathMapping.computeBoundaryConditionSource(model, simContext, surfaceClass);
SubVolume innerSubVolume = ret.one;
java.awt.Color handleColor = new java.awt.Color(colormap[innerSubVolume.getHandle()]);
// small square icon with subdomain color
Icon icon = new ColorIcon(8, 8, handleColor, true);
setHorizontalTextPosition(SwingConstants.LEFT);
setIcon(icon);
setText("from");
// override default tooltip
toolTip = "Boundary condition inherited from Subdomain '" + innerSubVolume.getName() + "'";
setToolTipText(toolTip);
} else {
setText(((BoundaryConditionType) value).boundaryTypeStringValue());
}
}
List<Issue> issueList = structureMappingTableModel.getIssues(row, column, Issue.SEVERITY_ERROR);
if (issueList.size() > 0) {
// override default tooltip
setToolTipText(Issue.getHtmlIssueMessage(issueList));
if (column == 0) {
setBorder(new MatteBorder(1, 1, 1, 0, Color.red));
} else if (column == table.getColumnCount() - 1) {
setBorder(new MatteBorder(1, 0, 1, 1, Color.red));
} else {
setBorder(new MatteBorder(1, 0, 1, 0, Color.red));
}
} else {
setToolTipText(toolTip);
setBorder(DEFAULT_GAP);
}
}
return this;
}
use of cbit.vcell.mapping.StructureMapping in project vcell by virtualcell.
the class SbmlExtensionFilter method askUser.
@Override
public void askUser(ChooseContext c) throws UserCancelException {
BioModel bioModel = c.chosenContext.getBioModel();
JFrame currentWindow = c.currentWindow;
selectedSimWOSBE = null;
selectedSimContext = c.chosenContext;
// get user choice of structure and its size and computes absolute sizes of compartments using the StructureSizeSolver.
Structure[] structures = bioModel.getModel().getStructures();
// get the nonspatial simulationContexts corresponding to names in applicableAppNameList
// This is needed in ApplnSelectionAndStructureSizeInputPanel
String strucName = null;
double structSize = 1.0;
int structSelection = -1;
int option = JOptionPane.CANCEL_OPTION;
ApplnSelectionAndStructureSizeInputPanel applnStructInputPanel = null;
while (structSelection < 0) {
applnStructInputPanel = new ApplnSelectionAndStructureSizeInputPanel();
applnStructInputPanel.setSimContext(c.chosenContext);
applnStructInputPanel.setStructures(structures);
if (applnStructInputPanel.isNeedStructureSizes()) {
applnStructInputPanel.setPreferredSize(new java.awt.Dimension(350, 400));
applnStructInputPanel.setMaximumSize(new java.awt.Dimension(350, 400));
option = DialogUtils.showComponentOKCancelDialog(currentWindow, applnStructInputPanel, "Specify Structure Size to Export:");
structSelection = applnStructInputPanel.getStructSelectionIndex();
if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
break;
} else if (option == JOptionPane.OK_OPTION && structSelection < 0) {
DialogUtils.showErrorDialog(currentWindow, "Please select a structure and set its size");
}
} else {
// adapt to legacy logic ...
structSelection = 0;
option = JOptionPane.OK_OPTION;
}
}
if (option == JOptionPane.OK_OPTION) {
applnStructInputPanel.applyStructureNameAndSizeValues();
strucName = applnStructInputPanel.getSelectedStructureName();
selectedSimContext = applnStructInputPanel.getSelectedSimContext();
GeometryContext geoContext = selectedSimContext.getGeometryContext();
if (!isSpatial) {
// calculate structure Sizes only if appln is not spatial
structSize = applnStructInputPanel.getStructureSize();
// Invoke StructureSizeEvaluator to compute absolute sizes of compartments if all sizes are not set
if ((geoContext.isAllSizeSpecifiedNull() && geoContext.isAllVolFracAndSurfVolSpecifiedNull()) || ((strucName == null || structSize <= 0.0) && (geoContext.isAllSizeSpecifiedNull() && geoContext.isAllVolFracAndSurfVolSpecified())) || (!geoContext.isAllSizeSpecifiedPositive() && geoContext.isAllVolFracAndSurfVolSpecifiedNull()) || (!geoContext.isAllSizeSpecifiedPositive() && !geoContext.isAllVolFracAndSurfVolSpecified()) || (geoContext.isAllSizeSpecifiedNull() && !geoContext.isAllVolFracAndSurfVolSpecified())) {
DialogUtils.showErrorDialog(currentWindow, "Cannot export to SBML without compartment sizes being set. This can be automatically " + " computed if the absolute size of at least one compartment and the relative sizes (Surface-to-volume-ratio/Volume-fraction) " + " of all compartments are known. Sufficient information is not available to perform this computation." + "\n\nThis can be fixed by going back to the application '" + selectedSimContext.getName() + "' and setting structure sizes in the 'StructureMapping' tab.");
throw UserCancelException.CANCEL_XML_TRANSLATION;
}
if (!geoContext.isAllSizeSpecifiedPositive() && geoContext.isAllVolFracAndSurfVolSpecified()) {
Structure chosenStructure = selectedSimContext.getModel().getStructure(strucName);
StructureMapping chosenStructMapping = selectedSimContext.getGeometryContext().getStructureMapping(chosenStructure);
try {
StructureSizeSolver.updateAbsoluteStructureSizes(selectedSimContext, chosenStructure, structSize, chosenStructMapping.getSizeParameter().getUnitDefinition());
} catch (Exception e) {
throw new ProgrammingException("exception updating sizes", e);
}
}
} else {
if (!geoContext.isAllUnitSizeParameterSetForSpatial()) {
DialogUtils.showErrorDialog(currentWindow, "Cannot export to SBML without compartment size ratios being set." + "\n\nThis can be fixed by going back to the application '" + selectedSimContext.getName() + "' and setting structure" + " size ratios in the 'StructureMapping' tab.");
throw UserCancelException.CANCEL_XML_TRANSLATION;
}
}
// Select simulation whose overrides need to be exported
// If simContext doesn't have simulations, don't pop up simulationSelectionPanel
Simulation[] sims = bioModel.getSimulations(selectedSimContext);
// display only those simulations that have overrides in the simulationSelectionPanel.
Vector<Simulation> orSims = new Vector<Simulation>();
for (int s = 0; (sims != null) && (s < sims.length); s++) {
if (sims[s].getMathOverrides().hasOverrides()) {
orSims.addElement(sims[s]);
}
}
Simulation[] overriddenSims = orSims.toArray(new Simulation[orSims.size()]);
if (overriddenSims.length > 0) {
SimulationSelectionPanel simSelectionPanel = new SimulationSelectionPanel();
simSelectionPanel.setPreferredSize(new java.awt.Dimension(600, 400));
simSelectionPanel.setMaximumSize(new java.awt.Dimension(600, 400));
simSelectionPanel.setSimulations(overriddenSims);
int simOption = DialogUtils.showComponentOKCancelDialog(currentWindow, simSelectionPanel, "Select Simulation whose overrides should be exported:");
if (simOption == JOptionPane.OK_OPTION) {
selectedSimWOSBE = simSelectionPanel.getSelectedSimulation();
// if (chosenSimulation != null) {
// CARRY hashTable.put("selectedSimulation", chosenSimulation);
// }
} else if (simOption == JOptionPane.CANCEL_OPTION || simOption == JOptionPane.CLOSED_OPTION) {
// Hence canceling the entire export to SBML operation.
throw UserCancelException.CANCEL_XML_TRANSLATION;
}
}
} else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.CLOSED_OPTION) {
// Hence canceling the entire export to SBML operation.
throw UserCancelException.CANCEL_XML_TRANSLATION;
}
if (selectedSimWOSBE != null) {
String selectedFileName = c.filename;
// rename file to contain exported simulation.
String ext = FilenameUtils.getExtension(selectedFileName);
String base = FilenameUtils.getBaseName(selectedFileName);
String path = FilenameUtils.getPath(selectedFileName);
base += "_" + TokenMangler.mangleToSName(selectedSimWOSBE.getName());
selectedFileName = path + base + ext;
c.selectedFile.renameTo(new File(selectedFileName));
}
}
Aggregations