use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.
the class ClientRequestManager method openAfterChecking.
private void openAfterChecking(VCDocumentInfo documentInfo, final TopLevelWindowManager requester, final boolean inNewWindow) {
final String DOCUMENT_INFO = "documentInfo";
final String SEDML_TASK = "SedMLTask";
final String SEDML_MODELS = "SedMLModels";
final String BNG_UNIT_SYSTEM = "bngUnitSystem";
final String BMDB_DEFAULT_APPLICATION = "Deterministic";
/* asynchronous and not blocking any window */
bOpening = true;
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
// may want to insert corrected VCDocumentInfo later if our import debugger
// corrects it (BNGL Debugger).
hashTable.put(DOCUMENT_INFO, documentInfo);
hashTable.put("isBMDB", false);
hashTable.put("isSEDML", false);
// start a thread that gets it and updates the GUI by creating a new document
// desktop
String taskName = null;
if (documentInfo instanceof ExternalDocInfo) {
taskName = "Importing document";
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
File file = externalDocInfo.getFile();
if (file != null && !file.getName().isEmpty() && file.getName().endsWith("bngl")) {
BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
String fileText;
String originalFileText;
try {
fileText = BeanUtils.readBytesFromFile(file, null);
originalFileText = new String(fileText);
} catch (IOException e1) {
e1.printStackTrace();
DialogUtils.showErrorDialog(requester.getComponent(), "<html>Error reading file " + file.getPath() + "</html>");
return;
}
Reader reader = externalDocInfo.getReader();
boolean bException = true;
while (bException) {
try {
BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
boolean bStochastic = true;
boolean bRuleBased = true;
SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("temp NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(ruleBasedSimContext);
RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
RbmUtils.reactionRuleLabelIndex = 0;
RbmUtils.reactionRuleNames.clear();
ASTModel astModel = RbmUtils.importBnglFile(reader);
// for now, hasUnitSystem() always returns false
if (astModel.hasUnitSystem()) {
bngUnitSystem = astModel.getUnitSystem();
}
if (astModel.hasCompartments()) {
Structure struct = bioModel.getModel().getStructure(0);
if (struct != null) {
bioModel.getModel().removeStructure(struct);
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
if (!astModel.hasMolecularDefinitions()) {
System.out.println("Molecular Definition Block missing.");
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
} else {
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
}
astModel.jjtAccept(constructionVisitor, rbmModelContainer);
bException = false;
} catch (final Exception e) {
e.printStackTrace(System.out);
BNGLDebuggerPanel panel = new BNGLDebuggerPanel(fileText, e);
int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, "Bngl Debugger: " + file.getName());
if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
throw new UserCancelException("Canceling Import");
}
// inserting <potentially> corrected DocumentInfo
fileText = panel.getText();
externalDocInfo = new ExternalDocInfo(panel.getText());
reader = externalDocInfo.getReader();
hashTable.put(DOCUMENT_INFO, externalDocInfo);
}
}
if (!originalFileText.equals(fileText)) {
// file has been modified
String message = "Importing <b>" + file.getName() + "</b> into vCell. <br>Overwrite the file on the disk?<br>";
message = "<html>" + message + "</html>";
Object[] options = { "Overwrite and Import", "Import Only", "Cancel" };
int returnCode = JOptionPane.showOptionDialog(requester.getComponent(), message, "Bngl Debugger", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
if (returnCode == JOptionPane.YES_OPTION) {
try {
FileWriter fw = new FileWriter(file);
fw.write(fileText);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} else if (returnCode == JOptionPane.CANCEL_OPTION || returnCode == JOptionPane.CLOSED_OPTION) {
return;
}
}
if (!(bngUnitSystem.getOrigin() == BngUnitOrigin.PARSER)) {
BNGLUnitsPanel panel = new BNGLUnitsPanel(bngUnitSystem);
int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, " Bngl Units Selector", null, false);
if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
// TODO: or do nothing and continue with default values?
return;
} else {
bngUnitSystem = panel.getUnits();
}
}
hashTable.put(BNG_UNIT_SYSTEM, bngUnitSystem);
} else if (file != null && !file.getName().isEmpty() && file.getName().toLowerCase().endsWith(".sedml")) {
try {
XMLSource xmlSource = externalDocInfo.createXMLSource();
File sedmlFile = xmlSource.getXmlFile();
SedML sedml = Libsedml.readDocument(sedmlFile).getSedMLModel();
if (sedml == null || sedml.getModels().isEmpty()) {
return;
}
// AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(),
// file.getName());
List<SedML> sedmls = new ArrayList<>();
sedmls.add(sedml);
hashTable.put(SEDML_MODELS, sedmls);
// hashTable.put(SEDML_TASK, chosenTask);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("failed to read document: " + e.getMessage(), e);
}
} else if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
try {
ArchiveComponents ac = null;
ac = Libsedml.readSEDMLArchive(new FileInputStream(file));
List<SEDMLDocument> docs = ac.getSedmlDocuments();
List<SedML> sedmls = new ArrayList<>();
for (SEDMLDocument doc : docs) {
SedML sedml = doc.getSedMLModel();
if (sedml == null) {
throw new RuntimeException("Failed importing " + file.getName());
}
if (sedml.getModels().isEmpty()) {
throw new RuntimeException("Unable to find any model in " + file.getName());
}
sedmls.add(sedml);
}
// AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(),
// file.getName());
hashTable.put(SEDML_MODELS, sedmls);
// hashTable.put(SEDML_TASK, chosenTask);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("failed to read archive: " + e.getMessage(), e);
}
}
} else {
taskName = "Loading document '" + documentInfo.getVersion().getName() + "' from database";
}
AsynchClientTask task0 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
public void run(Hashtable<String, Object> hashTable) throws Exception {
if (!inNewWindow) {
// request was to replace the document in an existing window
getMdiManager().blockWindow(requester.getManagerID());
}
}
};
AsynchClientTask task1 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
VCDocument doc = null;
List<VCDocument> docs = new ArrayList<>();
boolean isBMDB = false;
boolean isSEDML = false;
VCDocumentInfo documentInfo = (VCDocumentInfo) hashTable.get(DOCUMENT_INFO);
if (documentInfo instanceof BioModelInfo) {
BioModelInfo bmi = (BioModelInfo) documentInfo;
doc = getDocumentManager().getBioModel(bmi);
} else if (documentInfo instanceof MathModelInfo) {
MathModelInfo mmi = (MathModelInfo) documentInfo;
doc = getDocumentManager().getMathModel(mmi);
} else if (documentInfo instanceof GeometryInfo) {
GeometryInfo gmi = (GeometryInfo) documentInfo;
doc = getDocumentManager().getGeometry(gmi);
} else if (documentInfo instanceof ExternalDocInfo) {
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
File file = externalDocInfo.getFile();
if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
TranslationLogger transLogger = new TranslationLogger(requester);
// iterate through one or more SEDML objects
List<SedML> sedmls = (List<SedML>) hashTable.get(SEDML_MODELS);
for (SedML sedml : sedmls) {
// default to import all tasks
List<VCDocument> vcdocs = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, sedml, null, null, false);
for (VCDocument vcdoc : vcdocs) {
docs.add(vcdoc);
}
}
// treat the same since OMEX is just and archive with SED-ML file(s)
isSEDML = true;
} else if (!externalDocInfo.isXML()) {
if (hashTable.containsKey(BNG_UNIT_SYSTEM)) {
// not XML, look for BNGL etc.
// we use the BngUnitSystem already created during the 1st pass
BngUnitSystem bngUnitSystem = (BngUnitSystem) hashTable.get(BNG_UNIT_SYSTEM);
BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
SimulationContext odeSimContext = bioModel.addNewSimulationContext("BioNetGen app", SimulationContext.Application.NETWORK_DETERMINISTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(ruleBasedSimContext);
appList.add(odeSimContext);
// set convention for initial conditions in generated application for seed
// species (concentration or count)
ruleBasedSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
odeSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
RbmUtils.reactionRuleLabelIndex = 0;
RbmUtils.reactionRuleNames.clear();
Reader reader = externalDocInfo.getReader();
ASTModel astModel = RbmUtils.importBnglFile(reader);
if (bioModel.getModel() != null && bioModel.getModel().getVcMetaData() != null) {
VCMetaData vcMetaData = bioModel.getModel().getVcMetaData();
vcMetaData.setFreeTextAnnotation(bioModel, astModel.getProlog());
}
if (astModel.hasCompartments()) {
Structure struct = bioModel.getModel().getStructure(0);
if (struct != null) {
bioModel.getModel().removeStructure(struct);
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
if (!astModel.hasMolecularDefinitions()) {
System.out.println("Molecular Definition Block missing. Extracting it from Species, Reactions, Obserbables.");
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
} else {
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
}
// we'll convert the kinetic parameters to BngUnitSystem inside the
// visit(ASTKineticsParameter...)
astModel.jjtAccept(constructionVisitor, rbmModelContainer);
// set the volume in the newly created application to
// BngUnitSystem.bnglModelVolume
// TODO: set the right values if we import compartments from the bngl file!
// if(!bngUnitSystem.isConcentration()) {
Expression sizeExpression = new Expression(bngUnitSystem.getVolume());
ruleBasedSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
odeSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
// }
// we remove the NFSim application if any seed species is clamped because NFSim
// doesn't know what to do with it
boolean bClamped = false;
for (SpeciesContextSpec scs : ruleBasedSimContext.getReactionContext().getSpeciesContextSpecs()) {
if (scs.isConstant()) {
bClamped = true;
break;
}
}
if (bClamped) {
bioModel.removeSimulationContext(ruleBasedSimContext);
}
// // TODO: DON'T delete this code
// // the code below is needed if we also want to create simulations, example for 1 rule based simulation
// // it is rule-based so it wont have to flatten, should be fast.
// MathMappingCallback callback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
// NetworkGenerationRequirements networkGenerationRequirements = null; // network generation should not be executed.
// ruleBasedSimContext.refreshMathDescription(callback,networkGenerationRequirements);
// Simulation sim = ruleBasedSimContext.addNewSimulation(SimulationOwner.DEFAULT_SIM_NAME_PREFIX,callback,networkGenerationRequirements);
doc = bioModel;
}
} else {
// is XML
try (TranslationLogger transLogger = new TranslationLogger(requester)) {
XMLSource xmlSource = externalDocInfo.createXMLSource();
org.jdom.Element rootElement = xmlSource.getXmlDoc().getRootElement();
String xmlType = rootElement.getName();
String modelXmlType = null;
if (xmlType.equals(XMLTags.VcmlRootNodeTag)) {
// For now, assuming that <vcml> element has only one child (biomodel, mathmodel
// or geometry).
// Will deal with multiple children of <vcml> Element when we get to model
// composition.
@SuppressWarnings("unchecked") List<Element> childElementList = rootElement.getChildren();
// assuming first child is the biomodel,
Element modelElement = childElementList.get(0);
// mathmodel or geometry.
modelXmlType = modelElement.getName();
}
if (xmlType.equals(XMLTags.BioModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.BioModelTag))) {
doc = XmlHelper.XMLToBioModel(xmlSource);
} else if (xmlType.equals(XMLTags.MathModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.MathModelTag))) {
doc = XmlHelper.XMLToMathModel(xmlSource);
} else if (xmlType.equals(XMLTags.GeometryTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.GeometryTag))) {
doc = XmlHelper.XMLToGeometry(xmlSource);
} else if (xmlType.equals(XMLTags.SbmlRootNodeTag)) {
Namespace namespace = rootElement.getNamespace(XMLTags.SBML_SPATIAL_NS_PREFIX);
isBMDB = externalDocInfo.isBioModelsNet();
boolean bIsSpatial = (namespace == null) ? false : true;
doc = XmlHelper.importSBML(transLogger, xmlSource, bIsSpatial);
} else if (xmlType.equals(XMLTags.CellmlRootNodeTag)) {
if (requester instanceof BioModelWindowManager) {
doc = XmlHelper.importBioCellML(transLogger, xmlSource);
} else {
doc = XmlHelper.importMathCellML(transLogger, xmlSource);
}
} else if (xmlType.equals(MicroscopyXMLTags.FRAPStudyTag)) {
doc = VFrapXmlHelper.VFRAPToBioModel(hashTable, xmlSource, getDocumentManager(), requester);
} else if (xmlType.equals(XMLTags.SedMLTypeTag)) {
// we know it is a single SedML since it is an actual XML source
List<SedML> sedmls = (List<SedML>) hashTable.get(SEDML_MODELS);
SedML sedml = sedmls.get(0);
// default to import all tasks
docs = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, sedml, null, externalDocInfo.getFile().getAbsolutePath(), false);
isSEDML = true;
} else {
// unknown XML format
throw new RuntimeException("unsupported XML format, first element tag is <" + rootElement.getName() + ">");
}
if (externalDocInfo.getDefaultName() != null) {
doc.setName(externalDocInfo.getDefaultName());
}
}
}
if (doc == null && docs == null) {
File f = externalDocInfo.getFile();
if (f != null) {
throw new RuntimeException("Unable to determine type of file " + f.getCanonicalPath());
}
throw new ProgrammingException();
}
}
// create biopax objects using annotation
if (doc instanceof BioModel) {
BioModel bioModel = (BioModel) doc;
try {
bioModel.getVCMetaData().createBioPaxObjects(bioModel);
} catch (Exception e) {
e.printStackTrace();
}
}
requester.prepareDocumentToLoad(doc, inNewWindow);
hashTable.put("isBMDB", isBMDB);
hashTable.put("isSEDML", isSEDML);
if (!isSEDML) {
hashTable.put("doc", doc);
} else {
hashTable.put("docs", docs);
}
}
};
AsynchClientTask task2 = new AsynchClientTask("Showing document", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
try {
Throwable exc = (Throwable) hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR);
if (exc == null) {
boolean isSEDML = (boolean) hashTable.get("isSEDML");
if (isSEDML) {
List<VCDocument> docs = (List<VCDocument>) hashTable.get("docs");
List<DocumentWindowManager> windowManagers = new ArrayList<DocumentWindowManager>();
for (VCDocument doc : docs) {
DocumentWindowManager windowManager = createDocumentWindowManager(doc);
getMdiManager().createNewDocumentWindow(windowManager);
windowManagers.add(windowManager);
}
hashTable.put("managers", windowManagers);
hashTable.put("docs", docs);
} else {
VCDocument doc = (VCDocument) hashTable.get("doc");
DocumentWindowManager windowManager = null;
if (inNewWindow) {
windowManager = createDocumentWindowManager(doc);
// request was to create a new top-level window with this doc
getMdiManager().createNewDocumentWindow(windowManager);
} else {
// request was to replace the document in an existing window
windowManager = (DocumentWindowManager) requester;
getMdiManager().setCanonicalTitle(requester.getManagerID());
windowManager.resetDocument(doc);
}
hashTable.put(WIN_MGR_KEY, windowManager);
hashTable.put("doc", doc);
}
}
} catch (Exception ex) {
ex.printStackTrace();
// TODO: check why getMdiManager().createNewDocumentWindow(windowManager) fails sometimes
} finally {
if (!inNewWindow) {
getMdiManager().unBlockWindow(requester.getManagerID());
}
bOpening = false;
}
}
};
AsynchClientTask task3 = new AsynchClientTask("Special Layout", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
if (documentInfo instanceof ExternalDocInfo) {
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
boolean isSEDML = (boolean) hashTable.get("isSEDML");
if (externalDocInfo.isBioModelsNet() || externalDocInfo.isFromXmlFile() || !isSEDML) {
DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
if (windowManager instanceof BioModelWindowManager) {
((BioModelWindowManager) windowManager).specialLayout();
}
}
if (isSEDML) {
List<DocumentWindowManager> windowManagers = (List<DocumentWindowManager>) hashTable.get("managers");
if (windowManagers != null) {
for (DocumentWindowManager manager : windowManagers) {
((BioModelWindowManager) manager).specialLayout();
}
}
}
}
}
};
AsynchClientTask task4 = new AsynchClientTaskFunction(ClientRequestManager::setWindowFocus, "Set window focus", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false);
AsynchClientTask task6 = new AsynchClientTask("Renaming, please wait...", // TASKTYPE_NONSWING_BLOCKING
AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, // TASKTYPE_NONSWING_BLOCKING
false, // TASKTYPE_NONSWING_BLOCKING
false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
VCDocument doc = (VCDocument) hashTable.get("doc");
if (!(doc instanceof BioModel)) {
return;
}
boolean isBMDB = (boolean) hashTable.get("isBMDB");
if (documentInfo instanceof ExternalDocInfo) {
if (isBMDB) {
idToNameConversion(doc);
}
}
if (isBMDB) {
BioModel bioModel = (BioModel) doc;
SimulationContext simulationContext = bioModel.getSimulationContext(0);
simulationContext.setName(BMDB_DEFAULT_APPLICATION);
MathMappingCallback callback = new MathMappingCallback() {
@Override
public void setProgressFraction(float fractionDone) {
}
@Override
public void setMessage(String message) {
}
@Override
public boolean isInterrupted() {
return false;
}
};
MathMapping mathMapping = simulationContext.createNewMathMapping(callback, NetworkGenerationRequirements.ComputeFullNoTimeout);
MathDescription mathDesc = null;
try {
mathDesc = mathMapping.getMathDescription(callback);
simulationContext.setMathDescription(mathDesc);
Simulation sim = new Simulation(mathDesc);
sim.setName(simulationContext.getBioModel().getFreeSimulationName());
simulationContext.addSimulation(sim);
bioModel.refreshDependencies();
} catch (MappingException | MathException | MatrixException | ExpressionException | ModelException e1) {
e1.printStackTrace();
}
hashTable.put("doc", doc);
}
}
};
ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] { task0, task1, task6, task2, task3, task4 }, false);
}
use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.
the class OutputFunctionsListTableModel method propertyChange.
/**
* This method gets called when a bound property is changed.
* @param evt A PropertyChangeEvent object describing the event source
* and the property that has changed.
*/
public void propertyChange(java.beans.PropertyChangeEvent evt) {
OutputFunctionContext fc = getOutputFunctionContext();
SimulationOwner so = null;
if (fc != null) {
so = fc.getSimulationOwner();
}
if (evt.getSource() == fc && evt.getPropertyName().equals(OutputFunctionContext.PROPERTY_OUTPUT_FUNCTIONS)) {
setData(outputFunctionContext.getOutputFunctionsList());
}
if (evt.getSource() instanceof SimulationContext && evt.getSource() == so && evt.getPropertyName().equals(Model.PROPERTY_NAME_MODEL_ENTITY_NAME)) {
SimulationContext simulationContext = (SimulationContext) so;
if (fc.getOutputFunctionsList() == null || fc.getOutputFunctionsList().isEmpty()) {
return;
}
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
//
// WARNING: this should NOT be used under any circumstance for batch renaming
// MathDescription, MathMapping, expressions are NOT thread safe
//
AsynchClientTask task0 = new AsynchClientTask("Renaming Functions", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
MathMappingCallback callback = new MathMappingCallback() {
@Override
public void setProgressFraction(float fractionDone) {
}
@Override
public void setMessage(String message) {
}
@Override
public boolean isInterrupted() {
return false;
}
};
MathMapping mathMapping = simulationContext.createNewMathMapping(callback, NetworkGenerationRequirements.ComputeFullNoTimeout);
MathDescription mathDesc = null;
try {
mathDesc = mathMapping.getMathDescription(callback);
} catch (MappingException | MathException | MatrixException | ExpressionException | ModelException e1) {
e1.printStackTrace();
}
String oldName = (String) evt.getOldValue();
String newName = (String) evt.getNewValue();
ArrayList<AnnotatedFunction> afList = fc.getOutputFunctionsList();
List<Expression> changedExpressions = new ArrayList<>();
for (AnnotatedFunction af : afList) {
if (af == null) {
continue;
}
Expression exp = af.getExpression();
if (exp == null || exp.getSymbols() == null || exp.getSymbols().length == 0) {
continue;
}
String errMsg = "Failed to rename symbol '" + oldName + "' with '" + newName + "' in the Expression of Function '" + af.getName() + "'.";
for (String symbol : exp.getSymbols()) {
if (symbol.contentEquals(oldName)) {
try {
exp.substituteInPlace(new Expression(oldName), new Expression(newName));
changedExpressions.add(exp);
} catch (ExpressionException e) {
e.printStackTrace();
throw new RuntimeException(errMsg);
}
}
}
}
if (changedExpressions.size() > 0) {
try {
simulationContext.setMathDescription(mathDesc);
for (Expression exp : changedExpressions) {
exp.bindExpression(outputFunctionContext);
}
} catch (ExpressionException | PropertyVetoException e) {
e.printStackTrace();
}
}
}
};
ClientTaskDispatcher.dispatch(ownerTable, hashTable, new AsynchClientTask[] { task0 }, false);
}
if (evt.getPropertyName().equals(GeometryOwner.PROPERTY_NAME_GEOMETRY)) {
Geometry oldGeometry = (Geometry) evt.getOldValue();
Geometry newGeometry = (Geometry) evt.getNewValue();
// changing from ode to pde
if (oldGeometry.getDimension() == 0 && newGeometry.getDimension() > 0) {
fireTableStructureChanged();
setData(getOutputFunctionContext().getOutputFunctionsList());
}
}
}
use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.
the class StructureMappingTableModel method setValueAt.
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (rowIndex < 0 || rowIndex >= getRowCount()) {
throw new RuntimeException("StructureMappingTableModel.setValueAt(), row = " + rowIndex + " out of range [" + 0 + "," + (getRowCount() - 1) + "]");
}
if (columnIndex < 0 || columnIndex >= getColumnCount()) {
throw new RuntimeException("StructureMappingTableModel.setValueAt(), column = " + columnIndex + " out of range [" + 0 + "," + (getColumnCount() - 1) + "]");
}
StructureMapping structureMapping = getValueAt(rowIndex);
Structure structure = structureMapping.getStructure();
if (bNonSpatial) {
switch(columnIndex) {
case NONSPATIAL_COLUMN_SIZE:
{
try {
Expression exp = null;
if (aValue instanceof String) {
exp = new Expression((String) aValue);
} else if (aValue instanceof Double) {
exp = new Expression(((Double) aValue).doubleValue());
}
// if the input volumn is null, leave it as it was.
if (exp != null) {
// for old ode model, once one size is input, solve the rest. if it is unnamed compartment(the only one), we don't need to solve anything
if (!getGeometryContext().getSimulationContext().isStoch() && getGeometryContext().isAllSizeSpecifiedNull() && getGeometryContext().isAllVolFracAndSurfVolSpecified() && getGeometryContext().getStructureMappings().length > 1) {
structureMapping.getSizeParameter().setExpression(exp);
double size;
try {
size = exp.evaluateConstant();
VCUnitDefinition volumeUnit = getGeometryContext().getSimulationContext().getModel().getUnitSystem().getVolumeUnit();
StructureSizeSolver.updateAbsoluteStructureSizes(getGeometryContext().getSimulationContext(), structure, size, volumeUnit);
fireTableRowsUpdated(0, getRowCount());
} catch (ExpressionException ex) {
ex.printStackTrace(System.out);
PopupGenerator.showErrorDialog(ownerTable, "Size of Feature " + structure.getName() + " can not be solved as constant!");
} catch (Exception ex) {
ex.printStackTrace(System.out);
PopupGenerator.showErrorDialog(ownerTable, ex.getMessage());
}
} else {
structureMapping.getSizeParameter().setExpression(exp);
// set fraction in stoch math description, because these might be used when copy from stoch app to ode app.
if (getGeometryContext().isAllSizeSpecifiedPositive()) /*&& !getGeometryContext().getSimulationContext().isStoch()*/
{
try {
StructureSizeSolver.updateRelativeStructureSizes(getGeometryContext().getSimulationContext());
} catch (Exception ex) {
ex.printStackTrace(System.out);
PopupGenerator.showErrorDialog(ownerTable, ex.getMessage());
}
}
}
}
} catch (ExpressionException e) {
e.printStackTrace(System.out);
PopupGenerator.showErrorDialog(ownerTable, "expression error\n" + e.getMessage());
}
break;
}
}
} else {
switch(columnIndex) {
case SPATIAL_COLUMN_SUBDOMAIN:
{
GeometryClass geometryClass = null;
if (aValue instanceof String) {
String svname = (String) aValue;
geometryClass = getGeometryContext().getGeometry().getGeometryClass(svname);
} else if (aValue instanceof GeometryClass) {
geometryClass = (GeometryClass) aValue;
}
if (geometryClass != null) {
try {
getGeometryContext().assignStructure(structure, geometryClass);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
PopupGenerator.showErrorDialog(ownerTable, e.getMessage());
} catch (IllegalMappingException e) {
e.printStackTrace(System.out);
PopupGenerator.showErrorDialog(ownerTable, e.getMessage());
} catch (MappingException e) {
e.printStackTrace(System.out);
PopupGenerator.showErrorDialog(ownerTable, e.getMessage());
}
}
break;
}
case SPATIAL_COLUMN_SIZERATIO:
try {
Expression exp = null;
if (aValue instanceof String) {
exp = new Expression((String) aValue);
} else if (aValue instanceof Double) {
exp = new Expression(((Double) aValue).doubleValue());
}
if (exp != null) {
structureMapping.getUnitSizeParameter().setExpression(exp);
StructureSizeSolver.updateUnitStructureSizes(getGeometryContext().getSimulationContext(), structureMapping.getGeometryClass());
}
} catch (ExpressionException e) {
e.printStackTrace(System.out);
PopupGenerator.showErrorDialog(ownerTable, "expression error\n" + e.getMessage());
}
break;
case SPATIAL_COLUMN_X_MINUS:
{
if (aValue != null) {
structureMapping.setBoundaryConditionTypeXm(new BoundaryConditionType((String) aValue));
}
break;
}
case SPATIAL_COLUMN_X_PLUS:
{
if (aValue != null) {
structureMapping.setBoundaryConditionTypeXp(new BoundaryConditionType((String) aValue));
}
break;
}
case SPATIAL_COLUMN_Y_MINUS:
{
if (aValue != null) {
structureMapping.setBoundaryConditionTypeYm(new BoundaryConditionType((String) aValue));
}
break;
}
case SPATIAL_COLUMN_Y_PLUS:
{
if (aValue != null) {
structureMapping.setBoundaryConditionTypeYp(new BoundaryConditionType((String) aValue));
}
break;
}
case SPATIAL_COLUMN_Z_MINUS:
{
if (aValue != null) {
structureMapping.setBoundaryConditionTypeZm(new BoundaryConditionType((String) aValue));
}
break;
}
case SPATIAL_COLUMN_Z_PLUS:
{
if (aValue != null) {
structureMapping.setBoundaryConditionTypeZp(new BoundaryConditionType((String) aValue));
}
break;
}
}
}
}
use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.
the class MathMapping_4_8 method refreshMathDescription.
/**
* This method was created in VisualAge.
*/
private void refreshMathDescription() throws MappingException, MatrixException, MathException, ExpressionException, ModelException {
// All sizes must be set for new ODE models and ratios must be set for old ones.
simContext.checkValidity();
//
// temporarily place all variables in a hashtable (before binding) and discarding duplicates (check for equality)
//
VariableHash varHash = new VariableHash();
StructureMapping[] structureMappings = simContext.getGeometryContext().getStructureMappings();
Model model = simContext.getModel();
StructureTopology structTopology = model.getStructureTopology();
//
// verify that all structures are mapped to subvolumes and all subvolumes are mapped to a structure
//
Structure[] structures = simContext.getGeometryContext().getModel().getStructures();
for (int i = 0; i < structures.length; i++) {
StructureMapping sm = simContext.getGeometryContext().getStructureMapping(structures[i]);
if (sm == null || (sm instanceof FeatureMapping && getSubVolume((FeatureMapping) sm) == null)) {
throw new MappingException("model structure '" + structures[i].getName() + "' not mapped to a geometry subdomain");
}
if (sm != null && (sm instanceof MembraneMapping) && ((MembraneMapping) sm).getVolumeFractionParameter() != null) {
Expression volFractExp = ((MembraneMapping) sm).getVolumeFractionParameter().getExpression();
if (volFractExp != null) {
try {
double volFract = volFractExp.evaluateConstant();
if (volFract >= 1.0) {
throw new MappingException("model structure '" + structTopology.getInsideFeature(((MembraneMapping) sm).getMembrane()).getName() + "' has volume fraction >= 1.0");
}
} catch (ExpressionException e) {
}
}
}
}
SubVolume[] subVolumes = simContext.getGeometryContext().getGeometry().getGeometrySpec().getSubVolumes();
for (int i = 0; i < subVolumes.length; i++) {
if (getStructures(subVolumes[i]) == null || getStructures(subVolumes[i]).length == 0) {
throw new MappingException("geometry subdomain '" + subVolumes[i].getName() + "' not mapped from a model structure");
}
}
// deals with model parameters
Hashtable<VolVariable, EventAssignmentInitParameter> eventVolVarHash = new Hashtable<VolVariable, EventAssignmentInitParameter>();
ModelParameter[] modelParameters = model.getModelParameters();
if (simContext.getGeometry().getDimension() == 0) {
//
// global parameters from model (that presently are constants)
//
BioEvent[] bioEvents = simContext.getBioEvents();
ArrayList<SymbolTableEntry> eventAssignTargets = new ArrayList<SymbolTableEntry>();
if (bioEvents != null && bioEvents.length > 0) {
for (BioEvent be : bioEvents) {
for (EventAssignment ea : be.getEventAssignments()) {
if (!eventAssignTargets.contains(ea.getTarget())) {
eventAssignTargets.add(ea.getTarget());
}
}
}
}
for (int j = 0; j < modelParameters.length; j++) {
Expression modelParamExpr = getIdentifierSubstitutions(modelParameters[j].getExpression(), modelParameters[j].getUnitDefinition(), null);
if (eventAssignTargets.contains(modelParameters[j])) {
EventAssignmentInitParameter eap = null;
try {
eap = addEventAssignmentInitParameter(modelParameters[j].getName(), modelParameters[j].getExpression(), PARAMETER_ROLE_EVENTASSIGN_INITCONDN, modelParameters[j].getUnitDefinition());
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new MappingException(e.getMessage());
}
// varHash.addVariable(newFunctionOrConstant(getMathSymbol(eap, null), modelParamExpr));
VolVariable volVar = new VolVariable(modelParameters[j].getName(), nullDomain);
varHash.addVariable(volVar);
eventVolVarHash.put(volVar, eap);
} else {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(modelParameters[j], null), modelParamExpr));
}
}
} else {
//
for (int pass = 0; pass < 2; pass++) {
for (int j = 0; j < modelParameters.length; j++) {
Hashtable<String, Expression> structMappingVariantsHash = new Hashtable<String, Expression>();
for (int k = 0; k < structureMappings.length; k++) {
String paramVariantName = null;
Expression paramVariantExpr = null;
if (modelParameters[j].getExpression().getSymbols() == null) {
paramVariantName = modelParameters[j].getName();
paramVariantExpr = getIdentifierSubstitutions(modelParameters[j].getExpression(), modelParameters[j].getUnitDefinition(), null);
} else {
paramVariantName = modelParameters[j].getName() + "_" + TokenMangler.fixTokenStrict(structureMappings[k].getStructure().getName());
// if the expression has symbols that do not belong in that structureMapping, do not create the variant.
Expression exp1 = modelParameters[j].getExpression();
Expression flattenedModelParamExpr = substituteGlobalParameters(exp1);
String[] symbols = flattenedModelParamExpr.getSymbols();
boolean bValid = true;
Structure sm_struct = structureMappings[k].getStructure();
if (symbols != null) {
for (int ii = 0; ii < symbols.length; ii++) {
SpeciesContext sc = model.getSpeciesContext(symbols[ii]);
if (sc != null) {
// symbol[ii] is a speciesContext, check its structure with structureMapping[k].structure. If they are the same or
// if it is the adjacent membrane(s), allow variant expression to be created. Else, continue.
Structure sp_struct = sc.getStructure();
if (sp_struct.compareEqual(sm_struct)) {
bValid = bValid && true;
} else {
// if the 2 structures are not the same, are they adjacent? then 'bValid' is true, else false.
if ((sm_struct instanceof Feature) && (sp_struct instanceof Membrane)) {
Feature sm_feature = (Feature) sm_struct;
Membrane sp_mem = (Membrane) sp_struct;
if (sp_mem.compareEqual(structTopology.getParentStructure(sm_feature)) || (structTopology.getInsideFeature(sp_mem).compareEqual(sm_feature) || structTopology.getOutsideFeature(sp_mem).compareEqual(sm_feature))) {
bValid = bValid && true;
} else {
bValid = bValid && false;
break;
}
} else if ((sm_struct instanceof Membrane) && (sp_struct instanceof Feature)) {
Feature sp_feature = (Feature) sp_struct;
Membrane sm_mem = (Membrane) sm_struct;
if (sm_mem.compareEqual(structTopology.getParentStructure(sp_feature)) || (structTopology.getInsideFeature(sm_mem).compareEqual(sp_feature) || structTopology.getOutsideFeature(sm_mem).compareEqual(sp_feature))) {
bValid = bValid && true;
} else {
bValid = bValid && false;
break;
}
} else {
bValid = bValid && false;
break;
}
}
}
}
}
if (bValid) {
if (pass == 0) {
paramVariantExpr = new Expression("VCELL_TEMPORARY_EXPRESSION_PLACEHOLDER");
} else {
paramVariantExpr = getIdentifierSubstitutions(modelParameters[j].getExpression(), modelParameters[j].getUnitDefinition(), structureMappings[k]);
}
}
}
if (paramVariantExpr != null) {
structMappingVariantsHash.put(paramVariantName, paramVariantExpr);
}
}
globalParamVariantsHash.put(modelParameters[j], structMappingVariantsHash);
}
}
//
for (int j = 0; j < modelParameters.length; j++) {
if (modelParameters[j].getExpression().getSymbols() == null) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(modelParameters[j], null), getIdentifierSubstitutions(modelParameters[j].getExpression(), modelParameters[j].getUnitDefinition(), null)));
} else {
Hashtable<String, Expression> smVariantsHash = globalParamVariantsHash.get(modelParameters[j]);
for (int k = 0; k < structureMappings.length; k++) {
String variantName = modelParameters[j].getName() + "_" + TokenMangler.fixTokenStrict(structureMappings[k].getStructure().getName());
Expression variantExpr = smVariantsHash.get(variantName);
if (variantExpr != null) {
varHash.addVariable(newFunctionOrConstant(variantName, variantExpr));
}
}
}
}
}
//
// gather only those reactionSteps that are not "excluded"
//
ReactionSpec[] reactionSpecs = simContext.getReactionContext().getReactionSpecs();
Vector<ReactionStep> rsList = new Vector<ReactionStep>();
for (int i = 0; i < reactionSpecs.length; i++) {
if (reactionSpecs[i].isExcluded() == false) {
rsList.add(reactionSpecs[i].getReactionStep());
}
}
ReactionStep[] reactionSteps = new ReactionStep[rsList.size()];
rsList.copyInto(reactionSteps);
//
for (int i = 0; i < reactionSteps.length; i++) {
Kinetics.UnresolvedParameter[] unresolvedParameters = reactionSteps[i].getKinetics().getUnresolvedParameters();
if (unresolvedParameters != null && unresolvedParameters.length > 0) {
StringBuffer buffer = new StringBuffer();
for (int j = 0; j < unresolvedParameters.length; j++) {
if (j > 0) {
buffer.append(", ");
}
buffer.append(unresolvedParameters[j].getName());
}
throw new MappingException(reactionSteps[i].getDisplayType() + " '" + reactionSteps[i].getName() + "' contains unresolved identifier(s): " + buffer);
}
}
//
// create new MathDescription (based on simContext's previous MathDescription if possible)
//
MathDescription oldMathDesc = simContext.getMathDescription();
mathDesc = null;
if (oldMathDesc != null) {
if (oldMathDesc.getVersion() != null) {
mathDesc = new MathDescription(oldMathDesc.getVersion());
} else {
mathDesc = new MathDescription(oldMathDesc.getName());
}
} else {
mathDesc = new MathDescription(simContext.getName() + "_generated");
}
//
// volume variables
//
Enumeration<SpeciesContextMapping> enum1 = getSpeciesContextMappings();
while (enum1.hasMoreElements()) {
SpeciesContextMapping scm = enum1.nextElement();
if (scm.getVariable() instanceof VolVariable) {
if (!(mathDesc.getVariable(scm.getVariable().getName()) instanceof VolVariable)) {
varHash.addVariable(scm.getVariable());
}
}
}
//
// membrane variables
//
enum1 = getSpeciesContextMappings();
while (enum1.hasMoreElements()) {
SpeciesContextMapping scm = (SpeciesContextMapping) enum1.nextElement();
if (scm.getVariable() instanceof MemVariable) {
varHash.addVariable(scm.getVariable());
}
}
varHash.addVariable(new Constant(getMathSymbol(model.getFARADAY_CONSTANT(), null), getIdentifierSubstitutions(model.getFARADAY_CONSTANT().getExpression(), model.getFARADAY_CONSTANT().getUnitDefinition(), null)));
varHash.addVariable(new Constant(getMathSymbol(model.getFARADAY_CONSTANT_NMOLE(), null), getIdentifierSubstitutions(model.getFARADAY_CONSTANT_NMOLE().getExpression(), model.getFARADAY_CONSTANT_NMOLE().getUnitDefinition(), null)));
varHash.addVariable(new Constant(getMathSymbol(model.getGAS_CONSTANT(), null), getIdentifierSubstitutions(model.getGAS_CONSTANT().getExpression(), model.getGAS_CONSTANT().getUnitDefinition(), null)));
varHash.addVariable(new Constant(getMathSymbol(model.getTEMPERATURE(), null), getIdentifierSubstitutions(new Expression(simContext.getTemperatureKelvin()), model.getTEMPERATURE().getUnitDefinition(), null)));
//
// only calculate potential if at least one MembraneMapping has CalculateVoltage == true
//
boolean bCalculatePotential = false;
for (int i = 0; i < structureMappings.length; i++) {
if (structureMappings[i] instanceof MembraneMapping) {
if (((MembraneMapping) structureMappings[i]).getCalculateVoltage()) {
bCalculatePotential = true;
}
}
}
// (simContext.getGeometry().getDimension() == 0);
potentialMapping = new PotentialMapping(simContext, this);
potentialMapping.computeMath();
if (bCalculatePotential) {
//
// copy functions for currents and constants for capacitances
//
ElectricalDevice[] devices = potentialMapping.getElectricalDevices();
for (int j = 0; j < devices.length; j++) {
if (devices[j] instanceof MembraneElectricalDevice) {
MembraneElectricalDevice membraneElectricalDevice = (MembraneElectricalDevice) devices[j];
MembraneMapping memMapping = membraneElectricalDevice.getMembraneMapping();
Parameter specificCapacitanceParm = memMapping.getParameterFromRole(MembraneMapping.ROLE_SpecificCapacitance);
varHash.addVariable(new Constant(getMathSymbol(specificCapacitanceParm, memMapping), getIdentifierSubstitutions(specificCapacitanceParm.getExpression(), specificCapacitanceParm.getUnitDefinition(), memMapping)));
ElectricalDevice.ElectricalDeviceParameter transmembraneCurrentParm = membraneElectricalDevice.getParameterFromRole(ElectricalDevice.ROLE_TransmembraneCurrent);
ElectricalDevice.ElectricalDeviceParameter totalCurrentParm = membraneElectricalDevice.getParameterFromRole(ElectricalDevice.ROLE_TotalCurrent);
ElectricalDevice.ElectricalDeviceParameter capacitanceParm = membraneElectricalDevice.getParameterFromRole(ElectricalDevice.ROLE_Capacitance);
if (totalCurrentParm != null && /* totalCurrentDensityParm.getExpression()!=null && */
memMapping.getCalculateVoltage()) {
Expression totalCurrentDensityExp = (totalCurrentParm.getExpression() != null) ? (totalCurrentParm.getExpression()) : (new Expression(0.0));
varHash.addVariable(newFunctionOrConstant(getMathSymbol(totalCurrentParm, membraneElectricalDevice.getMembraneMapping()), getIdentifierSubstitutions(totalCurrentDensityExp, totalCurrentParm.getUnitDefinition(), membraneElectricalDevice.getMembraneMapping())));
}
if (transmembraneCurrentParm != null && transmembraneCurrentParm.getExpression() != null && memMapping.getCalculateVoltage()) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(transmembraneCurrentParm, membraneElectricalDevice.getMembraneMapping()), getIdentifierSubstitutions(transmembraneCurrentParm.getExpression(), transmembraneCurrentParm.getUnitDefinition(), membraneElectricalDevice.getMembraneMapping())));
}
if (capacitanceParm != null && capacitanceParm.getExpression() != null && memMapping.getCalculateVoltage()) {
StructureMappingParameter sizeParameter = membraneElectricalDevice.getMembraneMapping().getSizeParameter();
if (simContext.getGeometry().getDimension() == 0 && (sizeParameter.getExpression() == null || sizeParameter.getExpression().isZero())) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(capacitanceParm, membraneElectricalDevice.getMembraneMapping()), getIdentifierSubstitutions(Expression.mult(memMapping.getNullSizeParameterValue(), specificCapacitanceParm.getExpression()), capacitanceParm.getUnitDefinition(), membraneElectricalDevice.getMembraneMapping())));
} else {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(capacitanceParm, membraneElectricalDevice.getMembraneMapping()), getIdentifierSubstitutions(capacitanceParm.getExpression(), capacitanceParm.getUnitDefinition(), membraneElectricalDevice.getMembraneMapping())));
}
}
//
if (membraneElectricalDevice.getDependentVoltageExpression() == null) {
// is Voltage Independent?
StructureMapping.StructureMappingParameter initialVoltageParm = memMapping.getInitialVoltageParameter();
varHash.addVariable(newFunctionOrConstant(getMathSymbol(initialVoltageParm, memMapping), getIdentifierSubstitutions(initialVoltageParm.getExpression(), initialVoltageParm.getUnitDefinition(), memMapping)));
} else //
// membrane forced potential
//
{
varHash.addVariable(newFunctionOrConstant(getMathSymbol(memMapping.getMembrane().getMembraneVoltage(), memMapping), getIdentifierSubstitutions(membraneElectricalDevice.getDependentVoltageExpression(), memMapping.getMembrane().getMembraneVoltage().getUnitDefinition(), memMapping)));
}
} else if (devices[j] instanceof CurrentClampElectricalDevice) {
CurrentClampElectricalDevice currentClampDevice = (CurrentClampElectricalDevice) devices[j];
// total current = current source (no capacitance)
Parameter totalCurrentParm = currentClampDevice.getParameterFromRole(CurrentClampElectricalDevice.ROLE_TotalCurrent);
Parameter currentParm = currentClampDevice.getParameterFromRole(CurrentClampElectricalDevice.ROLE_TransmembraneCurrent);
// Parameter dependentVoltage = currentClampDevice.getCurrentClampStimulus().getVoltageParameter();
varHash.addVariable(newFunctionOrConstant(getMathSymbol(totalCurrentParm, null), getIdentifierSubstitutions(totalCurrentParm.getExpression(), totalCurrentParm.getUnitDefinition(), null)));
varHash.addVariable(newFunctionOrConstant(getMathSymbol(currentParm, null), getIdentifierSubstitutions(currentParm.getExpression(), currentParm.getUnitDefinition(), null)));
// varHash.addVariable(newFunctionOrConstant(getMathSymbol(dependentVoltage,null),getIdentifierSubstitutions(currentClampDevice.getDependentVoltageExpression(),dependentVoltage.getUnitDefinition(),null)));
//
// add user-defined parameters
//
ElectricalDevice.ElectricalDeviceParameter[] parameters = currentClampDevice.getParameters();
for (int k = 0; k < parameters.length; k++) {
if (parameters[k].getExpression() != null) {
// guards against voltage parameters that are "variable".
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parameters[k], null), getIdentifierSubstitutions(parameters[k].getExpression(), parameters[k].getUnitDefinition(), null)));
}
}
} else if (devices[j] instanceof VoltageClampElectricalDevice) {
VoltageClampElectricalDevice voltageClampDevice = (VoltageClampElectricalDevice) devices[j];
// total current = current source (no capacitance)
Parameter totalCurrent = voltageClampDevice.getParameterFromRole(VoltageClampElectricalDevice.ROLE_TotalCurrent);
Parameter totalCurrentParm = voltageClampDevice.getParameterFromRole(VoltageClampElectricalDevice.ROLE_TotalCurrent);
Parameter voltageParm = voltageClampDevice.getParameterFromRole(VoltageClampElectricalDevice.ROLE_Voltage);
varHash.addVariable(newFunctionOrConstant(getMathSymbol(totalCurrent, null), getIdentifierSubstitutions(totalCurrent.getExpression(), totalCurrent.getUnitDefinition(), null)));
varHash.addVariable(newFunctionOrConstant(getMathSymbol(totalCurrentParm, null), getIdentifierSubstitutions(totalCurrentParm.getExpression(), totalCurrentParm.getUnitDefinition(), null)));
varHash.addVariable(newFunctionOrConstant(getMathSymbol(voltageParm, null), getIdentifierSubstitutions(voltageParm.getExpression(), voltageParm.getUnitDefinition(), null)));
//
// add user-defined parameters
//
ElectricalDevice.ElectricalDeviceParameter[] parameters = voltageClampDevice.getParameters();
for (int k = 0; k < parameters.length; k++) {
if (parameters[k].getRole() == ElectricalDevice.ROLE_UserDefined) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parameters[k], null), getIdentifierSubstitutions(parameters[k].getExpression(), parameters[k].getUnitDefinition(), null)));
}
}
}
}
} else {
//
for (int j = 0; j < structureMappings.length; j++) {
if (structureMappings[j] instanceof MembraneMapping) {
MembraneMapping memMapping = (MembraneMapping) structureMappings[j];
varHash.addVariable(newFunctionOrConstant(getMathSymbol(memMapping.getMembrane().getMembraneVoltage(), memMapping), getIdentifierSubstitutions(memMapping.getInitialVoltageParameter().getExpression(), memMapping.getInitialVoltageParameter().getUnitDefinition(), memMapping)));
}
}
}
//
for (int j = 0; j < structureMappings.length; j++) {
if (structureMappings[j] instanceof MembraneMapping) {
MembraneMapping membraneMapping = (MembraneMapping) structureMappings[j];
Membrane.MembraneVoltage membraneVoltage = membraneMapping.getMembrane().getMembraneVoltage();
ElectricalDevice[] membraneDevices = potentialMapping.getElectricalDevices(membraneMapping.getMembrane());
// ElectricalDevice membraneDevice = null;
for (int i = 0; i < membraneDevices.length; i++) {
if (membraneDevices[i].hasCapacitance() && membraneDevices[i].getDependentVoltageExpression() == null) {
if (membraneMapping.getCalculateVoltage() && bCalculatePotential) {
if (getResolved(membraneMapping)) {
//
if (mathDesc.getVariable(Membrane.MEMBRANE_VOLTAGE_REGION_NAME) == null) {
// varHash.addVariable(new MembraneRegionVariable(MembraneVoltage.MEMBRANE_VOLTAGE_REGION_NAME));
varHash.addVariable(new MembraneRegionVariable(getMathSymbol(membraneVoltage, membraneMapping), nullDomain));
}
} else {
//
// spatially unresolved membrane, and must solve for potential ... make VolVariable for this compartment
//
varHash.addVariable(new VolVariable(getMathSymbol(membraneVoltage, membraneMapping), nullDomain));
}
Parameter initialVoltageParm = membraneMapping.getInitialVoltageParameter();
Variable initVoltageFunction = newFunctionOrConstant(getMathSymbol(initialVoltageParm, membraneMapping), getIdentifierSubstitutions(initialVoltageParm.getExpression(), initialVoltageParm.getUnitDefinition(), membraneMapping));
varHash.addVariable(initVoltageFunction);
} else {
//
// don't calculate voltage, still may need it though
//
Parameter initialVoltageParm = membraneMapping.getInitialVoltageParameter();
Variable voltageFunction = newFunctionOrConstant(getMathSymbol(membraneMapping.getMembrane().getMembraneVoltage(), membraneMapping), getIdentifierSubstitutions(initialVoltageParm.getExpression(), initialVoltageParm.getUnitDefinition(), membraneMapping));
varHash.addVariable(voltageFunction);
}
}
}
}
}
//
for (int j = 0; j < reactionSteps.length; j++) {
ReactionStep rs = reactionSteps[j];
if (simContext.getReactionContext().getReactionSpec(rs).isExcluded()) {
continue;
}
Kinetics.KineticsParameter[] parameters = rs.getKinetics().getKineticsParameters();
StructureMapping sm = simContext.getGeometryContext().getStructureMapping(rs.getStructure());
if (parameters != null) {
for (int i = 0; i < parameters.length; i++) {
if (((parameters[i].getRole() == Kinetics.ROLE_CurrentDensity) || (parameters[i].getRole() == Kinetics.ROLE_LumpedCurrent)) && (parameters[i].getExpression() == null || parameters[i].getExpression().isZero())) {
continue;
}
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parameters[i], sm), getIdentifierSubstitutions(parameters[i].getExpression(), parameters[i].getUnitDefinition(), sm)));
}
}
}
//
// initial constants (either function or constant)
//
SpeciesContextSpec[] speciesContextSpecs = simContext.getReactionContext().getSpeciesContextSpecs();
for (int i = 0; i < speciesContextSpecs.length; i++) {
SpeciesContextSpecParameter initParm = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_InitialConcentration);
if (initParm != null) {
Expression initExpr = new Expression(initParm.getExpression());
StructureMapping sm = simContext.getGeometryContext().getStructureMapping(speciesContextSpecs[i].getSpeciesContext().getStructure());
String[] symbols = initExpr.getSymbols();
// Check if 'initExpr' has other speciesContexts in its expression, need to replace it with 'spContext_init'
for (int j = 0; symbols != null && j < symbols.length; j++) {
// if symbol is a speciesContext, replacing it with a reference to initial condition for that speciesContext.
SpeciesContext spC = null;
SymbolTableEntry ste = initExpr.getSymbolBinding(symbols[j]);
if (ste instanceof SpeciesContextSpecProxyParameter) {
SpeciesContextSpecProxyParameter spspp = (SpeciesContextSpecProxyParameter) ste;
if (spspp.getTarget() instanceof SpeciesContext) {
spC = (SpeciesContext) spspp.getTarget();
SpeciesContextSpec spcspec = simContext.getReactionContext().getSpeciesContextSpec(spC);
SpeciesContextSpecParameter spCInitParm = spcspec.getParameterFromRole(SpeciesContextSpec.ROLE_InitialConcentration);
// if initConc param expression is null, try initCount
if (spCInitParm.getExpression() == null) {
spCInitParm = spcspec.getParameterFromRole(SpeciesContextSpec.ROLE_InitialCount);
}
// need to get init condn expression, but can't get it from getMathSymbol() (mapping between bio and math), hence get it as below.
Expression scsInitExpr = new Expression(spCInitParm, getNameScope());
// scsInitExpr.bindExpression(this);
initExpr.substituteInPlace(new Expression(spC.getName()), scsInitExpr);
}
}
}
// now create the appropriate function for the current speciesContextSpec.
varHash.addVariable(newFunctionOrConstant(getMathSymbol(initParm, sm), getIdentifierSubstitutions(initExpr, initParm.getUnitDefinition(), sm)));
}
}
//
for (int i = 0; i < speciesContextSpecs.length; i++) {
SpeciesContextMapping scm = getSpeciesContextMapping(speciesContextSpecs[i].getSpeciesContext());
SpeciesContextSpec.SpeciesContextSpecParameter diffParm = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_DiffusionRate);
if (diffParm != null && (scm.isPDERequired())) {
StructureMapping sm = simContext.getGeometryContext().getStructureMapping(speciesContextSpecs[i].getSpeciesContext().getStructure());
varHash.addVariable(newFunctionOrConstant(getMathSymbol(diffParm, sm), getIdentifierSubstitutions(diffParm.getExpression(), diffParm.getUnitDefinition(), sm)));
}
}
//
for (int i = 0; i < speciesContextSpecs.length; i++) {
SpeciesContextSpec.SpeciesContextSpecParameter bc_xm = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_BoundaryValueXm);
StructureMapping sm = simContext.getGeometryContext().getStructureMapping(speciesContextSpecs[i].getSpeciesContext().getStructure());
if (bc_xm != null && (bc_xm.getExpression() != null)) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(bc_xm, sm), getIdentifierSubstitutions(bc_xm.getExpression(), bc_xm.getUnitDefinition(), sm)));
}
SpeciesContextSpec.SpeciesContextSpecParameter bc_xp = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_BoundaryValueXp);
if (bc_xp != null && (bc_xp.getExpression() != null)) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(bc_xp, sm), getIdentifierSubstitutions(bc_xp.getExpression(), bc_xp.getUnitDefinition(), sm)));
}
SpeciesContextSpec.SpeciesContextSpecParameter bc_ym = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_BoundaryValueYm);
if (bc_ym != null && (bc_ym.getExpression() != null)) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(bc_ym, sm), getIdentifierSubstitutions(bc_ym.getExpression(), bc_ym.getUnitDefinition(), sm)));
}
SpeciesContextSpec.SpeciesContextSpecParameter bc_yp = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_BoundaryValueYp);
if (bc_yp != null && (bc_yp.getExpression() != null)) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(bc_yp, sm), getIdentifierSubstitutions(bc_yp.getExpression(), bc_yp.getUnitDefinition(), sm)));
}
SpeciesContextSpec.SpeciesContextSpecParameter bc_zm = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_BoundaryValueZm);
if (bc_zm != null && (bc_zm.getExpression() != null)) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(bc_zm, sm), getIdentifierSubstitutions(bc_zm.getExpression(), bc_zm.getUnitDefinition(), sm)));
}
SpeciesContextSpec.SpeciesContextSpecParameter bc_zp = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_BoundaryValueZp);
if (bc_zp != null && (bc_zp.getExpression() != null)) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(bc_zp, sm), getIdentifierSubstitutions(bc_zp.getExpression(), bc_zp.getUnitDefinition(), sm)));
}
}
//
for (int i = 0; i < speciesContextSpecs.length; i++) {
SpeciesContextSpec.SpeciesContextSpecParameter advection_velX = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_VelocityX);
StructureMapping sm = simContext.getGeometryContext().getStructureMapping(speciesContextSpecs[i].getSpeciesContext().getStructure());
if (advection_velX != null && (advection_velX.getExpression() != null)) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(advection_velX, sm), getIdentifierSubstitutions(advection_velX.getExpression(), advection_velX.getUnitDefinition(), sm)));
}
SpeciesContextSpec.SpeciesContextSpecParameter advection_velY = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_VelocityY);
if (advection_velY != null && (advection_velY.getExpression() != null)) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(advection_velY, sm), getIdentifierSubstitutions(advection_velY.getExpression(), advection_velY.getUnitDefinition(), sm)));
}
SpeciesContextSpec.SpeciesContextSpecParameter advection_velZ = speciesContextSpecs[i].getParameterFromRole(SpeciesContextSpec.ROLE_VelocityZ);
if (advection_velZ != null && (advection_velZ.getExpression() != null)) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(advection_velZ, sm), getIdentifierSubstitutions(advection_velZ.getExpression(), advection_velZ.getUnitDefinition(), sm)));
}
}
//
// constant species (either function or constant)
//
enum1 = getSpeciesContextMappings();
while (enum1.hasMoreElements()) {
SpeciesContextMapping scm = (SpeciesContextMapping) enum1.nextElement();
if (scm.getVariable() instanceof Constant) {
varHash.addVariable(scm.getVariable());
}
}
//
// conversion factors
//
varHash.addVariable(new Constant(getMathSymbol(model.getKMOLE(), null), getIdentifierSubstitutions(model.getKMOLE().getExpression(), model.getKMOLE().getUnitDefinition(), null)));
varHash.addVariable(new Constant(model.getN_PMOLE().getName(), getIdentifierSubstitutions(model.getN_PMOLE().getExpression(), model.getN_PMOLE().getUnitDefinition(), null)));
varHash.addVariable(new Constant(model.getKMILLIVOLTS().getName(), getIdentifierSubstitutions(model.getKMILLIVOLTS().getExpression(), model.getKMILLIVOLTS().getUnitDefinition(), null)));
varHash.addVariable(new Constant(model.getK_GHK().getName(), getIdentifierSubstitutions(model.getK_GHK().getExpression(), model.getK_GHK().getUnitDefinition(), null)));
//
// geometric functions
//
ModelUnitSystem modelUnitSystem = simContext.getModel().getUnitSystem();
VCUnitDefinition lengthInverseUnit = modelUnitSystem.getLengthUnit().getInverse();
for (int i = 0; i < structureMappings.length; i++) {
StructureMapping sm = structureMappings[i];
Parameter parm = sm.getParameterFromRole(StructureMapping.ROLE_VolumeFraction);
if (parm != null && parm.getExpression() != null && sm.getGeometryClass() instanceof SubVolume) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parm, sm), getIdentifierSubstitutions(parm.getExpression(), parm.getUnitDefinition(), sm)));
}
parm = sm.getParameterFromRole(StructureMapping.ROLE_SurfaceToVolumeRatio);
if (parm != null && parm.getExpression() != null && sm.getGeometryClass() instanceof SubVolume) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parm, sm), getIdentifierSubstitutions(parm.getExpression(), parm.getUnitDefinition(), sm)));
}
if (sm instanceof MembraneMapping && !getResolved(sm)) {
MembraneMapping mm = (MembraneMapping) sm;
parm = ((MembraneMapping) sm).getVolumeFractionParameter();
if (parm.getExpression() == null) {
throw new MappingException("volume fraction not specified for feature '" + structTopology.getInsideFeature(mm.getMembrane()).getName() + "', please refer to Structure Mapping in Application '" + simContext.getName() + "'");
}
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parm, sm), getIdentifierSubstitutions(parm.getExpression(), modelUnitSystem.getInstance_DIMENSIONLESS(), sm)));
parm = mm.getSurfaceToVolumeParameter();
if (parm.getExpression() == null) {
throw new MappingException("surface to volume ratio not specified for membrane '" + mm.getMembrane().getName() + "', please refer to Structure Mapping in Application '" + simContext.getName() + "'");
}
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parm, sm), getIdentifierSubstitutions(parm.getExpression(), lengthInverseUnit, sm)));
}
StructureMappingParameter sizeParm = sm.getSizeParameter();
if (sizeParm != null) {
if (simContext.getGeometry().getDimension() == 0) {
if (sizeParm.getExpression() != null) {
try {
double value = sizeParm.getExpression().evaluateConstant();
varHash.addVariable(new Constant(getMathSymbol(sizeParm, sm), new Expression(value)));
} catch (ExpressionException e) {
// varHash.addVariable(new Function(getMathSymbol(parm,sm),getIdentifierSubstitutions(parm.getExpression(),parm.getUnitDefinition(),sm)));
e.printStackTrace(System.out);
throw new MappingException("Size of structure:" + sm.getNameScope().getName() + " cannot be evaluated as constant.");
}
}
} else {
String compartmentName = null;
VCUnitDefinition sizeUnit = sm.getSizeParameter().getUnitDefinition();
String sizeFunctionName = null;
if (sm instanceof MembraneMapping) {
MembraneMapping mm = (MembraneMapping) sm;
if (getResolved(mm)) {
FeatureMapping fm_inside = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(structTopology.getInsideFeature(mm.getMembrane()));
FeatureMapping fm_outside = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(structTopology.getOutsideFeature(mm.getMembrane()));
compartmentName = getSubVolume(fm_inside).getName() + "_" + getSubVolume(fm_outside).getName();
sizeFunctionName = MathFunctionDefinitions.Function_regionArea_current.getFunctionName();
} else {
FeatureMapping fm_inside = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(structTopology.getInsideFeature(mm.getMembrane()));
FeatureMapping fm_outside = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(structTopology.getOutsideFeature(mm.getMembrane()));
if (getSubVolume(fm_inside) == getSubVolume(fm_outside)) {
compartmentName = getSubVolume(fm_inside).getName();
sizeFunctionName = MathFunctionDefinitions.Function_regionVolume_current.getFunctionName();
} else {
throw new RuntimeException("unexpected structure mapping for membrane '" + mm.getMembrane().getName() + "'");
}
}
} else if (sm instanceof FeatureMapping) {
FeatureMapping fm = (FeatureMapping) sm;
compartmentName = getSubVolume(fm).getName();
sizeFunctionName = MathFunctionDefinitions.Function_regionVolume_current.getFunctionName();
} else {
throw new RuntimeException("structure mapping " + sm.getClass().getName() + " not yet supported");
}
Expression totalVolumeCorrection = sm.getStructureSizeCorrection(simContext, this);
Expression sizeFunctionExpression = Expression.function(sizeFunctionName, new Expression[] { new Expression("'" + compartmentName + "'") });
sizeFunctionExpression.bindExpression(mathDesc);
varHash.addVariable(newFunctionOrConstant(getMathSymbol(sizeParm, sm), getIdentifierSubstitutions(Expression.mult(totalVolumeCorrection, sizeFunctionExpression), sizeUnit, sm)));
parm = sm.getParameterFromRole(StructureMapping.ROLE_AreaPerUnitArea);
if (parm != null && parm.getExpression() != null && sm.getGeometryClass() instanceof SurfaceClass) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parm, sm), getIdentifierSubstitutions(parm.getExpression(), parm.getUnitDefinition(), sm)));
}
parm = sm.getParameterFromRole(StructureMapping.ROLE_AreaPerUnitVolume);
if (parm != null && parm.getExpression() != null && sm.getGeometryClass() instanceof SubVolume) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parm, sm), getIdentifierSubstitutions(parm.getExpression(), parm.getUnitDefinition(), sm)));
}
parm = sm.getParameterFromRole(StructureMapping.ROLE_VolumePerUnitArea);
if (parm != null && parm.getExpression() != null && sm.getGeometryClass() instanceof SurfaceClass) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parm, sm), getIdentifierSubstitutions(parm.getExpression(), parm.getUnitDefinition(), sm)));
}
parm = sm.getParameterFromRole(StructureMapping.ROLE_VolumePerUnitVolume);
if (parm != null && parm.getExpression() != null && sm.getGeometryClass() instanceof SubVolume) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parm, sm), getIdentifierSubstitutions(parm.getExpression(), parm.getUnitDefinition(), sm)));
}
}
}
}
//
for (int i = 0; i < fieldMathMappingParameters.length; i++) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], null), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), null)));
}
//
// functions
//
enum1 = getSpeciesContextMappings();
while (enum1.hasMoreElements()) {
SpeciesContextMapping scm = (SpeciesContextMapping) enum1.nextElement();
if (scm.getVariable() == null && scm.getDependencyExpression() != null) {
StructureMapping sm = simContext.getGeometryContext().getStructureMapping(scm.getSpeciesContext().getStructure());
varHash.addVariable(newFunctionOrConstant(getMathSymbol(scm.getSpeciesContext(), sm), getIdentifierSubstitutions(scm.getDependencyExpression(), scm.getSpeciesContext().getUnitDefinition(), sm)));
}
}
//
// set Variables to MathDescription all at once with the order resolved by "VariableHash"
//
mathDesc.setAllVariables(varHash.getAlphabeticallyOrderedVariables());
//
if (simContext.getGeometryContext().getGeometry() != null) {
try {
mathDesc.setGeometry(simContext.getGeometryContext().getGeometry());
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new MappingException("failure setting geometry " + e.getMessage());
}
} else {
throw new MappingException("geometry must be defined");
}
//
// volume subdomains
//
subVolumes = simContext.getGeometryContext().getGeometry().getGeometrySpec().getSubVolumes();
VCUnitDefinition timeUnit = modelUnitSystem.getTimeUnit();
for (int j = 0; j < subVolumes.length; j++) {
SubVolume subVolume = (SubVolume) subVolumes[j];
//
// get priority of subDomain
//
int priority;
Feature spatialFeature = getResolvedFeature(subVolume);
if (spatialFeature == null) {
if (simContext.getGeometryContext().getGeometry().getDimension() > 0) {
throw new MappingException("no compartment (in Physiology) is mapped to subdomain '" + subVolume.getName() + "' (in Geometry)");
} else {
priority = CompartmentSubDomain.NON_SPATIAL_PRIORITY;
}
} else {
// now does not have to match spatial feature, *BUT* needs to be unique
priority = j;
}
//
// create subDomain
//
CompartmentSubDomain subDomain = new CompartmentSubDomain(subVolume.getName(), priority);
mathDesc.addSubDomain(subDomain);
//
if (spatialFeature != null) {
FeatureMapping fm = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(spatialFeature);
subDomain.setBoundaryConditionXm(fm.getBoundaryConditionTypeXm());
subDomain.setBoundaryConditionXp(fm.getBoundaryConditionTypeXp());
if (simContext.getGeometry().getDimension() > 1) {
subDomain.setBoundaryConditionYm(fm.getBoundaryConditionTypeYm());
subDomain.setBoundaryConditionYp(fm.getBoundaryConditionTypeYp());
}
if (simContext.getGeometry().getDimension() > 2) {
subDomain.setBoundaryConditionZm(fm.getBoundaryConditionTypeZm());
subDomain.setBoundaryConditionZp(fm.getBoundaryConditionTypeZp());
}
}
//
// create equations
//
VolumeStructureAnalyzer structureAnalyzer = getVolumeStructureAnalyzer(subVolume);
Enumeration<SpeciesContextMapping> enumSCM = getSpeciesContextMappings();
while (enumSCM.hasMoreElements()) {
SpeciesContextMapping scm = enumSCM.nextElement();
//
if (scm.getVariable() instanceof VolVariable && scm.getDependencyExpression() == null) {
SpeciesContext sc = scm.getSpeciesContext();
StructureMapping sm = simContext.getGeometryContext().getStructureMapping(sc.getStructure());
SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
VolVariable variable = (VolVariable) scm.getVariable();
Equation equation = null;
if ((scm.isPDERequired()) && sm instanceof FeatureMapping) {
//
if (getSubVolume((FeatureMapping) sm) == subVolume) {
//
// species context belongs to this subDomain
//
Expression initial = new Expression(getMathSymbol(scs.getParameterFromRole(SpeciesContextSpec.ROLE_InitialConcentration), sm));
Expression rate = getIdentifierSubstitutions(scm.getRate(), scm.getSpeciesContext().getUnitDefinition().divideBy(timeUnit), simContext.getGeometryContext().getStructureMapping(sc.getStructure()));
Expression diffusion = new Expression(getMathSymbol(scs.getDiffusionParameter(), sm));
equation = new PdeEquation(variable, initial, rate, diffusion);
((PdeEquation) equation).setBoundaryXm((scs.getBoundaryXmParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryXmParameter(), sm)));
((PdeEquation) equation).setBoundaryXp((scs.getBoundaryXpParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryXpParameter(), sm)));
((PdeEquation) equation).setBoundaryYm((scs.getBoundaryYmParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryYmParameter(), sm)));
((PdeEquation) equation).setBoundaryYp((scs.getBoundaryYpParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryYpParameter(), sm)));
((PdeEquation) equation).setBoundaryZm((scs.getBoundaryZmParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryZmParameter(), sm)));
((PdeEquation) equation).setBoundaryZp((scs.getBoundaryZpParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryZpParameter(), sm)));
((PdeEquation) equation).setVelocityX((scs.getVelocityXParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getVelocityXParameter(), sm)));
((PdeEquation) equation).setVelocityY((scs.getVelocityYParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getVelocityYParameter(), sm)));
((PdeEquation) equation).setVelocityZ((scs.getVelocityZParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getVelocityZParameter(), sm)));
subDomain.replaceEquation(equation);
} else {
Expression initial = new Expression(0.0);
Expression rate = new Expression(0.0);
Expression diffusion = new Expression(getMathSymbol(scs.getDiffusionParameter(), sm));
equation = new PdeEquation(variable, initial, rate, diffusion);
if (subDomain.getEquation(variable) == null) {
subDomain.addEquation(equation);
}
}
} else {
//
// ODE
//
SubVolume mappedSubVolume = null;
if (sm instanceof FeatureMapping) {
mappedSubVolume = getSubVolume((FeatureMapping) sm);
} else if (sm instanceof MembraneMapping) {
// membrane is mapped to that of the inside feature
FeatureMapping featureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(structTopology.getInsideFeature((Membrane) sm.getStructure()));
mappedSubVolume = getSubVolume(featureMapping);
}
if (mappedSubVolume == subVolume) {
//
// species context belongs to this subDomain
//
Expression initial = new Expression(getMathSymbol(scs.getParameterFromRole(SpeciesContextSpec.ROLE_InitialConcentration), null));
Expression rate = (scm.getRate() == null) ? new Expression(0.0) : getIdentifierSubstitutions(scm.getRate(), scm.getSpeciesContext().getUnitDefinition().divideBy(timeUnit), simContext.getGeometryContext().getStructureMapping(sc.getStructure()));
equation = new OdeEquation(variable, initial, rate);
subDomain.replaceEquation(equation);
} else {
Expression initial = new Expression(0.0);
Expression rate = new Expression(0.0);
equation = new OdeEquation(variable, initial, rate);
if (subDomain.getEquation(variable) == null) {
subDomain.addEquation(equation);
}
}
}
}
}
//
// create fast system (if neccessary)
//
SpeciesContextMapping[] fastSpeciesContextMappings = structureAnalyzer.getFastSpeciesContextMappings();
VCUnitDefinition subDomainUnit = modelUnitSystem.getVolumeConcentrationUnit();
if (fastSpeciesContextMappings != null) {
FastSystem fastSystem = new FastSystem(mathDesc);
for (int i = 0; i < fastSpeciesContextMappings.length; i++) {
SpeciesContextMapping scm = fastSpeciesContextMappings[i];
if (scm.getFastInvariant() == null) {
//
// independant-fast variable, create a fastRate object
//
Expression rate = getIdentifierSubstitutions(scm.getFastRate(), scm.getSpeciesContext().getUnitDefinition().divideBy(timeUnit), simContext.getGeometryContext().getStructureMapping(getResolvedFeature(subVolume)));
FastRate fastRate = new FastRate(rate);
fastSystem.addFastRate(fastRate);
} else {
//
// dependant-fast variable, create a fastInvariant object
//
Expression rate = getIdentifierSubstitutions(scm.getFastInvariant(), subDomainUnit, simContext.getGeometryContext().getStructureMapping(getResolvedFeature(subVolume)));
FastInvariant fastInvariant = new FastInvariant(rate);
fastSystem.addFastInvariant(fastInvariant);
}
}
subDomain.setFastSystem(fastSystem);
// constructor calls the 'refresh' method which constructs depemdency matrix, dependent/independent vars and pseudoconstants, etc.
FastSystemAnalyzer fs_analyzer = new FastSystemAnalyzer(fastSystem, mathDesc);
}
//
// create ode's for voltages to be calculated on unresolved membranes mapped to this subVolume
//
Structure[] localStructures = getStructures(subVolume);
for (int sIndex = 0; sIndex < localStructures.length; sIndex++) {
if (localStructures[sIndex] instanceof Membrane) {
Membrane membrane = (Membrane) localStructures[sIndex];
MembraneMapping membraneMapping = (MembraneMapping) simContext.getGeometryContext().getStructureMapping(membrane);
if (!getResolved(membraneMapping) && membraneMapping.getCalculateVoltage()) {
MembraneElectricalDevice capacitiveDevice = potentialMapping.getCapacitiveDevice(membrane);
if (capacitiveDevice.getDependentVoltageExpression() == null) {
VolVariable vVar = (VolVariable) mathDesc.getVariable(getMathSymbol(capacitiveDevice.getVoltageSymbol(), membraneMapping));
Expression initExp = new Expression(getMathSymbol(capacitiveDevice.getMembraneMapping().getInitialVoltageParameter(), membraneMapping));
subDomain.addEquation(new OdeEquation(vVar, initExp, getIdentifierSubstitutions(potentialMapping.getOdeRHS(capacitiveDevice, this), membrane.getMembraneVoltage().getUnitDefinition().divideBy(timeUnit), membraneMapping)));
} else {
//
//
//
}
}
}
}
}
//
for (int k = 0; k < subVolumes.length; k++) {
SubVolume subVolume = (SubVolume) subVolumes[k];
//
// if there is a spatially resolved membrane surrounding this subVolume, then create a membraneSubDomain
//
structures = getStructures(subVolume);
Membrane membrane = null;
if (structures != null) {
for (int j = 0; j < structures.length; j++) {
if (structures[j] instanceof Membrane && getResolved(simContext.getGeometryContext().getStructureMapping(structures[j]))) {
membrane = (Membrane) structures[j];
}
}
}
if (membrane == null) {
continue;
}
SubVolume outerSubVolume = getSubVolume(((FeatureMapping) simContext.getGeometryContext().getStructureMapping(structTopology.getOutsideFeature(membrane))));
SubVolume innerSubVolume = getSubVolume(((FeatureMapping) simContext.getGeometryContext().getStructureMapping(structTopology.getInsideFeature(membrane))));
if (innerSubVolume != subVolume) {
throw new MappingException("membrane " + membrane.getName() + " improperly mapped to inner subVolume " + innerSubVolume.getName());
}
//
// get priority of subDomain
//
// Feature spatialFeature = simContext.getGeometryContext().getResolvedFeature(subVolume);
// int priority = spatialFeature.getPriority();
//
// create subDomain
//
CompartmentSubDomain outerCompartment = mathDesc.getCompartmentSubDomain(outerSubVolume.getName());
CompartmentSubDomain innerCompartment = mathDesc.getCompartmentSubDomain(innerSubVolume.getName());
SurfaceClass surfaceClass = simContext.getGeometry().getGeometrySurfaceDescription().getSurfaceClass(innerSubVolume, outerSubVolume);
MembraneSubDomain memSubDomain = new MembraneSubDomain(innerCompartment, outerCompartment, surfaceClass.getName());
mathDesc.addSubDomain(memSubDomain);
//
// create equations for membrane-bound molecular species
//
MembraneStructureAnalyzer membraneStructureAnalyzer = getMembraneStructureAnalyzer(membrane);
Enumeration<SpeciesContextMapping> enumSCM = getSpeciesContextMappings();
while (enumSCM.hasMoreElements()) {
SpeciesContextMapping scm = enumSCM.nextElement();
SpeciesContext sc = scm.getSpeciesContext();
SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
//
if ((scm.getVariable() instanceof MemVariable) && scm.getDependencyExpression() == null) {
//
// independant variable, create an equation object
//
Equation equation = null;
MemVariable variable = (MemVariable) scm.getVariable();
MembraneMapping mm = (MembraneMapping) simContext.getGeometryContext().getStructureMapping(sc.getStructure());
if (scm.isPDERequired()) {
//
if (mm.getMembrane() == membrane) {
//
// species context belongs to this subDomain
//
Expression initial = new Expression(getMathSymbol(scs.getParameterFromRole(SpeciesContextSpec.ROLE_InitialConcentration), mm));
Expression rate = getIdentifierSubstitutions(scm.getRate(), scm.getSpeciesContext().getUnitDefinition().divideBy(timeUnit), simContext.getGeometryContext().getStructureMapping(sc.getStructure()));
Expression diffusion = new Expression(getMathSymbol(scs.getDiffusionParameter(), mm));
equation = new PdeEquation(variable, initial, rate, diffusion);
((PdeEquation) equation).setBoundaryXm((scs.getBoundaryXmParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryXmParameter(), mm)));
((PdeEquation) equation).setBoundaryXp((scs.getBoundaryXpParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryXpParameter(), mm)));
((PdeEquation) equation).setBoundaryYm((scs.getBoundaryYmParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryYmParameter(), mm)));
((PdeEquation) equation).setBoundaryYp((scs.getBoundaryYpParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryYpParameter(), mm)));
((PdeEquation) equation).setBoundaryZm((scs.getBoundaryZmParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryZmParameter(), mm)));
((PdeEquation) equation).setBoundaryZp((scs.getBoundaryZpParameter().getExpression() == null) ? (null) : new Expression(getMathSymbol(scs.getBoundaryZpParameter(), mm)));
memSubDomain.replaceEquation(equation);
} else {
Expression initial = new Expression(0.0);
Expression rate = new Expression(0.0);
Expression diffusion = new Expression(getMathSymbol(scs.getDiffusionParameter(), mm));
equation = new PdeEquation(variable, initial, rate, diffusion);
if (memSubDomain.getEquation(variable) == null) {
memSubDomain.addEquation(equation);
}
}
} else {
//
if (mm.getMembrane() == membrane) {
//
// species context belongs to this subDomain
//
Expression initial = new Expression(getMathSymbol(scs.getParameterFromRole(SpeciesContextSpec.ROLE_InitialConcentration), null));
Expression rate = getIdentifierSubstitutions(scm.getRate(), scm.getSpeciesContext().getUnitDefinition().divideBy(timeUnit), simContext.getGeometryContext().getStructureMapping(sc.getStructure()));
equation = new OdeEquation(variable, initial, rate);
memSubDomain.replaceEquation(equation);
} else {
Expression initial = new Expression(0.0);
Expression rate = new Expression(0.0);
equation = new OdeEquation(variable, initial, rate);
if (memSubDomain.getEquation(variable) == null) {
memSubDomain.addEquation(equation);
}
}
}
}
}
//
// create dummy jump conditions for all volume variables that diffuse and/or advect
//
Enumeration<SpeciesContextMapping> enum_scm = getSpeciesContextMappings();
while (enum_scm.hasMoreElements()) {
SpeciesContextMapping scm = enum_scm.nextElement();
if (scm.isPDERequired()) {
// Species species = scm.getSpeciesContext().getSpecies();
Variable var = scm.getVariable();
if (var instanceof VolVariable && (scm.isPDERequired())) {
JumpCondition jc = memSubDomain.getJumpCondition((VolVariable) var);
if (jc == null) {
// System.out.println("MathMapping.refreshMathDescription(), adding jump condition for diffusing variable "+var.getName()+" on membrane "+membraneStructureAnalyzer.getMembrane().getName());
jc = new JumpCondition((VolVariable) var);
memSubDomain.addJumpCondition(jc);
}
}
}
}
//
// create jump conditions for any volume variables that bind to membrane or have explicitly defined fluxes
//
ResolvedFlux[] resolvedFluxes = membraneStructureAnalyzer.getResolvedFluxes();
if (resolvedFluxes != null) {
for (int i = 0; i < resolvedFluxes.length; i++) {
Species species = resolvedFluxes[i].getSpecies();
SpeciesContext sc = simContext.getReactionContext().getModel().getSpeciesContext(species, structTopology.getInsideFeature(membraneStructureAnalyzer.getMembrane()));
if (sc == null) {
sc = simContext.getReactionContext().getModel().getSpeciesContext(species, structTopology.getOutsideFeature(membraneStructureAnalyzer.getMembrane()));
}
SpeciesContextMapping scm = getSpeciesContextMapping(sc);
// if (scm.getVariable() instanceof VolVariable && scm.isDiffusing()){
if (scm.getVariable() instanceof VolVariable && ((MembraneStructureAnalyzer.bNoFluxIfFixed || (scm.isPDERequired())))) {
if (MembraneStructureAnalyzer.bNoFluxIfFixed && !scm.isPDERequired()) {
MembraneStructureAnalyzer.bNoFluxIfFixedExercised = true;
}
JumpCondition jc = memSubDomain.getJumpCondition((VolVariable) scm.getVariable());
if (jc == null) {
jc = new JumpCondition((VolVariable) scm.getVariable());
memSubDomain.addJumpCondition(jc);
}
Expression inFlux = getIdentifierSubstitutions(resolvedFluxes[i].inFluxExpression, resolvedFluxes[i].getUnitDefinition(), simContext.getGeometryContext().getStructureMapping(membraneStructureAnalyzer.getMembrane()));
jc.setInFlux(inFlux);
Expression outFlux = getIdentifierSubstitutions(resolvedFluxes[i].outFluxExpression, resolvedFluxes[i].getUnitDefinition(), simContext.getGeometryContext().getStructureMapping(membraneStructureAnalyzer.getMembrane()));
jc.setOutFlux(outFlux);
} else {
throw new MappingException("APPLICATION " + simContext.getName() + " : " + scm.getSpeciesContext().getName() + " has spatially resolved flux at membrane " + membrane.getName() + ", but doesn't diffuse in compartment " + scm.getSpeciesContext().getStructure().getName());
}
}
}
//
// create fast system (if neccessary)
//
SpeciesContextMapping[] fastSpeciesContextMappings = membraneStructureAnalyzer.getFastSpeciesContextMappings();
if (fastSpeciesContextMappings != null) {
FastSystem fastSystem = new FastSystem(mathDesc);
for (int i = 0; i < fastSpeciesContextMappings.length; i++) {
SpeciesContextMapping scm = fastSpeciesContextMappings[i];
if (scm.getFastInvariant() == null) {
//
// independant-fast variable, create a fastRate object
//
VCUnitDefinition rateUnit = scm.getSpeciesContext().getUnitDefinition().divideBy(timeUnit);
MembraneMapping membraneMapping = (MembraneMapping) simContext.getGeometryContext().getStructureMapping(membraneStructureAnalyzer.getMembrane());
FastRate fastRate = new FastRate(getIdentifierSubstitutions(scm.getFastRate(), rateUnit, membraneMapping));
fastSystem.addFastRate(fastRate);
} else {
//
// dependant-fast variable, create a fastInvariant object
//
VCUnitDefinition invariantUnit = scm.getSpeciesContext().getUnitDefinition();
MembraneMapping membraneMapping = (MembraneMapping) simContext.getGeometryContext().getStructureMapping(membraneStructureAnalyzer.getMembrane());
FastInvariant fastInvariant = new FastInvariant(getIdentifierSubstitutions(scm.getFastInvariant(), invariantUnit, membraneMapping));
fastSystem.addFastInvariant(fastInvariant);
}
}
memSubDomain.setFastSystem(fastSystem);
// constructor calls the 'refresh' method which constructs depemdency matrix, dependent/independent vars and pseudoconstants, etc.
FastSystemAnalyzer fs_analyzer = new FastSystemAnalyzer(fastSystem, mathDesc);
}
//
// create Membrane-region equations for potential of this resolved membrane
//
MembraneMapping membraneMapping = (MembraneMapping) simContext.getGeometryContext().getStructureMapping(membrane);
if (membraneMapping.getCalculateVoltage()) {
ElectricalDevice[] membraneDevices = potentialMapping.getElectricalDevices(membrane);
int numCapacitiveDevices = 0;
MembraneElectricalDevice capacitiveDevice = null;
for (int i = 0; i < membraneDevices.length; i++) {
if (membraneDevices[i] instanceof MembraneElectricalDevice) {
numCapacitiveDevices++;
capacitiveDevice = (MembraneElectricalDevice) membraneDevices[i];
}
}
if (numCapacitiveDevices != 1) {
throw new MappingException("expecting 1 capacitive electrical device on graph edge for membrane " + membrane.getName() + ", found '" + numCapacitiveDevices + "'");
}
if (mathDesc.getVariable(getMathSymbol(capacitiveDevice.getVoltageSymbol(), membraneMapping)) instanceof MembraneRegionVariable) {
MembraneRegionVariable vVar = (MembraneRegionVariable) mathDesc.getVariable(getMathSymbol(capacitiveDevice.getVoltageSymbol(), membraneMapping));
Parameter initialVoltageParm = capacitiveDevice.getMembraneMapping().getInitialVoltageParameter();
Expression initExp = getIdentifierSubstitutions(initialVoltageParm.getExpression(), initialVoltageParm.getUnitDefinition(), capacitiveDevice.getMembraneMapping());
MembraneRegionEquation vEquation = new MembraneRegionEquation(vVar, initExp);
vEquation.setMembraneRateExpression(getIdentifierSubstitutions(potentialMapping.getOdeRHS(capacitiveDevice, this), membrane.getMembraneVoltage().getUnitDefinition().divideBy(timeUnit), capacitiveDevice.getMembraneMapping()));
memSubDomain.addEquation(vEquation);
}
}
}
// create equations for event assign targets that are model params/strutureSize, etc.
Set<VolVariable> hashKeySet = eventVolVarHash.keySet();
Iterator<VolVariable> volVarsIter = hashKeySet.iterator();
// working under teh assumption that we are dealing with non-spatial math, hence only one compartment domain!
SubDomain subDomain = mathDesc.getSubDomains().nextElement();
while (volVarsIter.hasNext()) {
VolVariable volVar = volVarsIter.next();
EventAssignmentInitParameter eap = eventVolVarHash.get(volVar);
Expression rateExpr = new Expression(0.0);
Equation equation = new OdeEquation(volVar, new Expression(getMathSymbol(eap, null)), rateExpr);
subDomain.addEquation(equation);
}
// events - add events to math desc and odes for event assignments that have parameters as target variables
BioEvent[] bioevents = simContext.getBioEvents();
if (bioevents != null && bioevents.length > 0) {
for (BioEvent be : bioevents) {
// transform the bioEvent trigger/delay to math Event
Expression mathTriggerExpr = getIdentifierSubstitutions(be.generateTriggerExpression(), modelUnitSystem.getInstance_DIMENSIONLESS(), null);
Delay mathDelay = null;
if (be.getParameter(BioEventParameterType.TriggerDelay) != null) {
boolean bUseValsFromTriggerTime = be.getUseValuesFromTriggerTime();
Expression mathDelayExpr = getIdentifierSubstitutions(be.getParameter(BioEventParameterType.TriggerDelay).getExpression(), timeUnit, null);
mathDelay = new Delay(bUseValsFromTriggerTime, mathDelayExpr);
}
// now deal with (bio)event Assignment translation to math EventAssignment
ArrayList<EventAssignment> eventAssignments = be.getEventAssignments();
ArrayList<Event.EventAssignment> mathEventAssignmentsList = new ArrayList<Event.EventAssignment>();
for (EventAssignment ea : eventAssignments) {
SymbolTableEntry ste = simContext.getEntry(ea.getTarget().getName());
VCUnitDefinition eventAssignVarUnit = ste.getUnitDefinition();
Variable variable = varHash.getVariable(ste.getName());
Event.EventAssignment mathEA = new Event.EventAssignment(variable, getIdentifierSubstitutions(ea.getAssignmentExpression(), eventAssignVarUnit, null));
mathEventAssignmentsList.add(mathEA);
}
// use the translated trigger, delay and event assignments to create (math) event
Event mathEvent = new Event(be.getName(), mathTriggerExpr, mathDelay, mathEventAssignmentsList);
mathDesc.addEvent(mathEvent);
}
}
if (!mathDesc.isValid()) {
throw new MappingException("generated an invalid mathDescription: " + mathDesc.getWarning());
}
// System.out.println("]]]]]]]]]]]]]]]]]]]]]] VCML string begin ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]");
// System.out.println(mathDesc.getVCML());
// System.out.println("]]]]]]]]]]]]]]]]]]]]]] VCML string end ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]");
}
use of cbit.vcell.mapping.MappingException in project vcell by virtualcell.
the class MathMapping_4_8 method getMathSymbol0.
/**
* Substitutes appropriate variables for speciesContext bindings
*
* @return cbit.vcell.parser.Expression
* @param origExp cbit.vcell.parser.Expression
* @param structureMapping cbit.vcell.mapping.StructureMapping
*/
private String getMathSymbol0(SymbolTableEntry ste, StructureMapping structureMapping) throws MappingException {
String steName = ste.getName();
if (ste instanceof Kinetics.KineticsParameter) {
Integer count = localNameCountHash.get(steName);
if (count == null) {
throw new MappingException("KineticsParameter " + steName + " not found in local name count");
}
if (count > 1 || steName.equals("J")) {
return steName + "_" + ste.getNameScope().getName();
// return getNameScope().getSymbolName(ste);
} else {
return steName;
}
}
if (ste instanceof MathMapping_4_8.ProbabilityParameter) {
// be careful here, to see if we need mangle the reaction name
MathMapping_4_8.ProbabilityParameter probParm = (MathMapping_4_8.ProbabilityParameter) ste;
return probParm.getName();
}
if (ste instanceof MathMapping_4_8.SpeciesConcentrationParameter) {
MathMapping_4_8.SpeciesConcentrationParameter concParm = (MathMapping_4_8.SpeciesConcentrationParameter) ste;
return concParm.getSpeciesContextSpec().getSpeciesContext().getName() + MATH_FUNC_SUFFIX_SPECIES_CONCENTRATION;
}
if (ste instanceof MathMapping_4_8.SpeciesCountParameter) {
MathMapping_4_8.SpeciesCountParameter countParm = (MathMapping_4_8.SpeciesCountParameter) ste;
return countParm.getSpeciesContextSpec().getSpeciesContext().getName() + MATH_VAR_SUFFIX_SPECIES_COUNT;
}
if (ste instanceof MathMapping_4_8.EventAssignmentInitParameter) {
MathMapping_4_8.EventAssignmentInitParameter eventInitParm = (MathMapping_4_8.EventAssignmentInitParameter) ste;
return eventInitParm.getName() + MATH_FUNC_SUFFIX_EVENTASSIGN_INIT;
}
if (ste instanceof Model.ReservedSymbol) {
return steName;
}
if (ste instanceof Membrane.MembraneVoltage) {
return steName;
}
if (ste instanceof Structure.StructureSize) {
Structure structure = ((Structure.StructureSize) ste).getStructure();
StructureMapping.StructureMappingParameter sizeParameter = simContext.getGeometryContext().getStructureMapping(structure).getSizeParameter();
return getMathSymbol(sizeParameter, structureMapping);
}
if (ste instanceof ProxyParameter) {
ProxyParameter pp = (ProxyParameter) ste;
return getMathSymbol0(pp.getTarget(), structureMapping);
}
//
Model model = simContext.getModel();
if (ste instanceof ModelParameter) {
ModelParameter mp = (ModelParameter) ste;
if (simContext.getGeometry().getDimension() == 0) {
return mp.getName();
} else {
if (mp.getExpression().getSymbols() == null) {
return mp.getName();
}
// check if global param variant name exists in globalVarsHash. If so, return it, else, throw exception.
Hashtable<String, Expression> smVariantsHash = globalParamVariantsHash.get(mp);
String variantName = mp.getName() + "_" + TokenMangler.fixTokenStrict(structureMapping.getStructure().getName());
if (smVariantsHash.get(variantName) != null) {
return variantName;
} else {
// global param variant doesn't exist in the hash, so get the substituted expression for global param and
// gather all symbols (speciesContexts) that do not match with arg 'structureMapping' to display a proper error message.
Expression expr = null;
try {
expr = substituteGlobalParameters(mp.getExpression());
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Could not substitute expression for global parameter '" + mp.getName() + "' with expression '" + "'" + e.getMessage());
}
// find symbols (typically speciesContexts) in 'exp' that do not match with the arg 'structureMapping'
String[] symbols = expr.getSymbols();
String msg = "";
if (symbols != null) {
Vector<String> spContextNamesVector = new Vector<String>();
for (int j = 0; j < symbols.length; j++) {
SpeciesContext sc = model.getSpeciesContext(symbols[j]);
if (sc != null) {
if (!sc.getStructure().compareEqual(structureMapping.getStructure())) {
spContextNamesVector.addElement(sc.getName());
}
}
}
for (int i = 0; (spContextNamesVector != null && i < spContextNamesVector.size()); i++) {
if (i == 0) {
msg += "'" + spContextNamesVector.elementAt(i) + ", ";
} else if (i == spContextNamesVector.size() - 1) {
msg += spContextNamesVector.elementAt(i) + "'";
} else {
msg += spContextNamesVector.elementAt(i) + ", ";
}
}
}
throw new RuntimeException("Global parameter '" + mp.getName() + "' is not defined in compartment '" + structureMapping.getStructure().getName() + "', but was referenced in that compartment." + "\n\nExpression '" + mp.getExpression().infix() + "' for global parameter '" + mp.getName() + "' expands to '" + expr.infix() + "' " + "and contains species " + msg + " that is/are not in adjacent compartments.");
}
// return (mp.getName()+"_"+TokenMangler.fixTokenStrict(structureMapping.getStructure().getName()));
}
}
if (ste instanceof SpeciesContextSpec.SpeciesContextSpecParameter) {
SpeciesContextSpec.SpeciesContextSpecParameter scsParm = (SpeciesContextSpec.SpeciesContextSpecParameter) ste;
if (scsParm.getRole() == SpeciesContextSpec.ROLE_InitialConcentration) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + MATH_FUNC_SUFFIX_SPECIES_INIT_CONCENTRATION;
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_InitialCount) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + MATH_FUNC_SUFFIX_SPECIES_INIT_COUNT;
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_DiffusionRate) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_diffusionRate";
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueXm) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryXm";
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueXp) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryXp";
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueYm) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryYm";
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueYp) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryYp";
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueZm) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryZm";
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_BoundaryValueZp) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_boundaryZp";
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_VelocityX) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_velocityX";
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_VelocityY) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_velocityY";
}
if (scsParm.getRole() == SpeciesContextSpec.ROLE_VelocityZ) {
return ((SpeciesContextSpec) (scsParm.getNameScope().getScopedSymbolTable())).getSpeciesContext().getName() + "_velocityZ";
}
}
if (ste instanceof ElectricalDevice.ElectricalDeviceParameter) {
ElectricalDevice.ElectricalDeviceParameter edParm = (ElectricalDevice.ElectricalDeviceParameter) ste;
ElectricalDevice electricalDevice = (ElectricalDevice) edParm.getNameScope().getScopedSymbolTable();
if (electricalDevice instanceof MembraneElectricalDevice) {
String nameWithScope = ((MembraneElectricalDevice) electricalDevice).getMembraneMapping().getMembrane().getNameScope().getName();
if (edParm.getRole() == ElectricalDevice.ROLE_TotalCurrent) {
return "I_" + nameWithScope;
}
if (edParm.getRole() == ElectricalDevice.ROLE_TransmembraneCurrent) {
return "F_" + nameWithScope;
}
// }else if (electricalDevice instanceof CurrentClampElectricalDevice) {
// if (edParm.getRole()==ElectricalDevice.ROLE_TotalCurrentDensity){
// return "I_"+((CurrentClampElectricalDevice)electricalDevice).getCurrentClampStimulus().getNameScope().getName();
// }
// if (edParm.getRole()==ElectricalDevice.ROLE_TransmembraneCurrentDensity){
// return "F_"+((CurrentClampElectricalDevice)electricalDevice).getCurrentClampStimulus().getNameScope().getName();
// }
// }else if (electricalDevice instanceof VoltageClampElectricalDevice) {
// if (edParm.getRole()==ElectricalDevice.ROLE_TotalCurrentDensity){
// return "I_"+((VoltageClampElectricalDevice)electricalDevice).getVoltageClampStimulus().getNameScope().getName();
// }
// if (edParm.getRole()==ElectricalDevice.ROLE_TransmembraneCurrentDensity){
// return "F_"+((VoltageClampElectricalDevice)electricalDevice).getVoltageClampStimulus().getNameScope().getName();
// }
}
}
if (ste instanceof LocalParameter && ((LocalParameter) ste).getNameScope() instanceof ElectricalStimulus.ElectricalStimulusNameScope) {
LocalParameter esParm = (LocalParameter) ste;
String nameWithScope = esParm.getNameScope().getName();
if (esParm.getRole() == ElectricalStimulusParameterType.TotalCurrent) {
return "I_" + nameWithScope;
} else if (esParm.getRole() == ElectricalStimulusParameterType.Voltage) {
return "V_" + nameWithScope;
}
}
StructureTopology structTopology = model.getStructureTopology();
if (ste instanceof StructureMapping.StructureMappingParameter) {
StructureMapping.StructureMappingParameter smParm = (StructureMapping.StructureMappingParameter) ste;
Structure structure = ((StructureMapping) (smParm.getNameScope().getScopedSymbolTable())).getStructure();
int role = smParm.getRole();
if (role == StructureMapping.ROLE_VolumeFraction) {
return "VolFract_" + (structTopology.getInsideFeature((Membrane) structure)).getNameScope().getName();
} else {
String nameWithScope = structure.getNameScope().getName();
if (role == StructureMapping.ROLE_SurfaceToVolumeRatio) {
return "SurfToVol_" + nameWithScope;
} else if (role == StructureMapping.ROLE_InitialVoltage) {
return smParm.getName();
} else if (role == StructureMapping.ROLE_SpecificCapacitance) {
return "C_" + nameWithScope;
} else if (role == StructureMapping.ROLE_AreaPerUnitArea) {
return "AreaPerUnitArea_" + nameWithScope;
} else if (role == StructureMapping.ROLE_AreaPerUnitVolume) {
return "AreaPerUnitVolume_" + nameWithScope;
} else if (role == StructureMapping.ROLE_VolumePerUnitArea) {
return "VolumePerUnitArea_" + nameWithScope;
} else if (role == StructureMapping.ROLE_VolumePerUnitVolume) {
return "VolumePerUnitVolume_" + nameWithScope;
} else if (role == StructureMapping.ROLE_Size) {
if (simContext.getGeometry().getDimension() == 0) {
// if geometry is compartmental, make sure compartment sizes are set if referenced in model.
if (smParm.getExpression() == null || smParm.getExpression().isZero()) {
throw new MappingException("\nIn non-spatial application '" + getSimulationContext().getName() + "', " + "size of structure '" + structure.getName() + "' must be assigned a " + "positive value if referenced in the model.\n\nPlease go to 'Structure Mapping' tab to check the size.");
}
}
return "Size_" + nameWithScope;
}
}
}
//
if (ste instanceof SpeciesContext) {
SpeciesContext sc = (SpeciesContext) ste;
SpeciesContextMapping scm = getSpeciesContextMapping(sc);
//
if (structureMapping instanceof FeatureMapping) {
//
if (scm.getVariable() != null && !scm.getVariable().getName().equals(steName)) {
return scm.getVariable().getName();
}
//
// for reactions within a spatially resolved membrane, may need "_INSIDE" or "_OUTSIDE" for jump condition
//
// if the membrane is distributed, then always use the plain variable.
//
} else if (structureMapping instanceof MembraneMapping) {
Membrane membrane = ((MembraneMapping) structureMapping).getMembrane();
//
if (sc.getStructure() instanceof Membrane || getResolved(structureMapping) == false) {
if (scm.getVariable() != null && !(scm.getVariable().getName().equals(steName))) {
return scm.getVariable().getName();
}
//
// if the speciesContext is outside the membrane
//
} else {
SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
if (sc.getStructure() == structTopology.getInsideFeature(membrane) || sc.getStructure() == structTopology.getOutsideFeature(membrane)) {
if (getResolved(structureMapping) && !scs.isConstant()) {
if (!scs.isDiffusing()) {
throw new MappingException("Enable diffusion in Application '" + simContext.getName() + "'. This must be done for any species (e.g '" + sc.getName() + "') in flux reactions.\n\n" + "To save or run simulations, set the diffusion rate to a non-zero " + "value in Initial Conditions or disable those reactions in Specifications->Reactions.");
}
return scm.getVariable().getName() + (sc.getStructure() == structTopology.getInsideFeature(membrane) ? "_INSIDE" : "_OUTSIDE");
} else {
return scm.getSpeciesContext().getName();
}
} else {
throw new MappingException(sc.getName() + " shouldn't be involved with structure " + structureMapping.getStructure().getName());
}
}
}
}
return getNameScope().getSymbolName(ste);
}
Aggregations