use of cbit.vcell.parser.SimpleSymbolTable in project vcell by virtualcell.
the class FunctionRangeGenerator method getFunctionStatistics.
//
// note: functionExp should already be flattened to only have symbols for state variables, x, y, z, and t
//
public static FunctionStatistics getFunctionStatistics(Expression functionExp, VarStatistics[] varStatistics, double[] times, CartesianMesh cartesianMesh, BitSet inDomainBitSetOrig, VariableType variableType) throws /*,int numSamplesPerDim*/
Exception {
ArrayList<Integer> inDomainIndexesInit = new ArrayList<>();
// make list of all indexes in domain
for (int i = inDomainBitSetOrig.nextSetBit(0); i >= 0; i = inDomainBitSetOrig.nextSetBit(i + 1)) {
if (i == Integer.MAX_VALUE) {
break;
}
inDomainIndexesInit.add(i);
}
if (varStatistics.length == 0) {
double constantValue = functionExp.evaluateConstant();
double[] minValues = new double[times.length];
Arrays.fill(minValues, constantValue);
double[] maxValues = new double[times.length];
Arrays.fill(maxValues, constantValue);
return new FunctionStatistics(minValues, maxValues);
}
if (varStatistics[0].minValuesOverTime.length != times.length) {
// happens if viewing data of running sim
double[] temp = new double[varStatistics[0].minValuesOverTime.length];
System.arraycopy(times, 0, temp, 0, temp.length);
times = temp;
}
// int numVars = varStatistics.length;
// Math.min(1000, b)
long numSamples = (inDomainIndexesInit.size() < 10000 ? inDomainIndexesInit.size() : 10000);
// long numSamples = numVars*numSamplesPerDim;
ArrayList<String> symbols = new ArrayList<>();
// if (functionExp.hasSymbol("x")){
// numSamples *= numSamplesPerDim;
// }
// if (functionExp.hasSymbol("y")){
// numSamples *= numSamplesPerDim;
// }
// if (functionExp.hasSymbol("z")){
// numSamples *= numSamplesPerDim;
// }
// boolean bSampleSpace = functionExp.hasSymbol(ReservedVariable.X.getSyntax()) || functionExp.hasSymbol(ReservedVariable.Y.getSyntax()) || functionExp.hasSymbol(ReservedVariable.Z.getSyntax());
//
// establishes order of values when evaluating, values={t,x,y,z,var1,var2, ... varN}
//
symbols.add("t");
symbols.add("x");
symbols.add("y");
symbols.add("z");
for (VarStatistics varStat : varStatistics) {
symbols.add(varStat.stateVariableName);
}
SimpleSymbolTable symTable = new SimpleSymbolTable(symbols.toArray(new String[0]));
functionExp.bindExpression(symTable);
// loop through time, at each time sample state variables (and x,y,z if necessary) to estimate
// the min and max values for that time.
Random rand = new Random(0);
double[] values = new double[symbols.size()];
double[] minFunctionValues = new double[times.length];
double[] maxFunctionValues = new double[times.length];
// Extent extent = cartesianMesh.getExtent();
for (int tIndex = 0; tIndex < times.length; tIndex++) {
ArrayList<Integer> inDomainIndexes = new ArrayList<>(inDomainIndexesInit);
values[0] = times[tIndex];
double minValue = Double.POSITIVE_INFINITY;
double maxValue = Double.NEGATIVE_INFINITY;
for (int sample = 0; sample < numSamples; sample++) {
Coordinate coord = null;
int rndIndex = rand.nextInt(inDomainIndexes.size());
int index = inDomainIndexes.remove(rndIndex);
if (variableType.equals(VariableType.MEMBRANE)) {
coord = cartesianMesh.getCoordinateFromMembraneIndex(index);
} else if (variableType.equals(VariableType.VOLUME)) {
coord = cartesianMesh.getCoordinateFromVolumeIndex(index);
} else {
throw new Exception("Not implemented " + variableType.getTypeName());
}
values[1] = coord.getX();
values[2] = coord.getY();
values[3] = coord.getZ();
for (int varIndex = 0; varIndex < varStatistics.length; varIndex++) {
double s = rand.nextDouble();
values[4 + varIndex] = s * varStatistics[varIndex].minValuesOverTime[tIndex] + (1 - s) * varStatistics[varIndex].maxValuesOverTime[tIndex];
}
double evaluation = functionExp.evaluateVector(values);
minValue = Math.min(minValue, evaluation);
maxValue = Math.max(maxValue, evaluation);
}
minFunctionValues[tIndex] = minValue;
maxFunctionValues[tIndex] = maxValue;
// System.out.println("tIndex="+tIndex+" min="+minValue+" max="+maxValue);
}
FunctionStatistics functionStats = new FunctionStatistics(minFunctionValues, maxFunctionValues);
return functionStats;
}
use of cbit.vcell.parser.SimpleSymbolTable in project vcell by virtualcell.
the class OptimizationSpec method read.
/**
* Insert the method's description here.
* Creation date: (3/3/00 3:59:31 PM)
* @return cbit.vcell.opt.OptimizationSpec
* @param vcmlString java.lang.String
*/
public void read(CommentStringTokenizer tokens) {
try {
String token = null;
while (tokens.hasMoreTokens()) {
token = tokens.nextToken();
if (token.equalsIgnoreCase("Parameter")) {
String name = tokens.nextToken();
String lowerBound = tokens.nextToken();
double lowerBoundDouble = 0.0;
try {
lowerBoundDouble = Double.parseDouble(lowerBound);
} catch (NumberFormatException e) {
if (lowerBound.equalsIgnoreCase("-Infinity") || lowerBound.equalsIgnoreCase("-Inf")) {
lowerBoundDouble = Double.NEGATIVE_INFINITY;
}
}
String upperBound = tokens.nextToken();
double upperBoundDouble = 0.0;
try {
upperBoundDouble = Double.parseDouble(upperBound);
} catch (NumberFormatException e) {
if (upperBound.equalsIgnoreCase("Infinity") || upperBound.equalsIgnoreCase("Inf")) {
upperBoundDouble = Double.POSITIVE_INFINITY;
}
}
String scale = tokens.nextToken();
String initialValue = tokens.nextToken();
Parameter parameter = new Parameter(name, lowerBoundDouble, upperBoundDouble, Double.parseDouble(scale), Double.parseDouble(initialValue));
addParameter(parameter);
continue;
}
if (token.equalsIgnoreCase("ExplicitObjectiveFunction")) {
ObjectiveFunction objFunction = ExplicitObjectiveFunction.fromVCML(tokens);
setObjectiveFunction(objFunction);
continue;
}
if (token.equalsIgnoreCase("OdeObjectiveFunction")) {
throw new RuntimeException("OdeObjectiveFunction no longer supported");
}
if (token.equalsIgnoreCase(ConstraintType.LinearEquality.toString())) {
Expression exp = MathFunctionDefinitions.fixFunctionSyntax(tokens);
SimpleSymbolTable symbolTable = new SimpleSymbolTable(getParameterNames());
exp.bindExpression(symbolTable);
Constraint constraint = new Constraint(ConstraintType.LinearEquality, exp);
addConstraint(constraint);
continue;
}
if (token.equalsIgnoreCase(ConstraintType.LinearInequality.toString())) {
Expression exp = MathFunctionDefinitions.fixFunctionSyntax(tokens);
SimpleSymbolTable symbolTable = new SimpleSymbolTable(getParameterNames());
exp.bindExpression(symbolTable);
Constraint constraint = new Constraint(ConstraintType.LinearInequality, exp);
addConstraint(constraint);
continue;
}
if (token.equalsIgnoreCase(ConstraintType.NonlinearInequality.toString())) {
Expression exp = MathFunctionDefinitions.fixFunctionSyntax(tokens);
SimpleSymbolTable symbolTable = new SimpleSymbolTable(getParameterNames());
exp.bindExpression(symbolTable);
Constraint constraint = new Constraint(ConstraintType.NonlinearInequality, exp);
addConstraint(constraint);
continue;
}
if (token.equalsIgnoreCase(ConstraintType.NonlinearEquality.toString())) {
Expression exp = MathFunctionDefinitions.fixFunctionSyntax(tokens);
SimpleSymbolTable symbolTable = new SimpleSymbolTable(getParameterNames());
exp.bindExpression(symbolTable);
Constraint constraint = new Constraint(ConstraintType.NonlinearEquality, exp);
addConstraint(constraint);
continue;
}
throw new RuntimeException("unexpected identifier " + token);
}
} catch (Throwable e) {
e.printStackTrace(System.out);
throw new RuntimeException("line #" + (tokens.lineIndex() + 1) + " Exception: " + e.getMessage());
}
}
use of cbit.vcell.parser.SimpleSymbolTable in project vcell by virtualcell.
the class TimeFunctionPanel method refreshPlot.
private void refreshPlot() throws Exception {
// try {
Expression exp = new Expression(funcTextField.getText());
exp.flatten();
SimpleSymbolTable symbolTable = new SimpleSymbolTable(new String[] { "t", "pi" /*, "x", "y", "z"*/
});
exp.bindExpression(symbolTable);
double[] valueArray = new double[2];
valueArray[1] = Math.PI;
// valueArray[ReservedVariable.Z.getIndex()] = 0 ;
// valueArray[ReservedVariable.Y.getIndex()] = 0 ;
// valueArray[ReservedVariable.X.getIndex()] = 0 ;
int totalTimePoints = 0;
double beginTime = 0;
double timeStep = 0;
double parseEndTime = 0;
try {
beginTime = Double.parseDouble(timeBegTextField.getText());
} catch (Exception e) {
throw new Exception("Couldn't evaluate 'Time Begin' as number\n" + e.getMessage());
}
try {
timeStep = Double.parseDouble(timeStepTextField.getText());
if (timeStep <= 0) {
throw new Exception("timestep value = " + timeStep);
}
} catch (Exception e) {
throw new Exception("'Time Step' must be > 0\n" + e.getMessage());
}
try {
parseEndTime = Double.parseDouble(endTimeTextField.getText());
} catch (Exception e) {
throw new Exception("Couldn't evaluate 'Time End' as number\n" + e.getMessage());
}
try {
if (beginTime > parseEndTime || beginTime == parseEndTime) {
throw new Exception("endTime must be greater than beginTime");
}
totalTimePoints = (int) Math.ceil((parseEndTime - beginTime) / timeStep);
// if(totalTimePoints <= 0){
// throw new Exception("calculated number of time points ="+totalTimePoints);
// }
} catch (Exception e) {
throw new Exception("check beginTime, endTime and timeStep: ((endTime-beginTime)/timeStep) must be greater than 0" + "\n" + e.getMessage());
}
double[] timePoints = new double[totalTimePoints];
double[] funcVals = new double[totalTimePoints];
for (int i = 0; i < totalTimePoints; i++) {
valueArray[ReservedVariable.TIME.getIndex()] = beginTime + i * timeStep;
timePoints[i] = valueArray[ReservedVariable.TIME.getIndex()];
funcVals[i] = exp.evaluateVector(valueArray);
}
PlotData plotData = new PlotData(timePoints, funcVals);
Plot2D plot2D = new Plot2D(null, null, new String[] { "Time Function" }, new PlotData[] { plotData }, new String[] { "Time Function Value", "Time", "[" + "Time Function" + "]" });
plotPane.setPlot2D(plot2D);
// } catch (Exception e) {
// e.printStackTrace();
// DialogUtils.showErrorDialog(this, "Error refreshing Plot:\n"+e.getMessage(), e);
// plotPane.setPlot2D( null);
// }
}
use of cbit.vcell.parser.SimpleSymbolTable in project vcell by virtualcell.
the class PDEDataViewer method plotSpaceStats.
void plotSpaceStats(TSJobResultsSpaceStats tsjrss) {
// Determine if Volume or Membrane
DataIdentifier[] diArr = getPdeDataContext().getDataIdentifiers();
boolean bVolume = true;
for (int i = 0; i < diArr.length; i += 1) {
if (diArr[i].getName().equals(tsjrss.getVariableNames()[0])) {
if (diArr[i].getVariableType().equals(VariableType.MEMBRANE) || diArr[i].getVariableType().equals(VariableType.MEMBRANE_REGION)) {
bVolume = false;
break;
}
}
}
SymbolTableEntry[] symbolTableEntries = null;
if (tsjrss.getVariableNames().length == 1) {
// max.mean.min,sum
symbolTableEntries = new SymbolTableEntry[3];
if (getSimulation() != null && getSimulation().getMathDescription() != null) {
symbolTableEntries[0] = getSimulation().getMathDescription().getEntry(tsjrss.getVariableNames()[0]);
} else {
symbolTableEntries[0] = new SimpleSymbolTable(tsjrss.getVariableNames()).getEntry(tsjrss.getVariableNames()[0]);
}
symbolTableEntries[1] = symbolTableEntries[0];
symbolTableEntries[2] = symbolTableEntries[0];
}
SymbolTableEntry[] finalSymbolTableEntries = symbolTableEntries;
boolean finalBVolume = bVolume;
PlotPane plotPane = new cbit.plot.gui.PlotPane();
plotPane.setPlot2D(new SingleXPlot2D(finalSymbolTableEntries, getSimulationModelInfo().getDataSymbolMetadataResolver(), "Time", new String[] { "Max", (tsjrss.getWeightedMean() != null ? "WeightedMean" : "UnweightedMean"), "Min" /*,
(tsjrss.getWeightedSum() != null?"WeightedSum":"UnweightedSum")*/
}, new double[][] { tsjrss.getTimes(), tsjrss.getMaximums()[0], (tsjrss.getWeightedMean() != null ? tsjrss.getWeightedMean()[0] : tsjrss.getUnweightedMean()[0]), tsjrss.getMinimums()[0] /*,
(tsjrss.getWeightedSum() != null?tsjrss.getWeightedSum()[0]:tsjrss.getUnweightedSum()[0])*/
}, new String[] { "Statistics Plot for " + tsjrss.getVariableNames()[0] + (tsjrss.getTotalSpace() != null ? " (ROI " + (finalBVolume ? "volume" : "area") + "=" + tsjrss.getTotalSpace()[0] + ")" : ""), ReservedVariable.TIME.getName(), "[" + tsjrss.getVariableNames()[0] + "]" }));
String title = "Statistics: (" + tsjrss.getVariableNames()[0] + ") ";
if (getSimulationModelInfo() != null) {
title += getSimulationModelInfo().getContextName() + " " + getSimulationModelInfo().getSimulationName();
}
ChildWindowManager childWindowManager = ChildWindowManager.findChildWindowManager(PDEDataViewer.this);
ChildWindow childWindow = childWindowManager.addChildWindow(plotPane, plotPane, title);
childWindow.setIsCenteredOnParent();
childWindow.pack();
childWindow.show();
}
use of cbit.vcell.parser.SimpleSymbolTable in project vcell by virtualcell.
the class PDEDataViewer method showKymograph.
private void showKymograph() {
String title = createContextTitle(PDEDataViewer.this.isPostProcess(), "Kymograph: ", getPdeDataContext(), getSimulationModelInfo(), getSimulation());
final String INDICES_KEY = "INDICES_KEY";
final String CROSSING_KEY = "CROSSING_KEY";
final String ACCUM_KEY = "ACCUM_KEY";
AsynchClientTask multiTimePlotHelperTask = new AsynchClientTask("multiTimePlotHelperTask...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
// Collect all sample curves created by user
SpatialSelection[] spatialSelectionArr = getPDEDataContextPanel1().fetchSpatialSelections(false, true);
final Vector<SpatialSelection> lineSSOnly = new Vector<SpatialSelection>();
if (spatialSelectionArr != null && spatialSelectionArr.length > 0) {
//
for (int i = 0; i < spatialSelectionArr.length; i++) {
if (spatialSelectionArr[i].isPoint() || (spatialSelectionArr[i] instanceof SpatialSelectionMembrane && ((SpatialSelectionMembrane) spatialSelectionArr[i]).getSelectionSource() instanceof cbit.vcell.geometry.SinglePoint)) {
} else {
lineSSOnly.add(spatialSelectionArr[i]);
}
}
}
//
if (lineSSOnly.size() == 0) {
throw new Exception("No line samples match DataType=" + getPdeDataContext().getDataIdentifier().getVariableType());
}
VariableType varType = getPdeDataContext().getDataIdentifier().getVariableType();
int[] indices = null;
int[] crossingMembraneIndices = null;
double[] accumDistances = null;
for (int i = 0; i < lineSSOnly.size(); i++) {
if (varType.equals(VariableType.VOLUME) || varType.equals(VariableType.VOLUME_REGION) || varType.equals(VariableType.POSTPROCESSING)) {
SpatialSelectionVolume ssv = (SpatialSelectionVolume) lineSSOnly.get(i);
SpatialSelection.SSHelper ssh = ssv.getIndexSamples(0.0, 1.0);
indices = ssh.getSampledIndexes();
crossingMembraneIndices = ssh.getMembraneIndexesInOut();
accumDistances = ssh.getWorldCoordinateLengths();
} else if (varType.equals(VariableType.MEMBRANE) || varType.equals(VariableType.MEMBRANE_REGION)) {
SpatialSelectionMembrane ssm = (SpatialSelectionMembrane) lineSSOnly.get(i);
SpatialSelection.SSHelper ssh = ssm.getIndexSamples();
indices = ssh.getSampledIndexes();
accumDistances = ssh.getWorldCoordinateLengths();
}
}
if (indices != null) {
hashTable.put(INDICES_KEY, indices);
}
if (crossingMembraneIndices != null) {
hashTable.put(CROSSING_KEY, crossingMembraneIndices);
}
if (accumDistances != null) {
hashTable.put(ACCUM_KEY, accumDistances);
}
MultiTimePlotHelper multiTimePlotHelper = createMultiTimePlotHelper((ClientPDEDataContext) getPdeDataContext(), getDataViewerManager().getUser(), getSimulationModelInfo().getDataSymbolMetadataResolver());
hashTable.put(MULTITPHELPER_TASK_KEY, multiTimePlotHelper);
}
};
AsynchClientTask kymographTask = new AsynchClientTask("Kymograph showing...", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
KymographPanel kymographPanel = new KymographPanel(PDEDataViewer.this, title, (MultiTimePlotHelper) hashTable.get(MULTITPHELPER_TASK_KEY));
SymbolTable symbolTable;
if (getSimulation() != null && getSimulation().getMathDescription() != null) {
symbolTable = getSimulation().getMathDescription();
} else {
symbolTable = new SimpleSymbolTable(new String[] { getPdeDataContext().getDataIdentifier().getName() });
}
ChildWindowManager childWindowManager = ChildWindowManager.findChildWindowManager(PDEDataViewer.this);
ChildWindow childWindow = childWindowManager.addChildWindow(kymographPanel, kymographPanel, title);
childWindow.setSize(new Dimension(700, 500));
childWindow.show();
kymographPanel.initDataManager(getPdeDataContext().getDataIdentifier(), getPdeDataContext().getTimePoints()[0], 1, getPdeDataContext().getTimePoints()[getPdeDataContext().getTimePoints().length - 1], (int[]) hashTable.get(INDICES_KEY), (int[]) hashTable.get(CROSSING_KEY), (double[]) hashTable.get(ACCUM_KEY), true, getPdeDataContext().getTimePoint(), symbolTable);
}
};
ClientTaskDispatcher.dispatch(this, new Hashtable<String, Object>(), new AsynchClientTask[] { multiTimePlotHelperTask, kymographTask }, null, false, false, true, null, false);
}
Aggregations