001/**
002 * EvaluationResultGUI.java
003 * jCOLIBRI2 framework. 
004 * @author Juan A. Recio-Garc�a.
005 * GAIA - Group for Artificial Intelligence Applications
006 * http://gaia.fdi.ucm.es
007 * 07/05/2007
008 */
009package es.ucm.fdi.gaia.jcolibri.evaluation.tools;
010
011import java.awt.BorderLayout;
012import java.awt.Dimension;
013import java.awt.FileDialog;
014import java.awt.event.ActionEvent;
015import java.awt.event.ActionListener;
016import java.awt.event.WindowAdapter;
017import java.awt.event.WindowEvent;
018import java.io.File;
019import java.io.IOException;
020import java.io.PrintWriter;
021import java.util.Vector;
022
023import javax.swing.Box;
024import javax.swing.BoxLayout;
025import javax.swing.JButton;
026import javax.swing.JFrame;
027import javax.swing.JLabel;
028import javax.swing.JPanel;
029import javax.swing.JScrollPane;
030import javax.swing.JTextArea;
031
032import org.apache.commons.lang.ArrayUtils;
033import org.knowm.xchart.BitmapEncoder;
034import org.knowm.xchart.BitmapEncoder.BitmapFormat;
035import org.knowm.xchart.VectorGraphicsEncoder;
036import org.knowm.xchart.VectorGraphicsEncoder.VectorGraphicsFormat;
037import org.knowm.xchart.XChartPanel;
038import org.knowm.xchart.XYChart;
039import org.knowm.xchart.XYChartBuilder;
040import org.knowm.xchart.XYSeries.XYSeriesRenderStyle;
041import org.knowm.xchart.style.Styler;
042import org.knowm.xchart.style.Styler.LegendPosition;
043
044import es.ucm.fdi.gaia.jcolibri.evaluation.EvaluationReport;
045
046/**
047 * Class that visualizates the result of an evaluation in a Swing frame.
048 * It generates a chart with the evaluation result an other information returned by the evaluator.
049 * 
050 * @author Juan A. Recio-Garcia
051 *
052 */
053public class EvaluationResultGUI
054{
055    
056    private static XYChart chart;
057    private static JFrame dialog;
058    private static EvaluationReport evalReport; 
059    
060    public static void show(EvaluationReport er, String title, boolean exitOnClose)
061    {
062        evalReport = er;
063        
064       dialog = new JFrame();
065       dialog.setTitle("jCOLIBRI Evaluation");
066       dialog.getContentPane().setLayout(new BorderLayout());
067       
068       JPanel data = new JPanel();
069       data.setLayout(new BoxLayout(data,BoxLayout.X_AXIS));
070       data.add(new JLabel("Cycles: "+ er.getNumberOfCycles()));
071       data.add(Box.createGlue());
072       data.add(new JLabel("Time: "+ er.getTotalTime()+" ms"));
073       data.add(Box.createGlue());
074       data.add(new JLabel("Time per cycle: "+ er.getTimePerCycle()+" ms"));
075       //data.add(Box.createGlue());
076       //data.add( new JLabel("Average: "+ String.format("%6f",er.getEvaluationAverage())));
077       dialog.getContentPane().add(data,BorderLayout.NORTH);
078
079       chart = getChart(title, er);
080       
081       JTextArea textArea = new JTextArea();
082       JScrollPane sp = new JScrollPane(textArea);
083       sp.setViewportView(textArea);
084       textArea.setText(er.toString());
085       textArea.setEditable(false);
086       XChartPanel<XYChart> xcpanel = new XChartPanel<XYChart>(chart);
087       dialog.getContentPane().add(xcpanel, BorderLayout.CENTER);
088       
089       JPanel buttons = new JPanel();
090       //buttons.setLayout(new BoxLayout(buttons,BoxLayout.X_AXIS));
091       JButton exportData = new JButton("Export data");
092       exportData.addActionListener( new ActionListener(){
093            public void actionPerformed(ActionEvent e)
094            {
095                try{
096                    FileDialog fd = new FileDialog(dialog, "Save as CSV", FileDialog.SAVE);
097                    fd.setFile("evaluation.csv");
098                    fd.setVisible(true);
099                    String name = fd.getDirectory() + fd.getFile();
100                    File file = new File(name);
101                    saveEvaluationToCSV(evalReport, file);
102                }
103                catch(Exception ex) { 
104                    ex.printStackTrace(); 
105                }                
106            }
107           
108       });
109       
110       
111       JButton exportChart = new JButton("Export as PNG");
112       exportChart.addActionListener( new ActionListener(){
113            public void actionPerformed(ActionEvent e) {
114                try{
115                    FileDialog fd = new FileDialog(dialog, "Save as PNG", FileDialog.SAVE);
116                    fd.setFile("evaluation.png");
117                    fd.setVisible(true);
118                    String name = fd.getDirectory() + fd.getFile();
119                    File file = new File(name);
120                    BitmapEncoder.saveBitmap(chart, file.getCanonicalPath(), BitmapFormat.PNG);
121                }
122                catch(Exception ex) { 
123                    ex.printStackTrace(); 
124                }
125            }
126       });
127
128       JButton exportChartVector = new JButton("Export as EPS");
129       exportChartVector.addActionListener( new ActionListener(){
130            public void actionPerformed(ActionEvent e) {
131                try{
132                    FileDialog fd = new FileDialog(dialog, "Save as EPS", FileDialog.SAVE);
133                    fd.setFile("evaluation.eps");
134                    fd.setVisible(true);
135                    String name = fd.getDirectory() + fd.getFile();
136                    File file = new File(name);
137                    VectorGraphicsEncoder.saveVectorGraphic(chart, file.getCanonicalPath(), VectorGraphicsFormat.EPS);
138                }
139                catch(Exception ex) { 
140                    ex.printStackTrace(); 
141                }
142            }
143       });
144    
145       buttons.add(exportData);
146       buttons.add(exportChart);
147       buttons.add(exportChartVector);
148       
149       JPanel p = new JPanel();
150       p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
151       p.add(sp);
152       p.add(buttons);
153
154       
155       dialog.getContentPane().add(p, BorderLayout.SOUTH);
156
157       /*
158       dialog.addWindowListener(new WindowAdapter()
159       {  public void windowClosing(WindowEvent we)
160          {  System.exit(0);
161          }
162       });
163       */
164       dialog.setPreferredSize(new Dimension(800,600));
165       dialog.pack();
166       dialog.doLayout();
167       dialog.setVisible(true);
168
169       if(exitOnClose)
170           dialog.addWindowListener(new WindowAdapter() 
171           {   public void windowClosing(WindowEvent arg0) 
172               {   System.exit(0);
173               }
174           });
175    }
176    
177    private static XYChart getChart(String title, EvaluationReport er) {
178        // Create Chart
179        XYChart chart = new XYChartBuilder().title("Performance").xAxisTitle("Evaluation").yAxisTitle("Value").build();
180     
181        // Customize Chart
182        chart.getStyler().setLegendPosition(LegendPosition.OutsideS);
183        chart.getStyler().setDefaultSeriesRenderStyle(XYSeriesRenderStyle.Line);
184        chart.getStyler().setYAxisLabelAlignment(Styler.TextAlignment.Right);
185        chart.getStyler().setPlotMargin(0);
186        chart.getStyler().setPlotContentSize(.95);
187     
188        String[] labels = er.getSeriesLabels();
189        int lines = labels.length;
190        int lineSize = er.getSeries(labels[0]).size();
191        
192        double[] xAges = new double[lineSize];
193        for(int i=0; i<lineSize; i++) xAges[i] = i;
194        
195        for( int l=0; l<lines; l++)
196        {
197            Double[] line = er.getSeries(labels[l]).toArray(new Double[0]);
198            chart.addSeries(labels[l], xAges, ArrayUtils.toPrimitive(line));
199        }
200     
201        return chart;
202    }
203    
204/*    private static XYChart getChart(String title, EvaluationReport er) {
205
206        //<-- Begin Chart2D configuration -->
207
208        //Configure object properties
209        Object2DProperties object2DProps = new Object2DProperties();
210        object2DProps.setObjectTitleText (title);
211
212        //Configure chart properties
213        Chart2DProperties chart2DProps = new Chart2DProperties();
214        chart2DProps.setChartDataLabelsPrecision (-2);
215
216        //Configure legend properties
217        LegendProperties legendProps = new LegendProperties();
218        legendProps.setLegendExistence(true);
219        String[] labels = er.getSeriesLabels();
220        legendProps.setLegendLabelsTexts (labels);
221
222        //Configure graph chart properties
223        GraphChart2DProperties graphChart2DProps = new GraphChart2DProperties();
224        //String[] labelsAxisLabels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
225        graphChart2DProps.setLabelsAxisExistence(false); //setLabelsAxisLabelsTexts (labelsAxisLabels);
226        //graphChart2DProps.setLabelsAxisTitleText ("Iteration");
227        graphChart2DProps.setNumbersAxisTitleText ("Evaluation");
228        graphChart2DProps.setLabelsAxisTicksAlignment (GraphChart2DProperties.CENTERED);
229        //graphChart2DProps.setChartDatasetCustomGreatestValue(1);
230        //graphChart2DProps.setChartDatasetCustomizeGreatestValue(true);
231
232        //Configure graph properties
233        GraphProperties graphProps = new GraphProperties();
234        graphProps.setGraphBarsExistence (false);
235        graphProps.setGraphLinesExistence (true);
236        graphProps.setGraphLinesThicknessModel (2);
237        graphProps.setGraphLinesWithinCategoryOverlapRatio (1f);
238        graphProps.setGraphDotsExistence (false);
239        graphProps.setGraphDotsThicknessModel (4);
240        graphProps.setGraphDotsWithinCategoryOverlapRatio (1f);
241        graphProps.setGraphAllowComponentAlignment (true);
242        graphProps.setGraphOutlineComponentsExistence (true);
243
244        int lines = labels.length;
245        int lineSize = er.getSeries(labels[0]).size();
246        
247        //Configure dataset
248        Dataset dataset = new Dataset (lines, lineSize, 1);
249          
250        for( int l=0; l<lines; l++)
251        {
252            Vector<Double> line = er.getSeries(labels[l]);
253            for (int j = 0; j < dataset.getNumCats(); ++j) {
254                  dataset.set (l, j, 0, (float)line.get(j).floatValue());
255                }
256        }
257
258        //Configure graph component colors
259        MultiColorsProperties multiColorsProps = new MultiColorsProperties();
260
261        //Configure chart
262        LBChart2D chart2D = new LBChart2D();
263        chart2D.setObject2DProperties (object2DProps);
264        chart2D.setChart2DProperties (chart2DProps);
265        chart2D.setLegendProperties (legendProps);
266        chart2D.setGraphChart2DProperties (graphChart2DProps);
267        chart2D.addGraphProperties (graphProps);
268        chart2D.addDataset (dataset);
269        chart2D.addMultiColorsProperties (multiColorsProps);
270
271        //Optional validation:  Prints debug messages if invalid only.
272        if (!chart2D.validate (false)) chart2D.validate (true);
273
274        //<-- End Chart2D configuration -->
275
276        return chart2D;
277      }
278*/    
279
280     static void saveEvaluationToCSV(EvaluationReport er, File file) throws IOException{
281         PrintWriter pw = new PrintWriter(file);
282         pw.println("# Cycles: "+ er.getNumberOfCycles());
283         pw.println("# Time: "+ er.getTotalTime()+" ms");
284         pw.println("# Time per cycle: "+ er.getTimePerCycle()+" ms");
285         //pw.println("# Average: "+ String.format("%6f",er.getEvaluationAverage()));
286         
287         String[] labels = er.getSeriesLabels();
288         
289         for(int l = 0; l<labels.length; l++)
290         {
291             Vector<Double> res = er.getSeries(labels[l]);
292             pw.print(labels[l]);
293             for(int i=0; i<res.size(); i++)
294                 pw.print(";"+res.get(i));
295             pw.println();
296         }
297             
298         pw.close();
299     }
300          
301
302     
303}