use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.
the class PlotPane method updateLegend.
/**
* Comment
*/
private void updateLegend() {
Plot2D plot = getPlot2DPanel1().getPlot2D();
SymbolTableEntry[] steList = plot.getSymbolTableEntries();
DataSymbolMetadataResolver metadataResolver = plot.getDataSymbolMetadataResolver();
String[] plotLabels = plot.getVisiblePlotColumnTitles();
int[] plotIndices = plot.getVisiblePlotIndices();
Component[] legends = getJPanelPlotLegends().getComponents();
// add legends if necessarry
if (ml == null) {
ml = new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
String name = ((JLabel) evt.getSource()).getText();
getPlot2DPanel1().setCurrentPlot(name);
}
};
}
for (int i = 0; i < plotIndices.length - legends.length / 2; i++) {
JLabel line = new JLabel();
JLabel text = new JLabel();
line.setBorder(new EmptyBorder(6, 0, 0, 0));
text.setBorder(new EmptyBorder(0, 8, 6, 0));
getJPanelPlotLegends().add(line);
getJPanelPlotLegends().add(text);
text.addMouseListener(ml);
}
legends = getJPanelPlotLegends().getComponents();
// update labels and show them,use reverse loop to generate non-repeatable colors
for (int i = (plotIndices.length - 1); i >= 0; i--) {
LineIcon icon = new LineIcon(getPlot2DPanel1().getVisiblePlotPaint(i));
String plotLabel = null;
if (plot instanceof SingleXPlot2D) {
plotLabel = plotLabels[i + 1];
} else {
plotLabel = plotLabels[2 * i + 1];
}
((JLabel) legends[2 * i]).setIcon(icon);
final int head = 20;
final int tail = 0;
String tooltipString = "";
String unitSymbol = "";
if (metadataResolver != null) {
DataSymbolMetadata metaData = metadataResolver.getDataSymbolMetadata(plotLabel);
if (metaData != null && metaData.unit != null) {
VCUnitDefinition ud = metaData.unit;
if (ud != null) {
unitSymbol += ud.getSymbolUnicode();
}
}
if (metaData != null && metaData.tooltipString != null) {
tooltipString = metaData.tooltipString;
}
}
String shortLabel = plotLabel;
if (shortLabel.length() > head + 3 + tail) {
shortLabel = shortLabel.substring(0, head) + "..." + shortLabel.substring(shortLabel.length() - tail, shortLabel.length());
}
// shortLabel = "<html>" + shortLabel + "<font color=\"red\">" + " [" + unitSymbol + "] " + "</font></html>";
shortLabel = "<html>" + shortLabel + "<font color=\"#8B0000\">" + " [" + unitSymbol + "] " + "</font></html>";
tooltipString = "<html>" + plotLabel + "<font color=\"#0000FF\">" + " " + tooltipString + " " + "</font></html>";
((JLabel) legends[2 * i + 1]).setText(shortLabel);
((JLabel) legends[2 * i + 1]).setToolTipText(tooltipString);
legends[2 * i].setVisible(true);
legends[2 * i + 1].setVisible(true);
}
// if extra ones, hide them
for (int i = 2 * plotIndices.length; i < legends.length; i++) {
legends[i].setVisible(false);
}
}
use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.
the class RbmKineticLaw method refreshUnits.
protected void refreshUnits() {
if (bRefreshingUnits) {
return;
}
try {
bRefreshingUnits = true;
ModelUnitSystem modelUnitSystem = reactionRule.getModel().getUnitSystem();
LocalParameter rateParm = getLocalParameter(RbmKineticLawParameterType.RuleRate);
if (reactionRule.getStructure() instanceof Feature) {
rateParm.setUnitDefinition(modelUnitSystem.getVolumeReactionRateUnit());
} else if (reactionRule.getStructure() instanceof Membrane) {
rateParm.setUnitDefinition(modelUnitSystem.getMembraneReactionRateUnit());
}
switch(this.rateLawType) {
case MassAction:
{
LocalParameter forwardRateParm = getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate);
LocalParameter reverseRateParm = getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate);
// since units for kinetic parameters are set from model's unit system, if model is null (possible when model is not yet set on reactionStep when reading from XML)
// don't worry about setting units on kinetic parameters. Call this method when model is set on reactionStep (rebindToModel()).
Model model = reactionRule.getModel();
if (model != null) {
// if (reactionRule.getStructure() instanceof Membrane){
// rateParm.setUnitDefinition(modelUnitSystem.getMembraneReactionRateUnit());
// if (currentDensityParm!=null){
// currentDensityParm.setUnitDefinition(modelUnitSystem.getCurrentDensityUnit());
// }
// KineticsParameter chargeValenceParm = getChargeValenceParameter();
// if (chargeValenceParm!=null){
// chargeValenceParm.setUnitDefinition(modelUnitSystem.getInstance_DIMENSIONLESS());
// }
// }else if (getReactionStep().getStructure() instanceof Feature){
// rateParm.setUnitDefinition(modelUnitSystem.getVolumeReactionRateUnit());
// }else{
// throw new RuntimeException("unexpected structure type "+getReactionStep().getStructure()+" in MassActionKinetics.refreshUnits()");
// }
cbit.vcell.units.VCUnitDefinition kfUnits = rateParm.getUnitDefinition();
cbit.vcell.units.VCUnitDefinition krUnits = rateParm.getUnitDefinition();
for (ReactantPattern reactantPattern : reactionRule.getReactantPatterns()) {
VCUnitDefinition reactantUnit = modelUnitSystem.getConcentrationUnit(reactantPattern.getStructure());
kfUnits = kfUnits.divideBy(reactantUnit);
}
for (ProductPattern productPattern : reactionRule.getProductPatterns()) {
VCUnitDefinition productUnit = modelUnitSystem.getConcentrationUnit(productPattern.getStructure());
krUnits = krUnits.divideBy(productUnit);
}
if (forwardRateParm != null && !kfUnits.compareEqual(forwardRateParm.getUnitDefinition())) {
forwardRateParm.setUnitDefinition(kfUnits);
}
if (reverseRateParm != null && !krUnits.compareEqual(reverseRateParm.getUnitDefinition())) {
reverseRateParm.setUnitDefinition(krUnits);
}
}
break;
}
}
// end switch (rateLawType)
} finally {
bRefreshingUnits = false;
}
}
use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.
the class DistributedKinetics method getReactionRate.
private Expression getReactionRate() throws ExpressionException, PropertyVetoException {
//
// lumped kinetics always have same units (molecules/s) or (pA) whether used in a FluxReaction or a SimpleReaction
//
// RateMagnitude = inwardCurrent / (valence*F_NMOLE)
//
// for FluxReaction, we are using the flux Carrier
//
Model model = getReactionStep().getModel();
Expression F = getSymbolExpression(model.getFARADAY_CONSTANT());
Expression inwardCurrentDensity = getSymbolExpression(getCurrentDensityParameter());
Expression z = getSymbolExpression(getChargeValenceParameter());
Expression tempRateExpression = Expression.div(inwardCurrentDensity, Expression.mult(z, F));
VCUnitDefinition tempRateUnit = getCurrentDensityParameter().getUnitDefinition().divideBy(model.getFARADAY_CONSTANT().getUnitDefinition());
VCUnitDefinition desiredUnit = getReactionRateParameter().getUnitDefinition();
Expression unitFactorExp = getElectricalUnitFactor(desiredUnit.divideBy(tempRateUnit));
if (unitFactorExp != null) {
tempRateExpression = Expression.mult(tempRateExpression, unitFactorExp);
}
if (hasOutwardFlux()) {
tempRateExpression = Expression.negate(tempRateExpression);
}
return tempRateExpression;
}
use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.
the class DistributedKinetics method toDistributedKinetics.
public static DistributedKinetics toDistributedKinetics(LumpedKinetics origLumpedKinetics) {
KineticsParameter[] origLumpedKineticsParms = origLumpedKinetics.getKineticsParameters();
ReactionStep reactionStep = origLumpedKinetics.getReactionStep();
try {
Vector<KineticsParameter> parmsToAdd = new Vector<KineticsParameter>();
DistributedKinetics distributedKinetics = null;
StructureSize structureSize = origLumpedKinetics.getReactionStep().getStructure().getStructureSize();
Expression sizeExp = new Expression(structureSize.getName());
VCUnitDefinition sizeUnit = structureSize.getUnitDefinition();
if (origLumpedKinetics.getKineticsDescription().isElectrical()) {
if (origLumpedKinetics.getReactionStep() instanceof FluxReaction) {
distributedKinetics = new GeneralCurrentKinetics((FluxReaction) reactionStep);
} else if (origLumpedKinetics.getReactionStep() instanceof SimpleReaction) {
distributedKinetics = new GeneralCurrentKinetics((SimpleReaction) reactionStep);
} else {
throw new RuntimeException("DistributedKinetics.toDistributedKinetics(" + origLumpedKinetics.getReactionStep() + ") not supported");
}
} else {
if (origLumpedKinetics.getReactionStep() instanceof FluxReaction) {
distributedKinetics = new GeneralKinetics((FluxReaction) reactionStep);
} else if (origLumpedKinetics.getReactionStep() instanceof SimpleReaction) {
distributedKinetics = new GeneralKinetics((SimpleReaction) reactionStep);
} else {
throw new RuntimeException("DistributedKinetics.toDistributedKinetics(" + origLumpedKinetics.getReactionStep() + ") not supported");
}
}
Expression unitFactor = new Expression(distributedKinetics.getAuthoritativeParameter().getUnitDefinition().multiplyBy(sizeUnit).divideBy(origLumpedKinetics.getAuthoritativeParameter().getUnitDefinition()).getDimensionlessScale());
Expression distributionFactor = Expression.div(unitFactor, sizeExp);
KineticsParameter lumpedAuthoritativeParm = origLumpedKinetics.getAuthoritativeParameter();
KineticsParameter distAuthoritativeParam = distributedKinetics.getAuthoritativeParameter();
Expression newDistributedAuthoritativeExp = Expression.mult(distributionFactor, lumpedAuthoritativeParm.getExpression()).flatten();
Expression substitutedExp = newDistributedAuthoritativeExp.getSubstitutedExpression(sizeExp, new Expression(1.0));
if (ExpressionUtils.functionallyEquivalent(newDistributedAuthoritativeExp, substitutedExp, false)) {
newDistributedAuthoritativeExp = substitutedExp.flatten();
}
parmsToAdd.add(distributedKinetics.new KineticsParameter(distAuthoritativeParam.getName(), newDistributedAuthoritativeExp, distAuthoritativeParam.getRole(), distAuthoritativeParam.getUnitDefinition()));
for (int i = 0; i < origLumpedKineticsParms.length; i++) {
if (origLumpedKineticsParms[i].getRole() != Kinetics.ROLE_LumpedReactionRate && origLumpedKineticsParms[i].getRole() != Kinetics.ROLE_LumpedCurrent) {
parmsToAdd.add(distributedKinetics.new KineticsParameter(origLumpedKineticsParms[i].getName(), new Expression(origLumpedKineticsParms[i].getExpression()), Kinetics.ROLE_UserDefined, origLumpedKineticsParms[i].getUnitDefinition()));
}
}
distributedKinetics.addKineticsParameters(parmsToAdd.toArray(new KineticsParameter[parmsToAdd.size()]));
return distributedKinetics;
} catch (PropertyVetoException e) {
e.printStackTrace();
throw new RuntimeException("failed to create distributed Kinetics for reaction: \"" + origLumpedKinetics.getReactionStep().getName() + "\": " + e.getMessage());
} catch (ExpressionException e) {
e.printStackTrace();
throw new RuntimeException("failed to create distributed Kinetics for reaction: \"" + origLumpedKinetics.getReactionStep().getName() + "\": " + e.getMessage());
}
}
use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.
the class Kinetics method getKineticsParametersFromTokens.
private ArrayList<KineticsParameter> getKineticsParametersFromTokens(String kinetics_vcmlStr) throws ExpressionException, PropertyVetoException {
//
// old format (version 1) (still supported for reading)
//
// Kinetics GeneralCurrentKinetics {
// Parameter a 10;
// Parameter b 3;
// Parameter c d/2;
// Parameter d 5;
// CurrentDensity a+b/c;
// }
//
//
// new format (version 2) (deprecated, incompatible with Version 1, still supported for reading)
//
// Kinetics GeneralCurrentKinetics {
// CurrentDensity 'currentDensity'
// Parameter currentDensity a+b/c;
// Parameter a 10;
// Parameter b 3;
// Parameter c d/2;
// Parameter d 5;
// }
//
// latest format (version 3), which is backward compatable with version 1
// ParameterVCMLTokens (such as "CurrentDensity") have simple expressions
// that always consist of only the requiredIdentifier (e.g. currentDensity; )
//
// Kinetics GeneralCurrentKinetics {
// Parameter currentDensity a+b/c;
// Parameter a 10;
// Parameter b 3;
// Parameter c d/2;
// Parameter d 5;
// CurrentDensity currentDensity;
// }
//
// Kinetics GeneralCurrentKinetics {
// Parameter currentDensity a+b/c; [uM]
// Parameter a 10; [s-1]
// Parameter b 3; [m-1]
// Parameter c d/2; [uM.s-1]
// Parameter d 5; [s]
// CurrentDensity currentDensity; [s]
// }
//
//
// first pass :
// protect predefined parameters
ArrayList<KineticsParameter> localParameters = new ArrayList<Kinetics.KineticsParameter>();
KineticsParameter[] predefinedKineticParameters = getKineticsParameters();
for (KineticsParameter kp : predefinedKineticParameters) {
if (kp.getRole() != ROLE_UserDefined) {
localParameters.add(kp);
}
}
CommentStringTokenizer tokens = new CommentStringTokenizer(kinetics_vcmlStr);
@SuppressWarnings("unused") String kineticsKeywordToken = tokens.nextToken();
@SuppressWarnings("unused") String kineticsNameToken = tokens.nextToken();
@SuppressWarnings("unused") String // read "{"
beginBraceToken = tokens.nextToken();
ModelUnitSystem unitSystem = reactionStep.getModel().getUnitSystem();
HashMap<String, String> symbolRenamings = new HashMap<String, String>();
while (tokens.hasMoreTokens()) {
String firstTokenOfLine = tokens.nextToken();
if (firstTokenOfLine.equalsIgnoreCase(VCMODL.EndBlock)) {
break;
}
if (firstTokenOfLine.equalsIgnoreCase(VCMODL.Fast)) {
// setFast(true);
continue;
}
if (firstTokenOfLine.equalsIgnoreCase(VCMODL.Parameter)) {
String name = tokens.nextToken();
Expression exp = new Expression(tokens.readToSemicolon());
String unitsString = tokens.nextToken();
VCUnitDefinition unitDef = unitSystem.getInstance_TBD();
if (unitsString.startsWith("[")) {
while (!unitsString.endsWith("]")) {
String tempToken = tokens.nextToken();
unitsString = unitsString + " " + tempToken;
}
//
// now string starts with '[' and ends with ']'
//
unitDef = unitSystem.getInstance(unitsString.substring(1, unitsString.length() - 1));
} else {
// read too far, put it back in the stream.
tokens.pushToken(unitsString);
}
// could have two parameters with same name (one reserved, one user defined)
localParameters.add(new KineticsParameter(name, exp, ROLE_UserDefined, unitDef));
continue;
}
//
if (this instanceof GeneralLumpedKinetics) {
if (firstTokenOfLine.equals(VCMODL.ReactionRate) || firstTokenOfLine.equals(VCMODL.CurrentDensity) || firstTokenOfLine.equals(VCMODL.AssumedCompartmentSize_oldname)) {
firstTokenOfLine = tokens.nextToken();
continue;
} else if (firstTokenOfLine.equals(VCMODL.TotalRate_oldname)) {
firstTokenOfLine = VCMODL.LumpedReactionRate;
}
}
//
// assume that this line is a reserved ROLE
//
KineticsParameter parameterForRole = null;
for (int i = 0; i < RoleTags.length; i++) {
if (firstTokenOfLine.equalsIgnoreCase(RoleTags[i])) {
//
for (KineticsParameter kp : localParameters) {
if (kp.getRole() == i) {
parameterForRole = kp;
break;
}
}
if (parameterForRole == null) {
for (KineticsParameter kp : localParameters) {
if (isEquivalentRoleFromKineticsVCMLTokens(i, kp.getRole())) {
parameterForRole = kp;
break;
}
}
}
// may need to generate on the fly during database reading.
if (parameterForRole == null && i == ROLE_ElectricalUnitFactor) {
KineticsParameter unitFactorParm = new KineticsParameter(getDefaultParameterName(ROLE_ElectricalUnitFactor), new Expression(1.0), ROLE_ElectricalUnitFactor, null);
addKineticsParameter(unitFactorParm);
parameterForRole = unitFactorParm;
}
// be forgiving while parsing charge parameter variants from the database - to support legacy models.
if (parameterForRole == null && (i == ROLE_ChargeValence || i == ROLE_NetChargeValence || i == ROLE_CarrierChargeValence)) {
parameterForRole = getChargeValenceParameter();
}
if (parameterForRole == null) {
throw new RuntimeException("parameter for role " + RoleTags[i] + " not found in kinetic law " + this.getKineticsDescription().getName());
}
}
}
String nextTokenAfterRole = tokens.nextToken();
if (nextTokenAfterRole.endsWith("'") && nextTokenAfterRole.startsWith("'")) {
//
// if requiredIdentifier name is present (delimited by single quotes)
// use it as the user-supplied name for that required parameter
//
// e.g. CurrentDensity 'currentDensity'
//
String parmName = nextTokenAfterRole.substring(1, nextTokenAfterRole.length() - 1);
if (!parameterForRole.getName().equals(parmName)) {
symbolRenamings.put(parameterForRole.getName(), parmName);
}
} else {
//
// else if a non-trivial expression, then use the default name for the requiredParameter.
// if a single identifier expression, then use that identifier as the requiredParameter name.
//
// first token (already popped) must be part of the expression (need to push it back).
//
// e.g. CurrentDensity a+b/c;
//
// put back expression token for subsequent parsing.
tokens.pushToken(nextTokenAfterRole);
Expression exp = new Expression(tokens.readToSemicolon());
//
// find out if expression refers to another parameter declaration (expression of type "paramName;").
//
String[] symbols = exp.getSymbols();
boolean bIsSingleId = false;
if (symbols != null && symbols.length == 1) {
if (exp.compareEqual(new Expression(symbols[0]))) {
bIsSingleId = true;
}
}
//
// get unit definition (optional)
//
String unitsString = tokens.nextToken();
VCUnitDefinition unitDef = unitSystem.getInstance_TBD();
if (unitsString.startsWith("[")) {
while (!unitsString.endsWith("]")) {
String tempToken = tokens.nextToken();
unitsString = unitsString + " " + tempToken;
}
//
// now string starts with '[' and ends with ']'
//
unitDef = unitSystem.getInstance(unitsString.substring(1, unitsString.length() - 1));
} else {
// from the next line put it back in the stream.
tokens.pushToken(unitsString);
}
if (!bIsSingleId) {
//
// expression is real, not just a reference to a parameter defined on another line
// set expression and unit
//
parameterForRole.setExpression(exp);
if (unitDef != null && !unitDef.isTBD()) {
parameterForRole.setUnitDefinition(unitDef);
}
} else {
//
// expression is just a reference to a parameter defined on another line (e.g. Kf_012;)
// rename the reserved parameter to that name
//
// NOTE: COULD CREATE A CONFLICT ... TWO PARAMETERS WITH THE SAME NAME (RESOLVE LATER)
//
String parmName = symbols[0];
if (!parameterForRole.getName().equals(parmName)) {
symbolRenamings.put(parameterForRole.getName(), parmName);
}
}
}
}
//
for (String origSymbol : symbolRenamings.keySet()) {
String newSymbol = symbolRenamings.get(origSymbol);
for (KineticsParameter kp : localParameters) {
if (kp.getName().equals(origSymbol)) {
kp.setName(newSymbol);
}
if (kp.getExpression().hasSymbol(origSymbol)) {
kp.getExpression().substituteInPlace(new Expression(origSymbol), new Expression(newSymbol));
}
}
}
//
// merge parameters with same name (one is UserDefined, the other is Reserved role)
//
boolean bDirty = true;
while (bDirty) {
bDirty = false;
for (KineticsParameter kp1 : localParameters) {
KineticsParameter kp_withSameName = null;
for (KineticsParameter kp2 : localParameters) {
if (kp1 != kp2 && kp1.getName().equals(kp2.getName())) {
kp_withSameName = kp2;
}
}
if (kp_withSameName != null) {
// copy expression and unit from UserDefined Parameter to the Reserved Parmaeter and remove the user defined parameter
KineticsParameter userParameter = null;
KineticsParameter reservedParameter = null;
if (kp1.getRole() == ROLE_UserDefined && kp_withSameName.getRole() != ROLE_UserDefined) {
userParameter = kp1;
reservedParameter = kp_withSameName;
} else if (kp_withSameName.getRole() == ROLE_UserDefined && kp1.getRole() != ROLE_UserDefined) {
reservedParameter = kp1;
userParameter = kp_withSameName;
} else {
throw new RuntimeException("found two parameters with same name '" + kp1.getName() + "' in reaction '" + reactionStep.getName() + "', not able to reconcile");
}
reservedParameter.setExpression(userParameter.getExpression());
if (userParameter.getUnitDefinition() == null || userParameter.getUnitDefinition().isTBD()) {
reservedParameter.setUnitDefinition(userParameter.getUnitDefinition());
}
localParameters.remove(userParameter);
bDirty = true;
break;
}
}
}
return localParameters;
}
Aggregations