use of cbit.vcell.model.Kinetics.KineticsParameter 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);
}
use of cbit.vcell.model.Kinetics.KineticsParameter in project vcell by virtualcell.
the class ParameterTableModel method isCellEditable.
/**
* Insert the method's description here.
* Creation date: (2/24/01 12:27:46 AM)
* @return boolean
* @param rowIndex int
* @param columnIndex int
*/
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (!bEditable) {
return false;
}
Parameter parameter = getValueAt(rowIndex);
if (reactionStep != null && parameter instanceof KineticsParameter) {
KineticsParameter kp = (KineticsParameter) parameter;
if (kp.getRole() == Kinetics.ROLE_KReverse) {
if (!reactionStep.isReversible()) {
// disable Kr if rule is not reversible
return false;
}
}
}
switch(columnIndex) {
case COLUMN_NAME:
return parameter.isNameEditable();
case COLUMN_DESCRIPTION:
return false;
case COLUMN_IS_GLOBAL:
// if the parameter is reaction rate param or a ReservedSymbol in the model, it should not be editable
if ((parameter instanceof KineticsParameter) && (((KineticsParameter) parameter).getRole() != Kinetics.ROLE_UserDefined)) {
return false;
}
if (parameter instanceof UnresolvedParameter) {
return false;
}
if (parameter instanceof KineticsProxyParameter) {
KineticsProxyParameter kpp = (KineticsProxyParameter) parameter;
SymbolTableEntry ste = kpp.getTarget();
if ((ste instanceof Model.ReservedSymbol) || (ste instanceof SpeciesContext) || (ste instanceof ModelQuantity)) {
return false;
}
}
return true;
case COLUMN_VALUE:
return parameter.isExpressionEditable();
case COLUMN_UNITS:
return parameter.isUnitEditable();
}
return false;
}
use of cbit.vcell.model.Kinetics.KineticsParameter in project vcell by virtualcell.
the class TransformMassActionTableModel method saveTransformedReactions.
public void saveTransformedReactions() throws Exception {
// isTransformable and TransformedREactions are stored according to the indexes in model reaction steps.
boolean[] isTransformable = getTransformMassActions().getIsTransformable();
TransformMassActions.TransformedReaction[] trs = getTransformMassActions().getTransformedReactionSteps();
ReactionStep[] origReactions = getModel().getReactionSteps();
// names of those who can be transformed and will be transformed
String okTransReacNames = "";
// names of those who can be transformed and will not be transformed
String noTransReacNames = "";
// names of those who can not be transformed
String errReacNames = "";
for (int i = 0; i < isTransformable.length; i++) {
if (trs[i].getTransformType() == TransformMassActions.TransformedReaction.TRANSFORMABLE && getIsSelected(i)) {
okTransReacNames = okTransReacNames + origReactions[i].getName() + ",";
} else if (trs[i].getTransformType() == TransformMassActions.TransformedReaction.TRANSFORMABLE && !getIsSelected(i)) {
noTransReacNames = noTransReacNames + origReactions[i].getName() + ",";
} else if (!isTransformable[i]) {
errReacNames = errReacNames + origReactions[i].getName() + ",";
}
}
// set transformed Mass Action kinetics to model reactions
for (int i = 0; i < origReactions.length; i++) {
if (getIsSelected(i)) {
// for simple reaction, we replace the original kinetics with MassActionKinetics if it wasn't MassActionKinetics
if (origReactions[i] instanceof SimpleReaction) {
if (!(origReactions[i].getKinetics() instanceof MassActionKinetics)) {
// ***Below we will physically change the simple reaction***
// put all kinetic parameters together into array newKps
Vector<Kinetics.KineticsParameter> newKps = new Vector<Kinetics.KineticsParameter>();
// get original kinetic parameters which are not current density and reaction rate.
// those parameters are basically the symbols in rate expression.
Vector<Kinetics.KineticsParameter> origKps = new Vector<Kinetics.KineticsParameter>();
Kinetics.KineticsParameter[] Kps = origReactions[i].getKinetics().getKineticsParameters();
for (int j = 0; j < Kps.length; j++) {
if (!(Kps[j].getRole() == Kinetics.ROLE_CurrentDensity || Kps[j].getRole() == Kinetics.ROLE_ReactionRate)) {
origKps.add(Kps[j]);
}
}
// create mass action kinetics for the original reaction step
MassActionKinetics maKinetics = new MassActionKinetics(origReactions[i]);
maKinetics.getKineticsParameterFromRole(Kinetics.ROLE_KForward).setExpression(trs[i].getMassActionFunction().getForwardRate());
maKinetics.getKineticsParameterFromRole(Kinetics.ROLE_KReverse).setExpression(trs[i].getMassActionFunction().getReverseRate());
// Kinetics)
for (int j = 0; j < maKinetics.getKineticsParameters().length; j++) {
newKps.add(maKinetics.getKineticsParameters(j));
}
// copy other kinetic parameters from original kinetics
for (int j = 0; j < origKps.size(); j++) {
newKps.add(origKps.elementAt(j));
}
// add parameters to mass action kinetics
KineticsParameter[] newParameters = new KineticsParameter[newKps.size()];
newParameters = (KineticsParameter[]) newKps.toArray(newParameters);
maKinetics.addKineticsParameters(newParameters);
// after adding all the parameters, we bind the forward/reverse rate expression with symbol table (the reaction step itself)
origReactions[i].getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_KForward).getExpression().bindExpression(origReactions[i]);
origReactions[i].getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_KReverse).getExpression().bindExpression(origReactions[i]);
}
}
// for flux, we set the flux reaction back, coz we will parse it to mass action form in stochastic math mapping.
// However, we don't physically change it.
}
}
String msg = "";
if (!okTransReacNames.equals("")) {
msg = msg + okTransReacNames + " have been transformed.\n";
}
// message to be displayed in popupdialog of DocumentWindow
if (!msg.equals("")) {
throw new Exception(msg);
}
}
use of cbit.vcell.model.Kinetics.KineticsParameter in project vcell by virtualcell.
the class ParameterEstimationPanel method initialize.
@Override
protected void initialize() {
super.initialize();
setName("Parameter Estimation");
setLayout(new java.awt.BorderLayout());
referenceDataPanel = new ReferenceDataPanel();
runTaskPanel = new ParameterEstimationRunTaskPanel();
getparameterMappingPanel().setBorder(GuiConstants.TAB_PANEL_BORDER);
referenceDataPanel.setBorder(GuiConstants.TAB_PANEL_BORDER);
getDataMappingPanel().setBorder(GuiConstants.TAB_PANEL_BORDER);
runTaskPanel.setBorder(GuiConstants.TAB_PANEL_BORDER);
tabbedPane.addTab(ParameterEstimationPanelTabID.parameters.title, getparameterMappingPanel());
tabbedPane.addTab(ParameterEstimationPanelTabID.experimental_data_import.title, referenceDataPanel);
tabbedPane.addTab(ParameterEstimationPanelTabID.experimental_data_mapping.title, getDataMappingPanel());
tabbedPane.addTab(ParameterEstimationPanelTabID.run_task.title, runTaskPanel);
add(tabbedPane, BorderLayout.CENTER);
add(getButtonPanel(), BorderLayout.NORTH);
getNewAnalysisTaskButton().addActionListener(eventHandler);
getDeleteAnalysisTaskButton().addActionListener(eventHandler);
getCopyButton().addActionListener(eventHandler);
getAnalysisTaskComboBox().addActionListener(eventHandler);
getMapButton().addActionListener(eventHandler);
getEvaluateConfidenceIntervalButton().addActionListener(eventHandler);
getDataModelMappingTable().getSelectionModel().addListSelectionListener(eventHandler);
dataModelMappingTable.addMouseListener(eventHandler);
getDataModelMappingTable().setDefaultRenderer(SymbolTableEntry.class, new DefaultScrollTableCellRenderer() {
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (value == null) {
setText("unmapped");
return this;
}
SymbolTableEntry ste = (SymbolTableEntry) value;
if (ste instanceof Model.ReservedSymbol) {
setText(ste.getName());
} else if (ste instanceof SpeciesContext) {
setText("[" + ste.getName() + "]");
} else if (ste instanceof KineticsParameter) {
setText(ste.getNameScope().getName() + ":" + ste.getName());
} else if (ste instanceof ModelParameter) {
setText(ste.getName());
} else if (ste instanceof ReservedVariable) {
setText(ste.getName());
} else {
setText(ste.getNameScope().getAbsoluteScopePrefix() + ste.getName());
}
return this;
}
});
getDataModelMappingTable().setModel(getreferenceDataMappingSpecTableModel());
getDataModelMappingTable().createDefaultColumnsFromModel();
}
use of cbit.vcell.model.Kinetics.KineticsParameter in project vcell by virtualcell.
the class NetworkTransformer method transform.
private void transform(SimulationContext simContext, SimulationContext transformedSimulationContext, ArrayList<ModelEntityMapping> entityMappings, MathMappingCallback mathMappingCallback, NetworkGenerationRequirements networkGenerationRequirements) {
String msg = "Generating network: flattening...";
mathMappingCallback.setMessage(msg);
TaskCallbackMessage tcm = new TaskCallbackMessage(TaskCallbackStatus.Clean, "");
simContext.appendToConsole(tcm);
tcm = new TaskCallbackMessage(TaskCallbackStatus.TaskStart, msg);
simContext.appendToConsole(tcm);
long startTime = System.currentTimeMillis();
System.out.println("Convert to bngl, execute BNG, retrieve the results.");
try {
BNGOutputSpec outputSpec = generateNetwork(simContext, mathMappingCallback, networkGenerationRequirements);
if (mathMappingCallback.isInterrupted()) {
msg = "Canceled by user.";
tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
simContext.appendToConsole(tcm);
throw new UserCancelException(msg);
}
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println(" " + elapsedTime + " milliseconds");
Model model = transformedSimulationContext.getModel();
ReactionContext reactionContext = transformedSimulationContext.getReactionContext();
// ---- Parameters -----------------------------------------------------------------------------------------------
startTime = System.currentTimeMillis();
for (int i = 0; i < outputSpec.getBNGParams().length; i++) {
BNGParameter p = outputSpec.getBNGParams()[i];
// System.out.println(i+1 + ":\t\t"+ p.toString());
if (model.getRbmModelContainer().getParameter(p.getName()) != null) {
// if it's already there we don't try to add it again; this should be true for all of them!
continue;
}
String s = p.getName();
FakeSeedSpeciesInitialConditionsParameter fakeICParam = FakeSeedSpeciesInitialConditionsParameter.fromString(s);
if (speciesEquivalenceMap.containsKey(fakeICParam)) {
// we get rid of the fake parameters we use as keys
continue;
}
FakeReactionRuleRateParameter fakeKineticParam = FakeReactionRuleRateParameter.fromString(s);
if (fakeKineticParam != null) {
System.out.println("found fakeKineticParam " + fakeKineticParam.fakeParameterName);
// we get rid of the fake parameters we use as keys
continue;
}
throw new RuntimeException("unexpected parameter " + p.getName() + " in internal BNG processing");
// Expression exp = new Expression(p.getValue());
// exp.bindExpression(model.getRbmModelContainer().getSymbolTable());
// model.getRbmModelContainer().addParameter(p.getName(), exp, model.getUnitSystem().getInstance_TBD());
}
endTime = System.currentTimeMillis();
elapsedTime = endTime - startTime;
msg = "Adding " + outputSpec.getBNGParams().length + " parameters to model, " + elapsedTime + " ms";
System.out.println(msg);
// ---- Species ------------------------------------------------------------------------------------------------------------
mathMappingCallback.setMessage("generating network: adding species...");
mathMappingCallback.setProgressFraction(progressFractionQuota / 4.0f);
startTime = System.currentTimeMillis();
System.out.println("\nSpecies :");
// the reactions will need this map to recover the names of species knowing only the networkFileIndex
HashMap<Integer, String> speciesMap = new HashMap<Integer, String>();
LinkedHashMap<String, Species> sMap = new LinkedHashMap<String, Species>();
LinkedHashMap<String, SpeciesContext> scMap = new LinkedHashMap<String, SpeciesContext>();
LinkedHashMap<String, BNGSpecies> crossMap = new LinkedHashMap<String, BNGSpecies>();
List<SpeciesContext> noMapForThese = new ArrayList<SpeciesContext>();
// final int decimalTickCount = Math.max(outputSpec.getBNGSpecies().length/10, 1);
for (int i = 0; i < outputSpec.getBNGSpecies().length; i++) {
BNGSpecies s = outputSpec.getBNGSpecies()[i];
// System.out.println(i+1 + ":\t\t"+ s.toString());
String key = s.getConcentration().infix();
FakeSeedSpeciesInitialConditionsParameter fakeParam = FakeSeedSpeciesInitialConditionsParameter.fromString(key);
if (fakeParam != null) {
Pair<SpeciesContext, Expression> value = speciesEquivalenceMap.get(fakeParam);
// the species context of the original model
SpeciesContext originalsc = value.one;
Expression initial = value.two;
// replace the fake initial condition with the real one
s.setConcentration(initial);
// we'll have to find the species context from the cloned model which correspond to the original species
SpeciesContext sc = model.getSpeciesContext(originalsc.getName());
// System.out.println(sc.getName() + ", " + sc.getSpecies().getCommonName() + " ...is one of the original seed species.");
// existing name
speciesMap.put(s.getNetworkFileIndex(), sc.getName());
sMap.put(sc.getName(), sc.getSpecies());
scMap.put(sc.getName(), sc);
crossMap.put(sc.getName(), s);
noMapForThese.add(sc);
continue;
}
// all these species are new!
// generate unique name for the species
int count = 0;
String speciesName = null;
String nameRoot = "s";
String speciesPatternNameString = s.extractName();
while (true) {
speciesName = nameRoot + count;
if (Model.isNameUnused(speciesName, model) && !sMap.containsKey(speciesName) && !scMap.containsKey(speciesName)) {
break;
}
count++;
}
// newly created name
speciesMap.put(s.getNetworkFileIndex(), speciesName);
SpeciesContext speciesContext;
if (s.hasCompartment()) {
String speciesPatternCompartmentString = s.extractCompartment();
speciesContext = new SpeciesContext(new Species(speciesName, s.getName()), model.getStructure(speciesPatternCompartmentString), null);
} else {
speciesContext = new SpeciesContext(new Species(speciesName, s.getName()), model.getStructure(0), null);
}
speciesContext.setName(speciesName);
try {
if (speciesPatternNameString != null) {
SpeciesPattern sp = RbmUtils.parseSpeciesPattern(speciesPatternNameString, model);
speciesContext.setSpeciesPattern(sp);
}
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException("Bad format for species pattern string: " + e.getMessage());
}
// speciesContext.setSpeciesPatternString(speciesPatternString);
// model.addSpecies(speciesContext.getSpecies());
// model.addSpeciesContext(speciesContext);
sMap.put(speciesName, speciesContext.getSpecies());
scMap.put(speciesName, speciesContext);
crossMap.put(speciesName, s);
// }
if (mathMappingCallback.isInterrupted()) {
msg = "Canceled by user.";
tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
simContext.appendToConsole(tcm);
throw new UserCancelException(msg);
}
// if(i%50 == 0) {
// System.out.println(i+"");
// }
// if(i%decimalTickCount == 0) {
// int multiplier = i/decimalTickCount;
// float progress = progressFractionQuota/4.0f + progressFractionQuotaSpecies*multiplier;
// mathMappingCallback.setProgressFraction(progress);
// }
}
for (SpeciesContext sc1 : model.getSpeciesContexts()) {
boolean found = false;
for (Map.Entry<String, SpeciesContext> entry : scMap.entrySet()) {
SpeciesContext sc2 = entry.getValue();
if (sc1.getName().equals(sc2.getName())) {
found = true;
// System.out.println("found species context " + sc1.getName() + " of species " + sc1.getSpecies().getCommonName() + " // " + sc2.getSpecies().getCommonName());
break;
}
}
if (found == false) {
// we add to the map the species context and the species which exist in the model but which are not in the map yet
// the only ones in this situation should be plain species which were not given to bngl for flattening (they are flat already)
// System.out.println("species context " + sc1.getName() + " not found in the map. Adding it.");
scMap.put(sc1.getName(), sc1);
sMap.put(sc1.getName(), sc1.getSpecies());
noMapForThese.add(sc1);
}
}
for (Species s1 : model.getSpecies()) {
boolean found = false;
for (Map.Entry<String, Species> entry : sMap.entrySet()) {
Species s2 = entry.getValue();
if (s1.getCommonName().equals(s2.getCommonName())) {
found = true;
// System.out.println("found species " + s1.getCommonName());
break;
}
}
if (found == false) {
System.err.println("species " + s1.getCommonName() + " not found in the map!");
}
}
SpeciesContext[] sca = new SpeciesContext[scMap.size()];
scMap.values().toArray(sca);
Species[] sa = new HashSet<Species>(sMap.values()).toArray(new Species[0]);
model.setSpecies(sa);
model.setSpeciesContexts(sca);
boolean isSpatial = transformedSimulationContext.getGeometry().getDimension() > 0;
for (SpeciesContext sc : sca) {
if (noMapForThese.contains(sc)) {
continue;
}
SpeciesContextSpec scs = reactionContext.getSpeciesContextSpec(sc);
Parameter param = scs.getParameter(SpeciesContextSpec.ROLE_InitialConcentration);
BNGSpecies s = crossMap.get(sc.getName());
param.setExpression(s.getConcentration());
SpeciesContext origSpeciesContext = simContext.getModel().getSpeciesContext(s.getName());
if (origSpeciesContext != null) {
ModelEntityMapping em = new ModelEntityMapping(origSpeciesContext, sc);
entityMappings.add(em);
} else {
ModelEntityMapping em = new ModelEntityMapping(new GeneratedSpeciesSymbolTableEntry(sc), sc);
if (isSpatial) {
scs.initializeForSpatial();
}
entityMappings.add(em);
}
}
// for(SpeciesContext sc : sca) { // clean all the species patterns from the flattened species, we have no sp now
// sc.setSpeciesPattern(null);
// }
endTime = System.currentTimeMillis();
elapsedTime = endTime - startTime;
msg = "Adding " + outputSpec.getBNGSpecies().length + " species to model, " + elapsedTime + " ms";
System.out.println(msg);
// ---- Reactions -----------------------------------------------------------------------------------------------------
mathMappingCallback.setMessage("generating network: adding reactions...");
mathMappingCallback.setProgressFraction(progressFractionQuota / 4.0f * 3.0f);
startTime = System.currentTimeMillis();
System.out.println("\nReactions :");
Map<String, HashSet<String>> ruleKeyMap = new HashMap<String, HashSet<String>>();
Map<String, BNGReaction> directBNGReactionsMap = new HashMap<String, BNGReaction>();
Map<String, BNGReaction> reverseBNGReactionsMap = new HashMap<String, BNGReaction>();
for (int i = 0; i < outputSpec.getBNGReactions().length; i++) {
BNGReaction r = outputSpec.getBNGReactions()[i];
if (!r.isRuleReversed()) {
// direct
directBNGReactionsMap.put(r.getKey(), r);
} else {
reverseBNGReactionsMap.put(r.getKey(), r);
}
//
// for each rule name, store set of keySets (number of unique keysets are number of generated reactions from this ruleName).
//
HashSet<String> keySet = ruleKeyMap.get(r.getRuleName());
if (keySet == null) {
keySet = new HashSet<String>();
ruleKeyMap.put(r.getRuleName(), keySet);
}
keySet.add(r.getKey());
}
Map<String, ReactionStep> reactionStepMap = new HashMap<String, ReactionStep>();
for (int i = 0; i < outputSpec.getBNGReactions().length; i++) {
BNGReaction bngReaction = outputSpec.getBNGReactions()[i];
// System.out.println(i+1 + ":\t\t"+ r.writeReaction());
String baseName = bngReaction.getRuleName();
String reactionName = null;
HashSet<String> keySetsForThisRule = ruleKeyMap.get(bngReaction.getRuleName());
if (keySetsForThisRule.size() == 1 && model.getReactionStep(bngReaction.getRuleName()) == null && !reactionStepMap.containsKey(bngReaction.getRuleName())) {
// we can reuse the reaction rule labels
reactionName = bngReaction.getRuleName();
} else {
reactionName = bngReaction.getRuleName() + "_0";
while (true) {
if (model.getReactionStep(reactionName) == null && !reactionStepMap.containsKey(reactionName)) {
// we can reuse the reaction rule labels
break;
}
reactionName = TokenMangler.getNextEnumeratedToken(reactionName);
}
}
//
if (directBNGReactionsMap.containsValue(bngReaction)) {
BNGReaction forwardBNGReaction = bngReaction;
BNGReaction reverseBNGReaction = reverseBNGReactionsMap.get(bngReaction.getKey());
String name = forwardBNGReaction.getRuleName();
if (name.endsWith(ReactionRule.DirectHalf)) {
name = name.substring(0, name.indexOf(ReactionRule.DirectHalf));
}
if (name.endsWith(ReactionRule.InverseHalf)) {
name = name.substring(0, name.indexOf(ReactionRule.InverseHalf));
}
ReactionRule rr = model.getRbmModelContainer().getReactionRule(name);
Structure structure = rr.getStructure();
boolean bReversible = reverseBNGReaction != null;
SimpleReaction sr = new SimpleReaction(model, structure, reactionName, bReversible);
for (int j = 0; j < forwardBNGReaction.getReactants().length; j++) {
BNGSpecies s = forwardBNGReaction.getReactants()[j];
String scName = speciesMap.get(s.getNetworkFileIndex());
SpeciesContext sc = model.getSpeciesContext(scName);
Reactant reactant = sr.getReactant(scName);
if (reactant == null) {
int stoichiometry = 1;
sr.addReactant(sc, stoichiometry);
} else {
int stoichiometry = reactant.getStoichiometry();
stoichiometry += 1;
reactant.setStoichiometry(stoichiometry);
}
}
for (int j = 0; j < forwardBNGReaction.getProducts().length; j++) {
BNGSpecies s = forwardBNGReaction.getProducts()[j];
String scName = speciesMap.get(s.getNetworkFileIndex());
SpeciesContext sc = model.getSpeciesContext(scName);
Product product = sr.getProduct(scName);
if (product == null) {
int stoichiometry = 1;
sr.addProduct(sc, stoichiometry);
} else {
int stoichiometry = product.getStoichiometry();
stoichiometry += 1;
product.setStoichiometry(stoichiometry);
}
}
MassActionKinetics targetKinetics = new MassActionKinetics(sr);
sr.setKinetics(targetKinetics);
KineticsParameter kforward = targetKinetics.getForwardRateParameter();
KineticsParameter kreverse = targetKinetics.getReverseRateParameter();
String kforwardNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate).getName();
if (!kforward.getName().equals(kforwardNewName)) {
targetKinetics.renameParameter(kforward.getName(), kforwardNewName);
kforward = targetKinetics.getForwardRateParameter();
}
final String kreverseNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate).getName();
if (!kreverse.getName().equals(kreverseNewName)) {
targetKinetics.renameParameter(kreverse.getName(), kreverseNewName);
kreverse = targetKinetics.getReverseRateParameter();
}
applyKineticsExpressions(forwardBNGReaction, kforward, targetKinetics);
if (reverseBNGReaction != null) {
applyKineticsExpressions(reverseBNGReaction, kreverse, targetKinetics);
}
// String fieldParameterName = kforward.getName();
// fieldParameterName += "_" + r.getRuleName();
// kforward.setName(fieldParameterName);
reactionStepMap.put(reactionName, sr);
} else if (reverseBNGReactionsMap.containsValue(bngReaction) && !directBNGReactionsMap.containsKey(bngReaction.getKey())) {
// reverse only (must be irreversible)
BNGReaction reverseBNGReaction = reverseBNGReactionsMap.get(bngReaction.getKey());
ReactionRule rr = model.getRbmModelContainer().getReactionRule(reverseBNGReaction.extractRuleName());
Structure structure = rr.getStructure();
boolean bReversible = false;
SimpleReaction sr = new SimpleReaction(model, structure, reactionName, bReversible);
for (int j = 0; j < reverseBNGReaction.getReactants().length; j++) {
BNGSpecies s = reverseBNGReaction.getReactants()[j];
String scName = speciesMap.get(s.getNetworkFileIndex());
SpeciesContext sc = model.getSpeciesContext(scName);
Reactant reactant = sr.getReactant(scName);
if (reactant == null) {
int stoichiometry = 1;
sr.addReactant(sc, stoichiometry);
} else {
int stoichiometry = reactant.getStoichiometry();
stoichiometry += 1;
reactant.setStoichiometry(stoichiometry);
}
}
for (int j = 0; j < reverseBNGReaction.getProducts().length; j++) {
BNGSpecies s = reverseBNGReaction.getProducts()[j];
String scName = speciesMap.get(s.getNetworkFileIndex());
SpeciesContext sc = model.getSpeciesContext(scName);
Product product = sr.getProduct(scName);
if (product == null) {
int stoichiometry = 1;
sr.addProduct(sc, stoichiometry);
} else {
int stoichiometry = product.getStoichiometry();
stoichiometry += 1;
product.setStoichiometry(stoichiometry);
}
}
MassActionKinetics k = new MassActionKinetics(sr);
sr.setKinetics(k);
KineticsParameter kforward = k.getForwardRateParameter();
KineticsParameter kreverse = k.getReverseRateParameter();
String kforwardNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate).getName();
if (!kforward.getName().equals(kforwardNewName)) {
k.renameParameter(kforward.getName(), kforwardNewName);
kforward = k.getForwardRateParameter();
}
final String kreverseNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate).getName();
if (!kreverse.getName().equals(kreverseNewName)) {
k.renameParameter(kreverse.getName(), kreverseNewName);
kreverse = k.getReverseRateParameter();
}
applyKineticsExpressions(reverseBNGReaction, kforward, k);
// String fieldParameterName = kforward.getName();
// fieldParameterName += "_" + r.getRuleName();
// kforward.setName(fieldParameterName);
reactionStepMap.put(reactionName, sr);
}
}
for (ReactionStep rs : model.getReactionSteps()) {
reactionStepMap.put(rs.getName(), rs);
}
ReactionStep[] reactionSteps = new ReactionStep[reactionStepMap.size()];
reactionStepMap.values().toArray(reactionSteps);
model.setReactionSteps(reactionSteps);
if (mathMappingCallback.isInterrupted()) {
msg = "Canceled by user.";
tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
simContext.appendToConsole(tcm);
throw new UserCancelException(msg);
}
endTime = System.currentTimeMillis();
elapsedTime = endTime - startTime;
msg = "Adding " + outputSpec.getBNGReactions().length + " reactions to model, " + elapsedTime + " ms";
System.out.println(msg);
// clean all the reaction rules
model.getRbmModelContainer().getReactionRuleList().clear();
// ---- Observables -------------------------------------------------------------------------------------------------
mathMappingCallback.setMessage("generating network: adding observables...");
mathMappingCallback.setProgressFraction(progressFractionQuota / 8.0f * 7.0f);
startTime = System.currentTimeMillis();
System.out.println("\nObservables :");
RbmModelContainer rbmmc = model.getRbmModelContainer();
for (int i = 0; i < outputSpec.getObservableGroups().length; i++) {
ObservableGroup o = outputSpec.getObservableGroups()[i];
if (rbmmc.getParameter(o.getObservableGroupName()) != null) {
System.out.println(" ...already exists.");
// if it's already there we don't try to add it again; this should be true for all of them!
continue;
}
ArrayList<Expression> terms = new ArrayList<Expression>();
for (int j = 0; j < o.getListofSpecies().length; j++) {
Expression term = Expression.mult(new Expression(o.getSpeciesMultiplicity()[j]), new Expression(speciesMap.get(o.getListofSpecies()[j].getNetworkFileIndex())));
terms.add(term);
}
Expression exp = Expression.add(terms.toArray(new Expression[terms.size()])).flatten();
exp.bindExpression(rbmmc.getSymbolTable());
RbmObservable originalObservable = rbmmc.getObservable(o.getObservableGroupName());
VCUnitDefinition observableUnitDefinition = originalObservable.getUnitDefinition();
rbmmc.removeObservable(originalObservable);
Parameter newParameter = rbmmc.addParameter(o.getObservableGroupName(), exp, observableUnitDefinition);
RbmObservable origObservable = simContext.getModel().getRbmModelContainer().getObservable(o.getObservableGroupName());
ModelEntityMapping em = new ModelEntityMapping(origObservable, newParameter);
entityMappings.add(em);
}
if (mathMappingCallback.isInterrupted()) {
msg = "Canceled by user.";
tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
simContext.appendToConsole(tcm);
throw new UserCancelException(msg);
}
endTime = System.currentTimeMillis();
elapsedTime = endTime - startTime;
msg = "Adding " + outputSpec.getObservableGroups().length + " observables to model, " + elapsedTime + " ms";
System.out.println(msg);
} catch (PropertyVetoException ex) {
ex.printStackTrace(System.out);
throw new RuntimeException(ex.getMessage());
} catch (ExpressionBindingException ex) {
ex.printStackTrace(System.out);
throw new RuntimeException(ex.getMessage());
} catch (ModelException ex) {
ex.printStackTrace(System.out);
throw new RuntimeException(ex.getMessage());
} catch (ExpressionException ex) {
ex.printStackTrace(System.out);
throw new RuntimeException(ex.getMessage());
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex.getMessage());
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage());
}
System.out.println("Done transforming");
msg = "Generating math...";
System.out.println(msg);
mathMappingCallback.setMessage(msg);
mathMappingCallback.setProgressFraction(progressFractionQuota);
}
Aggregations