e41cfba7b6e72a6f0e15f6b603522d0e7c0a57a6
[sw/motorsim] / gui / com / billkuker / rocketry / motorsim / visual / Chart.java
1 package com.billkuker.rocketry.motorsim.visual;\r
2 \r
3 import java.awt.BasicStroke;\r
4 import java.awt.BorderLayout;\r
5 import java.awt.Color;\r
6 import java.awt.Font;\r
7 import java.awt.Stroke;\r
8 import java.lang.reflect.InvocationTargetException;\r
9 import java.lang.reflect.Method;\r
10 import java.util.Collection;\r
11 import java.util.Iterator;\r
12 import java.util.concurrent.ExecutorService;\r
13 import java.util.concurrent.Executors;\r
14 import java.util.concurrent.ThreadFactory;\r
15 \r
16 import javax.measure.quantity.Area;\r
17 import javax.measure.quantity.Length;\r
18 import javax.measure.quantity.Quantity;\r
19 import javax.measure.quantity.Volume;\r
20 import javax.measure.unit.SI;\r
21 import javax.measure.unit.Unit;\r
22 import javax.swing.JFrame;\r
23 import javax.swing.JPanel;\r
24 import javax.swing.SwingUtilities;\r
25 \r
26 import org.apache.log4j.Logger;\r
27 import org.jfree.chart.ChartFactory;\r
28 import org.jfree.chart.ChartPanel;\r
29 import org.jfree.chart.JFreeChart;\r
30 import org.jfree.chart.plot.Marker;\r
31 import org.jfree.chart.plot.PlotOrientation;\r
32 import org.jfree.chart.plot.ValueMarker;\r
33 import org.jfree.data.xy.XYSeries;\r
34 import org.jfree.data.xy.XYSeriesCollection;\r
35 import org.jfree.ui.RectangleAnchor;\r
36 import org.jfree.ui.RectangleInsets;\r
37 import org.jfree.ui.TextAnchor;\r
38 import org.jscience.physics.amount.Amount;\r
39 \r
40 import com.billkuker.rocketry.motorsim.RocketScience;\r
41 import com.billkuker.rocketry.motorsim.grain.CoredCylindricalGrain;\r
42 \r
43 public class Chart<X extends Quantity, Y extends Quantity> extends JPanel {\r
44         private static final long serialVersionUID = 1L;\r
45         private static Logger log = Logger.getLogger(Chart.class);\r
46         \r
47         private final Stroke dashed = new BasicStroke(1, 1, 1, 1, new float[]{2,4}, 0);\r
48         private final Font labelFont = new Font(Font.DIALOG, Font.BOLD, 10);\r
49 \r
50         private static ThreadFactory tf = new ThreadFactory() {\r
51                 public Thread newThread(Runnable r) {\r
52                         Thread t = new Thread(r);\r
53                         t.setDaemon(true);\r
54                         return t;\r
55                 }\r
56         };\r
57         private static ExecutorService fast = Executors.newFixedThreadPool(2, tf);\r
58         private static ExecutorService slow = Executors.newFixedThreadPool(2, tf);\r
59 \r
60 \r
61         public class IntervalDomain implements Iterable<Amount<X>> {\r
62 \r
63                 Amount<X> low, high, delta;\r
64                 int steps = 100;\r
65 \r
66                 public IntervalDomain(Amount<X> low, Amount<X> high) {\r
67                         this.low = low;\r
68                         this.high = high;\r
69                         delta = high.minus(low).divide(steps);\r
70                 }\r
71 \r
72                 public IntervalDomain(Amount<X> low, Amount<X> high, int steps) {\r
73                         this.steps = steps;\r
74                         this.low = low;\r
75                         this.high = high;\r
76                         delta = high.minus(low).divide(steps);\r
77                 }\r
78 \r
79                 public Iterator<Amount<X>> iterator() {\r
80                         return new Iterator<Amount<X>>() {\r
81                                 Amount<X> current = low;\r
82 \r
83                                 public boolean hasNext() {\r
84                                         return current.isLessThan(high.plus(delta));\r
85                                 }\r
86 \r
87                                 public Amount<X> next() {\r
88                                         Amount<X> ret = current;\r
89                                         current = current.plus(delta);\r
90                                         return ret;\r
91                                 }\r
92 \r
93                                 public final void remove() {\r
94                                         throw new UnsupportedOperationException(\r
95                                                         "Chart domain iterators are not modifiable.");\r
96                                 }\r
97                         };\r
98                 }\r
99 \r
100         }\r
101 \r
102         XYSeriesCollection dataset = new XYSeriesCollection();\r
103         JFreeChart chart;\r
104 \r
105         Unit<X> xUnit;\r
106         Unit<Y> yUnit;\r
107 \r
108         Object source;\r
109         Method f;\r
110 \r
111         public Chart(Unit<X> xUnit, Unit<Y> yUnit, Object source, String method)\r
112                         throws NoSuchMethodException {\r
113                 super(new BorderLayout());\r
114                 f = source.getClass().getMethod(method, Amount.class);\r
115 \r
116                 this.source = source;\r
117 \r
118 \r
119                 this.xUnit = RocketScience.UnitPreference.getUnitPreference()\r
120                                 .getPreferredUnit(xUnit);\r
121                 this.yUnit = RocketScience.UnitPreference.getUnitPreference()\r
122                                 .getPreferredUnit(yUnit);\r
123 \r
124                 chart = ChartFactory.createXYLineChart(method.substring(0, 1)\r
125                                 .toUpperCase()\r
126                                 + method.substring(1), // Title\r
127                                 this.xUnit.toString(), // x-axis Label\r
128                                 this.yUnit.toString(), // y-axis Label\r
129                                 dataset, PlotOrientation.VERTICAL, // Plot Orientation\r
130                                 false, // Show Legend\r
131                                 true, // Use tool tips\r
132                                 false // Configure chart to generate URLs?\r
133                                 );\r
134                 add(new ChartPanel(chart));\r
135         }\r
136         \r
137         public void addDomainMarker(Amount<X> x, String label, Color c){\r
138                 double xVal = x.doubleValue(xUnit);\r
139                 Marker marker = new ValueMarker(xVal);\r
140                 marker.setStroke(dashed);\r
141                 marker.setPaint(c);\r
142                 marker.setLabelPaint(c);\r
143                 marker.setLabelFont(labelFont);\r
144                 marker.setLabel(label + ": " + RocketScience.ammountToRoundedString(x));\r
145                 marker.setLabelTextAnchor(TextAnchor.TOP_LEFT);\r
146                 marker.setLabelOffset(new RectangleInsets(0, -5, 0, 0));\r
147                 chart.getXYPlot().addDomainMarker(marker);\r
148         }\r
149         \r
150         public void addRangeMarker(Amount<Y> y, String label, Color c){\r
151                 double yVal = y.doubleValue(yUnit);\r
152                 Marker marker = new ValueMarker(yVal);\r
153                 marker.setStroke(dashed);\r
154                 marker.setPaint(Color.BLACK);\r
155                 marker.setLabelFont(labelFont);\r
156                 marker.setLabel("Max: "\r
157                                 + RocketScience.ammountToRoundedString(Amount.valueOf(yVal,\r
158                                                 yUnit)));\r
159                 marker.setLabelTextAnchor(TextAnchor.TOP_LEFT);\r
160                 marker.setLabelOffset(new RectangleInsets(0, 5, 0, 0));\r
161                 chart.getXYPlot().addRangeMarker(marker);\r
162         }\r
163 \r
164         private Marker focusMarkerX, focusMarkerY;\r
165 \r
166         public void mark(Amount<X> m) {\r
167                 if (focusMarkerX != null)\r
168                         chart.getXYPlot().removeDomainMarker(focusMarkerX);\r
169                 if (focusMarkerY != null)\r
170                         chart.getXYPlot().removeRangeMarker(focusMarkerY);\r
171                 \r
172                 if (m != null) {\r
173                         focusMarkerX = new ValueMarker(m.doubleValue(xUnit));\r
174                         focusMarkerX.setPaint(Color.blue);\r
175                         focusMarkerX.setAlpha(0.8f);\r
176                         \r
177                         chart.getXYPlot().addDomainMarker(focusMarkerX);\r
178                         \r
179                         Amount<Y> val = getNear(m);\r
180                         if ( val != null ){\r
181                                 focusMarkerY = new ValueMarker(val.doubleValue(yUnit));\r
182                                 focusMarkerY.setPaint(Color.BLUE);\r
183                                 focusMarkerY.setLabelAnchor(RectangleAnchor.TOP_RIGHT);\r
184                                 focusMarkerY.setLabelTextAnchor(TextAnchor.TOP_RIGHT);\r
185                                 focusMarkerY.setLabelPaint(Color.BLUE);\r
186                                 focusMarkerY.setLabelFont(labelFont);\r
187                                 focusMarkerY.setLabelOffset(new RectangleInsets(0,5,0,0));\r
188                                 chart.getXYPlot().addRangeMarker(focusMarkerY);\r
189                                 focusMarkerY.setLabel(RocketScience.ammountToRoundedString(val));\r
190                         }\r
191                 }\r
192         }\r
193         \r
194         /**\r
195          * Get the Y value at or near a given X\r
196          * For display use only!\r
197          * \r
198          * @param ax\r
199          * @return\r
200          */\r
201         private Amount<Y> getNear(final Amount<X> ax){\r
202                 if ( dataset.getSeriesCount() != 1 )\r
203                         return null;\r
204                 final XYSeries s = dataset.getSeries(0);\r
205                 final double x = ax.doubleValue(xUnit);\r
206                 int idx = s.getItemCount() / 2;\r
207                 int delta = s.getItemCount() / 4;\r
208                 while(true){\r
209                         if ( s.getX(idx).doubleValue() < x ){\r
210                                 idx += delta;\r
211                         } else {\r
212                                 idx -= delta;\r
213                         }\r
214                         delta = delta / 2;\r
215                         if ( delta < 1 ){\r
216                                 int idxL = idx-1;\r
217                                 int idxH = idx;\r
218                                 final double lowerX = s.getX(idxL).doubleValue();\r
219                                 final double higherX = s.getX(idxH).doubleValue();\r
220                                 final double sampleXDiff = higherX - lowerX;\r
221                                 final double xDiff = x - lowerX;\r
222                                 final double dist = xDiff / sampleXDiff;\r
223                                 final double lowerY = s.getY(idxL).doubleValue();\r
224                                 final double higherY = s.getY(idxH).doubleValue();\r
225                                 final double y = lowerY + dist * (higherY - lowerY);\r
226                                 \r
227                                 return Amount.valueOf( y, yUnit);\r
228                         }\r
229                 }\r
230         }\r
231         \r
232         private void drawDone(){\r
233         \r
234         }\r
235 \r
236         private volatile boolean stop = false;\r
237         private volatile int lastSkipStepShown;\r
238         public void setDomain(final Iterable<Amount<X>> d) {\r
239                 chart.getXYPlot().clearDomainMarkers();\r
240                 chart.getXYPlot().clearRangeMarkers();\r
241                 lastSkipStepShown = Integer.MAX_VALUE;\r
242                 stop = true;\r
243                 fill(d, 100);\r
244                 fast.submit(new Thread() {\r
245                         public void run() {\r
246                                 if (!stop)\r
247                                         fill(d, 10);\r
248                                 slow.submit(new Thread() {\r
249                                         public void run() {\r
250                                                 if (!stop){\r
251                                                         fill(d, 1);\r
252                                                 }\r
253                                         }\r
254                                 });\r
255                         }\r
256                 });\r
257         }\r
258 \r
259         @SuppressWarnings("unchecked")\r
260         private synchronized void fill(Iterable<Amount<X>> d, final int requestedSkip) {\r
261                 log.debug(f.getName() + " " + requestedSkip + " Start");\r
262                 stop = false;\r
263                 int sz = 0;\r
264                 int calculatedSkip = requestedSkip;\r
265                 if (d instanceof Collection) {\r
266                         sz = ((Collection<Amount<X>>) d).size();\r
267                         int sk2 = sz / 200;\r
268                         if (calculatedSkip < sk2)\r
269                                 calculatedSkip = sk2;\r
270                 }\r
271                 // series.clear();\r
272                 int cnt = 0;\r
273 \r
274                 final XYSeries newSeries = new XYSeries(f.getName());\r
275                 try {\r
276                         Amount<X> last = null;\r
277                         for (Amount<X> ax : d) {\r
278                                 if (stop) {\r
279                                         log.debug(f.getName() + " " + calculatedSkip + " Abort");\r
280                                         return;\r
281                                 }\r
282                                 last = ax;\r
283                                 if (cnt % calculatedSkip == 0) {\r
284                                         Amount<Y> y = (Amount<Y>) f.invoke(source, ax);\r
285                                         newSeries.add(ax.doubleValue(xUnit), y.doubleValue(yUnit));\r
286                                 }\r
287                                 cnt++;\r
288                         }\r
289                         Amount<Y> y = (Amount<Y>) f.invoke(source, last);\r
290                         newSeries.add(last.doubleValue(xUnit), y.doubleValue(yUnit));\r
291                         SwingUtilities.invokeLater(new Thread() {\r
292                                 @Override\r
293                                 public void run() {\r
294                                         if ( requestedSkip < lastSkipStepShown ){\r
295                                                 lastSkipStepShown = requestedSkip;\r
296                                                 dataset.removeAllSeries();\r
297                                                 dataset.addSeries(newSeries);\r
298                                                 log.debug(f.getName() + " Replaced with " + requestedSkip);\r
299                                         }\r
300                                         if ( requestedSkip == 1 ){\r
301                                                 drawDone();\r
302                                         }\r
303                                 }\r
304                         });\r
305                 } catch (IllegalArgumentException e) {\r
306                         // TODO Auto-generated catch block\r
307                         e.printStackTrace();\r
308                 } catch (IllegalAccessException e) {\r
309                         // TODO Auto-generated catch block\r
310                         e.printStackTrace();\r
311                 } catch (InvocationTargetException e) {\r
312                         // TODO Auto-generated catch block\r
313                         e.printStackTrace();\r
314                 }\r
315                 log.debug(f.getName() + " " + calculatedSkip + " Done");\r
316         }\r
317 \r
318         public void show() {\r
319                 new JFrame() {\r
320                         private static final long serialVersionUID = 1L;\r
321                         {\r
322                                 setContentPane(Chart.this);\r
323                                 setSize(640, 480);\r
324                                 setDefaultCloseOperation(DISPOSE_ON_CLOSE);\r
325                         }\r
326                 }.setVisible(true);\r
327         }\r
328 \r
329         public static void main(String args[]) throws Exception {\r
330                 CoredCylindricalGrain g = new CoredCylindricalGrain();\r
331                 g.setLength(Amount.valueOf(70, SI.MILLIMETER));\r
332                 g.setOD(Amount.valueOf(30, SI.MILLIMETER));\r
333                 g.setID(Amount.valueOf(10, SI.MILLIMETER));\r
334 \r
335                 Chart<Length, Area> c = new Chart<Length, Area>(SI.MILLIMETER,\r
336                                 SI.MILLIMETER.pow(2).asType(Area.class), g, "surfaceArea");\r
337 \r
338                 c.setDomain(c.new IntervalDomain(Amount.valueOf(0, SI.CENTIMETER), g\r
339                                 .webThickness()));\r
340 \r
341                 c.show();\r
342 \r
343                 Chart<Length, Volume> v = new Chart<Length, Volume>(SI.MILLIMETER,\r
344                                 SI.MILLIMETER.pow(3).asType(Volume.class), g, "volume");\r
345 \r
346                 v.setDomain(c.new IntervalDomain(Amount.valueOf(0, SI.CENTIMETER), g\r
347                                 .webThickness()));\r
348 \r
349                 v.show();\r
350         }\r
351 \r
352 }\r