use of cbit.vcell.model.Structure in project vcell by virtualcell.
the class RulebasedMathMapping method addSpeciesPatterns.
private HashMap<SpeciesPattern, VolumeParticleSpeciesPattern> addSpeciesPatterns(Domain domain, List<ReactionRule> rrList) throws MathException {
// Particle Molecular Types
//
Model model = getSimulationContext().getModel();
List<RbmObservable> observableList = model.getRbmModelContainer().getObservableList();
List<MolecularType> molecularTypeList = model.getRbmModelContainer().getMolecularTypeList();
for (MolecularType molecularType : molecularTypeList) {
ParticleMolecularType particleMolecularType = new ParticleMolecularType(molecularType.getName());
for (MolecularComponent molecularComponent : molecularType.getComponentList()) {
String pmcName = molecularComponent.getName();
String pmcId = particleMolecularType.getName() + "_" + molecularComponent.getName();
ParticleMolecularComponent particleMolecularComponent = new ParticleMolecularComponent(pmcId, pmcName);
for (ComponentStateDefinition componentState : molecularComponent.getComponentStateDefinitions()) {
ParticleComponentStateDefinition pcsd = particleMolecularComponent.getComponentStateDefinition(componentState.getName());
if (pcsd == null) {
particleMolecularComponent.addComponentStateDefinition(new ParticleComponentStateDefinition(componentState.getName()));
}
}
particleMolecularType.addMolecularComponent(particleMolecularComponent);
}
if (!molecularType.isAnchorAll()) {
List<String> anchorList = new ArrayList<>();
for (Structure struct : molecularType.getAnchors()) {
anchorList.add(struct.getName());
}
particleMolecularType.setAnchorList(anchorList);
}
mathDesc.addParticleMolecularType(particleMolecularType);
}
//
// Assemble list of all Species Patterns (from observables, reaction rules, and seed species).
//
// linked hash set maintains insertion order
LinkedHashMap<SpeciesPattern, Structure> speciesPatternStructureMap = new LinkedHashMap<SpeciesPattern, Structure>();
for (RbmObservable observable : observableList) {
for (SpeciesPattern speciesPattern : observable.getSpeciesPatternList()) {
speciesPatternStructureMap.put(speciesPattern, observable.getStructure());
}
}
for (ReactionRule reactionRule : rrList) {
for (ReactantPattern rp : reactionRule.getReactantPatterns()) {
speciesPatternStructureMap.put(rp.getSpeciesPattern(), rp.getStructure());
}
for (ProductPattern pp : reactionRule.getProductPatterns()) {
speciesPatternStructureMap.put(pp.getSpeciesPattern(), pp.getStructure());
}
}
for (SpeciesContext sc : model.getSpeciesContexts()) {
if (!sc.hasSpeciesPattern()) {
continue;
}
speciesPatternStructureMap.put(sc.getSpeciesPattern(), sc.getStructure());
}
//
// add list of unique speciesPatterns
//
HashMap<String, VolumeParticleSpeciesPattern> speciesPatternVCMLMap = new HashMap<String, VolumeParticleSpeciesPattern>();
HashMap<SpeciesPattern, VolumeParticleSpeciesPattern> speciesPatternMap = new HashMap<SpeciesPattern, VolumeParticleSpeciesPattern>();
String speciesPatternName = "speciesPattern0";
for (SpeciesPattern speciesPattern : speciesPatternStructureMap.keySet()) {
VolumeParticleSpeciesPattern volumeParticleSpeciesPattern = new VolumeParticleSpeciesPattern(speciesPatternName, domain, speciesPatternStructureMap.get(speciesPattern).getName());
for (MolecularTypePattern molecularTypePattern : speciesPattern.getMolecularTypePatterns()) {
ParticleMolecularType particleMolecularType = mathDesc.getParticleMolecularType(molecularTypePattern.getMolecularType().getName());
ParticleMolecularTypePattern particleMolecularTypePattern = new ParticleMolecularTypePattern(particleMolecularType);
String participantMatchLabel = molecularTypePattern.getParticipantMatchLabel();
if (molecularTypePattern.getParticipantMatchLabel() != null) {
particleMolecularTypePattern.setMatchLabel(participantMatchLabel);
}
for (MolecularComponentPattern molecularComponentPattern : molecularTypePattern.getComponentPatternList()) {
MolecularComponent molecularComponent = molecularComponentPattern.getMolecularComponent();
ParticleMolecularComponent particleMolecularComponent = particleMolecularType.getMolecularComponent(molecularComponent.getName());
ParticleMolecularComponentPattern particleMolecularComponentPattern = new ParticleMolecularComponentPattern(particleMolecularComponent);
ComponentStatePattern componentState = molecularComponentPattern.getComponentStatePattern();
if (componentState != null) {
if (componentState.isAny()) {
ParticleComponentStatePattern pcsp = new ParticleComponentStatePattern();
particleMolecularComponentPattern.setComponentStatePattern(pcsp);
} else {
String name = componentState.getComponentStateDefinition().getName();
ParticleComponentStateDefinition pcsd = particleMolecularComponent.getComponentStateDefinition(name);
// ParticleComponentStateDefinition pcsd = new ParticleComponentStateDefinition(componentState.getComponentStateDefinition().getName());
// particleMolecularComponent.addComponentStateDefinition(pcsd);
ParticleComponentStatePattern pcsp = new ParticleComponentStatePattern(pcsd);
particleMolecularComponentPattern.setComponentStatePattern(pcsp);
}
} else {
ParticleComponentStatePattern pcsp = new ParticleComponentStatePattern();
particleMolecularComponentPattern.setComponentStatePattern(pcsp);
}
switch(molecularComponentPattern.getBondType()) {
case Specified:
{
particleMolecularComponentPattern.setBondType(ParticleBondType.Specified);
particleMolecularComponentPattern.setBondId(molecularComponentPattern.getBondId());
break;
}
case Exists:
{
particleMolecularComponentPattern.setBondType(ParticleBondType.Exists);
particleMolecularComponentPattern.setBondId(-1);
break;
}
case None:
{
particleMolecularComponentPattern.setBondType(ParticleBondType.None);
particleMolecularComponentPattern.setBondId(-1);
break;
}
case Possible:
{
particleMolecularComponentPattern.setBondType(ParticleBondType.Possible);
particleMolecularComponentPattern.setBondId(-1);
break;
}
}
particleMolecularTypePattern.addMolecularComponentPattern(particleMolecularComponentPattern);
}
volumeParticleSpeciesPattern.addMolecularTypePattern(particleMolecularTypePattern);
}
String speciesPatternVCML = volumeParticleSpeciesPattern.getVCML("tempName");
VolumeParticleSpeciesPattern uniqueVolumeParticleSpeciesPattern = speciesPatternVCMLMap.get(speciesPatternVCML);
if (uniqueVolumeParticleSpeciesPattern == null) {
speciesPatternVCMLMap.put(speciesPatternVCML, volumeParticleSpeciesPattern);
speciesPatternName = TokenMangler.getNextEnumeratedToken(speciesPatternName);
speciesPatternMap.put(speciesPattern, volumeParticleSpeciesPattern);
} else {
speciesPatternMap.put(speciesPattern, uniqueVolumeParticleSpeciesPattern);
}
}
return speciesPatternMap;
}
use of cbit.vcell.model.Structure in project vcell by virtualcell.
the class RulebasedMathMapping method refreshMathDescription.
/**
* This method was created in VisualAge.
*/
@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 transform 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("rule-based particle math mapping not implemented for spatial geometry - dimension >= 1");
}
//
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 reactionRules that are not "excluded"
//
ArrayList<ReactionRule> rrList = new ArrayList<ReactionRule>();
for (ReactionRuleSpec reactionRuleSpec : simContext.getReactionContext().getReactionRuleSpecs()) {
if (!reactionRuleSpec.isExcluded()) {
rrList.add(reactionRuleSpec.getReactionRule());
}
}
//
for (ReactionRule reactionRule : rrList) {
UnresolvedParameter[] unresolvedParameters = reactionRule.getKineticLaw().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() + "', " + reactionRule.getDisplayType() + " '" + reactionRule.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 (ReactionRule reactionRule : rrList) {
// if (reactionRule.getKineticLaw() instanceof LumpedKinetics){
// throw new RuntimeException("Lumped Kinetics not yet supported for RuleBased Modeling");
// }
LocalParameter[] parameters = reactionRule.getKineticLaw().getLocalParameters();
for (LocalParameter parameter : parameters) {
//
if ((parameter.getRole() == RbmKineticLawParameterType.RuleRate)) {
continue;
}
//
if (!reactionRule.isReversible() && parameter.getRole() == RbmKineticLawParameterType.MassActionReverseRate) {
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);
//
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);
//
// define all molecules and unique species patterns (add molecules to mathDesc and speciesPatterns to varHash).
//
HashMap<SpeciesPattern, VolumeParticleSpeciesPattern> speciesPatternMap = addSpeciesPatterns(domain, rrList);
HashSet<VolumeParticleSpeciesPattern> uniqueParticleSpeciesPatterns = new HashSet<>(speciesPatternMap.values());
for (VolumeParticleSpeciesPattern volumeParticleSpeciesPattern : uniqueParticleSpeciesPatterns) {
varHash.addVariable(volumeParticleSpeciesPattern);
}
//
// define observables (those explicitly declared and those corresponding to seed species.
//
List<ParticleObservable> observables = addObservables(geometryClass, domain, speciesPatternMap);
for (ParticleObservable particleObservable : observables) {
varHash.addVariable(particleObservable);
}
try {
addParticleJumpProcesses(varHash, geometryClass, subDomain, speciesPatternMap);
} catch (PropertyVetoException e1) {
e1.printStackTrace();
throw new MappingException(e1.getMessage(), e1);
}
//
for (int i = 0; i < fieldMathMappingParameters.length; i++) {
if (fieldMathMappingParameters[i] instanceof UnitFactorParameter || fieldMathMappingParameters[i] instanceof ObservableConcentrationParameter) {
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());
//
for (SpeciesContext sc : model.getSpeciesContexts()) {
if (!sc.hasSpeciesPattern()) {
throw new MappingException("species " + sc.getName() + " has no molecular pattern");
}
VolumeParticleSpeciesPattern volumeParticleSpeciesPattern = speciesPatternMap.get(sc.getSpeciesPattern());
ArrayList<ParticleInitialCondition> particleInitialConditions = new ArrayList<ParticleProperties.ParticleInitialCondition>();
// initial conditions from scs
SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
Parameter initialCountParameter = scs.getInitialCountParameter();
Expression e = getIdentifierSubstitutions(new Expression(initialCountParameter, getNameScope()), initialCountParameter.getUnitDefinition(), geometryClass);
particleInitialConditions.add(new ParticleInitialConditionCount(e, new Expression(0.0), new Expression(0.0), new Expression(0.0)));
ParticleProperties particleProperies = new ParticleProperties(volumeParticleSpeciesPattern, new Expression(0.0), new Expression(0.0), new Expression(0.0), new Expression(0.0), particleInitialConditions);
subDomain.addParticleProperties(particleProperies);
}
//
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 ObservableConcentrationParameter) {
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.Structure in project vcell by virtualcell.
the class BNGExecutorServiceMultipass method preprocessInput.
// parse the compartmental bngl file and produce the "trick"
// where each molecule has an extra Site with the compartments as possible States
// a reserved name will be used for this Site
//
private String preprocessInput(String cBngInputString) throws ParseException, PropertyVetoException, ExpressionBindingException {
// take the cBNGL file (as string), parse it to recover the rules (we'll need them later)
// and create the bngl string with the extra, fake site for the compartments
BioModel bioModel = new BioModel(null);
bioModel.setName("BngBioModel");
model = new Model("model");
bioModel.setModel(model);
model.createFeature();
simContext = bioModel.addNewSimulationContext("BioNetGen app", SimulationContext.Application.NETWORK_DETERMINISTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(simContext);
// set convention for initial conditions in generated application for seed species (concentration or count)
BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
InputStream is = new ByteArrayInputStream(cBngInputString.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
ASTModel astModel = RbmUtils.importBnglFile(br);
if (astModel.hasCompartments()) {
Structure struct = model.getStructure(0);
if (struct != null) {
try {
model.removeStructure(struct);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
constructionVisitor = new BnglObjectConstructionVisitor(model, appList, bngUnitSystem, true);
astModel.jjtAccept(constructionVisitor, model.getRbmModelContainer());
int numCompartments = model.getStructures().length;
if (numCompartments == 0) {
throw new RuntimeException("No structure present in the bngl file.");
} else if (numCompartments == 1) {
// for single compartment we don't need the 'trick'
compartmentMode = CompartmentMode.hide;
} else {
compartmentMode = CompartmentMode.asSite;
}
// extract all polymer observables for special treatment at the end
for (RbmObservable oo : model.getRbmModelContainer().getObservableList()) {
if (oo.getSequence() == RbmObservable.Sequence.PolymerLengthEqual) {
polymerEqualObservables.add(oo);
} else if (oo.getSequence() == RbmObservable.Sequence.PolymerLengthGreater) {
polymerGreaterObservables.add(oo);
}
}
for (RbmObservable oo : polymerEqualObservables) {
model.getRbmModelContainer().removeObservable(oo);
}
for (RbmObservable oo : polymerGreaterObservables) {
model.getRbmModelContainer().removeObservable(oo);
}
// replace all reversible rules with 2 direct rules
List<ReactionRule> newRRList = new ArrayList<>();
for (ReactionRule rr : model.getRbmModelContainer().getReactionRuleList()) {
if (rr.isReversible()) {
ReactionRule rr1 = ReactionRule.deriveDirectRule(rr);
newRRList.add(rr1);
ReactionRule rr2 = ReactionRule.deriveInverseRule(rr);
newRRList.add(rr2);
} else {
newRRList.add(rr);
}
model.getRbmModelContainer().removeReactionRule(rr);
}
// model.getRbmModelContainer().getReactionRuleList().clear();
model.getRbmModelContainer().setReactionRules(newRRList);
StringWriter bnglStringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(bnglStringWriter);
writer.println(RbmNetworkGenerator.BEGIN_MODEL);
writer.println();
// RbmNetworkGenerator.writeCompartments(writer, model, null);
RbmNetworkGenerator.writeParameters(writer, model.getRbmModelContainer(), false);
RbmNetworkGenerator.writeMolecularTypes(writer, model, compartmentMode);
RbmNetworkGenerator.writeSpeciesSortedAlphabetically(writer, model, simContext, compartmentMode);
RbmNetworkGenerator.writeObservables(writer, model.getRbmModelContainer(), compartmentMode);
// RbmNetworkGenerator.writeFunctions(writer, rbmModelContainer, ignoreFunctions);
RbmNetworkGenerator.writeReactions(writer, model.getRbmModelContainer(), null, false, compartmentMode);
writer.println(RbmNetworkGenerator.END_MODEL);
writer.println();
// we parse the real numbers from the bngl file provided by the caller, the nc in the simContext has the default ones
NetworkConstraints realNC = extractNetworkConstraints(cBngInputString);
simContext.getNetworkConstraints().setMaxMoleculesPerSpecies(realNC.getMaxMoleculesPerSpecies());
simContext.getNetworkConstraints().setMaxIteration(realNC.getMaxIteration());
RbmNetworkGenerator.generateNetworkEx(1, simContext.getNetworkConstraints().getMaxMoleculesPerSpecies(), writer, model.getRbmModelContainer(), simContext, NetworkGenerationRequirements.AllowTruncatedStandardTimeout);
String sInputString = bnglStringWriter.toString();
return sInputString;
}
use of cbit.vcell.model.Structure in project vcell by virtualcell.
the class ModelOptimizationSpec method calculateTimeDependentModelObjects.
/**
* Insert the method's description here.
* Creation date: (11/29/2005 5:10:51 PM)
* @return cbit.vcell.parser.SymbolTableEntry[]
*/
public static SymbolTableEntry[] calculateTimeDependentModelObjects(SimulationContext simulationContext) {
Graph digraph = new Graph();
//
// add time
//
Model model = simulationContext.getModel();
Node timeNode = new Node("t", model.getTIME());
digraph.addNode(timeNode);
//
// add all species concentrations (that are not fixed with a constant initial condition).
//
SpeciesContextSpec[] scs = simulationContext.getReactionContext().getSpeciesContextSpecs();
for (int i = 0; scs != null && i < scs.length; i++) {
SpeciesContextSpecParameter initParam = scs[i].getInitialConditionParameter();
Expression iniExp = initParam == null ? null : initParam.getExpression();
if (!scs[i].isConstant() || (iniExp != null && !iniExp.isNumeric())) {
String speciesContextScopedName = scs[i].getSpeciesContext().getNameScope().getAbsoluteScopePrefix() + scs[i].getSpeciesContext().getName();
Node speciesContextNode = new Node(speciesContextScopedName, scs[i].getSpeciesContext());
digraph.addNode(speciesContextNode);
digraph.addEdge(new Edge(speciesContextNode, timeNode));
}
}
//
// add all model (global) parameters that are not simple constants
//
ModelParameter[] modelParams = model.getModelParameters();
for (int i = 0; modelParams != null && i < modelParams.length; i++) {
Expression exp = modelParams[i].getExpression();
if (exp != null) {
String[] symbols = exp.getSymbols();
if (symbols != null && symbols.length > 0) {
//
// add parameter to graph as a node (if not already there).
//
String parameterScopedName = modelParams[i].getNameScope().getAbsoluteScopePrefix() + modelParams[i].getName();
Node parameterNode = digraph.getNode(parameterScopedName);
if (parameterNode == null) {
parameterNode = new Node(parameterScopedName, modelParams[i]);
digraph.addNode(parameterNode);
}
//
for (int k = 0; symbols != null && k < symbols.length; k++) {
SymbolTableEntry ste = exp.getSymbolBinding(symbols[k]);
if (ste == null) {
throw new RuntimeException("Error, symbol '" + symbols[k] + "' not bound in parameter '" + modelParams[i].getName() + "'");
}
String symbolScopedName = ste.getNameScope().getAbsoluteScopePrefix() + ste.getName();
Node symbolNode = digraph.getNode(symbolScopedName);
if (symbolNode == null) {
symbolNode = new Node(symbolScopedName, ste);
digraph.addNode(symbolNode);
}
digraph.addEdge(new Edge(parameterNode, symbolNode));
}
}
}
}
//
// add all reaction parameters that are not simple constants
//
ReactionStep[] reactionSteps = model.getReactionSteps();
for (int i = 0; reactionSteps != null && i < reactionSteps.length; i++) {
Parameter[] parameters = reactionSteps[i].getKinetics().getKineticsParameters();
for (int j = 0; parameters != null && j < parameters.length; j++) {
Expression exp = parameters[j].getExpression();
if (exp != null) {
String[] symbols = exp.getSymbols();
if (symbols != null && symbols.length > 0) {
//
// add parameter to graph as a node (if not already there).
//
String parameterScopedName = parameters[j].getNameScope().getAbsoluteScopePrefix() + parameters[j].getName();
Node parameterNode = digraph.getNode(parameterScopedName);
if (parameterNode == null) {
parameterNode = new Node(parameterScopedName, parameters[j]);
digraph.addNode(parameterNode);
}
//
for (int k = 0; symbols != null && k < symbols.length; k++) {
SymbolTableEntry ste = exp.getSymbolBinding(symbols[k]);
if (ste == null) {
throw new RuntimeException("Error, symbol '" + symbols[k] + "' not bound in parameter '" + parameters[j].getName() + "'");
}
String symbolScopedName = ste.getNameScope().getAbsoluteScopePrefix() + ste.getName();
Node symbolNode = digraph.getNode(symbolScopedName);
if (symbolNode == null) {
symbolNode = new Node(symbolScopedName, ste);
digraph.addNode(symbolNode);
}
digraph.addEdge(new Edge(parameterNode, symbolNode));
}
}
}
}
}
//
for (Structure structure : model.getStructures()) {
if (structure instanceof Membrane && ((MembraneMapping) simulationContext.getGeometryContext().getStructureMapping(structure)).getCalculateVoltage()) {
MembraneVoltage membraneVoltage = ((Membrane) structure).getMembraneVoltage();
String membraneVoltageScopedName = membraneVoltage.getNameScope().getAbsoluteScopePrefix() + membraneVoltage.getName();
Node membraneVoltageNode = digraph.getNode(membraneVoltageScopedName);
if (membraneVoltageNode == null) {
membraneVoltageNode = new Node(membraneVoltageScopedName, membraneVoltage);
digraph.addNode(membraneVoltageNode);
}
digraph.addEdge(new Edge(membraneVoltageNode, timeNode));
}
}
Node[] timeDependentNodes = digraph.getDigraphAttractorSet(timeNode);
SymbolTableEntry[] steArray = new SymbolTableEntry[timeDependentNodes.length];
for (int i = 0; i < steArray.length; i++) {
steArray[i] = (SymbolTableEntry) timeDependentNodes[i].getData();
}
return steArray;
}
use of cbit.vcell.model.Structure in project vcell by virtualcell.
the class ModelProcessEquation method parseReaction.
public static ReactionParticipant[] parseReaction(ReactionStep reactionStep, Model model, String equationString) throws ExpressionException, PropertyVetoException {
int gotoIndex = equationString.indexOf(REACTION_GOESTO);
if (gotoIndex < 1 && equationString.length() == 0) {
throw new ExpressionException("Syntax error! " + REACTION_GOESTO + " not found. (e.g. a+b->c)");
}
if (reactionStep == null) {
return null;
}
String leftHand = equationString.substring(0, gotoIndex);
String rightHand = equationString.substring(gotoIndex + REACTION_GOESTO.length());
StringTokenizer st = new StringTokenizer(leftHand, "+");
ArrayList<ReactionParticipant> rplist = new ArrayList<ReactionParticipant>();
HashMap<String, SpeciesContext> speciesContextMap = new HashMap<String, SpeciesContext>();
Structure rxnStructure = reactionStep.getStructure();
while (st.hasMoreElements()) {
String nextToken = st.nextToken().trim();
if (nextToken.length() == 0) {
continue;
}
int stoichiIndex = 0;
while (true) {
if (Character.isDigit(nextToken.charAt(stoichiIndex))) {
stoichiIndex++;
} else {
break;
}
}
int stoichi = 1;
String tmp = nextToken.substring(0, stoichiIndex);
if (tmp.length() > 0) {
stoichi = Integer.parseInt(tmp);
}
String var = nextToken.substring(stoichiIndex).trim();
SpeciesContext sc = model.getSpeciesContext(var);
if (sc == null) {
sc = speciesContextMap.get(var);
if (sc == null) {
Species species = model.getSpecies(var);
if (species == null) {
species = new Species(var, null);
}
sc = new SpeciesContext(species, rxnStructure);
sc.setName(var);
speciesContextMap.put(var, sc);
}
}
// if (reactionStep instanceof SimpleReaction) {
rplist.add(new Reactant(null, (SimpleReaction) reactionStep, sc, stoichi));
// } else if (reactionStep instanceof FluxReaction) {
// rplist.add(new Flux(null, (FluxReaction) reactionStep, sc));
// }
}
st = new StringTokenizer(rightHand, "+");
while (st.hasMoreElements()) {
String nextToken = st.nextToken().trim();
if (nextToken.length() == 0) {
continue;
}
int stoichiIndex = 0;
while (true) {
if (Character.isDigit(nextToken.charAt(stoichiIndex))) {
stoichiIndex++;
} else {
break;
}
}
int stoichi = 1;
String tmp = nextToken.substring(0, stoichiIndex);
if (tmp.length() > 0) {
stoichi = Integer.parseInt(tmp);
}
String var = nextToken.substring(stoichiIndex);
SpeciesContext sc = model.getSpeciesContext(var);
if (sc == null) {
sc = speciesContextMap.get(var);
if (sc == null) {
Species species = model.getSpecies(var);
if (species == null) {
species = new Species(var, null);
}
sc = new SpeciesContext(species, rxnStructure);
sc.setName(var);
speciesContextMap.put(var, sc);
}
}
// if (reactionStep instanceof SimpleReaction) {
rplist.add(new Product(null, (SimpleReaction) reactionStep, sc, stoichi));
// } else if (reactionStep instanceof FluxReaction) {
// rplist.add(new Flux(null, (FluxReaction) reactionStep, sc));
// }
}
return rplist.toArray(new ReactionParticipant[0]);
}
Aggregations