use of cbit.vcell.model.Model in project vcell by virtualcell.
the class SBPAXParameterExtractor method extractParameter.
public static Map<SBOTerm, ModelParameter> extractParameter(ReactionStep reaction, SBMeasurable measurable) throws PropertyVetoException {
Map<SBOTerm, ModelParameter> sboToParameters = new HashMap<SBOTerm, ModelParameter>();
Set<SBOTerm> sboTerms = SBPAXSBOExtractor.extractSBOTerms(measurable);
String symbol = null;
VCUnitDefinition targetUnit = null;
Model model = reaction.getModel();
ModelUnitSystem modelUnitSystem = model.getUnitSystem();
Set<SBOTerm> termsWithUnituM = SetUtil.newSet(SBOList.sbo0000027MichaelisConstant, SBOList.sbo0000322MichaelisConstantForSubstrate);
for (SBOTerm sboTerm : sboTerms) {
if (termsWithUnituM.contains(sboTerm)) {
targetUnit = modelUnitSystem.getVolumeConcentrationUnit();
// targetUnit = VCUnitDefinition.UNIT_uM;
}
if (StringUtil.notEmpty(sboTerm.getSymbol())) {
symbol = sboTerm.getSymbol();
}
for (int i = 0; i < symbol.length(); ++i) {
char charAt = symbol.charAt(i);
if (!Character.isJavaIdentifierPart(charAt)) {
symbol = symbol.replace(charAt, '_');
}
}
}
VCUnitDefinition unit = UOMEUnitExtractor.extractVCUnitDefinition(measurable, modelUnitSystem);
double conversionFactor = 1.0;
if (targetUnit != null && unit != null && unit != modelUnitSystem.getInstance_TBD() && !targetUnit.equals(unit)) {
// if(unit.equals(VCUnitDefinition.UNIT_M) && targetUnit.equals(VCUnitDefinition.UNIT_uM)) {
if (unit.isCompatible(targetUnit)) {
conversionFactor = unit.convertTo(conversionFactor, targetUnit);
unit = targetUnit;
}
}
ArrayList<Double> numbers = measurable.getNumber();
if (StringUtil.isEmpty(symbol)) {
symbol = "p" + (++nParameter);
}
for (Double number : numbers) {
String parameterName = symbol + "_" + reaction.getName();
if (model.getModelParameter(parameterName) != null) {
int count = 0;
while (model.getModelParameter(parameterName + "_" + count) != null) {
++count;
}
parameterName = parameterName + "_" + count;
}
ModelParameter parameter = model.new ModelParameter(parameterName, new Expression(conversionFactor * number.doubleValue()), Model.ROLE_UserDefined, unit);
model.addModelParameter(parameter);
for (SBOTerm sboTerm : sboTerms) {
sboToParameters.put(sboTerm, parameter);
}
}
return sboToParameters;
}
use of cbit.vcell.model.Model in project vcell by virtualcell.
the class StochMathMapping method refreshMathDescription.
/**
* set up a math description based on current simulationContext.
*/
@Override
protected void refreshMathDescription() throws MappingException, MatrixException, MathException, ExpressionException, ModelException {
// use local variable instead of using getter all the time.
SimulationContext simContext = getSimulationContext();
GeometryClass geometryClass = simContext.getGeometry().getGeometrySpec().getSubVolumes()[0];
Domain domain = new Domain(geometryClass);
// local structure mapping list
StructureMapping[] structureMappings = simContext.getGeometryContext().getStructureMappings();
// We have to check if all the reactions are able to tranform to stochastic jump processes before generating the math.
String stochChkMsg = simContext.getModel().isValidForStochApp();
if (!(stochChkMsg.equals(""))) {
throw new ModelException("Problem updating math description: " + simContext.getName() + "\n" + stochChkMsg);
}
simContext.checkValidity();
//
if (simContext.getGeometry().getDimension() > 0) {
throw new MappingException("nonspatial stochastic math mapping requires 0-dimensional geometry");
}
//
for (int i = 0; i < structureMappings.length; i++) {
if (structureMappings[i] instanceof MembraneMapping) {
if (((MembraneMapping) structureMappings[i]).getCalculateVoltage()) {
throw new MappingException("electric potential not yet supported for particle models");
}
}
}
//
// fail if any events
//
BioEvent[] bioEvents = simContext.getBioEvents();
if (bioEvents != null && bioEvents.length > 0) {
throw new MappingException("events not yet supported for particle-based models");
}
//
// 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 && ((FeatureMapping) sm).getGeometryClass() == null)) {
throw new MappingException("model structure '" + structures[i].getName() + "' not mapped to a geometry subVolume");
}
if (sm != null && (sm instanceof MembraneMapping) && ((MembraneMapping) sm).getVolumeFractionParameter() != null) {
Expression volFractExp = ((MembraneMapping) sm).getVolumeFractionParameter().getExpression();
try {
if (volFractExp != null) {
double volFract = volFractExp.evaluateConstant();
if (volFract >= 1.0) {
throw new MappingException("model structure '" + (getSimulationContext().getModel().getStructureTopology().getInsideFeature(((MembraneMapping) sm).getMembrane()).getName() + "' has volume fraction >= 1.0"));
}
}
} catch (ExpressionException e) {
e.printStackTrace(System.out);
}
}
}
SubVolume[] subVolumes = simContext.getGeometryContext().getGeometry().getGeometrySpec().getSubVolumes();
for (int i = 0; i < subVolumes.length; i++) {
Structure[] mappedStructures = simContext.getGeometryContext().getStructuresFromGeometryClass(subVolumes[i]);
if (mappedStructures == null || mappedStructures.length == 0) {
throw new MappingException("geometry subVolume '" + subVolumes[i].getName() + "' not mapped from a model structure");
}
}
//
// 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()) {
rsList.add(reactionSpecs[i].getReactionStep());
}
}
//
for (ReactionStep reactionStep : rsList) {
Kinetics.UnresolvedParameter[] unresolvedParameters = reactionStep.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("In Application '" + simContext.getName() + "', " + reactionStep.getDisplayType() + " '" + reactionStep.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");
}
//
// temporarily place all variables in a hashtable (before binding) and discarding duplicates
//
VariableHash varHash = new VariableHash();
//
// conversion factors
//
Model model = simContext.getModel();
varHash.addVariable(new Constant(getMathSymbol(model.getKMOLE(), null), getIdentifierSubstitutions(model.getKMOLE().getExpression(), model.getKMOLE().getUnitDefinition(), null)));
varHash.addVariable(new Constant(getMathSymbol(model.getN_PMOLE(), null), getIdentifierSubstitutions(model.getN_PMOLE().getExpression(), model.getN_PMOLE().getUnitDefinition(), null)));
varHash.addVariable(new Constant(getMathSymbol(model.getPI_CONSTANT(), null), getIdentifierSubstitutions(model.getPI_CONSTANT().getExpression(), model.getPI_CONSTANT().getUnitDefinition(), null)));
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)));
Enumeration<SpeciesContextMapping> enum1 = getSpeciesContextMappings();
while (enum1.hasMoreElements()) {
SpeciesContextMapping scm = enum1.nextElement();
if (scm.getVariable() instanceof StochVolVariable) {
varHash.addVariable(scm.getVariable());
}
}
// deals with model parameters
ModelParameter[] modelParameters = simContext.getModel().getModelParameters();
for (int j = 0; j < modelParameters.length; j++) {
Expression expr = getSubstitutedExpr(modelParameters[j].getExpression(), true, false);
expr = getIdentifierSubstitutions(expr, modelParameters[j].getUnitDefinition(), geometryClass);
varHash.addVariable(newFunctionOrConstant(getMathSymbol(modelParameters[j], geometryClass), expr, geometryClass));
}
// added July 2009, ElectricalStimulusParameter electric mapping tab
ElectricalStimulus[] elecStimulus = simContext.getElectricalStimuli();
if (elecStimulus.length > 0) {
throw new MappingException("Modles with electrophysiology are not supported for stochastic applications.");
}
for (int j = 0; j < structureMappings.length; j++) {
if (structureMappings[j] instanceof MembraneMapping) {
MembraneMapping memMapping = (MembraneMapping) structureMappings[j];
Parameter initialVoltageParm = memMapping.getInitialVoltageParameter();
try {
Expression exp = initialVoltageParm.getExpression();
exp.evaluateConstant();
varHash.addVariable(newFunctionOrConstant(getMathSymbol(memMapping.getMembrane().getMembraneVoltage(), memMapping.getGeometryClass()), getIdentifierSubstitutions(memMapping.getInitialVoltageParameter().getExpression(), memMapping.getInitialVoltageParameter().getUnitDefinition(), memMapping.getGeometryClass()), memMapping.getGeometryClass()));
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new MappingException("Membrane initial voltage: " + initialVoltageParm.getName() + " cannot be evaluated as constant.");
}
}
}
//
for (ReactionStep rs : rsList) {
if (rs.getKinetics() instanceof LumpedKinetics) {
throw new RuntimeException("Lumped Kinetics not yet supported for Stochastic Math Generation");
}
Kinetics.KineticsParameter[] parameters = rs.getKinetics().getKineticsParameters();
for (KineticsParameter parameter : parameters) {
//
if ((parameter.getRole() == Kinetics.ROLE_CurrentDensity) && (parameter.getExpression() == null || parameter.getExpression().isZero())) {
continue;
}
//
// don't add rate, we'll do it later when creating the jump processes
//
// if (parameter.getRole() == Kinetics.ROLE_ReactionRate) {
// continue;
// }
//
// don't add mass action reverse parameter if irreversible
//
// if (!rs.isReversible() && parameters[i].getRole() == Kinetics.ROLE_KReverse){
// continue;
// }
Expression expr = getSubstitutedExpr(parameter.getExpression(), true, false);
varHash.addVariable(newFunctionOrConstant(getMathSymbol(parameter, geometryClass), getIdentifierSubstitutions(expr, parameter.getUnitDefinition(), geometryClass), geometryClass));
}
}
// the parameter "Size" is already put into mathsymbolmapping in refreshSpeciesContextMapping()
for (int i = 0; i < structureMappings.length; i++) {
StructureMapping sm = structureMappings[i];
StructureMapping.StructureMappingParameter parm = sm.getParameterFromRole(StructureMapping.ROLE_Size);
if (parm.getExpression() != null) {
try {
double value = parm.getExpression().evaluateConstant();
varHash.addVariable(new Constant(getMathSymbol(parm, sm.getGeometryClass()), new Expression(value)));
} catch (ExpressionException e) {
// varHash.addVariable(new Function(getMathSymbol0(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.");
}
}
}
SpeciesContextSpec[] speciesContextSpecs = getSimulationContext().getReactionContext().getSpeciesContextSpecs();
addInitialConditions(domain, speciesContextSpecs, varHash);
//
// 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());
}
}
//
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 in Application " + simContext.getName());
}
//
// create subDomains
//
SubVolume subVolume = simContext.getGeometry().getGeometrySpec().getSubVolumes()[0];
SubDomain subDomain = new CompartmentSubDomain(subVolume.getName(), 0);
mathDesc.addSubDomain(subDomain);
//
// functions: species which is not a variable, but has dependency expression
//
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());
Expression exp = scm.getDependencyExpression();
exp.bindExpression(this);
SpeciesCountParameter spCountParam = getSpeciesCountParameter(scm.getSpeciesContext());
varHash.addVariable(new Function(getMathSymbol(spCountParam, sm.getGeometryClass()), getIdentifierSubstitutions(exp, spCountParam.getUnitDefinition(), sm.getGeometryClass()), domain));
}
}
addJumpProcesses(varHash, geometryClass, subDomain);
//
for (int i = 0; i < fieldMathMappingParameters.length; i++) {
if (fieldMathMappingParameters[i] instanceof UnitFactorParameter) {
varHash.addVariable(newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass()));
}
}
//
// set Variables to MathDescription all at once with the order resolved by "VariableHash"
//
mathDesc.setAllVariables(varHash.getAlphabeticallyOrderedVariables());
//
// set up variable initial conditions in subDomain
//
SpeciesContextSpec[] scSpecs = simContext.getReactionContext().getSpeciesContextSpecs();
for (int i = 0; i < speciesContextSpecs.length; i++) {
// get stochastic variable by name
SpeciesCountParameter spCountParam = getSpeciesCountParameter(speciesContextSpecs[i].getSpeciesContext());
StructureMapping sm = simContext.getGeometryContext().getStructureMapping(speciesContextSpecs[i].getSpeciesContext().getStructure());
String varName = getMathSymbol(spCountParam, sm.getGeometryClass());
StochVolVariable var = (StochVolVariable) mathDesc.getVariable(varName);
// stochastic use initial number of particles
SpeciesContextSpec.SpeciesContextSpecParameter initParm = scSpecs[i].getInitialCountParameter();
// stochastic variables initial expression.
if (initParm != null) {
VarIniCondition varIni = null;
if (!scSpecs[i].isConstant() && getSimulationContext().isRandomizeInitCondition()) {
varIni = new VarIniPoissonExpectedCount(var, new Expression(getMathSymbol(initParm, sm.getGeometryClass())));
} else {
varIni = new VarIniCount(var, new Expression(getMathSymbol(initParm, sm.getGeometryClass())));
}
subDomain.addVarIniCondition(varIni);
}
}
//
for (int i = 0; i < fieldMathMappingParameters.length; i++) {
if (fieldMathMappingParameters[i] instanceof UnitFactorParameter) {
Variable variable = newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass());
if (mathDesc.getVariable(variable.getName()) == null) {
mathDesc.addVariable(variable);
}
}
if (fieldMathMappingParameters[i] instanceof ObservableCountParameter) {
Variable variable = newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass());
if (mathDesc.getVariable(variable.getName()) == null) {
mathDesc.addVariable(variable);
}
}
}
if (!mathDesc.isValid()) {
System.out.println(mathDesc.getVCML_database());
throw new MappingException("generated an invalid mathDescription: " + mathDesc.getWarning());
}
}
use of cbit.vcell.model.Model in project vcell by virtualcell.
the class StructureAnalyzer method refreshTotalSpeciesContextMappings.
/**
* This method was created in VisualAge.
*/
private void refreshTotalSpeciesContextMappings() throws java.beans.PropertyVetoException {
if (structures == null) {
return;
}
// System.out.println("StructureAnalyzer.refreshSpeciesContextMappings()");
// GeometryContext geoContext = mathMapping.getSimulationContext().getGeometryContext();
SimulationContext simContext = mathMapping.getSimulationContext();
Model model = simContext.getReactionContext().getModel();
//
// note, the order of species is specified such that the first species have priority
// when the null space is solved for dependent variables. So the order of priority
// for elimination are as follows:
//
// 1) Species involved with fast reactions.
// 2) Species not involved with fast reactions.
//
Vector<SpeciesContextMapping> scmList = new Vector<SpeciesContextMapping>();
//
for (int i = 0; i < structures.length; i++) {
SpeciesContext[] speciesContexts = model.getSpeciesContexts(structures[i]);
for (int j = 0; j < speciesContexts.length; j++) {
SpeciesContext sc = speciesContexts[j];
SpeciesContextMapping scm = mathMapping.getSpeciesContextMapping(sc);
SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
if (scm.isFastParticipant() && !scs.isConstant()) {
scmList.addElement(scm);
}
}
}
//
for (int i = 0; i < structures.length; i++) {
SpeciesContext[] speciesContexts = model.getSpeciesContexts(structures[i]);
for (int j = 0; j < speciesContexts.length; j++) {
SpeciesContext sc = speciesContexts[j];
SpeciesContextMapping scm = mathMapping.getSpeciesContextMapping(sc);
SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
if (!scm.isFastParticipant() && !scs.isConstant()) {
scmList.addElement(scm);
}
}
}
if (scmList.size() > 0) {
speciesContextMappings = new SpeciesContextMapping[scmList.size()];
scmList.copyInto(speciesContextMappings);
for (int i = 0; i < speciesContextMappings.length; i++) {
speciesContextMappings[i].setRate(new Expression(0.0));
// System.out.println("speciesContextMappings["+i+"] = "+speciesContextMappings[i].getSpeciesContext().getName());
}
} else {
speciesContextMappings = null;
}
// System.out.println("StructureAnalyzer.refreshTotalSpeciesContextMapping(), speciesContextMappings.length = "+scmList.size());
//
// get all reactionSteps associated with these structures
//
Vector<ReactionStep> rsList = new Vector<ReactionStep>();
ReactionSpec[] allReactionSpecs = simContext.getReactionContext().getReactionSpecs();
for (int i = 0; i < allReactionSpecs.length; i++) {
if (allReactionSpecs[i].isExcluded()) {
continue;
}
ReactionStep rs = allReactionSpecs[i].getReactionStep();
for (int j = 0; j < structures.length; j++) {
if (rs.getStructure() == structures[j]) {
rsList.addElement(rs);
}
}
}
//
for (int i = 0; i < scmList.size(); i++) {
SpeciesContextMapping scm = (SpeciesContextMapping) scmList.elementAt(i);
if (!simContext.isUsingMassConservationModelReduction()) {
//
// break mass conservation on all species (disables model reduction).
//
rsList.addElement(new DisableModelReductionReactionStep("DisableModelReductionReactionStep" + i, model, scm.getSpeciesContext().getStructure(), scm.getSpeciesContext()));
} else {
//
if (scm.isPDERequired() || simContext.getReactionContext().getSpeciesContextSpec(scm.getSpeciesContext()).isWellMixed()) {
rsList.addElement(new DiffusionDummyReactionStep("DiffusionDummyReactionStep" + i, model, scm.getSpeciesContext().getStructure(), scm.getSpeciesContext()));
}
if (scm.hasEventAssignment()) {
rsList.addElement(new EventDummyReactionStep("EventDummyReactionStep" + i, model, scm.getSpeciesContext().getStructure(), scm.getSpeciesContext()));
}
if (scm.hasHybridReaction()) {
rsList.addElement(new HybridDummyReactionStep("HybridDummyReactionStep" + i, model, scm.getSpeciesContext().getStructure(), scm.getSpeciesContext()));
}
if (simContext.isStoch() && simContext.getGeometry().getDimension() > 0 && !simContext.getReactionContext().getSpeciesContextSpec(scm.getSpeciesContext()).isForceContinuous()) {
rsList.addElement(new ParticleDummyReactionStep("ParticleDummyReactionStep" + i, model, scm.getSpeciesContext().getStructure(), scm.getSpeciesContext()));
}
}
}
if (rsList.size() > 0) {
reactionSteps = new ReactionStep[rsList.size()];
rsList.copyInto(reactionSteps);
} else {
reactionSteps = null;
}
// System.out.println("StructureAnalyzer.refreshTotalSpeciesContextMapping(), reactionSteps.length = "+scmList.size());
}
use of cbit.vcell.model.Model in project vcell by virtualcell.
the class ElectricalCircuitGraph method getCircuitGraph.
/**
* Insert the method's description here.
* Creation date: (2/19/2002 11:24:04 AM)
* @return cbit.vcell.mapping.potential.Graph
* @param simContext cbit.vcell.mapping.SimulationContext
*/
public static Graph getCircuitGraph(SimulationContext simContext, AbstractMathMapping mathMapping) throws ExpressionException {
Graph graph = new Graph();
Model model = simContext.getModel();
//
// add nodes to the graph (one for each Feature)
//
Structure[] structures = model.getStructures();
for (int i = 0; i < structures.length; i++) {
if (structures[i] instanceof Feature) {
graph.addNode(new Node(structures[i].getName(), structures[i]));
}
}
//
// add edges for all current clamp electrodes (always have dependent voltages)
//
ElectricalStimulus[] stimuli = simContext.getElectricalStimuli();
Electrode groundElectrode = simContext.getGroundElectrode();
for (int i = 0; i < stimuli.length; i++) {
ElectricalStimulus stimulus = stimuli[i];
//
// get electrodes
//
Electrode probeElectrode = stimulus.getElectrode();
if (probeElectrode == null) {
throw new RuntimeException("null electrode for electrical stimulus");
}
if (groundElectrode == null) {
throw new RuntimeException("null ground electrode for electrical stimulus");
}
// if (!membraneMapping.getResolved()){
Node groundNode = graph.getNode(groundElectrode.getFeature().getName());
Node probeNode = graph.getNode(probeElectrode.getFeature().getName());
if (stimulus instanceof CurrentDensityClampStimulus) {
CurrentDensityClampStimulus ccStimulus = (CurrentDensityClampStimulus) stimulus;
ElectricalDevice device = new CurrentClampElectricalDevice(ccStimulus, mathMapping);
Edge edge = new Edge(probeNode, groundNode, device);
graph.addEdge(edge);
} else if (stimulus instanceof TotalCurrentClampStimulus) {
TotalCurrentClampStimulus ccStimulus = (TotalCurrentClampStimulus) stimulus;
ElectricalDevice device = new CurrentClampElectricalDevice(ccStimulus, mathMapping);
Edge edge = new Edge(probeNode, groundNode, device);
graph.addEdge(edge);
}
// }
}
//
// add edges for all membranes
//
ElectricalTopology electricalTopology = simContext.getModel().getElectricalTopology();
for (int i = 0; i < structures.length; i++) {
if (structures[i] instanceof Membrane) {
Membrane membrane = (Membrane) structures[i];
MembraneMapping membraneMapping = (MembraneMapping) simContext.getGeometryContext().getStructureMapping(membrane);
Feature positiveFeature = electricalTopology.getPositiveFeature(membrane);
Feature negativeFeature = electricalTopology.getNegativeFeature(membrane);
if (positiveFeature != null && negativeFeature != null) {
Node insideNode = graph.getNode(positiveFeature.getName());
Node outsideNode = graph.getNode(negativeFeature.getName());
//
// getTotalMembraneCurrent() already converts to "outwardCurrent" so that same convention as voltage
//
Expression currentSource = getTotalMembraneCurrent(simContext, membrane, mathMapping);
MembraneElectricalDevice device = new MembraneElectricalDevice(membraneMapping, mathMapping);
device.getParameterFromRole(ElectricalDevice.ROLE_TransmembraneCurrent).setExpression(currentSource);
Edge edge = new Edge(insideNode, outsideNode, device);
graph.addEdge(edge);
}
}
}
//
for (int i = 0; i < stimuli.length; i++) {
ElectricalStimulus stimulus = stimuli[i];
//
// get electrodes
//
Electrode probeElectrode = stimulus.getElectrode();
if (probeElectrode == null) {
throw new RuntimeException("null electrode for electrical stimulus");
}
if (groundElectrode == null) {
throw new RuntimeException("null ground electrode for electrical stimulus");
}
// if (!membraneMapping.getResolved()){
Node groundNode = graph.getNode(groundElectrode.getFeature().getName());
Node probeNode = graph.getNode(probeElectrode.getFeature().getName());
if (stimulus instanceof VoltageClampStimulus) {
VoltageClampStimulus vcStimulus = (VoltageClampStimulus) stimulus;
ElectricalDevice device = new VoltageClampElectricalDevice(vcStimulus, mathMapping);
Edge edge = new Edge(probeNode, groundNode, device);
graph.addEdge(edge);
}
// }
}
// System.out.println(graph);
return graph;
}
use of cbit.vcell.model.Model 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