From 00b6af14ff8d4f32e61c37281dce483fcf1b69b5 Mon Sep 17 00:00:00 2001 From: Fabian Becker Date: Fri, 22 Jun 2012 14:26:51 +0000 Subject: [PATCH] refs #23 Renamed StatsParameter to StatisticsParameter. Refactored code. Added comments. --- src/eva2/OptimizerRunnable.java | 2 +- src/eva2/gui/FunctionArea.java | 2207 +++++++++-------- src/eva2/gui/Plot.java | 4 +- .../go/operators/postprocess/PostProcess.java | 4 +- src/eva2/server/stat/AbstractStatistics.java | 16 +- src/eva2/server/stat/GenericStatistics.java | 345 +-- .../stat/InterfaceStatisticsParameter.java | 75 +- src/eva2/server/stat/StatisticsDummy.java | 10 +- src/eva2/server/stat/StatisticsParameter.java | 390 +++ .../server/stat/StatisticsStandalone.java | 12 +- src/eva2/server/stat/StatisticsWithGUI.java | 461 ++-- src/eva2/server/stat/StatsParameter.java | 419 ---- src/eva2/tools/StringSelection.java | 624 ++--- src/eva2/tools/chart2d/DArea.java | 2 +- 14 files changed, 2306 insertions(+), 2265 deletions(-) create mode 100644 src/eva2/server/stat/StatisticsParameter.java delete mode 100644 src/eva2/server/stat/StatsParameter.java diff --git a/src/eva2/OptimizerRunnable.java b/src/eva2/OptimizerRunnable.java index 162e8237..5c8db2b7 100644 --- a/src/eva2/OptimizerRunnable.java +++ b/src/eva2/OptimizerRunnable.java @@ -246,7 +246,7 @@ public class OptimizerRunnable implements Runnable { * @param outp */ public void setOutputTo(int outp) { - ((StatsParameter)proc.getStatistics().getStatisticsParameter()).setOutputTo(outp); + ((StatisticsParameter)proc.getStatistics().getStatisticsParameter()).setOutputTo(outp); } /** diff --git a/src/eva2/gui/FunctionArea.java b/src/eva2/gui/FunctionArea.java index cd2d6655..29c3b1ae 100644 --- a/src/eva2/gui/FunctionArea.java +++ b/src/eva2/gui/FunctionArea.java @@ -1,18 +1,16 @@ package eva2.gui; /* - * Title: EvA2 - * Description: - * Copyright: Copyright (c) 2003 - * Company: University of Tuebingen, Computer Architecture - * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 306 $ - * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ - * $Author: mkron $ + * Title: EvA2 Description: Copyright: Copyright (c) 2003 Company: University of + * Tuebingen, Computer Architecture @author Holger Ulmer, Felix Streichert, + * Hannes Planatscher @version: $Revision: 306 $ $Date: 2007-12-04 14:22:52 + * +0100 (Tue, 04 Dec 2007) $ $Author: mkron $ */ -/*==========================================================================* +/* + * ==========================================================================* * IMPORTS - *==========================================================================*/ + *========================================================================== + */ import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; @@ -49,143 +47,147 @@ import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.DPointSet; import eva2.tools.chart2d.ScaledBorder; +import java.util.logging.Logger; -/*==========================================================================* +/* + * ==========================================================================* * CLASS DECLARATION - *==========================================================================*/ + *========================================================================== + */ /** * */ public class FunctionArea extends DArea implements Serializable { - /** - * Generated serial version identifier. - */ - private static final long serialVersionUID = 1238444548498667204L; - private GraphPointSetLegend legendBox = null; - private ScaledBorder m_Border; - private DPointIcon m_CurrentPointIcon; - private JFileChooser m_FileChooser; - private boolean m_legend = true; - private boolean m_log = false; - private ArrayList m_PointSetContainer; - private InterfaceRefPointListener m_RefPointListener; - private int m_x; - /** - * - */ - private int m_y; + /** + * Generated serial version identifier. + */ + private static final long serialVersionUID = 1238444548498667204L; + private static final Logger LOGGER = Logger.getLogger(FunctionArea.class.getName()); + private GraphPointSetLegend legendBox = null; + private ScaledBorder scaledBorder; + private DPointIcon currentPointIcon; + private JFileChooser fileChooser; + private boolean legend = true; + private boolean log = false; + private ArrayList pointSetContainer; + private InterfaceRefPointListener refPointListener; + private int xPos; + /** + * + */ + private int yPos; + /** + * + */ + private boolean notifyNegLog = true; + /** + * Indicate whether graphs should be annotated with tool tips if pointed to + * with the mouse. + */ + private boolean doShowGraphToolTips = true; + /** + * Indicate whether graph legend entries should show their unique number. + */ + private boolean appendIndexInLegend = true; - /** - * - */ - private boolean notifyNegLog = true; + /** + * + */ + public FunctionArea() { + super(); + setToolTipText("Graph Info "); + } - /** - * Indicate whether graphs should be annotated with tool tips if pointed to - * with the mouse. - */ - private boolean doShowGraphToolTips = true; + /** + * + */ + public FunctionArea(String xname, String yname) { + this(); + setPreferredSize(new Dimension(600, 500)); + setVisibleRectangle(1, 1, 100000, 1000); + setAutoFocus(true); + setMinRectangle(0, 0, 1, 1); + setBackground(new Color(253, 253, 253)); // not quite white + // setAutoFocus(true); + scaledBorder = new ScaledBorder(); + scaledBorder.x_label = xname; // "App. " + Name + " func. calls"; + scaledBorder.y_label = yname; // "fitness"; + setBorder(scaledBorder); + setAutoGrid(true); + setGridVisible(true); + pointSetContainer = new ArrayList(20); + // new DMouseZoom( this ); + addPopup(); + repaint(); + notifyNegLog = true; + } - /** - * Indicate whether graph legend entries should show their unique number. - */ - private boolean appendIndexInLegend = true; + /* + * (non-Javadoc) + * + * @see javax.swing.JComponent#getToolTipText(java.awt.event.MouseEvent) + */ + @Override + public String getToolTipText(MouseEvent event) { + if (isShowGraphToolTips()) { + int gIndex = getNearestGraphIndex(event.getX(), event.getY()); + if (gIndex >= 0) { + StringBuffer sb = new StringBuffer(super.getToolTipText()); + sb.append(gIndex); + sb.append(": "); + sb.append(getGraphInfo(gIndex)); + return sb.toString(); + } else { + return null; + } + } else { + return null; + } + } - /** - * - */ - public FunctionArea() { - super(); - setToolTipText("Graph Info "); - } + /* + * (non-Javadoc) + * + * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent) + */ + @Override + public Point getToolTipLocation(MouseEvent event) { + if (isShowGraphToolTips()) { + int gIndex = getNearestGraphIndex(event.getX(), event.getY()); + if (gIndex >= 0) { + DPoint pt = ((GraphPointSet) (pointSetContainer.get(gIndex))).getMedPoint(); + Point pt2 = getDMeasures().getPoint(pt.x, pt.y); + pt2.x += (5 * (gIndex % 7)); // slight shift depending on index + // - easier distinction of very + // close graphs + pt2.y -= (10 + (gIndex % 3) * 5); + return pt2; + } else { + return null; + } + } else { + return null; + } + } - /** - * - */ - public FunctionArea(String xname, String yname) { - this(); - setPreferredSize(new Dimension(600, 500)); - setVisibleRectangle(1, 1, 100000, 1000); - setAutoFocus(true); - setMinRectangle(0, 0, 1, 1); - setBackground(new Color(253, 253, 253)); // not quite white - // setAutoFocus(true); - m_Border = new ScaledBorder(); - m_Border.x_label = xname; // "App. " + Name + " func. calls"; - m_Border.y_label = yname; // "fitness"; - setBorder(m_Border); - setAutoGrid(true); - setGridVisible(true); - m_PointSetContainer = new ArrayList(20); - // new DMouseZoom( this ); - addPopup(); - repaint(); - notifyNegLog = true; - } + /** + * + */ + public void addGraph(int GraphLabel_1, int GraphLabel_2, boolean forceAdd) { + getGraphPointSet(GraphLabel_1).addGraph(getGraphPointSet(GraphLabel_2), + this.getDMeasures(), forceAdd); + notifyNegLog = true; + } - /* - * (non-Javadoc) - * - * @see javax.swing.JComponent#getToolTipText(java.awt.event.MouseEvent) - */ - @Override - public String getToolTipText(MouseEvent event) { - if (isShowGraphToolTips()) { - int gIndex = getNearestGraphIndex(event.getX(), event.getY()); - if (gIndex >= 0) { - StringBuffer sb = new StringBuffer(super.getToolTipText()); - sb.append(gIndex); - sb.append(": "); - sb.append(getGraphInfo(gIndex)); - return sb.toString(); - } else - return null; - } else - return null; - } + public void addGraphPointSet(GraphPointSet d) { + this.pointSetContainer.add(d); + } - /* - * (non-Javadoc) - * - * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent) - */ - @Override - public Point getToolTipLocation(MouseEvent event) { - if (isShowGraphToolTips()) { - int gIndex = getNearestGraphIndex(event.getX(), event.getY()); - if (gIndex >= 0) { - DPoint pt = ((GraphPointSet) (m_PointSetContainer.get(gIndex))) - .getMedPoint(); - Point pt2 = getDMeasures().getPoint(pt.x, pt.y); - pt2.x += (5 * (gIndex % 7)); // slight shift depending on index - // - easier distinction of very - // close graphs - pt2.y -= (10 + (gIndex % 3) * 5); - return pt2; - } else - return null; - } else - return null; - } - - /** - * - */ - public void addGraph(int GraphLabel_1, int GraphLabel_2, boolean forceAdd) { - getGraphPointSet(GraphLabel_1).addGraph(getGraphPointSet(GraphLabel_2), - this.getDMeasures(), forceAdd); - notifyNegLog = true; - } - - public void addGraphPointSet(GraphPointSet d) { - this.m_PointSetContainer.add(d); - } - - /** - * Add a popup menu for displaying certain information. - */ - private void addPopup() { + /** + * Add a popup menu for displaying certain information. + */ + private void addPopup() { addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { @@ -193,13 +195,13 @@ public class FunctionArea extends DArea implements Serializable { // do nothing } else { JPopupMenu graphPopupMenu = new JPopupMenu(); - m_x = e.getX(); - m_y = e.getY(); + xPos = e.getX(); + yPos = e.getY(); addMenuItem(graphPopupMenu, "Rename graph", new ActionListener() { public void actionPerformed(ActionEvent ee) { - renameGraph(getNearestGraphIndex(FunctionArea.this.m_x, FunctionArea.this.m_y)); + renameGraph(getNearestGraphIndex(FunctionArea.this.xPos, FunctionArea.this.yPos)); } }); // General entries @@ -230,7 +232,7 @@ public class FunctionArea extends DArea implements Serializable { } }); - if (FunctionArea.this.m_PointSetContainer.size() > 0) { + if (FunctionArea.this.pointSetContainer.size() > 0) { addMenuItem(graphPopupMenu, "Recolor all graphs", new ActionListener() { @@ -240,19 +242,19 @@ public class FunctionArea extends DArea implements Serializable { }); } - if (m_RefPointListener != null) { - DPoint temp = getDMeasures().getDPoint(m_x, m_y); + if (refPointListener != null) { + DPoint temp = getDMeasures().getDPoint(xPos, yPos); addMenuItem(graphPopupMenu, "Select Reference Point:(" + temp.x + "/" + temp.y + ")", new ActionListener() { public void actionPerformed(ActionEvent ee) { DPoint temp = getDMeasures().getDPoint( - m_x, m_y); + xPos, yPos); double[] point = new double[2]; point[0] = temp.x; point[1] = temp.y; - m_RefPointListener.refPointGiven(point); + refPointListener.refPointGiven(point); } }); } @@ -273,15 +275,15 @@ public class FunctionArea extends DArea implements Serializable { new ActionListener() { public void actionPerformed(ActionEvent ee) { - removePoint(FunctionArea.this.m_x, - FunctionArea.this.m_y); + removePoint(FunctionArea.this.xPos, + FunctionArea.this.yPos); } }); if (point.getIcon() instanceof InterfaceSelectablePointIcon) { - m_CurrentPointIcon = point.getIcon(); - if (((InterfaceSelectablePointIcon) m_CurrentPointIcon).getSelectionListener() != null) { - AbstractEAIndividual indy = ((InterfaceSelectablePointIcon) m_CurrentPointIcon).getEAIndividual(); + currentPointIcon = point.getIcon(); + if (((InterfaceSelectablePointIcon) currentPointIcon).getSelectionListener() != null) { + AbstractEAIndividual indy = ((InterfaceSelectablePointIcon) currentPointIcon).getEAIndividual(); String selectTitle = indy.isMarked() ? " Deselect individual" : " Select individual"; addMenuItem(graphPopupMenu, selectTitle, @@ -289,27 +291,27 @@ public class FunctionArea extends DArea implements Serializable { public void actionPerformed( ActionEvent ee) { - ((InterfaceSelectablePointIcon) m_CurrentPointIcon).getSelectionListener().individualSelected( - ((InterfaceSelectablePointIcon) m_CurrentPointIcon).getEAIndividual()); + ((InterfaceSelectablePointIcon) currentPointIcon).getSelectionListener().individualSelected( + ((InterfaceSelectablePointIcon) currentPointIcon).getEAIndividual()); } }); } } if (point.getIcon() instanceof InterfaceDPointWithContent) { - m_CurrentPointIcon = point.getIcon(); + currentPointIcon = point.getIcon(); addMenuItem(graphPopupMenu, " Show individual", new ActionListener() { public void actionPerformed( ActionEvent ee) { - ((InterfaceDPointWithContent) m_CurrentPointIcon).showIndividual(); + ((InterfaceDPointWithContent) currentPointIcon).showIndividual(); } }); } } - if (FunctionArea.this.m_PointSetContainer.size() > 0) { // there + if (FunctionArea.this.pointSetContainer.size() > 0) { // there // is // at // least @@ -324,8 +326,8 @@ public class FunctionArea extends DArea implements Serializable { public void actionPerformed(ActionEvent ee) { DPoint temp = FunctionArea.this.getDMeasures().getDPoint( - FunctionArea.this.m_x, - FunctionArea.this.m_y); + FunctionArea.this.xPos, + FunctionArea.this.yPos); DPointIcon icon1 = new DPointIcon() { public DBorder getDBorder() { @@ -346,8 +348,8 @@ public class FunctionArea extends DArea implements Serializable { new ActionListener() { public void actionPerformed(ActionEvent ee) { - clearGraph(FunctionArea.this.m_x, - FunctionArea.this.m_y); + clearGraph(FunctionArea.this.xPos, + FunctionArea.this.yPos); } }); @@ -355,8 +357,8 @@ public class FunctionArea extends DArea implements Serializable { new ActionListener() { public void actionPerformed(ActionEvent ee) { - changeColorGraph(FunctionArea.this.m_x, - FunctionArea.this.m_y); + changeColorGraph(FunctionArea.this.xPos, + FunctionArea.this.yPos); } }); } @@ -366,943 +368,956 @@ public class FunctionArea extends DArea implements Serializable { }); } - /** - * Create an enabled menu item with given title and listener, add it to the - * menu and return it. - * - * @param menu - * @param title - * @param aListener - * @return - */ - private JMenuItem addMenuItem(JPopupMenu menu, String title, - ActionListener aListener) { - return addMenuItem(menu, title, aListener, true); - } - - /** - * Create a menu item with given title and listener, add it to the menu and - * return it. It may be enabled or disabled. - * - * @param menu - * @param title - * @param aListener - * @param enabled - * @return - */ - private JMenuItem addMenuItem(JPopupMenu menu, String title, - ActionListener aListener, boolean enabled) { - JMenuItem item = new JMenuItem(title); - // if (bgColor!=null) item.setForeground(bgColor); - item.addActionListener(aListener); - item.setEnabled(enabled); - menu.add(item); - return item; - } - - /** - * This method allows to add a selection listener to the PointIcon it should - * need more than one listener to this abstruse event - * - * @param a - * The selection listener - */ - public void addRefPointSelectionListener(InterfaceRefPointListener a) { - this.m_RefPointListener = a; - } - - /** - * - */ - public void changeColorGraph(int GraphLabel) { - getGraphPointSet(GraphLabel).incColor(); - repaint(); - } - - public void setColorByIndex(int graphLabel, int colorIndex) { - getGraphPointSet(graphLabel).setColorByIndex(colorIndex); - } - - /** - * - */ - public void changeColorGraph(int x, int y) { - int index = getNearestGraphIndex(x, y); - if (index == -1) - return; - int GraphLabel = ((GraphPointSet) (this.m_PointSetContainer.get(index))) - .getGraphLabel(); - changeColorGraph(GraphLabel); - updateLegend(); - } - - /** - * Re-color all graphs which are nonempty by their index. - * - */ - public void recolorAllGraphsByIndex() { - int index = 0; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - GraphPointSet gps = ((GraphPointSet) (this.m_PointSetContainer - .get(i))); - if (gps.getPointCount() > 0) { - gps.setColorByIndex(index); - index++; - } - } - updateLegend(); - } - - /** - * - * @return - */ - public boolean checkLoggable() { - double minY = Double.MAX_VALUE; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - DPointSet pSet = (m_PointSetContainer.get(i).getConnectedPointSet()); - if (pSet.getSize() > 0) - minY = Math.min(minY, pSet.getMinYVal()); - } - // if (TRACE) System.out.println("min is " + minY); - return (minY > 0); - } - - protected double getMinimalPositiveYValue() { - double minY = Double.MAX_VALUE; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - DPointSet pSet = (m_PointSetContainer.get(i).getConnectedPointSet()); - if (pSet.getSize() > 0) { - double tmpMinY = Math.min(minY, pSet.getMinPositiveYValue()); - if (tmpMinY > 0) - minY = tmpMinY; - } - } - return minY; - } - - protected boolean checkLogValidYValue(double x, double y, int graphLabel) { - if (y <= 0.0) { - if (m_log && notifyNegLog) { - System.err.println("Warning: trying to plot value (" + x + "/" - + y + ") with y <= 0 in logarithmic mode!"); - notifyNegLog = false; - } - return false; - } - return true; - } - - private String cleanBlanks(String str, Character rpl) { - return str.replace(' ', rpl); - } - - /** - * - */ - public void clearAll() { - this.removeAllDElements(); - for (int i = 0; i < m_PointSetContainer.size(); i++) - ((GraphPointSet) (m_PointSetContainer.get(i))).removeAllPoints(); - m_PointSetContainer.clear(); - if (getYScale() instanceof Exp) - setYScale(new Exp()); // to remove smallest seen value - notifyNegLog = true; - } - - /** - * - */ - public void clearGraph(int graphLabel) { - getGraphPointSet(graphLabel).removeAllPoints(); - m_PointSetContainer.remove(getGraphPointSet(graphLabel)); - if (getYScale() instanceof Exp) { - ((Exp) getYScale()).setMinValue(getMinimalPositiveYValue()); - } - repaint(); - notifyNegLog = true; - } - - /** - * - */ - public void clearGraph(int x, int y) { - int index = getNearestGraphIndex(x, y); - if (index == -1) - return; - int GraphLabel = ((GraphPointSet) (this.m_PointSetContainer.get(index))) - .getGraphLabel(); - clearGraph(GraphLabel); - updateLegend(); - } - - /** - * Reset the legend clearing all information. - */ - public void clearLegend() { - setLegend(null); - } - - /** - * - */ - protected void createFileChooser() { - m_FileChooser = new JFileChooser(new File("/resources")); - m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - } - - /** - * Plot a circle icon to the function area which is annotated with a char - * and a double value. - * - * @param c - * @param val - * @param position - * @param graphID - */ - public void drawCircle(char c, double val, double[] position, int graphID) { - drawCircle(c + "" + val, position, graphID); - } - - /** - * Plot a circle icon to the function area which is annotated with a char - * and a double value. - * - * @param c - * @param val - * @param position - */ - public void drawCircle(double val, double[] position, int graphID) { - drawCircle("" + val, position, graphID); - } - - public void drawCircle(String label, double xPos, double yPos, int graphID) { - double[] pos = new double[2]; - pos[0] = xPos; - pos[1] = yPos; - drawCircle(label, pos, graphID); - } - - /** - * Plot a circle icon to the function area which is annotated with a char - * and a double value. The color corresponds to the color of the graph with - * given ID - * - * @param label - * @param position - * @param graphID - */ - public void drawCircle(String label, double[] position, int graphID) { - drawIcon(new Chart2DDPointIconCircle(), label, position, graphID); - } - - /** - * Plot a circle icon to the function area which is annotated with a char - * and a double value. The color corresponds to the color of the graph with - * given ID - * - * @param label - * @param position - * @param graphID - */ - public void drawIcon(DPointIcon theIcon, String label, double[] position, - int graphID) { - DPointSet popRep; - popRep = new DPointSet(); - popRep.addDPoint(new DPoint(position[0], position[1])); - DPointIcon icon = new Chart2DDPointIconText(label); - ((Chart2DDPointIconText) icon).setIcon(theIcon); - ((Chart2DDPointIconText) icon).setColor(getGraphPointSet(graphID) - .getColor()); - popRep.setIcon(icon); - addDElement(popRep); - } - - // public void setConnectedPoint(double x, double y, int GraphLabel) { - // if (m_log == true && y <= 0.0) { - // // y = Double.MIN_VALUE; - // if (notifyNegLog) { - // System.err.println("Warning: trying to plot value (" + x + "/" + y + - // ") with y <= 0 in logarithmic mode! Setting y to " + 1e-30); - // notifyNegLog = false; - // } - // y = 1e-30; - // } - // getGraphPointSet(GraphLabel).addDPoint(x, y); - // - // } - - /** - * Plot an icon to the function area which is annotated with a char and a - * double value. The color corresponds to the color of the graph with given - * ID Icon types are 0: circle, 1: cross, otherwise: point. - * - * @param label - * @param position - * @param graphID - */ - public void drawIcon(int iconType, String label, double[] position, - int graphID) { - DPointIcon theIcon; - switch (iconType) { - case 0: - theIcon = new Chart2DDPointIconCircle(); - break; - case 1: - theIcon = new Chart2DDPointIconCross(); - break; - default: - case 2: - theIcon = new Chart2DDPointIconPoint(); - break; - } - drawIcon(theIcon, label, position, graphID); - } - - /** - * Draw a line with given start and end points. - * - * @param p1 - * @param p2 - */ - public void drawLine(double[] p1, double[] p2) { - DPointSet popRep = new DPointSet(); - popRep.setConnected(true); - popRep.addDPoint(new DPoint(p1[0], p1[1])); - popRep.addDPoint(new DPoint(p2[0], p2[1])); - addDElement(popRep); - } - - /** - * Export contained data to standard output. - * - */ - public void exportToAscii() { - exportToAscii((File) null); - } - - /** - * Export contained data to a file or to standard out if null is given. The - * given File will be overwritten! - * - * @param file - * a File instance or null to export to standard out - * @return true if the export succeeded, else false - */ - public boolean exportToAscii(File file) { - String[] s = null; - int maxSize = 0; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - // find maximum length of all point sets - if (m_PointSetContainer.get(i).getConnectedPointSet().getSize() > maxSize) { - maxSize = m_PointSetContainer.get(i).getConnectedPointSet().getSize(); - } - } - if (maxSize > 0) { // if there is any data, init string array and set x - // value column - s = new String[maxSize+1]; - for (int j = 0; j <= maxSize; j++) s[j] = ""; - } else { - System.err.println("Error: no data to export"); - return true; - } - for (int i = 0; i < m_PointSetContainer.size(); i++) { - if (m_PointSetContainer.get(i) instanceof GraphPointSet) { - GraphPointSet set = (GraphPointSet) m_PointSetContainer.get(i); - DPointSet pset = set.getConnectedPointSet(); - // add column names - s[0] = s[0] + " t " + cleanBlanks(set.getInfoString(), '_'); - for (int j = 1; j < s.length; j++) { // add column data of place - if ((j - 1) < pset.getSize()) - s[j] = s[j] + " " + pset.getDPoint(j - 1).x + " " + pset.getDPoint(j - 1).y; - else - s[j] += " ? ?"; // placeholder if no value in this set - } - } else - System.err.println("error in FunctionArea::exportToAscii"); - } - if (file == null) { - for (int j = 0; j < s.length; j++) { - System.out.println(s[j]); - } - return true; - } else - try { - PrintWriter out = new PrintWriter(new FileOutputStream(file)); - for (int j = 0; j < s.length; j++) - out.println(s[j]); - out.flush(); - out.close(); - return true; - } catch (Exception e) { - System.err.println("Error on data export:" + e.getMessage()); - return false; - } - } - - /** - * Export contained data to a file with a given String as prefix - * - * @param prefix - * file name prefix - * @return true if the export succeeded, else false - */ - public boolean exportToAscii(String prefix) { - SimpleDateFormat formatter = new SimpleDateFormat( - "E'_'yyyy.MM.dd'_'HH.mm.ss"); - String fname = prefix + "PlotExport_" + formatter.format(new Date()) - + ".txt"; - try { - File f = new File(fname); - f.createNewFile(); - return exportToAscii(f); - } catch (Exception e) { - System.err.println("Error:" + e.getMessage()); - return false; - } - - } - - /** - * This gives the number of graphs already plotted. - * - * @return - */ - public int getContainerSize() { - return m_PointSetContainer.size(); - } - - /** - * - * @param x - * @param y - * @return - */ - public String getGraphInfo(int x, int y) { - String ret = ""; - if ((m_PointSetContainer == null) || (m_PointSetContainer.size() == 0)) - return ret; - int minindex = getNearestGraphIndex(x, y); - if (minindex >= 0) - return ((GraphPointSet) (m_PointSetContainer.get(minindex))) - .getInfoString(); - else - return "none"; - } - - public String getGraphInfo(int graphIndex) { - String ret = ""; - if ((m_PointSetContainer == null) || (m_PointSetContainer.size() == 0)) - return ret; - - if (graphIndex >= 0 && (graphIndex < m_PointSetContainer.size())) - return ((GraphPointSet) (m_PointSetContainer.get(graphIndex))) - .getInfoString(); - else - return "none"; - } - - public Color getGraphColor(int graphIndex) { - if (graphIndex >= 0) - return m_PointSetContainer.get(graphIndex).getColor(); - else - return null; - } - - /** - * - * @param GraphLabel - * @return - */ - private GraphPointSet getGraphPointSet(int GraphLabel) { - // System.out.println("looping through " + m_PointSetContainer.size() + - // " point sets..."); - for (int i = 0; i < m_PointSetContainer.size(); i++) { - if (m_PointSetContainer.get(i) instanceof GraphPointSet) { - GraphPointSet xx = (GraphPointSet) (m_PointSetContainer.get(i)); - // System.out.println("looking at "+xx.getGraphLabel()); - if (xx.getGraphLabel() == GraphLabel) { - // System.out.println("match!"); - return xx; - } - } - } - // create new GraphPointSet - GraphPointSet NewPointSet = new GraphPointSet(GraphLabel, this); - // System.out.println("adding new point set " + GraphLabel); - // NewPointSet.setStroke(new BasicStroke( (float)1.0 )); - // addGraphPointSet(NewPointSet); already done within GraphPointSet!!! - return NewPointSet; - } - - /** - * - */ - private DPoint getNearestDPoint(int x, int y) { - // get index of nearest Graph - double distmin = 10000000; - DPoint ret = null; - DPoint point1 = getDMeasures().getDPoint(x, y); - DPoint point2 = null; - double dist = 0; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - if (m_PointSetContainer.get(i) instanceof GraphPointSet) { - GraphPointSet pointset = (GraphPointSet) (m_PointSetContainer - .get(i)); - point2 = pointset.getNearestDPoint(point1); - if (point2 == null) - continue; - dist = (point1.x - point2.x) * (point1.x - point2.x) - + (point1.y - point2.y) * (point1.y - point2.y); - // System.out.println("dist="+dist+"i="+i); - if (dist < distmin) { - distmin = dist; - ret = point2; - } - if ((dist == distmin) - && !(ret.getIcon() instanceof Chart2DDPointIconContent) - && !(ret.getIcon() instanceof InterfaceSelectablePointIcon)) { - distmin = dist; - ret = point2; - } - } - } - return ret; - } - - /** - * - * @param x - * @param y - * @return - */ - private int getNearestGraphIndex(int x, int y) { - // get index of nearest Graph - double distmin = 10000000; - int minindex = -1; - DPoint point1 = getDMeasures().getDPoint(x, y); - DPoint point2 = null; - double dist = 0; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - GraphPointSet pointset = m_PointSetContainer.get(i); - point2 = pointset.getNearestDPoint(point1); - if (point2 == null) - continue; - if (point1 == null) - System.err.println("point1 == null"); - - dist = (point1.x - point2.x) * (point1.x - point2.x) - + (point1.y - point2.y) * (point1.y - point2.y); - // System.out.println("dist="+dist+"i="+i); - if (dist < distmin) { - distmin = dist; - minindex = i; - } - } - return minindex; - } - - /** - * Returns the number of points within the graph of the given label. - * - * @param index - * @return - */ - public int getPointCount(int label) { - return getGraphPointSet(label).getPointCount(); - } - - /** - * This method returns the selection listener to the PointIcon - * - * @return InterfaceSelectionListener - */ - public InterfaceRefPointListener getRefPointSelectionListener() { - return this.m_RefPointListener; - } - - /** - * - */ - public boolean isStatisticsGraph(int x, int y) { - boolean ret = false; - if ((m_PointSetContainer == null) || (m_PointSetContainer.size() == 0)) - return ret; - int minindex = getNearestGraphIndex(x, y); - ret = ((GraphPointSet) (m_PointSetContainer.get(minindex))) - .isStatisticsGraph(); - return ret; - } - - /** - * Causes all PointSets to interupt the connected painting at the current - * position. - */ - public void jump() { - for (int i = 0; i < m_PointSetContainer.size(); i++) - ((GraphPointSet) (m_PointSetContainer.get(i))).jump(); - } - - @Override - public void paint(Graphics g) { - super.paint(g); - if (legendBox != null && m_legend) - legendBox.paintIn(g, m_Border.getInnerRect(this)); - } - - /** - * - * @return - */ - public DPointSet[] printPoints() { - DPointSet[] ret = new DPointSet[m_PointSetContainer.size()]; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - System.out.println(""); - System.out.println("GraphPointSet No " + i); - - ret[i] = ((GraphPointSet) m_PointSetContainer.get(i)).printPoints(); - } - return ret; - - } - - /** - * - * @param i - * @return - */ - public DPointSet printPoints(int i) { - // for (int i = 0; i < m_PointSetContainer.size();i++) { - System.out.println(""); - System.out.println("GraphPointSet No " + i); - - return ((GraphPointSet) m_PointSetContainer.get(i)).printPoints(); - // } - } - - /** - * - * @param x - * @param y - */ - public void removePoint(int x, int y) { - DPoint point = getNearestDPoint(x, y); - int index = getNearestGraphIndex(x, y); - if (index == -1 || point == null) - return; - GraphPointSet pointset = (GraphPointSet) (this.m_PointSetContainer - .get(index)); - pointset.removePoint(point); - } - - /** - * This method allows to remove the selection listener to the PointIcon - */ - public void removeRefPointSelectionListeners() { - this.m_RefPointListener = null; - } - - public void setConnectedPoint(double x, double y, int graphLabel) { - DFunction scF = getYScale(); - if (scF instanceof Exp) - ((Exp) scF).updateMinValue(y); - if (!checkLogValidYValue(x, y, graphLabel)) { - // if (m_log) toggleLog(); - } - getGraphPointSet(graphLabel).addDPoint(x, y); - } - - /** - * - * @param p - * @param graphLabel - */ - public void setConnectedPoint(double[] p, int graphLabel) { - setConnectedPoint(p[0], p[1], graphLabel); - } - - /** - * - * @param GraphLabel - * @param color - */ - public void setGraphColor(int GraphLabel, Color color) { - this.getGraphPointSet(GraphLabel).setColor(color); - } - - // /** - // */ - // public Object openObject() { - // if (m_FileChooser == null) - // createFileChooser(); - // int returnVal = m_FileChooser.showOpenDialog(this); - // if (returnVal == JFileChooser.APPROVE_OPTION) { - // File selected = m_FileChooser.getSelectedFile(); - // try { - // ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new - // FileInputStream(selected))); - // Object obj = oi.readObject(); - // oi.close(); - // - // Object[] objects = (Object[]) obj; - // for (int i = 0; i < objects.length; i++) { - // GraphPointSet xx = ((GraphPointSet.SerPointSet) - // objects[i]).getGraphPointSet(); - // xx.initGraph(this); - // addGraphPointSet(xx); - // } - // repaint(); - // return obj; - // } catch (Exception ex) { - // JOptionPane.showMessageDialog(this, - // "Couldn't read object: " - // + selected.getName() - // + "\n" + ex.getMessage(), - // "Open object file", - // JOptionPane.ERROR_MESSAGE); - // } - // } - // return null; - // } - - // /** - // * - // */ - // public void saveObject() { - // Object[] object = new Object[m_PointSetContainer.size()]; - // for (int i = 0; i < m_PointSetContainer.size(); i++) { - // object[i] = ((GraphPointSet) - // m_PointSetContainer.get(i)).getSerPointSet(); - // } - // if (m_FileChooser == null) - // createFileChooser(); - // int returnVal = m_FileChooser.showSaveDialog(this); - // if (returnVal == JFileChooser.APPROVE_OPTION) { - // File sFile = m_FileChooser.getSelectedFile(); - // try { - // ObjectOutputStream oo = new ObjectOutputStream(new - // BufferedOutputStream(new FileOutputStream(sFile))); - // oo.writeObject(object); - // oo.close(); - // } catch (IOException ex) { - // JOptionPane.showMessageDialog(this, - // "Couldn't write to file: " - // + sFile.getName() - // + "\n" + ex.getMessage(), - // "Save object", - // JOptionPane.ERROR_MESSAGE); - // } - // } - // } - - /** - * - * @param GraphLabel - * @param colorindex - */ - public void setGraphColor(int GraphLabel, int colorindex) { - this.getGraphPointSet(GraphLabel).setColorByIndex(colorindex); - } - - /** - * - * @param GraphLabel - * @param Info - * @param stroke - */ - public void setInfoString(int GraphLabel, String Info, float stroke) { - getGraphPointSet(GraphLabel).setInfoString(Info, stroke); - } - - /** - * Set a legend for the function area. If null is given, the former legend - * is deactivated. - * - * @param lBox - */ - protected void setLegend(GraphPointSetLegend lBox) { - legendBox = lBox; - if (lBox != null && m_legend) - repaint(); - } - - /** - * - * @param x - * @param y - * @param GraphLabel - */ - public void setUnconnectedPoint(double x, double y, int GraphLabel) { - DFunction scF = getYScale(); - if (scF instanceof Exp) - ((Exp) scF).updateMinValue(y); - if (!checkLogValidYValue(x, y, GraphLabel)) { - // if (m_log) toggleLog(); - } - this.getGraphPointSet(GraphLabel).addDPoint(x, y); - this.getGraphPointSet(GraphLabel).setConnectedMode(false); - repaint(); - } - - /** - * - * @param p - * @param GraphLabel - */ - public void setUnconnectedPoint(double[] p, int GraphLabel) { - setUnconnectedPoint(p[0], p[1], GraphLabel); - } - - /** - * - */ - private void toggleLegend() { - m_legend = !m_legend; - repaint(); - } - - public boolean isShowLegend() { - return m_legend; - } - - /** - * Shows the legend or switches it off. - * - * @param on - */ - public void setShowLegend(boolean on) { - m_legend = on; - if (!on) { - legendBox = null; - } else { - legendBox = new GraphPointSetLegend(m_PointSetContainer, - isAppendIndexInLegend()); - } - repaint(); - } - - private boolean renameGraph(int graphIndex) { - if ((m_PointSetContainer == null) || (m_PointSetContainer.size() == 0)) { - return false; - } - if (graphIndex >= 0 && (graphIndex = 0 && (graphIndex 0) { + gps.setColorByIndex(index); + index++; + } + } + updateLegend(); + } + + /** + * + * @return + */ + public boolean checkLoggable() { + double minY = Double.MAX_VALUE; + for (int i = 0; i < pointSetContainer.size(); i++) { + DPointSet pSet = (pointSetContainer.get(i).getConnectedPointSet()); + if (pSet.getSize() > 0) { + minY = Math.min(minY, pSet.getMinYVal()); + } + } + // if (TRACE) System.out.println("min is " + minY); + return (minY > 0); + } + + protected double getMinimalPositiveYValue() { + double minY = Double.MAX_VALUE; + for (int i = 0; i < pointSetContainer.size(); i++) { + DPointSet pSet = (pointSetContainer.get(i).getConnectedPointSet()); + if (pSet.getSize() > 0) { + double tmpMinY = Math.min(minY, pSet.getMinPositiveYValue()); + if (tmpMinY > 0) { + minY = tmpMinY; + } + } + } + return minY; + } + + protected boolean checkLogValidYValue(double x, double y, int graphLabel) { + if (y <= 0.0) { + if (log && notifyNegLog) { + System.err.println("Warning: trying to plot value (" + x + "/" + + y + ") with y <= 0 in logarithmic mode!"); + notifyNegLog = false; + } + return false; + } + return true; + } + + private String cleanBlanks(String str, Character rpl) { + return str.replace(' ', rpl); + } + + /** + * + */ + public void clearAll() { + this.removeAllDElements(); + for (int i = 0; i < pointSetContainer.size(); i++) { + ((GraphPointSet) (pointSetContainer.get(i))).removeAllPoints(); + } + pointSetContainer.clear(); + if (getYScale() instanceof Exp) { + setYScale(new Exp()); // to remove smallest seen value + } + notifyNegLog = true; + } + + /** + * + */ + public void clearGraph(int graphLabel) { + getGraphPointSet(graphLabel).removeAllPoints(); + pointSetContainer.remove(getGraphPointSet(graphLabel)); + if (getYScale() instanceof Exp) { + ((Exp) getYScale()).setMinValue(getMinimalPositiveYValue()); + } + repaint(); + notifyNegLog = true; + } + + /** + * + */ + public void clearGraph(int x, int y) { + int index = getNearestGraphIndex(x, y); + if (index == -1) { + return; + } + int GraphLabel = ((GraphPointSet) (this.pointSetContainer.get(index))).getGraphLabel(); + clearGraph(GraphLabel); + updateLegend(); + } + + /** + * Reset the legend clearing all information. + */ + public void clearLegend() { + setLegend(null); + } + + /** + * + */ + protected void createFileChooser() { + fileChooser = new JFileChooser(new File("/resources")); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + } + + /** + * Plot a circle icon to the function area which is annotated with a char + * and a double value. + * + * @param c + * @param val + * @param position + * @param graphID + */ + public void drawCircle(char c, double val, double[] position, int graphID) { + drawCircle(c + "" + val, position, graphID); + } + + /** + * Plot a circle icon to the function area which is annotated with a char + * and a double value. + * + * @param c + * @param val + * @param position + */ + public void drawCircle(double val, double[] position, int graphID) { + drawCircle("" + val, position, graphID); + } + + public void drawCircle(String label, double xPos, double yPos, int graphID) { + double[] pos = new double[2]; + pos[0] = xPos; + pos[1] = yPos; + drawCircle(label, pos, graphID); + } + + /** + * Plot a circle icon to the function area which is annotated with a char + * and a double value. The color corresponds to the color of the graph with + * given ID + * + * @param label + * @param position + * @param graphID + */ + public void drawCircle(String label, double[] position, int graphID) { + drawIcon(new Chart2DDPointIconCircle(), label, position, graphID); + } + + /** + * Plot a circle icon to the function area which is annotated with a char + * and a double value. The color corresponds to the color of the graph with + * given ID + * + * @param label + * @param position + * @param graphID + */ + public void drawIcon(DPointIcon theIcon, String label, double[] position, + int graphID) { + DPointSet popRep; + popRep = new DPointSet(); + popRep.addDPoint(new DPoint(position[0], position[1])); + DPointIcon icon = new Chart2DDPointIconText(label); + ((Chart2DDPointIconText) icon).setIcon(theIcon); + ((Chart2DDPointIconText) icon).setColor(getGraphPointSet(graphID).getColor()); + popRep.setIcon(icon); + addDElement(popRep); + } + + // public void setConnectedPoint(double x, double y, int GraphLabel) { + // if (m_log == true && y <= 0.0) { + // // y = Double.MIN_VALUE; + // if (notifyNegLog) { + // System.err.println("Warning: trying to plot value (" + x + "/" + y + + // ") with y <= 0 in logarithmic mode! Setting y to " + 1e-30); + // notifyNegLog = false; + // } + // y = 1e-30; + // } + // getGraphPointSet(GraphLabel).addDPoint(x, y); + // + // } + /** + * Plot an icon to the function area which is annotated with a char and a + * double value. The color corresponds to the color of the graph with given + * ID Icon types are 0: circle, 1: cross, otherwise: point. + * + * @param label + * @param position + * @param graphID + */ + public void drawIcon(int iconType, String label, double[] position, + int graphID) { + DPointIcon theIcon; + switch (iconType) { + case 0: + theIcon = new Chart2DDPointIconCircle(); + break; + case 1: + theIcon = new Chart2DDPointIconCross(); + break; + default: + case 2: + theIcon = new Chart2DDPointIconPoint(); + break; + } + drawIcon(theIcon, label, position, graphID); + } + + /** + * Draw a line with given start and end points. + * + * @param p1 + * @param p2 + */ + public void drawLine(double[] p1, double[] p2) { + DPointSet popRep = new DPointSet(); + popRep.setConnected(true); + popRep.addDPoint(new DPoint(p1[0], p1[1])); + popRep.addDPoint(new DPoint(p2[0], p2[1])); + addDElement(popRep); + } + + /** + * Export contained data to standard output. + * + */ + public void exportToAscii() { + exportToAscii((File) null); + } + + /** + * Export contained data to a file or to standard out if null is given. The + * given File will be overwritten! + * + * @param file a File instance or null to export to standard out + * @return true if the export succeeded, else false + */ + public boolean exportToAscii(File file) { + String[] s = null; + int maxSize = 0; + for (int i = 0; i < pointSetContainer.size(); i++) { + // find maximum length of all point sets + if (pointSetContainer.get(i).getConnectedPointSet().getSize() > maxSize) { + maxSize = pointSetContainer.get(i).getConnectedPointSet().getSize(); + } + } + if (maxSize > 0) { // if there is any data, init string array and set x + // value column + s = new String[maxSize + 1]; + for (int j = 0; j <= maxSize; j++) { + s[j] = ""; + } + } else { + System.err.println("Error: no data to export"); + return true; + } + for (int i = 0; i < pointSetContainer.size(); i++) { + if (pointSetContainer.get(i) instanceof GraphPointSet) { + GraphPointSet set = (GraphPointSet) pointSetContainer.get(i); + DPointSet pset = set.getConnectedPointSet(); + // add column names + s[0] = s[0] + " t " + cleanBlanks(set.getInfoString(), '_'); + for (int j = 1; j < s.length; j++) { // add column data of place + if ((j - 1) < pset.getSize()) { + s[j] = s[j] + " " + pset.getDPoint(j - 1).x + " " + pset.getDPoint(j - 1).y; + } else { + s[j] += " ? ?"; // placeholder if no value in this set + } + } + } else { + System.err.println("error in FunctionArea::exportToAscii"); + } + } + if (file == null) { + for (int j = 0; j < s.length; j++) { + System.out.println(s[j]); + } + return true; + } else { + try { + PrintWriter out = new PrintWriter(new FileOutputStream(file)); + for (int j = 0; j < s.length; j++) { + out.println(s[j]); + } + out.flush(); + out.close(); + return true; + } catch (Exception e) { + System.err.println("Error on data export:" + e.getMessage()); + return false; + } + } + } + + /** + * Export contained data to a file with a given String as prefix + * + * @param prefix file name prefix + * @return true if the export succeeded, else false + */ + public boolean exportToAscii(String prefix) { + SimpleDateFormat formatter = new SimpleDateFormat( + "E'_'yyyy.MM.dd'_'HH.mm.ss"); + String fname = prefix + "PlotExport_" + formatter.format(new Date()) + + ".txt"; + try { + File f = new File(fname); + f.createNewFile(); + return exportToAscii(f); + } catch (Exception e) { + System.err.println("Error:" + e.getMessage()); + return false; + } + + } + + /** + * This gives the number of graphs already plotted. + * + * @return + */ + public int getContainerSize() { + return pointSetContainer.size(); + } + + /** + * + * @param x + * @param y + * @return + */ + public String getGraphInfo(int x, int y) { + String ret = ""; + if ((pointSetContainer == null) || (pointSetContainer.size() == 0)) { + return ret; + } + int minindex = getNearestGraphIndex(x, y); + if (minindex >= 0) { + return ((GraphPointSet) (pointSetContainer.get(minindex))).getInfoString(); + } else { + return "none"; + } + } + + public String getGraphInfo(int graphIndex) { + String ret = ""; + if ((pointSetContainer == null) || (pointSetContainer.size() == 0)) { + return ret; + } + + if (graphIndex >= 0 && (graphIndex < pointSetContainer.size())) { + return ((GraphPointSet) (pointSetContainer.get(graphIndex))).getInfoString(); + } else { + return "none"; + } + } + + public Color getGraphColor(int graphIndex) { + if (graphIndex >= 0) { + return pointSetContainer.get(graphIndex).getColor(); + } else { + return null; + } + } + + /** + * + * @param GraphLabel + * @return + */ + private GraphPointSet getGraphPointSet(int GraphLabel) { + // System.out.println("looping through " + m_PointSetContainer.size() + + // " point sets..."); + for (int i = 0; i < pointSetContainer.size(); i++) { + if (pointSetContainer.get(i) instanceof GraphPointSet) { + GraphPointSet xx = (GraphPointSet) (pointSetContainer.get(i)); + // System.out.println("looking at "+xx.getGraphLabel()); + if (xx.getGraphLabel() == GraphLabel) { + // System.out.println("match!"); + return xx; + } + } + } + // create new GraphPointSet + GraphPointSet NewPointSet = new GraphPointSet(GraphLabel, this); + // System.out.println("adding new point set " + GraphLabel); + // NewPointSet.setStroke(new BasicStroke( (float)1.0 )); + // addGraphPointSet(NewPointSet); already done within GraphPointSet!!! + return NewPointSet; + } + + /** + * + */ + private DPoint getNearestDPoint(int x, int y) { + // get index of nearest Graph + double distmin = 10000000; + DPoint ret = null; + DPoint point1 = getDMeasures().getDPoint(x, y); + DPoint point2 = null; + double dist = 0; + for (int i = 0; i < pointSetContainer.size(); i++) { + if (pointSetContainer.get(i) instanceof GraphPointSet) { + GraphPointSet pointset = (GraphPointSet) (pointSetContainer.get(i)); + point2 = pointset.getNearestDPoint(point1); + if (point2 == null) { + continue; + } + dist = (point1.x - point2.x) * (point1.x - point2.x) + + (point1.y - point2.y) * (point1.y - point2.y); + // System.out.println("dist="+dist+"i="+i); + if (dist < distmin) { + distmin = dist; + ret = point2; + } + if ((dist == distmin) + && !(ret.getIcon() instanceof Chart2DDPointIconContent) + && !(ret.getIcon() instanceof InterfaceSelectablePointIcon)) { + distmin = dist; + ret = point2; + } + } + } + return ret; + } + + /** + * + * @param x + * @param y + * @return + */ + private int getNearestGraphIndex(int x, int y) { + // get index of nearest Graph + double distmin = 10000000; + int minindex = -1; + DPoint point1 = getDMeasures().getDPoint(x, y); + DPoint point2 = null; + double dist = 0; + for (int i = 0; i < pointSetContainer.size(); i++) { + GraphPointSet pointset = pointSetContainer.get(i); + point2 = pointset.getNearestDPoint(point1); + if (point2 == null) { + continue; + } + if (point1 == null) { + System.err.println("point1 == null"); + } + + dist = (point1.x - point2.x) * (point1.x - point2.x) + + (point1.y - point2.y) * (point1.y - point2.y); + // System.out.println("dist="+dist+"i="+i); + if (dist < distmin) { + distmin = dist; + minindex = i; + } + } + return minindex; + } + + /** + * Returns the number of points within the graph of the given label. + * + * @param index + * @return + */ + public int getPointCount(int label) { + return getGraphPointSet(label).getPointCount(); + } + + /** + * This method returns the selection listener to the PointIcon + * + * @return InterfaceSelectionListener + */ + public InterfaceRefPointListener getRefPointSelectionListener() { + return this.refPointListener; + } + + /** + * + */ + public boolean isStatisticsGraph(int x, int y) { + boolean ret = false; + if ((pointSetContainer == null) || (pointSetContainer.size() == 0)) { + return ret; + } + int minindex = getNearestGraphIndex(x, y); + ret = ((GraphPointSet) (pointSetContainer.get(minindex))).isStatisticsGraph(); + return ret; + } + + /** + * Causes all PointSets to interupt the connected painting at the current + * position. + */ + public void jump() { + for (int i = 0; i < pointSetContainer.size(); i++) { + ((GraphPointSet) (pointSetContainer.get(i))).jump(); + } + } + + @Override + public void paint(Graphics g) { + super.paint(g); + if (legendBox != null && legend) { + legendBox.paintIn(g, scaledBorder.getInnerRect(this)); + } + } + + /** + * + * @return + */ + public DPointSet[] printPoints() { + DPointSet[] ret = new DPointSet[pointSetContainer.size()]; + for (int i = 0; i < pointSetContainer.size(); i++) { + System.out.println(""); + System.out.println("GraphPointSet No " + i); + + ret[i] = ((GraphPointSet) pointSetContainer.get(i)).printPoints(); + } + return ret; + + } + + /** + * + * @param i + * @return + */ + public DPointSet printPoints(int i) { + // for (int i = 0; i < m_PointSetContainer.size();i++) { + System.out.println(""); + System.out.println("GraphPointSet No " + i); + + return ((GraphPointSet) pointSetContainer.get(i)).printPoints(); + // } + } + + /** + * + * @param x + * @param y + */ + public void removePoint(int x, int y) { + DPoint point = getNearestDPoint(x, y); + int index = getNearestGraphIndex(x, y); + if (index == -1 || point == null) { + return; + } + GraphPointSet pointset = (GraphPointSet) (this.pointSetContainer.get(index)); + pointset.removePoint(point); + } + + /** + * This method allows to remove the selection listener to the PointIcon + */ + public void removeRefPointSelectionListeners() { + this.refPointListener = null; + } + + public void setConnectedPoint(double x, double y, int graphLabel) { + DFunction scF = getYScale(); + if (scF instanceof Exp) { + ((Exp) scF).updateMinValue(y); + } + if (!checkLogValidYValue(x, y, graphLabel)) { + // if (m_log) toggleLog(); + } + getGraphPointSet(graphLabel).addDPoint(x, y); + } + + /** + * + * @param p + * @param graphLabel + */ + public void setConnectedPoint(double[] p, int graphLabel) { + setConnectedPoint(p[0], p[1], graphLabel); + } + + /** + * + * @param GraphLabel + * @param color + */ + public void setGraphColor(int GraphLabel, Color color) { + this.getGraphPointSet(GraphLabel).setColor(color); + } + + // /** + // */ + // public Object openObject() { + // if (m_FileChooser == null) + // createFileChooser(); + // int returnVal = m_FileChooser.showOpenDialog(this); + // if (returnVal == JFileChooser.APPROVE_OPTION) { + // File selected = m_FileChooser.getSelectedFile(); + // try { + // ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new + // FileInputStream(selected))); + // Object obj = oi.readObject(); + // oi.close(); + // + // Object[] objects = (Object[]) obj; + // for (int i = 0; i < objects.length; i++) { + // GraphPointSet xx = ((GraphPointSet.SerPointSet) + // objects[i]).getGraphPointSet(); + // xx.initGraph(this); + // addGraphPointSet(xx); + // } + // repaint(); + // return obj; + // } catch (Exception ex) { + // JOptionPane.showMessageDialog(this, + // "Couldn't read object: " + // + selected.getName() + // + "\n" + ex.getMessage(), + // "Open object file", + // JOptionPane.ERROR_MESSAGE); + // } + // } + // return null; + // } + // /** + // * + // */ + // public void saveObject() { + // Object[] object = new Object[m_PointSetContainer.size()]; + // for (int i = 0; i < m_PointSetContainer.size(); i++) { + // object[i] = ((GraphPointSet) + // m_PointSetContainer.get(i)).getSerPointSet(); + // } + // if (m_FileChooser == null) + // createFileChooser(); + // int returnVal = m_FileChooser.showSaveDialog(this); + // if (returnVal == JFileChooser.APPROVE_OPTION) { + // File sFile = m_FileChooser.getSelectedFile(); + // try { + // ObjectOutputStream oo = new ObjectOutputStream(new + // BufferedOutputStream(new FileOutputStream(sFile))); + // oo.writeObject(object); + // oo.close(); + // } catch (IOException ex) { + // JOptionPane.showMessageDialog(this, + // "Couldn't write to file: " + // + sFile.getName() + // + "\n" + ex.getMessage(), + // "Save object", + // JOptionPane.ERROR_MESSAGE); + // } + // } + // } + /** + * + * @param GraphLabel + * @param colorindex + */ + public void setGraphColor(int GraphLabel, int colorindex) { + this.getGraphPointSet(GraphLabel).setColorByIndex(colorindex); + } + + /** + * + * @param GraphLabel + * @param Info + * @param stroke + */ + public void setInfoString(int GraphLabel, String Info, float stroke) { + getGraphPointSet(GraphLabel).setInfoString(Info, stroke); + } + + /** + * Set a legend for the function area. If null is given, the former legend + * is deactivated. + * + * @param lBox + */ + protected void setLegend(GraphPointSetLegend lBox) { + legendBox = lBox; + if (lBox != null && legend) { + repaint(); + } + } + + /** + * + * @param x + * @param y + * @param GraphLabel + */ + public void setUnconnectedPoint(double x, double y, int GraphLabel) { + DFunction scF = getYScale(); + if (scF instanceof Exp) { + ((Exp) scF).updateMinValue(y); + } + if (!checkLogValidYValue(x, y, GraphLabel)) { + // if (m_log) toggleLog(); + } + this.getGraphPointSet(GraphLabel).addDPoint(x, y); + this.getGraphPointSet(GraphLabel).setConnectedMode(false); + repaint(); + } + + /** + * + * @param p + * @param GraphLabel + */ + public void setUnconnectedPoint(double[] p, int GraphLabel) { + setUnconnectedPoint(p[0], p[1], GraphLabel); + } + + /** + * + */ + private void toggleLegend() { + legend = !legend; + repaint(); + } + + public boolean isShowLegend() { + return legend; + } + + /** + * Shows the legend or switches it off. + * + * @param on + */ + public void setShowLegend(boolean on) { + legend = on; + if (!on) { + legendBox = null; + } else { + legendBox = new GraphPointSetLegend(pointSetContainer, + isAppendIndexInLegend()); + } + repaint(); + } + + private boolean renameGraph(int graphIndex) { + if ((pointSetContainer == null) || (pointSetContainer.size() == 0)) { + return false; + } + if (graphIndex >= 0 && (graphIndex < pointSetContainer.size())) { + String oldName = getGraphInfo(graphIndex); + String newName = ToolBoxGui.getInputPaneInitialVal(this, "Rename a graph", "Enter new name for graph " + graphIndex + ":", oldName); + if (newName != null) { + return renameGraph(graphIndex, newName); + } + return true; + } else { + return false; + } + } + + private boolean renameGraph(int graphIndex, String newName) { + if ((pointSetContainer == null) || (pointSetContainer.size() == 0)) { + return false; + } + + if (graphIndex >= 0 && (graphIndex < pointSetContainer.size())) { + GraphPointSet gps = ((GraphPointSet) (pointSetContainer.get(graphIndex))); + gps.setInfoString(newName); + updateLegend(); + return true; + } else { + return false; + } + } + + /** + * + */ + public void toggleLog() { + // System.out.println("ToggleLog log was: "+m_log); + boolean setMinPos = false; + if (!log && !checkLoggable()) { + System.err.println("Warning: toggling logarithmics scale with values <= 0! Some points will not be displayed."); + setMinPos = true; + } + if (log == false) { + setMinRectangle(0.001, 0.001, 1, 1); + // setVisibleRectangle( 0.001, 0.001, 100000, 1000 ); + Exp exp = new Exp(); + if (setMinPos) { + exp.setMinValue(getMinimalPositiveYValue()); + } + setYScale(exp); + scaledBorder.setSrcdY(Math.log(10)); + scaledBorder.setScientificPattern(false); // scientific on y axis + log = true; + } else { + log = false; + setYScale(null); + ScaledBorder buffer = scaledBorder; + scaledBorder = new ScaledBorder(); + scaledBorder.x_label = buffer.x_label; // "App. " + Name + + // " func. calls"; + scaledBorder.y_label = buffer.y_label; // "fitness"; + scaledBorder.setStandardPattern(false); // default decimal pattern on y axis + setBorder(scaledBorder); + } + repaint(); + } + + /** + * Toggle between different decimal patterns on the y-axis. + * + * @param immediateRepaint if true, a repaint event is scheduled immediately + */ + public void toggleScientificY(boolean immediateRepaint) { + scaledBorder.toggleDecPattern(false); + if (immediateRepaint) { + repaint(); + } + } + + /** + * Allows setting whether or not to paint the y-axis in logarithmic scale. + * + * @param log if true logarithmic scale is used, linear scale in case of + * false. + */ + public void toggleLog(boolean log) { + if (log != log) { + toggleLog(); + } + } + + /** + * Recreate the legend object with the current point sets. + * + */ + public void updateLegend() { + GraphPointSetLegend lb = new GraphPointSetLegend(pointSetContainer, + isAppendIndexInLegend()); + setLegend(lb); + } + + /** + * Gives the info string for a graph label. + * + * @param j The graph label identifier. + * @return The associated info string. + */ + public String getInfoString(int j) { + return getGraphPointSet(j).getInfoString(); + } + + public void setShowGraphToolTips(boolean doShowGraphToolTips) { + this.doShowGraphToolTips = doShowGraphToolTips; + } + + public boolean isShowGraphToolTips() { + return doShowGraphToolTips; + } + + public void setAppendIndexInLegend(boolean appendIndexInLegend) { + this.appendIndexInLegend = appendIndexInLegend; + } + + public boolean isAppendIndexInLegend() { + return appendIndexInLegend; + } } diff --git a/src/eva2/gui/Plot.java b/src/eva2/gui/Plot.java index 43e7a9ba..83afbb3b 100644 --- a/src/eva2/gui/Plot.java +++ b/src/eva2/gui/Plot.java @@ -121,8 +121,8 @@ public class Plot implements PlotInterface, Serializable { m_PlotArea.toggleLog(); } }); - JButton ExportButton = new JButton("Export..."); - ExportButton.setToolTipText("Exports the graph data to a simple ascii file."); + JButton ExportButton = new JButton("Export to TSV"); + ExportButton.setToolTipText("Exports the graph data to a simple TSV file."); ExportButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { diff --git a/src/eva2/server/go/operators/postprocess/PostProcess.java b/src/eva2/server/go/operators/postprocess/PostProcess.java index b1f1c643..a11a5529 100644 --- a/src/eva2/server/go/operators/postprocess/PostProcess.java +++ b/src/eva2/server/go/operators/postprocess/PostProcess.java @@ -33,7 +33,7 @@ import eva2.server.go.strategies.HillClimbing; import eva2.server.go.strategies.NelderMeadSimplex; import eva2.server.modules.GOParameters; import eva2.server.stat.InterfaceTextListener; -import eva2.server.stat.StatsParameter; +import eva2.server.stat.StatisticsParameter; import eva2.tools.Pair; import eva2.tools.math.Mathematics; import java.util.ArrayList; @@ -805,7 +805,7 @@ public class PostProcess { */ private static void runPP(OptimizerRunnable rnbl) { rnbl.getGOParams().setDoPostProcessing(false); - rnbl.setVerbosityLevel(StatsParameter.VERBOSITY_NONE); + rnbl.setVerbosityLevel(StatisticsParameter.VERBOSITY_NONE); ppRunnables.add(rnbl); // System.err.println("Starting runbl " + rnbl); rnbl.run(); diff --git a/src/eva2/server/stat/AbstractStatistics.java b/src/eva2/server/stat/AbstractStatistics.java index aa2b310e..769b5953 100644 --- a/src/eva2/server/stat/AbstractStatistics.java +++ b/src/eva2/server/stat/AbstractStatistics.java @@ -188,7 +188,7 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter String startDate = getDateString(); // open the result file: if (doFileOutput() // not "text-window only" - && (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatsParameter.VERBOSITY_NONE)) { // verbosity accordingly high + && (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_NONE)) { // verbosity accordingly high //!resFName.equalsIgnoreCase("none") && !resFName.equals("")) { String fnameBase = makeOutputFileName(m_StatsParams.getResultFilePrefix(), infoString, startDate); int cnt=0; @@ -1136,22 +1136,22 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter * @return */ private boolean printLineByVerbosity(int iteration) { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatsParameter.VERBOSITY_KTH_IT) - || ((m_StatsParams.getOutputVerbosity().getSelectedTagID() == StatsParameter.VERBOSITY_KTH_IT) + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_KTH_IT) + || ((m_StatsParams.getOutputVerbosity().getSelectedTagID() == StatisticsParameter.VERBOSITY_KTH_IT) && (isKthRun(iteration, m_StatsParams.getOutputVerbosityK()))); } private boolean printRunIntroVerbosity() { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatsParameter.VERBOSITY_KTH_IT) - || (optRunsPerformed==0 && (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatsParameter.VERBOSITY_FINAL)); + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT) + || (optRunsPerformed==0 && (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_FINAL)); } private boolean printRunStoppedVerbosity() { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatsParameter.VERBOSITY_KTH_IT); + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT); } private boolean printFinalVerbosity() { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatsParameter.VERBOSITY_NONE); + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_NONE); } private boolean isKthRun(int i, int k) { @@ -1166,7 +1166,7 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter } private boolean printHeaderByVerbosity() { - return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatsParameter.VERBOSITY_KTH_IT); + return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT); } private static void divideMean(Double[] mean, double d) { diff --git a/src/eva2/server/stat/GenericStatistics.java b/src/eva2/server/stat/GenericStatistics.java index c7da52e4..5053c6f3 100644 --- a/src/eva2/server/stat/GenericStatistics.java +++ b/src/eva2/server/stat/GenericStatistics.java @@ -12,180 +12,203 @@ package eva2.server.stat; /*==========================================================================* * IMPORTS *==========================================================================*/ -import java.io.Serializable; -import java.lang.reflect.Field; - import eva2.gui.DataViewer; import eva2.gui.DataViewerInterface; import eva2.gui.Graph; import eva2.tools.jproxy.MainAdapterClient; +import java.io.Serializable; +import java.lang.reflect.Field; +import java.util.logging.Logger; /** * */ -public class GenericStatistics implements Serializable{ - public static boolean TRACE = false; - //private Object m_target; - private int m_Test; - private String[] m_PropertyNames; - private boolean[] m_State; - private transient Field[] m_fields; - private DataViewerInterface m_Viewer; - private Graph m_Graph; - private static MainAdapterClient m_MainAdapterClient; - /** - * - */ - public static void setMainAdapterClient (MainAdapterClient x) { - m_MainAdapterClient = x; - } - /** - * - */ - public GenericStatistics getClone() { - return new GenericStatistics(this); - } - /** - * - */ - private GenericStatistics (GenericStatistics Source) { - //m_target = Source.m_target; - m_Test = Source.m_Test; - m_PropertyNames = Source.m_PropertyNames; - m_State = Source.m_State; - m_fields = Source.m_fields; - m_Viewer = Source.m_Viewer; - m_Graph = Source.m_Graph; +public class GenericStatistics implements Serializable { - } - /** - * - */ - public GenericStatistics(Object target) { - //m_target = target; - //System.out.println("GenericStatistics-->"); - try { - m_fields = getDeclaredFields(target); - //if (TRACE) System.out.println("fields-->"+m_fields.length); - m_PropertyNames = new String [m_fields.length]; - m_State = new boolean [m_fields.length]; - for (int i=0;i"); + try { + fields = getDeclaredFields(target); + //if (TRACE) System.out.println("fields-->"+m_fields.length); + propertyNames = new String[fields.length]; + states = new boolean[fields.length]; + for (int i = 0; i < fields.length; i++) { + String desc = fields[i].toString(); //System.out.println("desc "+desc); + int istransient = desc.indexOf("transient"); + //if (TRACE) System.out.println("Field :"+m_fields[i].getName() ); + Object FieldValue = null; + if (istransient == -1 || fields[i].getName().equals("elementData")) { // the elementdatahack + fields[i].setAccessible(true); + FieldValue = fields[i].get(target); + } + propertyNames[i] = fields[i].getName(); } - } - break; + } catch (Exception ex) { + System.out.println("ERROR in GenericStatistics:" + ex.getMessage()); + ex.printStackTrace(); } - } } - m_Graph.setConnectedPoint(data[1],data[0]); - } + + /** + * + */ + public void setTest(int Test) { + test = Test; + } + + /** + * + */ + public int getTest() { + return test; + } + + /** + * + */ + public String[] getPropertyNames() { + return propertyNames; + } + + /** + * + */ + public boolean[] getState() { + return states; + } + + /** + * + */ + public void setState(boolean[] x) { + System.out.println("in statistics setState !!!!!!!!!!!!!!!!!!"); + states = x; + } + + /** + * + */ + public void initViewer() { + viewer = DataViewer.getInstance(mainAdapterClient, "test"); + graph = viewer.getNewGraph("test"); + } + + /** + * + */ + public Field[] getDeclaredFields(Object target) { + Field[] ret_1 = target.getClass().getSuperclass().getDeclaredFields(); + Field[] ret_2 = target.getClass().getDeclaredFields(); + Field[] ret = new Field[ret_1.length + ret_2.length]; + int index = 0; + for (int i = 0; i < ret_1.length; i++) { + ret[index] = ret_1[i]; + index++; + } + for (int i = 0; i < ret_2.length; i++) { + ret[index] = ret_2[i]; + index++; + } + return ret; + } + + /** + * + */ + public void statechanged(Object target) { + int len = 0; + for (int i = 0; i < states.length; i++) { + if (states[i] == true) { + len++; + } + } + if (len == 0) { + return; + } + if (viewer == null) { + initViewer(); + } + double[] data = new double[len]; + try { + fields = getDeclaredFields(target); + } catch (Exception ex) { + System.out.println("ERROR in GenericStatistics:" + ex.getMessage()); + ex.printStackTrace(); + } + int index = 0; + for (int i = 0; i < fields.length; i++) { + for (int n = 0; n < propertyNames.length; n++) { + if (this.states[n] == false) { + continue; + } + if (fields[i].getName().equals(propertyNames[n])) { + String desc = fields[i].toString(); //System.out.println("desc "+desc); + int istransient = desc.indexOf("transient"); + //if (TRACE) System.out.println("Field :"+m_fields[i].getName() ); + Object FieldValue = null; + if (istransient == -1 || fields[i].getName().equals("elementData")) { // the elementdatahack + fields[i].setAccessible(true); + try { + FieldValue = fields[i].get(target); + //System.out.println("m_PropertyNames "+m_PropertyNames[n] +" value "+FieldValue.toString()); + if (FieldValue instanceof Double) { + data[index] = ((Double) FieldValue).doubleValue(); + } + if (FieldValue instanceof Integer) { + data[index] = ((Integer) FieldValue).doubleValue(); + } + index++; + } catch (Exception ex) { + System.out.println("ERROR in GenericStatistics:" + ex.getMessage()); + ex.printStackTrace(); + } + } + break; + } + } + } + graph.setConnectedPoint(data[1], data[0]); + } } \ No newline at end of file diff --git a/src/eva2/server/stat/InterfaceStatisticsParameter.java b/src/eva2/server/stat/InterfaceStatisticsParameter.java index 116dfebc..d07b911c 100644 --- a/src/eva2/server/stat/InterfaceStatisticsParameter.java +++ b/src/eva2/server/stat/InterfaceStatisticsParameter.java @@ -9,51 +9,48 @@ import eva2.tools.StringSelection; * @see StatsParameter */ public interface InterfaceStatisticsParameter { - public String getName(); - public void saveInstance(); -// public String globalInfo(); -// public void setTextoutput(int i); -// public void setPlotoutput(int i); // noone knows what these were useful for... -// public int GetPlotoutput(); -// public int GetTextoutput(); -// public String textoutputTipText(); -// public String plotFrequencyTipText(); - public void setMultiRuns(int x); - public int getMultiRuns(); - public String multiRunsTipText(); + String getName(); + void saveInstance(); + void setMultiRuns(int x); + int getMultiRuns(); + String multiRunsTipText(); -// public String GetInfoString(); -// public void setInfoString(String s); - public boolean GetUseStatPlot(); // use averaged graph for multi-run plots or not - public void setUseStatPlot(boolean x); // activate averaged graph for multi-run plots + /** + * Use averaged graph for multi-run plots or not. + * + * @return If an average graph is used or not + */ + boolean getUseStatPlot(); -// public List getPlotDescriptions(); + /** + * Activate averaged graph for multi-run plots. + * + * @param x If averaged graph should be activated. + */ + void setUseStatPlot(boolean x); + + StringSelection getFieldSelection(); + void setFieldSelection(StringSelection v); + + String getResultFilePrefix(); + void setResultFilePrefix(String x); + + void setConvergenceRateThreshold(double x); + double getConvergenceRateThreshold(); -// public SelectedTag getPlotData(); -// public void setPlotData(SelectedTag newMethod); + void setShowTextOutput(boolean show); + boolean isShowTextOutput(); - public StringSelection getFieldSelection(); - public void setFieldSelection(StringSelection v); + boolean isOutputAllFieldsAsText(); + void setOutputAllFieldsAsText(boolean bShowFullText); - public String getResultFilePrefix(); - public void SetResultFilePrefix(String x); + void setOutputVerbosity(SelectedTag sTag); + SelectedTag getOutputVerbosity(); - public void setConvergenceRateThreshold(double x); - public double getConvergenceRateThreshold(); - - public void SetShowTextOutput(boolean show); - public boolean isShowTextOutput(); + int getOutputVerbosityK(); + void setOutputVerbosityK(int k); - public boolean isOutputAllFieldsAsText(); - public void setOutputAllFieldsAsText(boolean bShowFullText); - - public void setOutputVerbosity(SelectedTag sTag); - public SelectedTag getOutputVerbosity(); - - public int getOutputVerbosityK(); - public void setOutputVerbosityK(int k); - - public void setOutputTo(SelectedTag sTag); - public SelectedTag getOutputTo(); + void setOutputTo(SelectedTag sTag); + SelectedTag getOutputTo(); } \ No newline at end of file diff --git a/src/eva2/server/stat/StatisticsDummy.java b/src/eva2/server/stat/StatisticsDummy.java index 4839a1c9..6365eaa9 100644 --- a/src/eva2/server/stat/StatisticsDummy.java +++ b/src/eva2/server/stat/StatisticsDummy.java @@ -18,19 +18,19 @@ import eva2.server.go.strategies.InterfaceOptimizer; */ public class StatisticsDummy implements InterfaceStatistics, InterfaceTextListener { boolean consoleOut = false; - StatsParameter sParams = null; + StatisticsParameter sParams = null; AbstractEAIndividual bestCurrentIndividual, bestRunIndy, bestIndividualAllover; public StatisticsDummy() { bestIndividualAllover = null; - sParams = new StatsParameter(); - sParams.setOutputVerbosityK(StatsParameter.VERBOSITY_NONE); + sParams = new StatisticsParameter(); + sParams.setOutputVerbosityK(StatisticsParameter.VERBOSITY_NONE); } public StatisticsDummy(boolean doConsoleOut) { bestIndividualAllover = null; - sParams = new StatsParameter(); - sParams.setOutputVerbosityK(StatsParameter.VERBOSITY_NONE); + sParams = new StatisticsParameter(); + sParams.setOutputVerbosityK(StatisticsParameter.VERBOSITY_NONE); consoleOut = doConsoleOut; } diff --git a/src/eva2/server/stat/StatisticsParameter.java b/src/eva2/server/stat/StatisticsParameter.java new file mode 100644 index 00000000..7bc6581d --- /dev/null +++ b/src/eva2/server/stat/StatisticsParameter.java @@ -0,0 +1,390 @@ +package eva2.server.stat; + +import eva2.gui.BeanInspector; +import eva2.gui.GenericObjectEditor; +import eva2.server.go.InterfaceNotifyOnInformers; +import eva2.server.go.problems.InterfaceAdditionalPopulationInformer; +import eva2.tools.EVAERROR; +import eva2.tools.SelectedTag; +import eva2.tools.Serializer; +import eva2.tools.StringSelection; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * A set of parameters for statistics in EvA2. Several data entries are provided by the AbstractStatistics class, + * others by the additional informers. This class allows customization of entries and frequency of data output. + * Data entries can be selected using a StringSelection instance. + * There is a switch called "output full data as text" which will be interpreted by AbstractStatistics showing + * all or only the selected entities. + * + * @see AbstractStatistics + * @author mkron + */ +public class StatisticsParameter implements InterfaceStatisticsParameter, InterfaceNotifyOnInformers, Serializable { + private static final long serialVersionUID = -8681061379203108390L; + private static final Logger LOGGER = Logger.getLogger(StatisticsParameter.class.getName()); + public final static int VERBOSITY_NONE = 0; + public final static int VERBOSITY_FINAL = 1; + public final static int VERBOSITY_KTH_IT = 2; + public final static int VERBOSITY_ALL = 3; + SelectedTag outputVerbosity = new SelectedTag("No output", "Final results", "K-th iterations", "All iterations"); + public final static int OUTPUT_FILE = 0; + public final static int OUTPUT_WINDOW = 1; + public final static int OUTPUT_FILE_WINDOW = 2; + SelectedTag outputTo = new SelectedTag("File (current dir.)", "Text-window", "Both file and text-window"); + private int verboK = 10; + private int m_Textoutput = 0; + private int m_MultiRuns = 1; + private String m_ResultFilePrefix = "EvA2"; + protected String m_Name = "not defined"; + private boolean m_useStatPlot = true; + private boolean showAdditionalProblemInfo = false; + private double m_ConvergenceRateThreshold = 0.001; + private StringSelection graphSel = new StringSelection(GraphSelectionEnum.currentBest, GraphSelectionEnum.getInfoStrings()); + + /** + * + */ + public static StatisticsParameter getInstance(boolean loadDefaultSerFile) { + if (loadDefaultSerFile) { + return getInstance("Statistics.ser"); + } else { + return new StatisticsParameter(); + } + } + + /** + * Load or create a new instance of the class. + * + * @return A loaded (from file) or new instance of the class. + */ + public static StatisticsParameter getInstance(String serFileName) { + StatisticsParameter instance = null; + try { + FileInputStream fileStream = new FileInputStream(serFileName); + instance = (StatisticsParameter) Serializer.loadObject(fileStream); + } catch (FileNotFoundException ex) { + LOGGER.log(Level.WARNING, "Could not store instance object.", ex); + } + + if (instance == null) { + instance = new StatisticsParameter(); + } + return instance; + } + + /** + * + */ + public StatisticsParameter() { + m_Name = "Statistics"; + outputVerbosity.setSelectedTag(VERBOSITY_KTH_IT); + outputTo.setSelectedTag(1); + } + + /** + * + */ + @Override + public String toString() { + String ret = "\r\nStatisticsParameter (" + super.toString() + "):\r\nm_MultiRuns=" + m_MultiRuns + + ", m_Textoutput=" + m_Textoutput + + // ", m_Plotoutput=" + m_Plotoutput + + ", verbosity= " + outputVerbosity.getSelectedString() + + "\nTo " + outputTo.getSelectedString() + + ", " + BeanInspector.toString(graphSel.getStrings()); + return ret; + } + + /** + * + */ + @Override + public void saveInstance() { + try { + FileOutputStream fileStream = new FileOutputStream("Statistics.ser"); + Serializer.storeObject(fileStream, this); + } catch (FileNotFoundException ex) { + LOGGER.log(Level.WARNING, "Could not store instance object.", ex); + } + } + + /** + * + */ + private StatisticsParameter(StatisticsParameter Source) { + m_ConvergenceRateThreshold = Source.m_ConvergenceRateThreshold; + m_useStatPlot = Source.m_useStatPlot; + m_Textoutput = Source.m_Textoutput; +// m_Plotoutput = Source.m_Plotoutput; +// m_PlotFitness = Source.m_PlotFitness; + m_MultiRuns = Source.m_MultiRuns; + m_ResultFilePrefix = Source.m_ResultFilePrefix; + verboK = Source.verboK; + } + + /** + * + */ + public Object getClone() { + return new StatisticsParameter(this); + } + + /** + * + */ + @Override + public String getName() { + return m_Name; + } + + public static String globalInfo() { + return "Configure statistics and output of the optimization run. Changes to the data selection state will not take effect during a run."; + } + + /** + * + */ + @Override + public void setMultiRuns(int x) { + m_MultiRuns = x; + } + + /** + * + */ + @Override + public int getMultiRuns() { + return m_MultiRuns; + } + + /** + * + */ + @Override + public String multiRunsTipText() { + return "Number of independent optimization runs to evaluate."; + } + /** + * + */ + public String infoStringTipText() { + return "Infostring displayed on fitness graph by prssing the right mouse button."; + } + + /** + * Use averaged graph for multi-run plots or not + */ + @Override + public boolean getUseStatPlot() { + return m_useStatPlot; + } + + /** + * Activate or deactivate averaged graph for multi-run plots + */ + @Override + public void setUseStatPlot(boolean x) { + m_useStatPlot = x; + } + + public String useStatPlotTipText() { + return "Plotting each fitness graph separately if multiruns > 1."; + } + + /** + * + */ + @Override + public void setResultFilePrefix(String x) { + if (x == null) { + m_ResultFilePrefix = ""; + } else { + m_ResultFilePrefix = x; + } + } + + /** + * + */ + @Override + public String getResultFilePrefix() { + return m_ResultFilePrefix; + } + + @Override + public void setShowTextOutput(boolean show) { + // activate if not activated + if (show && outputTo.getSelectedTagID() == 0) { + outputTo.setSelectedTag(2); + } // deactivate if activated + else if (!show && outputTo.getSelectedTagID() > 0) { + outputTo.setSelectedTag(0); + } + } + + @Override + public boolean isShowTextOutput() { + return outputTo.getSelectedTagID() > 0; + } + +// /** +// * +// */ +// public String resultFileNameTipText() { +// return "File name for the result file. If empty or 'none', no output file will be created."; +// } + public String convergenceRateThresholdTipText() { + return "Provided the optimal fitness is at zero, give the threshold below which it is considered as 'reached'"; + } + + /** + * + * @param x + */ + @Override + public void setConvergenceRateThreshold(double x) { + m_ConvergenceRateThreshold = x; + } + + /** + * + */ + @Override + public double getConvergenceRateThreshold() { + return m_ConvergenceRateThreshold; + } + + @Override + public boolean isOutputAllFieldsAsText() { + return showAdditionalProblemInfo; + } + + @Override + public void setOutputAllFieldsAsText(boolean bShowFullText) { + showAdditionalProblemInfo = bShowFullText; + } + + public String outputAllFieldsAsTextTipText() { + return "Output all available data fields or only the selected entries as text."; + } + + public void hideHideable() { + setOutputVerbosity(getOutputVerbosity()); + } + + @Override + public void setOutputVerbosity(SelectedTag sTag) { + outputVerbosity = sTag; + GenericObjectEditor.setHideProperty(this.getClass(), "outputVerbosityK", sTag.getSelectedTagID() != VERBOSITY_KTH_IT); + } + + public void setOutputVerbosity(int i) { + outputVerbosity.setSelectedTag(i); + GenericObjectEditor.setHideProperty(this.getClass(), "outputVerbosityK", outputVerbosity.getSelectedTagID() != VERBOSITY_KTH_IT); + } + + @Override + public SelectedTag getOutputVerbosity() { + return outputVerbosity; + } + + public String outputVerbosityTipText() { + return "Set the data output level."; + } + + @Override + public int getOutputVerbosityK() { + return verboK; + } + + @Override + public void setOutputVerbosityK(int k) { + verboK = k; + } + + public String outputVerbosityKTipText() { + return "Set the interval of data output for intermediate verbosity (in generations)."; + } + + @Override + public SelectedTag getOutputTo() { + return outputTo; + } + + @Override + public void setOutputTo(SelectedTag tag) { + outputTo = tag; + } + + public void setOutputTo(int i) { + outputTo.setSelectedTag(i); + } + + public String outputToTipText() { + return "Set the output destination; to deactivate output, set verbosity to none."; + } + + @Override + public StringSelection getFieldSelection() { + return graphSel; + } + + @Override + public void setFieldSelection(StringSelection v) { + graphSel = v; + } + + public String fieldSelectionTipText() { + return "Select the data fields to be collected and plotted. Note that only simple types can be plotted to the GUI."; + } + + /** + * May be called to dynamically alter the set of graphs that can be + * selected, using a list of informer instances, which usually are the + * problem and the optimizer instance. + * + * @see InterfaceAdditionalPopulationInformer + */ + public void setInformers(List informers) { + ArrayList headerFields = new ArrayList(); + ArrayList infoFields = new ArrayList(); + // parse list of header elements, show additional Strings according to names. + for (InterfaceAdditionalPopulationInformer inf : informers) { + String[] dataHeader = inf.getAdditionalDataHeader(); + headerFields.addAll(Arrays.asList(dataHeader)); + if (infoFields.size() < headerFields.size()) { // add info strings for tool tips - fill up with null if none have been returned. + String[] infos = inf.getAdditionalDataInfo(); + if (infos != null) { + if (infos.length != dataHeader.length) { + System.out.println(BeanInspector.toString(infos)); + System.out.println(BeanInspector.toString(dataHeader)); + EVAERROR.errorMsgOnce("Warning, mismatching number of headers and additional data fields for " + inf.getClass() + " (" + dataHeader.length + " vs. " + infos.length + ")."); + } + infoFields.addAll(Arrays.asList(infos)); + } + while (infoFields.size() < headerFields.size()) { + infoFields.add(null); + } + } +// header += inf.getAdditionalDataHeader(null); // lets hope this works with a null + } + // create additional fields to be selectable by the user, defined by the informer headers +// StringSelection ss = new StringSelection(GraphSelectionEnum.getAndAppendArray(headerFields.toArray(new String[headerFields.size()]))); + StringSelection ss = new StringSelection(GraphSelectionEnum.currentBest, GraphSelectionEnum.getInfoStrings(), + headerFields, infoFields.toArray(new String[infoFields.size()])); + ss.takeOverSelection(graphSel); +// System.out.println("In " + this + ": setting new informers: " + BeanInspector.toString(ss.getStrings())); + // This works! + setFieldSelection(ss); +// System.out.println("After: " + this); + } +} \ No newline at end of file diff --git a/src/eva2/server/stat/StatisticsStandalone.java b/src/eva2/server/stat/StatisticsStandalone.java index 5db269c6..ed0d6758 100644 --- a/src/eva2/server/stat/StatisticsStandalone.java +++ b/src/eva2/server/stat/StatisticsStandalone.java @@ -58,21 +58,21 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac } public StatisticsStandalone(String resultFileName) { - this(resultFileName, 1, resultFileName==null ? StatsParameter.VERBOSITY_NONE : StatsParameter.VERBOSITY_FINAL, false); + this(resultFileName, 1, resultFileName==null ? StatisticsParameter.VERBOSITY_NONE : StatisticsParameter.VERBOSITY_FINAL, false); } public StatisticsStandalone(String resultFileName, int multiRuns, int verbosity, boolean outputAllFieldsAsText) { - this(StatsParameter.getInstance(false)); + this(StatisticsParameter.getInstance(false)); m_StatsParams.setMultiRuns(multiRuns); m_StatsParams.setOutputVerbosity(m_StatsParams.getOutputVerbosity().setSelectedTag(verbosity)); - m_StatsParams.SetResultFilePrefix(resultFileName); + m_StatsParams.setResultFilePrefix(resultFileName); m_StatsParams.setOutputAllFieldsAsText(outputAllFieldsAsText); - if (resultFileName==null) m_StatsParams.getOutputTo().setSelectedTag(StatsParameter.OUTPUT_WINDOW); - else m_StatsParams.setOutputTo(m_StatsParams.getOutputTo().setSelectedTag(StatsParameter.OUTPUT_FILE)); + if (resultFileName==null) m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_WINDOW); + else m_StatsParams.setOutputTo(m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_FILE)); } public StatisticsStandalone() { - this(new StatsParameter()); + this(new StatisticsParameter()); } protected void initPlots(PopulationInterface pop, List informerList) { diff --git a/src/eva2/server/stat/StatisticsWithGUI.java b/src/eva2/server/stat/StatisticsWithGUI.java index c4f02c05..65fd4c88 100644 --- a/src/eva2/server/stat/StatisticsWithGUI.java +++ b/src/eva2/server/stat/StatisticsWithGUI.java @@ -43,261 +43,270 @@ import java.util.logging.Logger; * from AbstractStatistics. */ public class StatisticsWithGUI extends AbstractStatistics implements Serializable, InterfaceStatistics { + private static final long serialVersionUID = 3213603978877954103L; - private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger); - // Plot frames: - private GraphWindow[] fitnessFrame; // frame for the fitness plots - private Graph[][] fitnessGraph; - private Graph[][] statGraph; - - private String graphInfoString; - protected int plotCounter; - - private MainAdapterClient mainAdapterClient; // the connection to the client MainAdapter - private JTextoutputFrameInterface proxyPrinter; - - /* List of descriptor strings and optional indices. strictly its - * redundant since super.lastGraphSelection is always available. - * However it spares some time. + private static final Logger LOGGER = Logger.getLogger(StatisticsWithGUI.class.getName()); + // Plot frames: + private GraphWindow[] fitnessFrame; // frame for the fitness plots + private Graph[][] fitnessGraph; + private Graph[][] statGraph; + private String graphInfoString; + protected int plotCounter; + private MainAdapterClient mainAdapterClient; // the connection to the client MainAdapter + private JTextoutputFrameInterface proxyPrinter; + /* + * List of descriptor strings and optional indices. strictly its redundant + * since super.lastGraphSelection is always available. However it spares + * some time. */ - private transient List> graphDesc = null; + private transient List> graphDesc = null; + protected static String hostName = null; - protected static String hostName = null; + /** + * + */ + public MainAdapterClient getMainAdapterClient() { + return mainAdapterClient; + } - /** - * - */ - public MainAdapterClient getMainAdapterClient() { - return mainAdapterClient; - } + /** + * + */ + public StatisticsWithGUI(MainAdapterClient client) { + mainAdapterClient = client; + if (client != null) { // We are probably in rmi mode + try { + hostName = InetAddress.getLocalHost().getHostName(); + } catch (Exception ex) { + LOGGER.log(Level.WARNING, "Could not retrieve hostname.", ex); + } + } else { + hostName = "localhost"; + } - /** - * - */ - public StatisticsWithGUI(MainAdapterClient client) { - mainAdapterClient = client; - if (client != null) { // We are probably in rmi mode - try { - hostName = InetAddress.getLocalHost().getHostName(); - } catch (Exception ex) { - LOGGER.log(Level.WARNING, "Could not retrieve hostname.", ex); - } - } else hostName = "localhost"; - - if ((client == null) || client.getHostName().equals(hostName)) { - m_StatsParams = StatsParameter.getInstance(true); - proxyPrinter = new JTextoutputFrame("TextOutput of " + hostName); - } else { // we use RMI - m_StatsParams = (InterfaceStatisticsParameter)RMIProxyLocal.newInstance( - StatsParameter.getInstance(true)); - proxyPrinter = (JTextoutputFrameInterface) RMIProxyRemote.newInstance(new - JTextoutputFrame("TextOutput " + hostName), - mainAdapterClient); - } - addTextListener(proxyPrinter); - } + if ((client == null) || client.getHostName().equals(hostName)) { + m_StatsParams = StatisticsParameter.getInstance(true); + proxyPrinter = new JTextoutputFrame("TextOutput of " + hostName); + } else { // we use RMI + m_StatsParams = (InterfaceStatisticsParameter) RMIProxyLocal.newInstance( + StatisticsParameter.getInstance(true)); + proxyPrinter = (JTextoutputFrameInterface) RMIProxyRemote.newInstance(new JTextoutputFrame("TextOutput " + hostName), + mainAdapterClient); + } + addTextListener(proxyPrinter); + } + + /** + * + */ + public synchronized void startOptPerformed(String infoString, int runNumber, Object goParams, List informerList) { + super.startOptPerformed(infoString, runNumber, goParams, informerList); + graphInfoString = infoString; - /** - * - */ - public synchronized void startOptPerformed(String infoString, int runNumber, Object goParams, List informerList) { - super.startOptPerformed(infoString, runNumber, goParams, informerList); - graphInfoString = infoString; - // m_TextCounter = m_StatisticsParameter.GetTextoutput(); // m_PlotCounter = m_StatsParams.GetPlotoutput(); - if ((fitnessFrame!=null) && (fitnessFrame[0]!=null)) { - PlotInterface p = fitnessFrame[0].getPlotter(); - if ((p!=null) && p.isValid()) ((Plot)p).getFunctionArea().clearLegend(); - } - } + if ((fitnessFrame != null) && (fitnessFrame[0] != null)) { + PlotInterface p = fitnessFrame[0].getPlotter(); + if ((p != null) && p.isValid()) { + ((Plot) p).getFunctionArea().clearLegend(); + } + } + } - public void stopOptPerformed(boolean normal, String stopMessage) { - super.stopOptPerformed(normal, stopMessage); - - if (optRunsPerformed > m_StatsParams.getMultiRuns()) { - // this may happen if the user reduces the multirun parameter during late multiruns - System.err.println("error: more runs performed than defined."); - } - - int fullRuns=optRunsPerformed; - if (!normal) fullRuns--; + public void stopOptPerformed(boolean normal, String stopMessage) { + super.stopOptPerformed(normal, stopMessage); - // unite the graphs only if the break was "normal" - if ((m_StatsParams.getMultiRuns() > 1) && (statGraph != null)) { - // unite the point sets for a multirun - for (int i = 0; i < fitnessGraph.length; i++) { - for (int j = 0; j < fitnessGraph[i].length; j++) { - statGraph[i][j].setInfoString( - (fitnessGraph[i][j].getInfo().length() > 0 ? (fitnessGraph[i][j].getInfo() + "_") : "" ) - + "Mean_of_" + fullRuns + " ", - (float) 2.0); - if (normal && fitnessFrame[i].isValid() && (fitnessGraph[i][j].getPointCount()>0)) { - statGraph[i][j].addGraph(fitnessGraph[i][j]); - fitnessGraph[i][j].clear(); - } - } - } - } - PlotInterface p = fitnessFrame[0].getPlotter(); - if ((optRunsPerformed >= m_StatsParams.getMultiRuns()) || !normal) { - // update the legend after the last multirun or after a user break - if ((p!=null) && p.isValid()) { - ((Plot)p).getFunctionArea().updateLegend(); - } - } - } - - public void maybeShowProxyPrinter() { - if (proxyPrinter != null) { + if (optRunsPerformed > m_StatsParams.getMultiRuns()) { + // this may happen if the user reduces the multirun parameter during late multiruns + System.err.println("error: more runs performed than defined."); + } + + int fullRuns = optRunsPerformed; + if (!normal) { + fullRuns--; + } + + // unite the graphs only if the break was "normal" + if ((m_StatsParams.getMultiRuns() > 1) && (statGraph != null)) { + // unite the point sets for a multirun + for (int i = 0; i < fitnessGraph.length; i++) { + for (int j = 0; j < fitnessGraph[i].length; j++) { + statGraph[i][j].setInfoString( + (fitnessGraph[i][j].getInfo().length() > 0 ? (fitnessGraph[i][j].getInfo() + "_") : "") + + "Mean_of_" + fullRuns + " ", + (float) 2.0); + if (normal && fitnessFrame[i].isValid() && (fitnessGraph[i][j].getPointCount() > 0)) { + statGraph[i][j].addGraph(fitnessGraph[i][j]); + fitnessGraph[i][j].clear(); + } + } + } + } + PlotInterface p = fitnessFrame[0].getPlotter(); + if ((optRunsPerformed >= m_StatsParams.getMultiRuns()) || !normal) { + // update the legend after the last multirun or after a user break + if ((p != null) && p.isValid()) { + ((Plot) p).getFunctionArea().updateLegend(); + } + } + } + + public void maybeShowProxyPrinter() { + if (proxyPrinter != null) { proxyPrinter.setShow(m_StatsParams.isShowTextOutput()); } - } - - protected void initPlots(PopulationInterface pop, List informerList) { - if (TRACE) System.out.println("initPlots"); - if (m_StatsParams instanceof StatsParameter) { -// StringSelection ss = ((StatsParameter)m_StatsParams).getGraphSelection(); - graphDesc = lastFieldSelection.getSelectedWithIndex(); -// for (int i=0; i 1 && - m_StatsParams.GetUseStatPlot() == true) { -// String Info = m_StatsParams.GetInfoString(); - statGraph = new Graph[windowCount][]; - for (int i = 0; i < statGraph.length; i++) { - statGraph[i] = new Graph[graphCount]; - for (int j = 0; j < statGraph[i].length; j++) { -// String[] d = (String[]) description.get(i); - statGraph[i][j] = fitnessFrame[i].getNewGraph(graphDesc.get(j).head + "_" + //Info + - graphInfoString); - } - } - } - } + } - private void plotFitnessPoint(int graph, int subGraph, int x, double y) { - if (fitnessGraph == null) { - EVAERROR.WARNING("fitness graph is null! (StatisticsWithGUI)"); - return; - } - if (graph >= fitnessGraph.length || subGraph >= fitnessGraph[graph].length) { - EVAERROR.WARNING("tried to plot to invalid graph! (StatisticsWithGUI)"); - return; - } - boolean isValidGraph = fitnessFrame[graph].isValid(); - if (!isValidGraph) { - // this happens if the user closed the plot window. - // if the plots are reinitialized immediately, the user might get angry, so wait (till next opt start) + protected void initPlots(PopulationInterface pop, List informerList) { + if (TRACE) { + System.out.println("initPlots"); + } + if (m_StatsParams instanceof StatisticsParameter) { +// StringSelection ss = ((StatsParameter)m_StatsParams).getGraphSelection(); + graphDesc = lastFieldSelection.getSelectedWithIndex(); +// for (int i=0; i 1 + && m_StatsParams.getUseStatPlot() == true) { +// String Info = m_StatsParams.GetInfoString(); + statGraph = new Graph[windowCount][]; + for (int i = 0; i < statGraph.length; i++) { + statGraph[i] = new Graph[graphCount]; + for (int j = 0; j < statGraph[i].length; j++) { +// String[] d = (String[]) description.get(i); + statGraph[i][j] = fitnessFrame[i].getNewGraph(graphDesc.get(j).head + "_" + //Info + + graphInfoString); + } + } + } + } + + private void plotFitnessPoint(int graph, int subGraph, int x, double y) { + if (fitnessGraph == null) { + EVAERROR.WARNING("fitness graph is null! (StatisticsWithGUI)"); + return; + } + if (graph >= fitnessGraph.length || subGraph >= fitnessGraph[graph].length) { + EVAERROR.WARNING("tried to plot to invalid graph! (StatisticsWithGUI)"); + return; + } + boolean isValidGraph = fitnessFrame[graph].isValid(); + if (!isValidGraph) { + // this happens if the user closed the plot window. + // if the plots are reinitialized immediately, the user might get angry, so wait (till next opt start) // EVAERROR.WARNING("fitness graph is invalid, trying to reinitialize..."); // initPlots(getDescription()); - } - if (isValidGraph) { + } + if (isValidGraph) { fitnessGraph[graph][subGraph].setConnectedPoint(x, y); } - } - - /** - * Plots the selected data to the fitness graphs. - */ - protected void plotCurrentResults() { + } + + /** + * Plots the selected data to the fitness graphs. + */ + protected void plotCurrentResults() { // m_PlotCounter--; // if (m_PlotCounter == 0) { // m_PlotCounter = m_StatsParams.GetPlotoutput(); - int subGraph=0; + int subGraph = 0; // boolean doPlotAdditionalInfo = m_StatsParams.isOutputAdditionalInfo(); - for (int i=0; i informer) { - double[] specificData = pop.getSpecificData(); - int calls = pop.getFunctionCalls(); - ArrayList description = new ArrayList(); - ArrayList temp = new ArrayList(); - String[] ss = pop.getSpecificDataNames(); - for (int i = 0; i < ss.length; i++) { - if (ss[i].lastIndexOf("*") == -1) { - temp.add(ss[i]); - } else { - String[] line = new String[temp.size()]; - temp.toArray(line); - description.add(line); - temp = new ArrayList(); - temp.add(ss[i]); - } - } - if (temp.size() > 0) { - String[] line = new String[temp.size()]; - temp.toArray(line); - description.add(line); + } - } - if (doTextOutput()) { - String s = "calls , " + calls + " bestfit , "; - s = s + BeanInspector.toString(currentBestFit); - if (currentWorstFit != null) { - s = s + " , worstfit , " + BeanInspector.toString(currentWorstFit); - } - printToTextListener(s + "\n"); - } + /** + * This method is more or less deprecated. The current standard population + * does not define specific data. However its used by the ES module + * implementation. + */ + public void plotSpecificData(PopulationInterface pop, List informer) { + double[] specificData = pop.getSpecificData(); + int calls = pop.getFunctionCalls(); + ArrayList description = new ArrayList(); + ArrayList temp = new ArrayList(); + String[] ss = pop.getSpecificDataNames(); + for (int i = 0; i < ss.length; i++) { + if (ss[i].lastIndexOf("*") == -1) { + temp.add(ss[i]); + } else { + String[] line = new String[temp.size()]; + temp.toArray(line); + description.add(line); + temp = new ArrayList(); + temp.add(ss[i]); + } + } + if (temp.size() > 0) { + String[] line = new String[temp.size()]; + temp.toArray(line); + description.add(line); + + } + if (doTextOutput()) { + String s = "calls , " + calls + " bestfit , "; + s = s + BeanInspector.toString(currentBestFit); + if (currentWorstFit != null) { + s = s + " , worstfit , " + BeanInspector.toString(currentWorstFit); + } + printToTextListener(s + "\n"); + } // m_PlotCounter--; // if (m_PlotCounter == 0) { // m_PlotCounter = m_StatsParams.GetPlotoutput(); - int index = 0; - for (int i = 0; i < fitnessGraph.length; i++) { - for (int j = 0; j < fitnessGraph[i].length; j++) { - plotFitnessPoint(i, j, calls, specificData[index]); - index++; - } - } + int index = 0; + for (int i = 0; i < fitnessGraph.length; i++) { + for (int j = 0; j < fitnessGraph[i].length; j++) { + plotFitnessPoint(i, j, calls, specificData[index]); + index++; + } + } // } - } - - public String getHostName() { - return hostName; - } + } + + public String getHostName() { + return hostName; + } } \ No newline at end of file diff --git a/src/eva2/server/stat/StatsParameter.java b/src/eva2/server/stat/StatsParameter.java deleted file mode 100644 index 6e0f9987..00000000 --- a/src/eva2/server/stat/StatsParameter.java +++ /dev/null @@ -1,419 +0,0 @@ -package eva2.server.stat; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import eva2.gui.BeanInspector; -import eva2.gui.GenericObjectEditor; -import eva2.server.go.InterfaceNotifyOnInformers; -import eva2.server.go.problems.InterfaceAdditionalPopulationInformer; -import eva2.tools.EVAERROR; -import eva2.tools.SelectedTag; -import eva2.tools.Serializer; -import eva2.tools.StringSelection; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A set of parameters for statistics in EvA2. Several data entries are provided by the AbstractStatistics class, - * others by the additional informers. This class allows customization of entries and frequency of data output. - * Data entries can be selected using a StringSelection instance. - * There is a switch called "output full data as text" which will be interpreted by AbstractStatistics showing - * all or only the selected entities. - * - * @see AbstractStatistics - * @author mkron - */ - -public class StatsParameter implements InterfaceStatisticsParameter, InterfaceNotifyOnInformers, Serializable { - private static final long serialVersionUID = -8681061379203108390L; - - private static boolean TRACE = false; - private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger); - - public final static int VERBOSITY_NONE = 0; - public final static int VERBOSITY_FINAL = 1; - public final static int VERBOSITY_KTH_IT = 2; - public final static int VERBOSITY_ALL = 3; - SelectedTag outputVerbosity = new SelectedTag("No output", "Final results", "K-th iterations", "All iterations"); - - public final static int OUTPUT_FILE = 0; - public final static int OUTPUT_WINDOW = 1; - public final static int OUTPUT_FILE_WINDOW = 2; - SelectedTag outputTo = new SelectedTag("File (current dir.)", "Text-window", "Both file and text-window"); - private int verboK = 10; - -// private int m_PlotFitness = PLOT_BEST; - private int m_Textoutput = 0; -// private int m_Plotoutput = 1; - private int m_MultiRuns = 1; - private String m_ResultFilePrefix = "EvA2"; - protected String m_Name = "not defined"; -// protected String m_InfoString = ""; - private boolean m_useStatPlot = true; - private boolean showAdditionalProblemInfo = false; - private double m_ConvergenceRateThreshold=0.001; - - private StringSelection graphSel = new StringSelection(GraphSelectionEnum.currentBest, GraphSelectionEnum.getInfoStrings()); - - /** - * - */ - public static StatsParameter getInstance(boolean loadDefaultSerFile) { - if (loadDefaultSerFile) { - return getInstance("Statistics.ser"); - } else { - return new StatsParameter(); - } - } - - /** - * Load or create a new instance of the class. - * - * @return A loaded (from file) or new instance of the class. - */ - public static StatsParameter getInstance(String serFileName) { - StatsParameter instance = null; - try { - FileInputStream fileStream = new FileInputStream(serFileName); - instance = (StatsParameter) Serializer.loadObject(fileStream); - } catch (FileNotFoundException ex) { - LOGGER.log(Level.WARNING, "Could not store instance object.", ex); - } - - if (instance == null) { - instance = new StatsParameter(); - } - return instance; - } - - /** - * - */ - public StatsParameter() { - m_Name = "Statistics"; - outputVerbosity.setSelectedTag(VERBOSITY_KTH_IT); - outputTo.setSelectedTag(1); - } - - /** - * - */ - public String toString() { - String ret = "\r\nStatParameter (" + super.toString() + "):\r\nm_MultiRuns=" + m_MultiRuns + - ", m_Textoutput=" + m_Textoutput + -// ", m_Plotoutput=" + m_Plotoutput + - ", verbosity= " + outputVerbosity.getSelectedString() + - "\nTo " + outputTo.getSelectedString() + - ", " + BeanInspector.toString(graphSel.getStrings()); - return ret; - } - - /** - * - */ - public void saveInstance() { - try { - FileOutputStream fileStream = new FileOutputStream("Statistics.ser"); - Serializer.storeObject(fileStream, this); - } catch (FileNotFoundException ex) { - LOGGER.log(Level.WARNING, "Could not store instance object.", ex); - } - } - - /** - * - */ - private StatsParameter(StatsParameter Source) { - m_ConvergenceRateThreshold = Source.m_ConvergenceRateThreshold; - m_useStatPlot = Source.m_useStatPlot; - m_Textoutput = Source.m_Textoutput; -// m_Plotoutput = Source.m_Plotoutput; -// m_PlotFitness = Source.m_PlotFitness; - m_MultiRuns = Source.m_MultiRuns; - m_ResultFilePrefix = Source.m_ResultFilePrefix; - verboK = Source.verboK; - } - - /** - * - */ - public Object getClone() { - return new StatsParameter(this); - } - - /** - * - */ - public String getName() { - return m_Name; - } - - public static String globalInfo() { - return "Configure statistics and output of the optimization run. Changes to the data selection state will not take effect during a run."; - } - -// /** -// * -// */ -// public String plotFrequencyTipText() { -// return "Frequency how often the fitness plot gets an update. plotoutput=1 -> there is a output every generation. plotoutput<0 -> there is no plot output"; -// } - -// /** -// * -// */ -// public String printMeanTipText() { -// return "Prints the mean of the fitness plot. Makes only sense when multiRuns > 1;"; -// } - - /** - * - */ - public void setMultiRuns(int x) { - m_MultiRuns = x; - } - - /** - * - */ - public int getMultiRuns() { - return m_MultiRuns; - } - - /** - * - */ - public String multiRunsTipText() { - return "Number of independent optimization runs to evaluate."; - } - -// /** -// * -// */ -// public String GetInfoString() { -// return m_InfoString; -// } -// -// /** -// * -// */ -// public void setInfoString(String s) { -// m_InfoString = s; -// } - - /** - * - */ - public String infoStringTipText() { - return "Infostring displayed on fitness graph by prssing the right mouse button."; - } - - /** - * Use averaged graph for multi-run plots or not - */ - public boolean GetUseStatPlot() { - return m_useStatPlot; - } - - /** - * Activate or deactivate averaged graph for multi-run plots - */ - public void setUseStatPlot(boolean x) { - m_useStatPlot = x; - } - - public String useStatPlotTipText() { - return "Plotting each fitness graph separately if multiruns > 1."; - } - - /** - * - */ - public void SetResultFilePrefix(String x) { - if (x==null) m_ResultFilePrefix = ""; - else m_ResultFilePrefix = x; - } - - /** - * - */ - public String getResultFilePrefix() { - return m_ResultFilePrefix; - } - - public void SetShowTextOutput(boolean show) { - // activate if not activated - if (show && outputTo.getSelectedTagID() == 0) outputTo.setSelectedTag(2); - // deactivate if activated - else if (!show && outputTo.getSelectedTagID()>0) outputTo.setSelectedTag(0); - } - - public boolean isShowTextOutput() { - return outputTo.getSelectedTagID()>0; - } - -// /** -// * -// */ -// public String resultFileNameTipText() { -// return "File name for the result file. If empty or 'none', no output file will be created."; -// } - - public String convergenceRateThresholdTipText() { - return "Provided the optimal fitness is at zero, give the threshold below which it is considered as 'reached'"; - } - - /** - * - * @param x - */ - public void setConvergenceRateThreshold(double x) { - m_ConvergenceRateThreshold = x; - } - - /** - * - */ - public double getConvergenceRateThreshold() { - return m_ConvergenceRateThreshold; - } - -// /** -// * @return the showOutputData -// */ -// public boolean isShowTextOutput() { -// return showTextOutput; -// } - -// /** -// * -// * @param showOutputData the showOutputData to set -// */ -// public void setShowTextOutput(boolean bShow) { -// this.showTextOutput = bShow; -// } - -// public String showTextOutputTipText() { -// return "Indicates whether further text output should be printed"; -// } - - public boolean isOutputAllFieldsAsText() { - return showAdditionalProblemInfo; - } - - public void setOutputAllFieldsAsText(boolean bShowFullText) { - showAdditionalProblemInfo = bShowFullText; - } - - public String outputAllFieldsAsTextTipText() { - return "Output all available data fields or only the selected entries as text."; - } - - public void hideHideable() { - setOutputVerbosity(getOutputVerbosity()); - } - - public void setOutputVerbosity(SelectedTag sTag) { - outputVerbosity = sTag; - GenericObjectEditor.setHideProperty(this.getClass(), "outputVerbosityK", sTag.getSelectedTagID() != VERBOSITY_KTH_IT); - } - - public void setOutputVerbosity(int i) { - outputVerbosity.setSelectedTag(i); - GenericObjectEditor.setHideProperty(this.getClass(), "outputVerbosityK", outputVerbosity.getSelectedTagID() != VERBOSITY_KTH_IT); - } - - public SelectedTag getOutputVerbosity() { - return outputVerbosity; - } - - public String outputVerbosityTipText() { - return "Set the data output level."; - } - - public int getOutputVerbosityK() { - return verboK; - } - - public void setOutputVerbosityK(int k) { - verboK = k; - } - - public String outputVerbosityKTipText() { - return "Set the interval of data output for intermediate verbosity (in generations)."; - } - - public SelectedTag getOutputTo() { - return outputTo; - } - - public void setOutputTo(SelectedTag tag) { - outputTo = tag; - } - - public void setOutputTo(int i) { - outputTo.setSelectedTag(i); - } - - public String outputToTipText() { - return "Set the output destination; to deactivate output, set verbosity to none."; - } - - public StringSelection getFieldSelection() { - return graphSel; - } - - public void setFieldSelection(StringSelection v) { - graphSel = v; - } - - public String fieldSelectionTipText() { - return "Select the data fields to be collected and plotted. Note that only simple types can be plotted to the GUI."; - } - - /** - * May be called to dynamically alter the set of graphs that can be selected, - * using a list of informer instances, which usually are the problem and the - * optimizer instance. - * - * @see InterfaceAdditionalPopulationInformer - */ - public void setInformers( - List informers) { - ArrayList headerFields = new ArrayList(); - ArrayList infoFields = new ArrayList(); - // parse list of header elements, show additional Strings according to names. - for (InterfaceAdditionalPopulationInformer inf : informers) { - String[] dataHeader = inf.getAdditionalDataHeader(); - headerFields.addAll(Arrays.asList(dataHeader)); - if (infoFields.size() stringToIndexHash = null; - private transient Class enumClass = null; - - /** - * Constructor with a String array of selectable strings and optional descriptions. - * - * @param sArr a String array of selectable strings - * @param tips descriptive strings of same length or null - */ - public StringSelection(String[] sArr, String[] tips) { - strObjects = sArr; - toolTips=tips; - selStates=new boolean[sArr.length]; - stringToIndexHash = null; - enumClass = null; - } - - /** - * Constructor with a String array of selectable strings and optional descriptions. - * A single element is preselected by index, all others deselected. - * - * @param sArr a String array of selectable strings - * @param tips descriptive strings of same length or null - * @param initialSel index of the preselected string - */ - public StringSelection(String[] sArr, String[] tips, int initialSel) { - this(sArr, tips); - if (initialSel e, String[] tips) { - strObjects = new String[e.getClass().getEnumConstants().length]; - toolTips=tips; - selStates = new boolean[strObjects.length]; - for (int i = 0; i < strObjects.length; i++) { - strObjects[i] = e.getClass().getEnumConstants()[i].toString(); - } - setSelected(e.ordinal(), true); - stringToIndexHash = null; - enumClass = e.getClass(); - } - - /** - * A copy constructor. - * - * @param stringSelection - */ - public StringSelection(StringSelection stringSelection) { - strObjects = stringSelection.strObjects.clone(); - selStates = stringSelection.selStates.clone(); - toolTips = stringSelection.toolTips.clone(); - stringToIndexHash = null; - enumClass = stringSelection.enumClass; - } - /** - * Construct a string selection that allows all enum fields of the given type plus a list of additional - * strings to be selected. The enum fields will be first in the selection list. - * - * @param e - * @param headerFields - */ - public StringSelection(Enum e, String[] enumTips, - List headerFields, String[] addTips) { - this(ToolBox.appendEnumAndArray(e, headerFields.toArray(new String[headerFields.size()])), - ToolBox.appendArrays(enumTips, addTips)); - enumClass = e.getClass(); - } + private static final long serialVersionUID = -1512329288445831907L; + private String[] strObjects; + private String[] toolTips; + boolean[] selStates; + private transient HashMap stringToIndexHash = null; + private transient Class enumClass = null; - public Object clone() { - return new StringSelection(this); - } - - public int getLength() { - return strObjects.length; - } - - public String getElement(int i) { - return strObjects[i]; - } - - /** - * Return a descriptive String for element i or null if none is provided. - * - * @param i index of the string element - * @return a descriptive String for element i or null - */ - public String getElementInfo(int i) { - if (toolTips!=null && (toolTips.length>i)) return toolTips[i]; - else return null; - } - - /** - * Retrieve the array of all selectable strings. - * - * @return - */ - public String[] getStrings() { - return strObjects; - } - - /** - * Get the selection state at the indicated index. - * - * @param i - * @return - */ - public boolean isSelected(int i) { - try { - return selStates[i]; - } catch(ArrayIndexOutOfBoundsException e) { - throw new ArrayIndexOutOfBoundsException(e.getMessage()+" - inconsistent implementation of InterfaceAdditionalPopulationInformer?"); - } - } - - /** - * Returns true if the given enum is selected (as its string representation) - * within the instance. This only works if the enum was used for the - * creation of this instance. - * - * @param e - * @return - */ - public boolean isSelected(Enum e) { + /** + * Constructor with a String array of selectable strings and optional + * descriptions. + * + * @param sArr a String array of selectable strings + * @param tips descriptive strings of same length or null + */ + public StringSelection(String[] sArr, String[] tips) { + strObjects = sArr; + toolTips = tips; + selStates = new boolean[sArr.length]; + stringToIndexHash = null; + enumClass = null; + } + + /** + * Constructor with a String array of selectable strings and optional + * descriptions. A single element is preselected by index, all others + * deselected. + * + * @param sArr a String array of selectable strings + * @param tips descriptive strings of same length or null + * @param initialSel index of the preselected string + */ + public StringSelection(String[] sArr, String[] tips, int initialSel) { + this(sArr, tips); + if (initialSel < getLength()) { + setSelected(initialSel, true); + } + enumClass = null; + } + + /** + * Constructor from an enum class and optional descriptions. + * + * @param e an enum from which the selectable strings will be taken + * @param tips descriptive strings of same length or null + */ + public StringSelection(Enum e, String[] tips) { + strObjects = new String[e.getClass().getEnumConstants().length]; + toolTips = tips; + selStates = new boolean[strObjects.length]; + for (int i = 0; i < strObjects.length; i++) { + strObjects[i] = e.getClass().getEnumConstants()[i].toString(); + } + setSelected(e.ordinal(), true); + stringToIndexHash = null; + enumClass = e.getClass(); + } + + /** + * A copy constructor. + * + * @param stringSelection + */ + public StringSelection(StringSelection stringSelection) { + strObjects = stringSelection.strObjects.clone(); + selStates = stringSelection.selStates.clone(); + toolTips = stringSelection.toolTips.clone(); + stringToIndexHash = null; + enumClass = stringSelection.enumClass; + } + + /** + * Construct a string selection that allows all enum fields of the given + * type plus a list of additional strings to be selected. The enum fields + * will be first in the selection list. + * + * @param e + * @param headerFields + */ + public StringSelection(Enum e, String[] enumTips, + List headerFields, String[] addTips) { + this(ToolBox.appendEnumAndArray(e, headerFields.toArray(new String[headerFields.size()])), + ToolBox.appendArrays(enumTips, addTips)); + enumClass = e.getClass(); + } + + public Object clone() { + return new StringSelection(this); + } + + public int getLength() { + return strObjects.length; + } + + public String getElement(int i) { + return strObjects[i]; + } + + /** + * Return a descriptive String for element i or null if none is provided. + * + * @param i index of the string element + * @return a descriptive String for element i or null + */ + public String getElementInfo(int i) { + if (toolTips != null && (toolTips.length > i)) { + return toolTips[i]; + } else { + return null; + } + } + + /** + * Retrieve the array of all selectable strings. + * + * @return + */ + public String[] getStrings() { + return strObjects; + } + + /** + * Get the selection state at the indicated index. + * + * @param i + * @return + */ + public boolean isSelected(int i) { + try { + return selStates[i]; + } catch (ArrayIndexOutOfBoundsException e) { + throw new ArrayIndexOutOfBoundsException(e.getMessage() + " - inconsistent implementation of InterfaceAdditionalPopulationInformer?"); + } + } + + /** + * Returns true if the given enum is selected (as its string representation) + * within the instance. This only works if the enum was used for the + * creation of this instance. + * + * @param e + * @return + */ + public boolean isSelected(Enum e) { // if (isSelected(e.ordinal())) { // return e.toString().equals(strObjects[e.ordinal()]); // } else return false; - if (enumClass!=null) { - if (e.getClass().equals(enumClass)) return isSelected(e.ordinal()); - else { - System.err.println("Error, the string selection was constructed with a different enum class - invalid request (StringSelection.isSelected(Enum)"); - return false; - } - } else { - System.err.println("Error, the string selection was constructed without an enum class - invalid request (StringSelection.isSelected(Enum)"); - return false; - } - } - - /** - * Check if a given string is selected within this instance. If the - * String is not found, false is returned. - * - * @param str - * @return - */ - public boolean isSelected(String str) { - if (stringToIndexHash == null) { // for some time efficiency... - stringToIndexHash = new HashMap(2*strObjects.length); - for (int i=0; i(2 * strObjects.length); + for (int i = 0; i < strObjects.length; i++) { + stringToIndexHash.put(strObjects[i], i); + } + } + Integer selIndex = stringToIndexHash.get(str); + if (selIndex == null) { + System.err.println("Error, unknown string for StringSelection: " + str + ", selectable were " + BeanInspector.toString(getStrings())); + return false; + } + return isSelected(selIndex); // for (int i=0; i(2*strObjects.length); - for (int i=0; i=0) { - setSelected(index,v); - } else { - System.err.println("Error, unknown string " + str + " cant be selected in " + this.getClass()); - } - } - - /** - * Set the selection state of a field. The index must be valid. - * - * @param i - * @param v - */ - public void setSelected(int i, boolean v) { - selStates[i]=v; - } - - /** - * Toggle the selection state of a field. The index must be valid. - * - * @param i - */ - public void toggleSelected(int i) { - selStates[i]=!selStates[i]; - } + } - /** - * Apply the selection state of the given instance to this instance. Compares - * Strings and takes over the selection state if they are equal. - * - * @param sel - */ - public void takeOverSelection(StringSelection sel) { - // try to apply the same selection for equivalent string (should be in same order) - int mismatchAt = -1; - for (int i=0; i(2 * strObjects.length); + for (int i = 0; i < strObjects.length; i++) { + stringToIndexHash.put(strObjects[i], i); + } + } + Integer selIndex = stringToIndexHash.get(str); + if (selIndex == null) { + return -1; + } else { + return selIndex.intValue(); + } + } + + /** + * Set the selection state of a field denoted by a String value. If the + * String is not represented within this instance, an error message is + * printed. + * + * @param str + * @param v + */ + public void setSelected(String str, boolean v) { + int index = stringToIndex(str); + if (index >= 0) { + setSelected(index, v); + } else { + System.err.println("Error, unknown string " + str + " can't be selected in " + this.getClass()); + } + } + + /** + * Set the selection state of a field. The index must be valid. + * + * @param i + * @param v + */ + public void setSelected(int i, boolean v) { + selStates[i] = v; + } + + /** + * Toggle the selection state of a field. The index must be valid. + * + * @param i + */ + public void toggleSelected(int i) { + selStates[i] = !selStates[i]; + } + + /** + * Apply the selection state of the given instance to this instance. + * Compares Strings and takes over the selection state if they are equal. + * + * @param sel + */ + public void takeOverSelection(StringSelection sel) { + // try to apply the same selection for equivalent string (should be in same order) + int mismatchAt = -1; + for (int i = 0; i < sel.getLength() && i < getLength(); i++) { + // hope that elements are aligned at the beginning and take over selection state + if (sel.getElement(i).equals(getElement(i))) { // System.out.println("Fit: " + getElement(i) + " / " + sel.getElement(i)); - setSelected(i, sel.isSelected(i)); - } else { + setSelected(i, sel.isSelected(i)); + } else { // System.out.println(" - does not fit: " + getElement(i) + " vs " + sel.getElement(i)); - mismatchAt = i; // if elements are not aligned, start double loop search at that point - break; - } - } - if (mismatchAt>=0) { - // double look search to find matching elements (equal strings) - for (int i=mismatchAt; i= 0) { + // double look search to find matching elements (equal strings) + for (int i = mismatchAt; i < getLength(); i++) { + for (int j = mismatchAt; j < sel.getLength(); j++) { + if (sel.getElement(j).equals(getElement(i))) { + // if strings match, take over the selection state // System.out.println("Fit: " + getElement(i) + " / " + sel.getElement(j)); - setSelected(i, sel.isSelected(j)); - } - } - } - } - } + setSelected(i, sel.isSelected(j)); + } + } + } + } + } - /** - * Return a sub-list of the selected items. - * - * @return - */ - public String[] getSelected() { - ArrayList ret = new ArrayList(); - for (int i=0; i> getSelectedWithIndex() { - ArrayList> ret = new ArrayList>(); - for (int i=0; i(getElement(i), i)); - return ret; - } + /** + * Return a sub-list of the selected items. + * + * @return + */ + public String[] getSelected() { + ArrayList ret = new ArrayList(); + for (int i = 0; i < getLength(); i++) { + if (isSelected(i)) { + ret.add(getElement(i)); + } + } + return ret.toArray(new String[ret.size()]); + } - /** - * Return only those selected fields which are members of the given enum. - * @param e - * @return - */ - public Enum[] getSelectedEnum(Enum[] e) { - LinkedList selectedList = new LinkedList(); - for (int i=0; i iter = selectedList.iterator(); - int i=0; - while (iter.hasNext()) { - ret[i++]=e[iter.next()]; - } - return ret; - } + /** + * Return a sub-list of the selected items paired up with the respective + * index. + * + * @return + */ + public List> getSelectedWithIndex() { + ArrayList> ret = new ArrayList>(); + for (int i = 0; i < getLength(); i++) { + if (isSelected(i)) { + ret.add(new Pair(getElement(i), i)); + } + } + return ret; + } - /** - * Select all or deselect all items. - * - * @param selState - */ - public void setAllSelectionStates(boolean selState) { - for (int i=0; i selectedList = new LinkedList(); + for (int i = 0; i < e.length; i++) { + if (isSelected(e[i])) { + selectedList.add(i); + } + } + Enum[] ret = (Enum[]) java.lang.reflect.Array.newInstance(e[0].getClass(), selectedList.size()); + Iterator iter = selectedList.iterator(); + int i = 0; + while (iter.hasNext()) { + ret[i++] = e[iter.next()]; + } + return ret; + } + + /** + * Select all or deselect all items. + * + * @param selState + */ + public void setAllSelectionStates(boolean selState) { + for (int i = 0; i < selStates.length; i++) { + selStates[i] = selState; + } + } } \ No newline at end of file diff --git a/src/eva2/tools/chart2d/DArea.java b/src/eva2/tools/chart2d/DArea.java index 0b5aaeb4..8737968d 100644 --- a/src/eva2/tools/chart2d/DArea.java +++ b/src/eva2/tools/chart2d/DArea.java @@ -786,7 +786,7 @@ public class DArea extends JComponent implements DParent, Printable { System.out.println("DArea.setVisibleRectangle(DRectangle)"); if (rect.isEmpty()) throw new IllegalArgumentException( - "You shopuld never try to set an empty rectangle\n" + "You should never try to set an empty rectangle\n" + "as the visible rectangle of an DArea"); if (!rect.equals(visible_rect) && rect.getWidth() > 0