1 package net.sf.openrocket.simulation.customexpression;
4 import java.util.regex.*;
6 import net.sf.openrocket.document.OpenRocketDocument;
7 import net.sf.openrocket.logging.LogHelper;
8 import net.sf.openrocket.simulation.FlightDataType;
9 import net.sf.openrocket.simulation.SimulationStatus;
10 import net.sf.openrocket.startup.Application;
11 import net.sf.openrocket.unit.FixedUnitGroup;
12 import net.sf.openrocket.unit.UnitGroup;
13 import net.sf.openrocket.util.ArrayList;
14 import de.congrace.exp4j.Calculable;
15 import de.congrace.exp4j.ExpressionBuilder;
16 import de.congrace.exp4j.UnknownFunctionException;
17 import de.congrace.exp4j.UnparsableExpressionException;
18 import de.congrace.exp4j.Variable;
21 * Represents a single custom expression
22 * @author Richard Graham
25 public class CustomExpression implements Cloneable{
27 private static final LogHelper log = Application.getLogger();
29 private OpenRocketDocument doc;
30 private String name, symbol, unit;
32 protected String expression;
33 private ExpressionBuilder builder;
34 private List<CustomExpression> subExpressions = new ArrayList<CustomExpression>();
36 public CustomExpression(OpenRocketDocument doc){
44 public CustomExpression(OpenRocketDocument doc,
54 setExpression(expression);
58 * Sets the long name of this expression, e.g. 'Kinetic energy'
60 public void setName(String name){
65 * Sets the string for the units of the result of this expression.
67 public void setUnit(String unit){
72 * Sets the symbol string. This is the short, locale independent symbol for this whole expression
74 public void setSymbol(String symbol){
79 * Sets the actual expression string for this expression
81 public void setExpression(String expression){
83 // This is the expression as supplied
84 this.expression = expression;
86 // Replace any indexed variables
87 expression = subTimeIndexes(expression);
88 expression = subTimeRanges(expression);
90 builder = new ExpressionBuilder(expression);
91 for (String n : getAllSymbols()){
92 builder.withVariable(new Variable(n));
94 for (CustomExpression exp : this.subExpressions){
95 builder.withVariable(new Variable(exp.hash()));
98 builder.withCustomFunctions(Functions.getInstance().getAllFunction());
99 log.info("Built expression "+expression);
103 * Replaces expressions of the form:
104 * a[x:y] with a hash and creates an associated RangeExpression from x to y
106 private String subTimeRanges(String str){
108 Pattern p = Pattern.compile(variableRegex()+"\\[[^\\]]*:.*?\\]");
109 Matcher m = p.matcher(str);
111 // for each match, make a new custom expression (in subExpressions) with a hashed name
112 // and replace the expression and variable in the original expression string with [hash].
114 String match = m.group();
116 int start = match.indexOf("[");
117 int end = match.indexOf("]");
118 int colon = match.indexOf(":");
120 String startTime = match.substring(start+1, colon);
121 String endTime = match.substring(colon+1, end);
122 String variableType = match.substring(0, start);
124 RangeExpression exp = new RangeExpression(doc, startTime, endTime, variableType);
125 subExpressions.add( exp );
126 str = str.replace(match, exp.hash());
132 * Replaces expressions of the form
133 * a[x] with a hash and creates an associated IndexExpression with x
135 private String subTimeIndexes(String str){
137 // find any matches of the time-indexed variable notation, e.g. m[1.2] for mass at 1.2 sec
138 Pattern p = Pattern.compile(variableRegex()+"\\[[^:]*?\\]");
139 Matcher m = p.matcher(str);
141 // for each match, make a new custom expression (in subExpressions) with a hashed name
142 // and replace the expression and variable in the original expression string with [hash].
144 String match = m.group();
145 // just the index part (in the square brackets) :
146 String indexText = match.substring(match.indexOf("[")+1, match.length()-1);
147 // just the flight data type
148 String typeText = match.substring(0, match.indexOf("["));
150 // Do the replacement and add a corresponding new IndexExpression to the list
151 IndexExpression exp = new IndexExpression(doc, indexText, typeText);
152 subExpressions.add( exp );
153 str = str.replace(match, exp.hash());
159 * Returns a string of the form (t|a| ... ) with all variable symbols available
160 * This is useful for regex evaluation
162 protected String variableRegex(){
164 for (String s : getAllSymbols()){
165 regex = regex + s + "|";
167 regex = regex.substring(0, regex.length()-1) + ")";
171 // get a list of all the names of all the available variables
172 protected ArrayList<String> getAllNames(){
173 ArrayList<String> names = new ArrayList<String>();
174 for (FlightDataType type : FlightDataType.ALL_TYPES)
175 names.add(type.getName());
178 List<CustomExpression> expressions = doc.getCustomExpressions();
179 for (CustomExpression exp : expressions ){
181 names.add(exp.getName());
187 // get a list of all the symbols of the available variables ignoring this one
188 protected ArrayList<String> getAllSymbols(){
189 ArrayList<String> symbols = new ArrayList<String>();
190 for (FlightDataType type : FlightDataType.ALL_TYPES)
191 symbols.add(type.getSymbol());
194 for (CustomExpression exp : doc.getCustomExpressions() ){
196 symbols.add(exp.getSymbol());
202 public boolean checkSymbol(){
203 if ("".equals(symbol.trim()))
207 for (char c : "0123456789.,()[]{}<>:#@%^&* ".toCharArray())
208 if (symbol.indexOf(c) != -1 )
211 // No operators (ignoring brackets)
212 for (String s : Functions.AVAILABLE_OPERATORS.keySet()){
213 if (symbol.equals(s.trim().replaceAll("\\(|\\)|\\]|\\[|:", "")))
217 // No already defined symbols
218 ArrayList<String> symbols = getAllSymbols().clone();
219 if (symbols.contains(symbol.trim())){
220 int index = symbols.indexOf(symbol.trim());
221 log.user("Symbol "+symbol+" already exists, found "+symbols.get(index));
228 public boolean checkName(){
229 if ("".equals(name.trim()))
232 // No characters that could mess things up saving etc
233 for (char c : ",()[]{}<>#".toCharArray())
234 if (name.indexOf(c) != -1 )
237 ArrayList<String> names = getAllNames().clone();
238 if (names.contains(name.trim())){
239 int index = names.indexOf(name.trim());
240 log.user("Name "+name+" already exists, found "+names.get(index));
247 // Currently no restrictions on unit
248 public boolean checkUnit(){
252 public boolean checkAll(){
253 return checkUnit() && checkSymbol() && checkName() && checkExpression();
256 public String getName(){
260 public String getSymbol(){
264 public String getUnit(){
268 public String getExpressionString(){
273 * Performs a basic check to see if the current expression string is valid
274 * This includes checking for bad characters and balanced brackets and test
275 * building the expression.
277 public boolean checkExpression(){
278 if ("".equals(expression.trim())){
282 int round = 0, square = 0; // count of bracket openings
283 for (char c : expression.toCharArray()){
285 case '(' : round++; break;
286 case ')' : round--; break;
287 case '[' : square++; break;
288 case ']' : square--; break;
291 log.user(": found outside range expression");
295 case '#' : return false;
296 case '=' : return false;
299 if (round != 0 || square != 0) {
300 log.user("Expression has unballanced brackets");
305 //// Define the available variables as empty
306 // The built in data types
307 for (FlightDataType type : FlightDataType.ALL_TYPES){
308 builder.withVariable(new Variable(type.getSymbol()));
311 for (String symb : getAllSymbols()){
312 builder.withVariable(new Variable(symb));
318 } catch (Exception e) {
319 log.user("Custom expression invalid : " + e.toString());
328 public Double evaluateDouble(SimulationStatus status){
329 return evaluate(status).getDoubleValue();
333 * Builds the expression, done automatically during evaluation. Logs any errors. Returns null in case of error.
335 protected Calculable buildExpression(){
336 return buildExpression(builder);
340 * Builds a specified expression, log any errors and returns null in case of error.
342 protected Calculable buildExpression(ExpressionBuilder b){
346 } catch (UnknownFunctionException e1) {
347 log.user("Unknown function. Could not build custom expression "+name);
349 } catch (UnparsableExpressionException e1) {
350 log.user("Unparsable expression. Could not build custom expression "+name+". "+e1.getMessage());
358 * Evaluate the expression using the last variable values from the simulation status.
359 * Returns NaN on any error.
361 public Variable evaluate(SimulationStatus status){
363 Calculable calc = buildExpression(builder);
365 return new Variable("Unknown");
368 // Evaluate any sub expressions and set associated variables in the calculable
369 for (CustomExpression expr : this.subExpressions){
370 calc.setVariable( expr.evaluate(status) );
373 // Set all the built-in variables. Strictly we surely won't need all of them
374 // Going through and checking them to include only the ones used *might* give a speedup
375 for (FlightDataType type : status.getFlightData().getTypes()){
376 double value = status.getFlightData().getLast(type);
377 calc.setVariable( new Variable(type.getSymbol(), value ) );
380 double result = Double.NaN;
382 result = calc.calculate().getDoubleValue();
384 catch (java.util.EmptyStackException e){
385 log.user("Unable to calculate expression "+this.expression+" due to empty stack exception");
388 return new Variable(name, result);
392 * Returns the new flight data type corresponding to this calculated data
393 * If the unit matches a SI unit string then the datatype will have the corresponding unitgroup.
394 * Otherwise, a fixed unit group will be created
396 public FlightDataType getType(){
398 UnitGroup ug = UnitGroup.SIUNITS.get(unit);
400 ug = new FixedUnitGroup(unit);
403 FlightDataType type = FlightDataType.getType(name, symbol, ug);
405 //log.debug(this.getClass().getSimpleName()+" returned type "+type.getName()+" (" + type.getSymbol() + ")" );
411 * Add this expression to the document if valid and not in document already
413 public void addToDocument(){
414 // Abort if exact expression already in
415 List<CustomExpression> expressions = doc.getCustomExpressions();
416 if ( !expressions.isEmpty() ) {
417 // check if expression already exists
418 if ( expressions.contains(this) ){
419 log.user("Expression already in document. This unit : "+this.getUnit()+", existing unit : "+expressions.get(0).getUnit());
424 if (this.checkAll()){
425 log.user("Custom expression added to rocket document");
426 doc.addCustomExpression( this );
431 * Removes this expression from the document, replacing it with a given new expression
433 public void overwrite(CustomExpression newExpression){
434 if (!doc.getCustomExpressions().contains(this))
437 int index = doc.getCustomExpressions().indexOf(this);
438 doc.getCustomExpressions().set(index, newExpression);
443 public String toString(){
444 return "Custom expression : "+this.name.toString()+ " " + this.expression.toString();
449 * Clone method makes a deep copy of everything except the reference to the document.
450 * If you want to apply this to another simulation, set simulation manually after cloning.
451 * @see java.lang.Object#clone()
453 public Object clone() {
455 return super.clone();
457 catch( CloneNotSupportedException e )
459 return new CustomExpression( doc ,
460 new String(this.getName()),
461 new String(this.getSymbol()),
462 new String(this.getUnit()),
463 new String(this.getExpressionString()));
468 * Returns a simple all upper case string hash code with a proceeding # mark.
469 * Used for temporary substitution when evaluating index and range expressions.
471 public String hash(){
472 Integer hashint = new Integer(this.getExpressionString().hashCode());
474 for (char c : hashint.toString().toCharArray()){
475 char newc = (char) (c + 17);
482 public boolean equals(Object obj){
483 CustomExpression other = (CustomExpression) obj;
485 return ( this.getName().equals( other.getName() ) &&
486 this.getSymbol().equals( other.getSymbol() ) &&
487 this.getExpressionString().equals( other.getExpressionString() ) &&
488 this.getUnit().equals( other.getUnit() )
493 public int hashCode() {
494 return hash().hashCode();