Big update to custom expression feature.
[debian/openrocket] / core / src / net / sf / openrocket / simulation / customexpression / IndexExpression.java
1 package net.sf.openrocket.simulation.customexpression;
2
3 import java.util.List;
4
5 import de.congrace.exp4j.Calculable;
6 import de.congrace.exp4j.Variable;
7 import net.sf.openrocket.document.OpenRocketDocument;
8 import net.sf.openrocket.logging.LogHelper;
9 import net.sf.openrocket.simulation.customexpression.CustomExpression;
10 import net.sf.openrocket.simulation.FlightDataType;
11 import net.sf.openrocket.simulation.SimulationStatus;
12 import net.sf.openrocket.startup.Application;
13 import net.sf.openrocket.util.LinearInterpolator;
14
15 public class IndexExpression extends CustomExpression {
16
17         FlightDataType type;
18         private static final LogHelper log = Application.getLogger();
19         
20         public IndexExpression(OpenRocketDocument doc, String indexText, String typeText){
21                 super(doc);
22                 
23                 setExpression(indexText);
24                 this.setName("");
25                 this.setSymbol(typeText);
26                 
27         }
28         
29         @Override
30         public Variable evaluate(SimulationStatus status){
31                 
32                 Calculable calc = buildExpression();
33                 if (calc == null){
34                         return new Variable("Unknown");
35                 }
36                 
37                 // From the given datatype, get the time and function values and make an interpolator
38                 FlightDataType type = getType();
39                 List<Double> data = status.getFlightData().get(type);
40                 List<Double> time = status.getFlightData().get(FlightDataType.TYPE_TIME);
41                 LinearInterpolator interp = new LinearInterpolator(time, data); 
42                 
43                 // Evaluate this expression to get the t value
44                 try{
45                         double tvalue = calc.calculate().getDoubleValue();
46                         return new Variable(hash(), interp.getValue( tvalue ) );
47                 }
48                 catch (java.util.EmptyStackException e){
49                         log.user("Unable to calculate time index for indexed expression "+getExpressionString()+" due to empty stack exception");
50                         return new Variable("Unknown");
51                 }
52                 
53         }
54 }