1 package com.billkuker.rocketry.motorsim.visual;
\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.awt.Toolkit;
\r
9 import java.awt.datatransfer.StringSelection;
\r
10 import java.awt.event.ActionEvent;
\r
11 import java.awt.event.ActionListener;
\r
12 import java.lang.reflect.InvocationTargetException;
\r
13 import java.lang.reflect.Method;
\r
14 import java.util.Collection;
\r
15 import java.util.Iterator;
\r
16 import java.util.concurrent.ExecutorService;
\r
17 import java.util.concurrent.Executors;
\r
18 import java.util.concurrent.ThreadFactory;
\r
20 import javax.measure.quantity.Area;
\r
21 import javax.measure.quantity.Length;
\r
22 import javax.measure.quantity.Quantity;
\r
23 import javax.measure.unit.SI;
\r
24 import javax.measure.unit.Unit;
\r
25 import javax.swing.JFrame;
\r
26 import javax.swing.JMenuItem;
\r
27 import javax.swing.JPanel;
\r
28 import javax.swing.SwingUtilities;
\r
30 import org.apache.log4j.Logger;
\r
31 import org.jfree.chart.ChartFactory;
\r
32 import org.jfree.chart.ChartPanel;
\r
33 import org.jfree.chart.JFreeChart;
\r
34 import org.jfree.chart.plot.Marker;
\r
35 import org.jfree.chart.plot.PlotOrientation;
\r
36 import org.jfree.chart.plot.ValueMarker;
\r
37 import org.jfree.data.xy.XYSeries;
\r
38 import org.jfree.data.xy.XYSeriesCollection;
\r
39 import org.jfree.ui.RectangleAnchor;
\r
40 import org.jfree.ui.RectangleInsets;
\r
41 import org.jfree.ui.TextAnchor;
\r
42 import org.jscience.physics.amount.Amount;
\r
44 import com.billkuker.rocketry.motorsim.RocketScience;
\r
45 import com.billkuker.rocketry.motorsim.grain.CoredCylindricalGrain;
\r
47 public class Chart<X extends Quantity, Y extends Quantity> extends JPanel implements RocketScience.UnitPreferenceListener {
\r
48 private static final long serialVersionUID = 1L;
\r
49 private static Logger log = Logger.getLogger(Chart.class);
\r
51 private final Stroke dashed = new BasicStroke(1, 1, 1, 1, new float[]{2,4}, 0);
\r
52 private final Font labelFont = new Font(Font.DIALOG, Font.BOLD, 10);
\r
54 private static ThreadFactory fastTF = new ThreadFactory() {
\r
55 public Thread newThread(Runnable r) {
\r
56 Thread t = new Thread(r);
\r
58 t.setName("Fast Chart Draw");
\r
62 private static ThreadFactory slowTF = new ThreadFactory() {
\r
63 public Thread newThread(Runnable r) {
\r
64 Thread t = new Thread(r);
\r
66 t.setName("Slow Chart Draw");
\r
70 private static ExecutorService fast = Executors.newFixedThreadPool(2, fastTF);
\r
71 private static ExecutorService slow = Executors.newFixedThreadPool(2, slowTF);
\r
74 public class IntervalDomain implements Iterable<Amount<X>> {
\r
76 Amount<X> low, high, delta;
\r
79 public IntervalDomain(Amount<X> low, Amount<X> high) {
\r
82 delta = high.minus(low).divide(steps);
\r
85 public IntervalDomain(Amount<X> low, Amount<X> high, int steps) {
\r
89 delta = high.minus(low).divide(steps);
\r
92 public Iterator<Amount<X>> iterator() {
\r
93 return new Iterator<Amount<X>>() {
\r
94 Amount<X> current = low;
\r
96 public boolean hasNext() {
\r
97 return current.isLessThan(high.plus(delta));
\r
100 public Amount<X> next() {
\r
101 Amount<X> ret = current;
\r
102 current = current.plus(delta);
\r
106 public final void remove() {
\r
107 throw new UnsupportedOperationException(
\r
108 "Chart domain iterators are not modifiable.");
\r
115 XYSeriesCollection dataset = new XYSeriesCollection();
\r
124 Iterable<Amount<X>> domain;
\r
126 public Chart(Unit<X> xUnit, Unit<Y> yUnit, Object source, String method)
\r
127 throws NoSuchMethodException {
\r
128 super(new BorderLayout());
\r
129 f = source.getClass().getMethod(method, Amount.class);
\r
131 this.source = source;
\r
133 this.xUnit = xUnit;
\r
134 this.yUnit = yUnit;
\r
136 RocketScience.addUnitPreferenceListener(this);
\r
141 private void setup(){
\r
143 this.xUnit = RocketScience.UnitPreference.getUnitPreference()
\r
144 .getPreferredUnit(xUnit);
\r
145 this.yUnit = RocketScience.UnitPreference.getUnitPreference()
\r
146 .getPreferredUnit(yUnit);
\r
148 chart = ChartFactory.createXYLineChart(f.getName().substring(0, 1)
\r
150 + f.getName().substring(1), // Title
\r
151 this.xUnit.toString(), // x-axis Label
\r
152 this.yUnit.toString(), // y-axis Label
\r
153 dataset, PlotOrientation.VERTICAL, // Plot Orientation
\r
154 false, // Show Legend
\r
155 true, // Use tool tips
\r
156 false // Configure chart to generate URLs?
\r
158 ChartPanel cp = new ChartPanel(chart);
\r
159 cp.getPopupMenu().add(new JMenuItem("Copy CSV to Clipboard") {
\r
160 private static final long serialVersionUID = 1L;
\r
162 addActionListener(new ActionListener() {
\r
164 public void actionPerformed(ActionEvent ae) {
\r
165 XYSeries s = dataset.getSeries(0);
\r
166 StringBuilder sb = new StringBuilder();
\r
167 sb.append(f.getName().substring(0, 1).toUpperCase()
\r
168 + f.getName().substring(1));
\r
170 sb.append(Chart.this.xUnit.toString());
\r
172 sb.append(Chart.this.yUnit.toString());
\r
174 for (int i = 0; i < s.getItemCount(); i++) {
\r
175 sb.append(s.getX(i));
\r
177 sb.append(s.getY(i));
\r
180 Toolkit.getDefaultToolkit()
\r
181 .getSystemClipboard()
\r
183 new StringSelection(sb.toString()),
\r
194 public void preferredUnitsChanged() {
\r
201 public void addDomainMarker(Amount<X> x, String label, Color c){
\r
202 double xVal = x.doubleValue(xUnit);
\r
203 Marker marker = new ValueMarker(xVal);
\r
204 marker.setStroke(dashed);
\r
205 marker.setPaint(c);
\r
206 marker.setLabelPaint(c);
\r
207 marker.setLabelFont(labelFont);
\r
208 marker.setLabel(label + ": " + RocketScience.ammountToRoundedString(x));
\r
209 marker.setLabelTextAnchor(TextAnchor.TOP_LEFT);
\r
210 marker.setLabelOffset(new RectangleInsets(0, -5, 0, 0));
\r
211 chart.getXYPlot().addDomainMarker(marker);
\r
214 public void addRangeMarker(Amount<Y> y, String label, Color c){
\r
215 double yVal = y.doubleValue(yUnit);
\r
216 Marker marker = new ValueMarker(yVal);
\r
217 marker.setStroke(dashed);
\r
218 marker.setPaint(c);
\r
219 marker.setLabelPaint(c);
\r
220 marker.setLabelFont(labelFont);
\r
221 marker.setLabel(label + ": " + RocketScience.ammountToRoundedString(y));
\r
222 marker.setLabelTextAnchor(TextAnchor.TOP_LEFT);
\r
223 marker.setLabelOffset(new RectangleInsets(0, 5, 0, 0));
\r
224 chart.getXYPlot().addRangeMarker(marker);
\r
227 private Marker focusMarkerX, focusMarkerY;
\r
229 public void mark(Amount<X> m) {
\r
230 if (focusMarkerX != null)
\r
231 chart.getXYPlot().removeDomainMarker(focusMarkerX);
\r
232 if (focusMarkerY != null)
\r
233 chart.getXYPlot().removeRangeMarker(focusMarkerY);
\r
236 focusMarkerX = new ValueMarker(m.doubleValue(xUnit));
\r
237 focusMarkerX.setPaint(Color.blue);
\r
238 focusMarkerX.setAlpha(0.8f);
\r
240 chart.getXYPlot().addDomainMarker(focusMarkerX);
\r
242 Amount<Y> val = getNear(m);
\r
243 if ( val != null ){
\r
244 focusMarkerY = new ValueMarker(val.doubleValue(yUnit));
\r
245 focusMarkerY.setPaint(Color.BLUE);
\r
246 focusMarkerY.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
\r
247 focusMarkerY.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
\r
248 focusMarkerY.setLabelPaint(Color.BLUE);
\r
249 focusMarkerY.setLabelFont(labelFont);
\r
250 focusMarkerY.setLabelOffset(new RectangleInsets(0,5,0,0));
\r
251 chart.getXYPlot().addRangeMarker(focusMarkerY);
\r
252 focusMarkerY.setLabel(RocketScience.ammountToRoundedString(val));
\r
258 * Get the Y value at or near a given X
\r
259 * For display use only!
\r
264 private Amount<Y> getNear(final Amount<X> ax){
\r
265 if ( dataset.getSeriesCount() != 1 )
\r
267 final XYSeries s = dataset.getSeries(0);
\r
268 final double x = ax.doubleValue(xUnit);
\r
269 int idx = s.getItemCount() / 2;
\r
270 int delta = s.getItemCount() / 4;
\r
272 if ( s.getX(idx).doubleValue() < x ){
\r
281 final double lowerX = s.getX(idxL).doubleValue();
\r
282 final double higherX = s.getX(idxH).doubleValue();
\r
283 final double sampleXDiff = higherX - lowerX;
\r
284 final double xDiff = x - lowerX;
\r
285 final double dist = xDiff / sampleXDiff;
\r
286 final double lowerY = s.getY(idxL).doubleValue();
\r
287 final double higherY = s.getY(idxH).doubleValue();
\r
288 final double y = lowerY + dist * (higherY - lowerY);
\r
290 return Amount.valueOf( y, yUnit);
\r
295 private void drawDone(){
\r
299 private volatile boolean stop = false;
\r
300 private volatile int lastSkipStepShown;
\r
301 public void setDomain(final Iterable<Amount<X>> d) {
\r
302 chart.getXYPlot().clearDomainMarkers();
\r
303 chart.getXYPlot().clearRangeMarkers();
\r
304 lastSkipStepShown = Integer.MAX_VALUE;
\r
307 fast.submit(new Thread() {
\r
308 public void run() {
\r
311 slow.submit(new Thread() {
\r
312 public void run() {
\r
322 @SuppressWarnings("unchecked")
\r
323 private synchronized void fill(Iterable<Amount<X>> d, final int requestedSkip) {
\r
326 log.debug(f.getName() + " " + requestedSkip + " Start");
\r
329 int calculatedSkip = requestedSkip;
\r
330 if (d instanceof Collection) {
\r
331 sz = ((Collection<Amount<X>>) d).size();
\r
332 int sk2 = sz / 200;
\r
333 if (calculatedSkip < sk2)
\r
334 calculatedSkip = sk2;
\r
339 final XYSeries newSeries = new XYSeries(f.getName());
\r
341 Amount<X> last = null;
\r
342 for (Amount<X> ax : d) {
\r
344 log.debug(f.getName() + " " + calculatedSkip + " Abort");
\r
348 if (cnt % calculatedSkip == 0) {
\r
349 Amount<Y> y = (Amount<Y>) f.invoke(source, ax);
\r
350 newSeries.add(ax.doubleValue(xUnit), y.doubleValue(yUnit));
\r
354 Amount<Y> y = (Amount<Y>) f.invoke(source, last);
\r
355 newSeries.add(last.doubleValue(xUnit), y.doubleValue(yUnit));
\r
356 SwingUtilities.invokeLater(new Thread() {
\r
358 public void run() {
\r
359 if ( requestedSkip < lastSkipStepShown ){
\r
360 lastSkipStepShown = requestedSkip;
\r
361 dataset.removeAllSeries();
\r
362 dataset.addSeries(newSeries);
\r
363 log.debug(f.getName() + " Replaced with " + requestedSkip);
\r
365 if ( requestedSkip == 1 ){
\r
370 } catch (IllegalArgumentException e) {
\r
372 } catch (IllegalAccessException e) {
\r
374 } catch (InvocationTargetException e) {
\r
377 log.debug(f.getName() + " " + calculatedSkip + " Done");
\r
380 public void show() {
\r
382 private static final long serialVersionUID = 1L;
\r
384 setContentPane(Chart.this);
\r
386 setDefaultCloseOperation(EXIT_ON_CLOSE);
\r
388 }.setVisible(true);
\r
391 public static void main(String args[]) throws Exception {
\r
392 CoredCylindricalGrain g = new CoredCylindricalGrain();
\r
393 g.setLength(Amount.valueOf(70, SI.MILLIMETER));
\r
394 g.setOD(Amount.valueOf(30, SI.MILLIMETER));
\r
395 g.setID(Amount.valueOf(10, SI.MILLIMETER));
\r
397 Chart<Length, Area> c = new Chart<Length, Area>(SI.MILLIMETER,
\r
398 SI.MILLIMETER.pow(2).asType(Area.class), g, "surfaceArea");
\r
400 c.setDomain(c.new IntervalDomain(Amount.valueOf(0, SI.CENTIMETER), g
\r
406 Chart<Length, Volume> v = new Chart<Length, Volume>(SI.MILLIMETER,
\r
407 SI.MILLIMETER.pow(3).asType(Volume.class), g, "volume");
\r
409 v.setDomain(c.new IntervalDomain(Amount.valueOf(0, SI.CENTIMETER), g
\r