27c71b4c633e3bdd3754e3208054dce6822bbee6
[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(c);\r
155                 marker.setLabelPaint(c);\r
156                 marker.setLabelFont(labelFont);\r
157                 marker.setLabel(label + ": " + RocketScience.ammountToRoundedString(y));\r
158                 marker.setLabelTextAnchor(TextAnchor.TOP_LEFT);\r
159                 marker.setLabelOffset(new RectangleInsets(0, 5, 0, 0));\r
160                 chart.getXYPlot().addRangeMarker(marker);\r
161         }\r
162 \r
163         private Marker focusMarkerX, focusMarkerY;\r
164 \r
165         public void mark(Amount<X> m) {\r
166                 if (focusMarkerX != null)\r
167                         chart.getXYPlot().removeDomainMarker(focusMarkerX);\r
168                 if (focusMarkerY != null)\r
169                         chart.getXYPlot().removeRangeMarker(focusMarkerY);\r
170                 \r
171                 if (m != null) {\r
172                         focusMarkerX = new ValueMarker(m.doubleValue(xUnit));\r
173                         focusMarkerX.setPaint(Color.blue);\r
174                         focusMarkerX.setAlpha(0.8f);\r
175                         \r
176                         chart.getXYPlot().addDomainMarker(focusMarkerX);\r
177                         \r
178                         Amount<Y> val = getNear(m);\r
179                         if ( val != null ){\r
180                                 focusMarkerY = new ValueMarker(val.doubleValue(yUnit));\r
181                                 focusMarkerY.setPaint(Color.BLUE);\r
182                                 focusMarkerY.setLabelAnchor(RectangleAnchor.TOP_RIGHT);\r
183                                 focusMarkerY.setLabelTextAnchor(TextAnchor.TOP_RIGHT);\r
184                                 focusMarkerY.setLabelPaint(Color.BLUE);\r
185                                 focusMarkerY.setLabelFont(labelFont);\r
186                                 focusMarkerY.setLabelOffset(new RectangleInsets(0,5,0,0));\r
187                                 chart.getXYPlot().addRangeMarker(focusMarkerY);\r
188                                 focusMarkerY.setLabel(RocketScience.ammountToRoundedString(val));\r
189                         }\r
190                 }\r
191         }\r
192         \r
193         /**\r
194          * Get the Y value at or near a given X\r
195          * For display use only!\r
196          * \r
197          * @param ax\r
198          * @return\r
199          */\r
200         private Amount<Y> getNear(final Amount<X> ax){\r
201                 if ( dataset.getSeriesCount() != 1 )\r
202                         return null;\r
203                 final XYSeries s = dataset.getSeries(0);\r
204                 final double x = ax.doubleValue(xUnit);\r
205                 int idx = s.getItemCount() / 2;\r
206                 int delta = s.getItemCount() / 4;\r
207                 while(true){\r
208                         if ( s.getX(idx).doubleValue() < x ){\r
209                                 idx += delta;\r
210                         } else {\r
211                                 idx -= delta;\r
212                         }\r
213                         delta = delta / 2;\r
214                         if ( delta < 1 ){\r
215                                 int idxL = idx-1;\r
216                                 int idxH = idx;\r
217                                 final double lowerX = s.getX(idxL).doubleValue();\r
218                                 final double higherX = s.getX(idxH).doubleValue();\r
219                                 final double sampleXDiff = higherX - lowerX;\r
220                                 final double xDiff = x - lowerX;\r
221                                 final double dist = xDiff / sampleXDiff;\r
222                                 final double lowerY = s.getY(idxL).doubleValue();\r
223                                 final double higherY = s.getY(idxH).doubleValue();\r
224                                 final double y = lowerY + dist * (higherY - lowerY);\r
225                                 \r
226                                 return Amount.valueOf( y, yUnit);\r
227                         }\r
228                 }\r
229         }\r
230         \r
231         private void drawDone(){\r
232         \r
233         }\r
234 \r
235         private volatile boolean stop = false;\r
236         private volatile int lastSkipStepShown;\r
237         public void setDomain(final Iterable<Amount<X>> d) {\r
238                 chart.getXYPlot().clearDomainMarkers();\r
239                 chart.getXYPlot().clearRangeMarkers();\r
240                 lastSkipStepShown = Integer.MAX_VALUE;\r
241                 stop = true;\r
242                 fill(d, 100);\r
243                 fast.submit(new Thread() {\r
244                         public void run() {\r
245                                 if (!stop)\r
246                                         fill(d, 10);\r
247                                 slow.submit(new Thread() {\r
248                                         public void run() {\r
249                                                 if (!stop){\r
250                                                         fill(d, 1);\r
251                                                 }\r
252                                         }\r
253                                 });\r
254                         }\r
255                 });\r
256         }\r
257 \r
258         @SuppressWarnings("unchecked")\r
259         private synchronized void fill(Iterable<Amount<X>> d, final int requestedSkip) {\r
260                 log.debug(f.getName() + " " + requestedSkip + " Start");\r
261                 stop = false;\r
262                 int sz = 0;\r
263                 int calculatedSkip = requestedSkip;\r
264                 if (d instanceof Collection) {\r
265                         sz = ((Collection<Amount<X>>) d).size();\r
266                         int sk2 = sz / 200;\r
267                         if (calculatedSkip < sk2)\r
268                                 calculatedSkip = sk2;\r
269                 }\r
270                 // series.clear();\r
271                 int cnt = 0;\r
272 \r
273                 final XYSeries newSeries = new XYSeries(f.getName());\r
274                 try {\r
275                         Amount<X> last = null;\r
276                         for (Amount<X> ax : d) {\r
277                                 if (stop) {\r
278                                         log.debug(f.getName() + " " + calculatedSkip + " Abort");\r
279                                         return;\r
280                                 }\r
281                                 last = ax;\r
282                                 if (cnt % calculatedSkip == 0) {\r
283                                         Amount<Y> y = (Amount<Y>) f.invoke(source, ax);\r
284                                         newSeries.add(ax.doubleValue(xUnit), y.doubleValue(yUnit));\r
285                                 }\r
286                                 cnt++;\r
287                         }\r
288                         Amount<Y> y = (Amount<Y>) f.invoke(source, last);\r
289                         newSeries.add(last.doubleValue(xUnit), y.doubleValue(yUnit));\r
290                         SwingUtilities.invokeLater(new Thread() {\r
291                                 @Override\r
292                                 public void run() {\r
293                                         if ( requestedSkip < lastSkipStepShown ){\r
294                                                 lastSkipStepShown = requestedSkip;\r
295                                                 dataset.removeAllSeries();\r
296                                                 dataset.addSeries(newSeries);\r
297                                                 log.debug(f.getName() + " Replaced with " + requestedSkip);\r
298                                         }\r
299                                         if ( requestedSkip == 1 ){\r
300                                                 drawDone();\r
301                                         }\r
302                                 }\r
303                         });\r
304                 } catch (IllegalArgumentException e) {\r
305                         // TODO Auto-generated catch block\r
306                         e.printStackTrace();\r
307                 } catch (IllegalAccessException e) {\r
308                         // TODO Auto-generated catch block\r
309                         e.printStackTrace();\r
310                 } catch (InvocationTargetException e) {\r
311                         // TODO Auto-generated catch block\r
312                         e.printStackTrace();\r
313                 }\r
314                 log.debug(f.getName() + " " + calculatedSkip + " Done");\r
315         }\r
316 \r
317         public void show() {\r
318                 new JFrame() {\r
319                         private static final long serialVersionUID = 1L;\r
320                         {\r
321                                 setContentPane(Chart.this);\r
322                                 setSize(640, 480);\r
323                                 setDefaultCloseOperation(DISPOSE_ON_CLOSE);\r
324                         }\r
325                 }.setVisible(true);\r
326         }\r
327 \r
328         public static void main(String args[]) throws Exception {\r
329                 CoredCylindricalGrain g = new CoredCylindricalGrain();\r
330                 g.setLength(Amount.valueOf(70, SI.MILLIMETER));\r
331                 g.setOD(Amount.valueOf(30, SI.MILLIMETER));\r
332                 g.setID(Amount.valueOf(10, SI.MILLIMETER));\r
333 \r
334                 Chart<Length, Area> c = new Chart<Length, Area>(SI.MILLIMETER,\r
335                                 SI.MILLIMETER.pow(2).asType(Area.class), g, "surfaceArea");\r
336 \r
337                 c.setDomain(c.new IntervalDomain(Amount.valueOf(0, SI.CENTIMETER), g\r
338                                 .webThickness()));\r
339 \r
340                 c.show();\r
341 \r
342                 Chart<Length, Volume> v = new Chart<Length, Volume>(SI.MILLIMETER,\r
343                                 SI.MILLIMETER.pow(3).asType(Volume.class), g, "volume");\r
344 \r
345                 v.setDomain(c.new IntervalDomain(Amount.valueOf(0, SI.CENTIMETER), g\r
346                                 .webThickness()));\r
347 \r
348                 v.show();\r
349         }\r
350 \r
351 }\r