Renamed StatsParameter to StatisticsParameter.

Refactored code. 

Added comments.
This commit is contained in:
Fabian Becker 2012-06-22 14:26:51 +00:00
parent 8582b79590
commit 00b6af14ff
14 changed files with 2306 additions and 2265 deletions

View File

@ -246,7 +246,7 @@ public class OptimizerRunnable implements Runnable {
* @param outp * @param outp
*/ */
public void setOutputTo(int outp) { public void setOutputTo(int outp) {
((StatsParameter)proc.getStatistics().getStatisticsParameter()).setOutputTo(outp); ((StatisticsParameter)proc.getStatistics().getStatisticsParameter()).setOutputTo(outp);
} }
/** /**

File diff suppressed because it is too large Load Diff

View File

@ -121,8 +121,8 @@ public class Plot implements PlotInterface, Serializable {
m_PlotArea.toggleLog(); m_PlotArea.toggleLog();
} }
}); });
JButton ExportButton = new JButton("Export..."); JButton ExportButton = new JButton("Export to TSV");
ExportButton.setToolTipText("Exports the graph data to a simple ascii file."); ExportButton.setToolTipText("Exports the graph data to a simple TSV file.");
ExportButton.addActionListener(new ActionListener() { ExportButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {

View File

@ -33,7 +33,7 @@ import eva2.server.go.strategies.HillClimbing;
import eva2.server.go.strategies.NelderMeadSimplex; import eva2.server.go.strategies.NelderMeadSimplex;
import eva2.server.modules.GOParameters; import eva2.server.modules.GOParameters;
import eva2.server.stat.InterfaceTextListener; import eva2.server.stat.InterfaceTextListener;
import eva2.server.stat.StatsParameter; import eva2.server.stat.StatisticsParameter;
import eva2.tools.Pair; import eva2.tools.Pair;
import eva2.tools.math.Mathematics; import eva2.tools.math.Mathematics;
import java.util.ArrayList; import java.util.ArrayList;
@ -805,7 +805,7 @@ public class PostProcess {
*/ */
private static void runPP(OptimizerRunnable rnbl) { private static void runPP(OptimizerRunnable rnbl) {
rnbl.getGOParams().setDoPostProcessing(false); rnbl.getGOParams().setDoPostProcessing(false);
rnbl.setVerbosityLevel(StatsParameter.VERBOSITY_NONE); rnbl.setVerbosityLevel(StatisticsParameter.VERBOSITY_NONE);
ppRunnables.add(rnbl); ppRunnables.add(rnbl);
// System.err.println("Starting runbl " + rnbl); // System.err.println("Starting runbl " + rnbl);
rnbl.run(); rnbl.run();

View File

@ -188,7 +188,7 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter
String startDate = getDateString(); String startDate = getDateString();
// open the result file: // open the result file:
if (doFileOutput() // not "text-window only" 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("")) { //!resFName.equalsIgnoreCase("none") && !resFName.equals("")) {
String fnameBase = makeOutputFileName(m_StatsParams.getResultFilePrefix(), infoString, startDate); String fnameBase = makeOutputFileName(m_StatsParams.getResultFilePrefix(), infoString, startDate);
int cnt=0; int cnt=0;
@ -1136,22 +1136,22 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter
* @return * @return
*/ */
private boolean printLineByVerbosity(int iteration) { private boolean printLineByVerbosity(int iteration) {
return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatsParameter.VERBOSITY_KTH_IT) return (m_StatsParams.getOutputVerbosity().getSelectedTagID() > StatisticsParameter.VERBOSITY_KTH_IT)
|| ((m_StatsParams.getOutputVerbosity().getSelectedTagID() == StatsParameter.VERBOSITY_KTH_IT) || ((m_StatsParams.getOutputVerbosity().getSelectedTagID() == StatisticsParameter.VERBOSITY_KTH_IT)
&& (isKthRun(iteration, m_StatsParams.getOutputVerbosityK()))); && (isKthRun(iteration, m_StatsParams.getOutputVerbosityK())));
} }
private boolean printRunIntroVerbosity() { private boolean printRunIntroVerbosity() {
return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatsParameter.VERBOSITY_KTH_IT) return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT)
|| (optRunsPerformed==0 && (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatsParameter.VERBOSITY_FINAL)); || (optRunsPerformed==0 && (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_FINAL));
} }
private boolean printRunStoppedVerbosity() { private boolean printRunStoppedVerbosity() {
return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatsParameter.VERBOSITY_KTH_IT); return (m_StatsParams.getOutputVerbosity().getSelectedTagID() >= StatisticsParameter.VERBOSITY_KTH_IT);
} }
private boolean printFinalVerbosity() { 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) { private boolean isKthRun(int i, int k) {
@ -1166,7 +1166,7 @@ public abstract class AbstractStatistics implements InterfaceTextListener, Inter
} }
private boolean printHeaderByVerbosity() { 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) { private static void divideMean(Double[] mean, double d) {

View File

@ -12,180 +12,203 @@ package eva2.server.stat;
/*==========================================================================* /*==========================================================================*
* IMPORTS * IMPORTS
*==========================================================================*/ *==========================================================================*/
import java.io.Serializable;
import java.lang.reflect.Field;
import eva2.gui.DataViewer; import eva2.gui.DataViewer;
import eva2.gui.DataViewerInterface; import eva2.gui.DataViewerInterface;
import eva2.gui.Graph; import eva2.gui.Graph;
import eva2.tools.jproxy.MainAdapterClient; 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 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;
} private static final Logger LOGGER = Logger.getLogger(GenericStatistics.class.getName());
/** //private Object m_target;
* private int test;
*/ private String[] propertyNames;
public GenericStatistics(Object target) { private boolean[] states;
//m_target = target; private transient Field[] fields;
//System.out.println("GenericStatistics-->"); private DataViewerInterface viewer;
try { private Graph graph;
m_fields = getDeclaredFields(target); private static MainAdapterClient mainAdapterClient;
//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<m_fields.length;i++) { */
String desc = m_fields[i].toString(); //System.out.println("desc "+desc); public static void setMainAdapterClient(MainAdapterClient adapter) {
int istransient = desc.indexOf("transient"); mainAdapterClient = adapter;
//if (TRACE) System.out.println("Field :"+m_fields[i].getName() );
Object FieldValue = null;
if (istransient==-1 || m_fields[i].getName().equals("elementData")) { // the elementdatahack
m_fields[i].setAccessible(true);
FieldValue = m_fields[i].get(target);
}
m_PropertyNames[i] = m_fields[i].getName();
}
} catch (Exception ex) {
System.out.println("ERROR in GenericStatistics:"+ex.getMessage());
ex.printStackTrace();
} }
}
/** /**
* *
*/ */
public void setTest(int Test) { public GenericStatistics getClone() {
m_Test = Test; return new GenericStatistics(this);
}
/**
*
*/
public int getTest() {
return m_Test;
}
/**
*
*/
public String[] getPropertyNames() {
return m_PropertyNames;
}
/**
*
*/
public boolean[] getState() {
return m_State;
}
/**
*
*/
public void setState(boolean[] x) {
System.out.println("in statistics setState !!!!!!!!!!!!!!!!!!");
m_State = x;
}
/**
*
*/
public void initViewer() {
m_Viewer = DataViewer.getInstance(m_MainAdapterClient,"test");
m_Graph = m_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++; *
*/
private GenericStatistics(GenericStatistics Source) {
//m_target = Source.m_target;
test = Source.test;
propertyNames = Source.propertyNames;
states = Source.states;
fields = Source.fields;
viewer = Source.viewer;
graph = Source.graph;
} }
return ret;
} /**
/** *
* */
*/ public GenericStatistics(Object target) {
public void statechanged(Object target) { //m_target = target;
int len=0; //System.out.println("GenericStatistics-->");
for (int i=0;i<m_State.length;i++) try {
if (m_State[i]==true) len++; fields = getDeclaredFields(target);
if (len==0) return; //if (TRACE) System.out.println("fields-->"+m_fields.length);
if (m_Viewer == null) initViewer(); propertyNames = new String[fields.length];
double[] data = new double[len]; states = new boolean[fields.length];
try { for (int i = 0; i < fields.length; i++) {
m_fields = getDeclaredFields(target); String desc = fields[i].toString(); //System.out.println("desc "+desc);
} catch (Exception ex) { int istransient = desc.indexOf("transient");
System.out.println("ERROR in GenericStatistics:"+ex.getMessage()); //if (TRACE) System.out.println("Field :"+m_fields[i].getName() );
ex.printStackTrace(); Object FieldValue = null;
} if (istransient == -1 || fields[i].getName().equals("elementData")) { // the elementdatahack
int index =0; fields[i].setAccessible(true);
for (int i=0;i<m_fields.length;i++) { FieldValue = fields[i].get(target);
for (int n=0;n<m_PropertyNames.length;n++) { }
if (this.m_State[n]==false) propertyNames[i] = fields[i].getName();
continue;
if (m_fields[i].getName().equals(m_PropertyNames[n])) {
String desc = m_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 || m_fields[i].getName().equals("elementData")) { // the elementdatahack
m_fields[i].setAccessible(true);
try {
FieldValue = m_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();
} }
} } catch (Exception ex) {
break; 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]);
}
} }

View File

@ -9,51 +9,48 @@ import eva2.tools.StringSelection;
* @see StatsParameter * @see StatsParameter
*/ */
public interface InterfaceStatisticsParameter { public interface InterfaceStatisticsParameter {
public String getName(); String getName();
public void saveInstance(); void saveInstance();
// public String globalInfo(); void setMultiRuns(int x);
// public void setTextoutput(int i); int getMultiRuns();
// public void setPlotoutput(int i); // noone knows what these were useful for... String multiRunsTipText();
// public int GetPlotoutput();
// public int GetTextoutput();
// public String textoutputTipText();
// public String plotFrequencyTipText();
public void setMultiRuns(int x);
public int getMultiRuns();
public 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<String[]> getPlotDescriptions(); /**
* Activate averaged graph for multi-run plots.
*
* @param x If averaged graph should be activated.
*/
void setUseStatPlot(boolean x);
// public SelectedTag getPlotData(); StringSelection getFieldSelection();
// public void setPlotData(SelectedTag newMethod); void setFieldSelection(StringSelection v);
public StringSelection getFieldSelection(); String getResultFilePrefix();
public void setFieldSelection(StringSelection v); void setResultFilePrefix(String x);
public String getResultFilePrefix(); void setConvergenceRateThreshold(double x);
public void SetResultFilePrefix(String x); double getConvergenceRateThreshold();
public void setConvergenceRateThreshold(double x); void setShowTextOutput(boolean show);
public double getConvergenceRateThreshold(); boolean isShowTextOutput();
public void SetShowTextOutput(boolean show); boolean isOutputAllFieldsAsText();
public boolean isShowTextOutput(); void setOutputAllFieldsAsText(boolean bShowFullText);
public boolean isOutputAllFieldsAsText(); void setOutputVerbosity(SelectedTag sTag);
public void setOutputAllFieldsAsText(boolean bShowFullText); SelectedTag getOutputVerbosity();
public void setOutputVerbosity(SelectedTag sTag); int getOutputVerbosityK();
public SelectedTag getOutputVerbosity(); void setOutputVerbosityK(int k);
public int getOutputVerbosityK(); void setOutputTo(SelectedTag sTag);
public void setOutputVerbosityK(int k); SelectedTag getOutputTo();
public void setOutputTo(SelectedTag sTag);
public SelectedTag getOutputTo();
} }

View File

@ -18,19 +18,19 @@ import eva2.server.go.strategies.InterfaceOptimizer;
*/ */
public class StatisticsDummy implements InterfaceStatistics, InterfaceTextListener { public class StatisticsDummy implements InterfaceStatistics, InterfaceTextListener {
boolean consoleOut = false; boolean consoleOut = false;
StatsParameter sParams = null; StatisticsParameter sParams = null;
AbstractEAIndividual bestCurrentIndividual, bestRunIndy, bestIndividualAllover; AbstractEAIndividual bestCurrentIndividual, bestRunIndy, bestIndividualAllover;
public StatisticsDummy() { public StatisticsDummy() {
bestIndividualAllover = null; bestIndividualAllover = null;
sParams = new StatsParameter(); sParams = new StatisticsParameter();
sParams.setOutputVerbosityK(StatsParameter.VERBOSITY_NONE); sParams.setOutputVerbosityK(StatisticsParameter.VERBOSITY_NONE);
} }
public StatisticsDummy(boolean doConsoleOut) { public StatisticsDummy(boolean doConsoleOut) {
bestIndividualAllover = null; bestIndividualAllover = null;
sParams = new StatsParameter(); sParams = new StatisticsParameter();
sParams.setOutputVerbosityK(StatsParameter.VERBOSITY_NONE); sParams.setOutputVerbosityK(StatisticsParameter.VERBOSITY_NONE);
consoleOut = doConsoleOut; consoleOut = doConsoleOut;
} }

View File

@ -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<InterfaceAdditionalPopulationInformer> informers) {
ArrayList<String> headerFields = new ArrayList<String>();
ArrayList<String> infoFields = new ArrayList<String>();
// 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);
}
}

View File

@ -58,21 +58,21 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac
} }
public StatisticsStandalone(String resultFileName) { 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) { public StatisticsStandalone(String resultFileName, int multiRuns, int verbosity, boolean outputAllFieldsAsText) {
this(StatsParameter.getInstance(false)); this(StatisticsParameter.getInstance(false));
m_StatsParams.setMultiRuns(multiRuns); m_StatsParams.setMultiRuns(multiRuns);
m_StatsParams.setOutputVerbosity(m_StatsParams.getOutputVerbosity().setSelectedTag(verbosity)); m_StatsParams.setOutputVerbosity(m_StatsParams.getOutputVerbosity().setSelectedTag(verbosity));
m_StatsParams.SetResultFilePrefix(resultFileName); m_StatsParams.setResultFilePrefix(resultFileName);
m_StatsParams.setOutputAllFieldsAsText(outputAllFieldsAsText); m_StatsParams.setOutputAllFieldsAsText(outputAllFieldsAsText);
if (resultFileName==null) m_StatsParams.getOutputTo().setSelectedTag(StatsParameter.OUTPUT_WINDOW); if (resultFileName==null) m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_WINDOW);
else m_StatsParams.setOutputTo(m_StatsParams.getOutputTo().setSelectedTag(StatsParameter.OUTPUT_FILE)); else m_StatsParams.setOutputTo(m_StatsParams.getOutputTo().setSelectedTag(StatisticsParameter.OUTPUT_FILE));
} }
public StatisticsStandalone() { public StatisticsStandalone() {
this(new StatsParameter()); this(new StatisticsParameter());
} }
protected void initPlots(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informerList) { protected void initPlots(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informerList) {

View File

@ -43,261 +43,270 @@ import java.util.logging.Logger;
* from AbstractStatistics. * from AbstractStatistics.
*/ */
public class StatisticsWithGUI extends AbstractStatistics implements Serializable, InterfaceStatistics { public class StatisticsWithGUI extends AbstractStatistics implements Serializable, InterfaceStatistics {
private static final long serialVersionUID = 3213603978877954103L; private static final long serialVersionUID = 3213603978877954103L;
private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger); private static final Logger LOGGER = Logger.getLogger(StatisticsWithGUI.class.getName());
// Plot frames: // Plot frames:
private GraphWindow[] fitnessFrame; // frame for the fitness plots private GraphWindow[] fitnessFrame; // frame for the fitness plots
private Graph[][] fitnessGraph; private Graph[][] fitnessGraph;
private Graph[][] statGraph; private Graph[][] statGraph;
private String graphInfoString;
private String graphInfoString; protected int plotCounter;
protected int plotCounter; private MainAdapterClient mainAdapterClient; // the connection to the client MainAdapter
private JTextoutputFrameInterface proxyPrinter;
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
/* List of descriptor strings and optional indices. strictly its * some time.
* redundant since super.lastGraphSelection is always available.
* However it spares some time.
*/ */
private transient List<Pair<String, Integer>> graphDesc = null; private transient List<Pair<String, Integer>> graphDesc = null;
protected static String hostName = null;
protected static String hostName = null; /**
*
*/
public MainAdapterClient getMainAdapterClient() {
return mainAdapterClient;
}
/** /**
* *
*/ */
public MainAdapterClient getMainAdapterClient() { public StatisticsWithGUI(MainAdapterClient client) {
return mainAdapterClient; 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);
public StatisticsWithGUI(MainAdapterClient client) { }
mainAdapterClient = client; } else {
if (client != null) { // We are probably in rmi mode hostName = "localhost";
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)) { if ((client == null) || client.getHostName().equals(hostName)) {
m_StatsParams = StatsParameter.getInstance(true); m_StatsParams = StatisticsParameter.getInstance(true);
proxyPrinter = new JTextoutputFrame("TextOutput of " + hostName); proxyPrinter = new JTextoutputFrame("TextOutput of " + hostName);
} else { // we use RMI } else { // we use RMI
m_StatsParams = (InterfaceStatisticsParameter)RMIProxyLocal.newInstance( m_StatsParams = (InterfaceStatisticsParameter) RMIProxyLocal.newInstance(
StatsParameter.getInstance(true)); StatisticsParameter.getInstance(true));
proxyPrinter = (JTextoutputFrameInterface) RMIProxyRemote.newInstance(new proxyPrinter = (JTextoutputFrameInterface) RMIProxyRemote.newInstance(new JTextoutputFrame("TextOutput " + hostName),
JTextoutputFrame("TextOutput " + hostName), mainAdapterClient);
mainAdapterClient); }
} addTextListener(proxyPrinter);
addTextListener(proxyPrinter); }
}
/** /**
* *
*/ */
public synchronized void startOptPerformed(String infoString, int runNumber, Object goParams, List<InterfaceAdditionalPopulationInformer> informerList) { public synchronized void startOptPerformed(String infoString, int runNumber, Object goParams, List<InterfaceAdditionalPopulationInformer> informerList) {
super.startOptPerformed(infoString, runNumber, goParams, informerList); super.startOptPerformed(infoString, runNumber, goParams, informerList);
graphInfoString = infoString; graphInfoString = infoString;
// m_TextCounter = m_StatisticsParameter.GetTextoutput(); // m_TextCounter = m_StatisticsParameter.GetTextoutput();
// m_PlotCounter = m_StatsParams.GetPlotoutput(); // m_PlotCounter = m_StatsParams.GetPlotoutput();
if ((fitnessFrame!=null) && (fitnessFrame[0]!=null)) { if ((fitnessFrame != null) && (fitnessFrame[0] != null)) {
PlotInterface p = fitnessFrame[0].getPlotter(); PlotInterface p = fitnessFrame[0].getPlotter();
if ((p!=null) && p.isValid()) ((Plot)p).getFunctionArea().clearLegend(); if ((p != null) && p.isValid()) {
} ((Plot) p).getFunctionArea().clearLegend();
} }
}
}
public void stopOptPerformed(boolean normal, String stopMessage) { public void stopOptPerformed(boolean normal, String stopMessage) {
super.stopOptPerformed(normal, stopMessage); super.stopOptPerformed(normal, stopMessage);
if (optRunsPerformed > m_StatsParams.getMultiRuns()) { if (optRunsPerformed > m_StatsParams.getMultiRuns()) {
// this may happen if the user reduces the multirun parameter during late multiruns // this may happen if the user reduces the multirun parameter during late multiruns
System.err.println("error: more runs performed than defined."); System.err.println("error: more runs performed than defined.");
} }
int fullRuns=optRunsPerformed; int fullRuns = optRunsPerformed;
if (!normal) fullRuns--; if (!normal) {
fullRuns--;
}
// unite the graphs only if the break was "normal" // unite the graphs only if the break was "normal"
if ((m_StatsParams.getMultiRuns() > 1) && (statGraph != null)) { if ((m_StatsParams.getMultiRuns() > 1) && (statGraph != null)) {
// unite the point sets for a multirun // unite the point sets for a multirun
for (int i = 0; i < fitnessGraph.length; i++) { for (int i = 0; i < fitnessGraph.length; i++) {
for (int j = 0; j < fitnessGraph[i].length; j++) { for (int j = 0; j < fitnessGraph[i].length; j++) {
statGraph[i][j].setInfoString( statGraph[i][j].setInfoString(
(fitnessGraph[i][j].getInfo().length() > 0 ? (fitnessGraph[i][j].getInfo() + "_") : "" ) (fitnessGraph[i][j].getInfo().length() > 0 ? (fitnessGraph[i][j].getInfo() + "_") : "")
+ "Mean_of_" + fullRuns + " ", + "Mean_of_" + fullRuns + " ",
(float) 2.0); (float) 2.0);
if (normal && fitnessFrame[i].isValid() && (fitnessGraph[i][j].getPointCount()>0)) { if (normal && fitnessFrame[i].isValid() && (fitnessGraph[i][j].getPointCount() > 0)) {
statGraph[i][j].addGraph(fitnessGraph[i][j]); statGraph[i][j].addGraph(fitnessGraph[i][j]);
fitnessGraph[i][j].clear(); fitnessGraph[i][j].clear();
} }
} }
} }
} }
PlotInterface p = fitnessFrame[0].getPlotter(); PlotInterface p = fitnessFrame[0].getPlotter();
if ((optRunsPerformed >= m_StatsParams.getMultiRuns()) || !normal) { if ((optRunsPerformed >= m_StatsParams.getMultiRuns()) || !normal) {
// update the legend after the last multirun or after a user break // update the legend after the last multirun or after a user break
if ((p!=null) && p.isValid()) { if ((p != null) && p.isValid()) {
((Plot)p).getFunctionArea().updateLegend(); ((Plot) p).getFunctionArea().updateLegend();
} }
} }
} }
public void maybeShowProxyPrinter() { public void maybeShowProxyPrinter() {
if (proxyPrinter != null) { if (proxyPrinter != null) {
proxyPrinter.setShow(m_StatsParams.isShowTextOutput()); proxyPrinter.setShow(m_StatsParams.isShowTextOutput());
} }
} }
protected void initPlots(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informerList) { protected void initPlots(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informerList) {
if (TRACE) System.out.println("initPlots"); if (TRACE) {
if (m_StatsParams instanceof StatsParameter) { System.out.println("initPlots");
}
if (m_StatsParams instanceof StatisticsParameter) {
// StringSelection ss = ((StatsParameter)m_StatsParams).getGraphSelection(); // StringSelection ss = ((StatsParameter)m_StatsParams).getGraphSelection();
graphDesc = lastFieldSelection.getSelectedWithIndex(); graphDesc = lastFieldSelection.getSelectedWithIndex();
// for (int i=0; i<description.get(0).length; i++) graphDesc.add(description.get(0)[i]); // for (int i=0; i<description.get(0).length; i++) graphDesc.add(description.get(0)[i]);
} else { } else {
graphDesc = null; graphDesc = null;
System.err.println("Error in StatisticsWithGUI.initPlots()!"); System.err.println("Error in StatisticsWithGUI.initPlots()!");
} }
maybeShowProxyPrinter(); maybeShowProxyPrinter();
int windowCount = 1; // TODO this was earlier description.length for the 2-D String-Array returned by m_StatsParams.getPlotDescriptions, which however always returned an array of length 1 (in the first dim). int windowCount = 1; // TODO this was earlier description.length for the 2-D String-Array returned by m_StatsParams.getPlotDescriptions, which however always returned an array of length 1 (in the first dim).
int graphCount = graphDesc.size(); int graphCount = graphDesc.size();
// System.out.println("Initializing " + graphCount + " plots (StatisticsWithGUI)"); // System.out.println("Initializing " + graphCount + " plots (StatisticsWithGUI)");
fitnessFrame = new GraphWindow[windowCount]; fitnessFrame = new GraphWindow[windowCount];
for (int i = 0; i < fitnessFrame.length; i++) { for (int i = 0; i < fitnessFrame.length; i++) {
fitnessFrame[i] = GraphWindow.getInstance(mainAdapterClient, "Optimization " + i + " " + " on " + hostName, "function calls", "fitness"); fitnessFrame[i] = GraphWindow.getInstance(mainAdapterClient, "Optimization " + i + " " + " on " + hostName, "function calls", "fitness");
} }
fitnessGraph = new Graph[windowCount][]; fitnessGraph = new Graph[windowCount][];
// contains one graph for every value to be plotted (best / worst / best+worst) // contains one graph for every value to be plotted (best / worst / best+worst)
// TODO Im really not sure why this is a 2-dimensional array. shouldnt one be enough? // TODO Im really not sure why this is a 2-dimensional array. shouldnt one be enough?
for (int i = 0; i < fitnessGraph.length; i++) { for (int i = 0; i < fitnessGraph.length; i++) {
fitnessGraph[i] = new Graph[graphCount]; fitnessGraph[i] = new Graph[graphCount];
for (int j = 0; j < fitnessGraph[i].length; j++) { for (int j = 0; j < fitnessGraph[i].length; j++) {
// String[] d = (String[]) description.get(i); // String[] d = (String[]) description.get(i);
// this is where the column string for ascii export is created! Uah! // this is where the column string for ascii export is created! Uah!
fitnessGraph[i][j] = fitnessGraph[i][j] =
fitnessFrame[i].getNewGraph(graphDesc.get(j).head + "_" fitnessFrame[i].getNewGraph(graphDesc.get(j).head + "_"
+ graphInfoString); + graphInfoString);
fitnessGraph[i][j].jump(); fitnessGraph[i][j].jump();
} }
} }
if (m_StatsParams.getMultiRuns() > 1 && if (m_StatsParams.getMultiRuns() > 1
m_StatsParams.GetUseStatPlot() == true) { && m_StatsParams.getUseStatPlot() == true) {
// String Info = m_StatsParams.GetInfoString(); // String Info = m_StatsParams.GetInfoString();
statGraph = new Graph[windowCount][]; statGraph = new Graph[windowCount][];
for (int i = 0; i < statGraph.length; i++) { for (int i = 0; i < statGraph.length; i++) {
statGraph[i] = new Graph[graphCount]; statGraph[i] = new Graph[graphCount];
for (int j = 0; j < statGraph[i].length; j++) { for (int j = 0; j < statGraph[i].length; j++) {
// String[] d = (String[]) description.get(i); // String[] d = (String[]) description.get(i);
statGraph[i][j] = fitnessFrame[i].getNewGraph(graphDesc.get(j).head + "_" + //Info + statGraph[i][j] = fitnessFrame[i].getNewGraph(graphDesc.get(j).head + "_" + //Info +
graphInfoString); graphInfoString);
} }
} }
} }
} }
private void plotFitnessPoint(int graph, int subGraph, int x, double y) { private void plotFitnessPoint(int graph, int subGraph, int x, double y) {
if (fitnessGraph == null) { if (fitnessGraph == null) {
EVAERROR.WARNING("fitness graph is null! (StatisticsWithGUI)"); EVAERROR.WARNING("fitness graph is null! (StatisticsWithGUI)");
return; return;
} }
if (graph >= fitnessGraph.length || subGraph >= fitnessGraph[graph].length) { if (graph >= fitnessGraph.length || subGraph >= fitnessGraph[graph].length) {
EVAERROR.WARNING("tried to plot to invalid graph! (StatisticsWithGUI)"); EVAERROR.WARNING("tried to plot to invalid graph! (StatisticsWithGUI)");
return; return;
} }
boolean isValidGraph = fitnessFrame[graph].isValid(); boolean isValidGraph = fitnessFrame[graph].isValid();
if (!isValidGraph) { if (!isValidGraph) {
// this happens if the user closed the plot window. // 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) // 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..."); // EVAERROR.WARNING("fitness graph is invalid, trying to reinitialize...");
// initPlots(getDescription()); // initPlots(getDescription());
} }
if (isValidGraph) { if (isValidGraph) {
fitnessGraph[graph][subGraph].setConnectedPoint(x, y); fitnessGraph[graph][subGraph].setConnectedPoint(x, y);
} }
} }
/** /**
* Plots the selected data to the fitness graphs. * Plots the selected data to the fitness graphs.
*/ */
protected void plotCurrentResults() { protected void plotCurrentResults() {
// m_PlotCounter--; // m_PlotCounter--;
// if (m_PlotCounter == 0) { // if (m_PlotCounter == 0) {
// m_PlotCounter = m_StatsParams.GetPlotoutput(); // m_PlotCounter = m_StatsParams.GetPlotoutput();
int subGraph=0; int subGraph = 0;
// boolean doPlotAdditionalInfo = m_StatsParams.isOutputAdditionalInfo(); // boolean doPlotAdditionalInfo = m_StatsParams.isOutputAdditionalInfo();
for (int i=0; i<graphDesc.size(); i++) { for (int i = 0; i < graphDesc.size(); i++) {
Integer colIndex = i+1; // always add one because the function calls are located in column zero Integer colIndex = i + 1; // always add one because the function calls are located in column zero
if (lastIsShowFull) colIndex = 1+graphDesc.get(i).tail; if (lastIsShowFull) {
// plot the column as indicated by the graph description colIndex = 1 + graphDesc.get(i).tail;
if (currentStatDoubleData[colIndex]!=null) plotFitnessPoint(0, subGraph++, functionCalls, currentStatDoubleData[colIndex]); }
else { // plot the column as indicated by the graph description
if (currentStatDoubleData[colIndex] != null) {
plotFitnessPoint(0, subGraph++, functionCalls, currentStatDoubleData[colIndex]);
} else {
// EVAERROR.errorMsgOnce("Error, data field " + graphDesc.get(i).head + " does not contain primitive data and cannot be plotted."); // EVAERROR.errorMsgOnce("Error, data field " + graphDesc.get(i).head + " does not contain primitive data and cannot be plotted.");
subGraph++; // increase index anyways or the name assignment gets inconsistent subGraph++; // increase index anyways or the name assignment gets inconsistent
} }
} }
// } // }
} }
/** /**
* This method is more or less deprecated. The current standard population does not * This method is more or less deprecated. The current standard population
* define specific data. However its used by the ES module implementation. * does not define specific data. However its used by the ES module
*/ * implementation.
public void plotSpecificData(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informer) { */
double[] specificData = pop.getSpecificData(); public void plotSpecificData(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informer) {
int calls = pop.getFunctionCalls(); double[] specificData = pop.getSpecificData();
ArrayList<String[]> description = new ArrayList<String[]>(); int calls = pop.getFunctionCalls();
ArrayList<String> temp = new ArrayList<String>(); ArrayList<String[]> description = new ArrayList<String[]>();
String[] ss = pop.getSpecificDataNames(); ArrayList<String> temp = new ArrayList<String>();
for (int i = 0; i < ss.length; i++) { String[] ss = pop.getSpecificDataNames();
if (ss[i].lastIndexOf("*") == -1) { for (int i = 0; i < ss.length; i++) {
temp.add(ss[i]); if (ss[i].lastIndexOf("*") == -1) {
} else { temp.add(ss[i]);
String[] line = new String[temp.size()]; } else {
temp.toArray(line); String[] line = new String[temp.size()];
description.add(line); temp.toArray(line);
temp = new ArrayList<String>(); description.add(line);
temp.add(ss[i]); temp = new ArrayList<String>();
} temp.add(ss[i]);
} }
if (temp.size() > 0) { }
String[] line = new String[temp.size()]; if (temp.size() > 0) {
temp.toArray(line); String[] line = new String[temp.size()];
description.add(line); temp.toArray(line);
description.add(line);
} }
if (doTextOutput()) { if (doTextOutput()) {
String s = "calls , " + calls + " bestfit , "; String s = "calls , " + calls + " bestfit , ";
s = s + BeanInspector.toString(currentBestFit); s = s + BeanInspector.toString(currentBestFit);
if (currentWorstFit != null) { if (currentWorstFit != null) {
s = s + " , worstfit , " + BeanInspector.toString(currentWorstFit); s = s + " , worstfit , " + BeanInspector.toString(currentWorstFit);
} }
printToTextListener(s + "\n"); printToTextListener(s + "\n");
} }
// m_PlotCounter--; // m_PlotCounter--;
// if (m_PlotCounter == 0) { // if (m_PlotCounter == 0) {
// m_PlotCounter = m_StatsParams.GetPlotoutput(); // m_PlotCounter = m_StatsParams.GetPlotoutput();
int index = 0; int index = 0;
for (int i = 0; i < fitnessGraph.length; i++) { for (int i = 0; i < fitnessGraph.length; i++) {
for (int j = 0; j < fitnessGraph[i].length; j++) { for (int j = 0; j < fitnessGraph[i].length; j++) {
plotFitnessPoint(i, j, calls, specificData[index]); plotFitnessPoint(i, j, calls, specificData[index]);
index++; index++;
} }
} }
// } // }
} }
public String getHostName() { public String getHostName() {
return hostName; return hostName;
} }
} }

View File

@ -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<InterfaceAdditionalPopulationInformer> informers) {
ArrayList<String> headerFields = new ArrayList<String>();
ArrayList<String> infoFields = new ArrayList<String>();
// 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);
}
}

View File

@ -18,319 +18,345 @@ import eva2.gui.BeanInspector;
* *
*/ */
public class StringSelection implements Serializable { public class StringSelection implements Serializable {
private static final long serialVersionUID = -1512329288445831907L;
private String[] strObjects;
private String[] toolTips;
boolean[] selStates;
private transient HashMap<String,Integer> stringToIndexHash = null;
private transient Class<? extends Enum> enumClass = null;
/** private static final long serialVersionUID = -1512329288445831907L;
* Constructor with a String array of selectable strings and optional descriptions. private String[] strObjects;
* private String[] toolTips;
* @param sArr a String array of selectable strings boolean[] selStates;
* @param tips descriptive strings of same length or null private transient HashMap<String, Integer> stringToIndexHash = null;
*/ private transient Class<? extends Enum> enumClass = 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. * Constructor with a String array of selectable strings and optional
* A single element is preselected by index, all others deselected. * descriptions.
* *
* @param sArr a String array of selectable strings * @param sArr a String array of selectable strings
* @param tips descriptive strings of same length or null * @param tips descriptive strings of same length or null
* @param initialSel index of the preselected string */
*/ public StringSelection(String[] sArr, String[] tips) {
public StringSelection(String[] sArr, String[] tips, int initialSel) { strObjects = sArr;
this(sArr, tips); toolTips = tips;
if (initialSel<getLength()) setSelected(initialSel, true); selStates = new boolean[sArr.length];
enumClass = null; stringToIndexHash = null;
} enumClass = null;
}
/** /**
* Constructor from an enum class and optional descriptions. * Constructor with a String array of selectable strings and optional
* * descriptions. A single element is preselected by index, all others
* @param e an enum from which the selectable strings will be taken * deselected.
* @param tips descriptive strings of same length or null *
*/ * @param sArr a String array of selectable strings
public StringSelection(Enum<?> e, String[] tips) { * @param tips descriptive strings of same length or null
strObjects = new String[e.getClass().getEnumConstants().length]; * @param initialSel index of the preselected string
toolTips=tips; */
selStates = new boolean[strObjects.length]; public StringSelection(String[] sArr, String[] tips, int initialSel) {
for (int i = 0; i < strObjects.length; i++) { this(sArr, tips);
strObjects[i] = e.getClass().getEnumConstants()[i].toString(); if (initialSel < getLength()) {
} setSelected(initialSel, true);
setSelected(e.ordinal(), true); }
stringToIndexHash = null; enumClass = null;
enumClass = e.getClass(); }
}
/** /**
* A copy constructor. * Constructor from an enum class and optional descriptions.
* *
* @param stringSelection * @param e an enum from which the selectable strings will be taken
*/ * @param tips descriptive strings of same length or null
public StringSelection(StringSelection stringSelection) { */
strObjects = stringSelection.strObjects.clone(); public StringSelection(Enum<?> e, String[] tips) {
selStates = stringSelection.selStates.clone(); strObjects = new String[e.getClass().getEnumConstants().length];
toolTips = stringSelection.toolTips.clone(); toolTips = tips;
stringToIndexHash = null; selStates = new boolean[strObjects.length];
enumClass = stringSelection.enumClass; for (int i = 0; i < strObjects.length; i++) {
} strObjects[i] = e.getClass().getEnumConstants()[i].toString();
}
setSelected(e.ordinal(), true);
stringToIndexHash = null;
enumClass = e.getClass();
}
/** /**
* Construct a string selection that allows all enum fields of the given type plus a list of additional * A copy constructor.
* strings to be selected. The enum fields will be first in the selection list. *
* * @param stringSelection
* @param e */
* @param headerFields public StringSelection(StringSelection stringSelection) {
*/ strObjects = stringSelection.strObjects.clone();
public StringSelection(Enum<?> e, String[] enumTips, selStates = stringSelection.selStates.clone();
List<String> headerFields, String[] addTips) { toolTips = stringSelection.toolTips.clone();
this(ToolBox.appendEnumAndArray(e, headerFields.toArray(new String[headerFields.size()])), stringToIndexHash = null;
ToolBox.appendArrays(enumTips, addTips)); enumClass = stringSelection.enumClass;
enumClass = e.getClass(); }
}
public Object clone() { /**
return new StringSelection(this); * 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<String> headerFields, String[] addTips) {
this(ToolBox.appendEnumAndArray(e, headerFields.toArray(new String[headerFields.size()])),
ToolBox.appendArrays(enumTips, addTips));
enumClass = e.getClass();
}
public int getLength() { public Object clone() {
return strObjects.length; return new StringSelection(this);
} }
public String getElement(int i) { public int getLength() {
return strObjects[i]; return strObjects.length;
} }
/** public String getElement(int i) {
* Return a descriptive String for element i or null if none is provided. return strObjects[i];
* }
* @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 a descriptive String for element i or null if none is provided.
* *
* @return * @param i index of the string element
*/ * @return a descriptive String for element i or null
public String[] getStrings() { */
return strObjects; public String getElementInfo(int i) {
} if (toolTips != null && (toolTips.length > i)) {
return toolTips[i];
} else {
return null;
}
}
/** /**
* Get the selection state at the indicated index. * Retrieve the array of all selectable strings.
* *
* @param i * @return
* @return */
*/ public String[] getStrings() {
public boolean isSelected(int i) { return strObjects;
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) * Get the selection state at the indicated index.
* within the instance. This only works if the enum was used for the *
* creation of this instance. * @param i
* * @return
* @param e */
* @return public boolean isSelected(int i) {
*/ try {
public boolean isSelected(Enum<?> e) { 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())) { // if (isSelected(e.ordinal())) {
// return e.toString().equals(strObjects[e.ordinal()]); // return e.toString().equals(strObjects[e.ordinal()]);
// } else return false; // } else return false;
if (enumClass!=null) { if (enumClass != null) {
if (e.getClass().equals(enumClass)) return isSelected(e.ordinal()); if (e.getClass().equals(enumClass)) {
else { return isSelected(e.ordinal());
System.err.println("Error, the string selection was constructed with a different enum class - invalid request (StringSelection.isSelected(Enum)"); } else {
return false; 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)"); } else {
return false; 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 * Check if a given string is selected within this instance. If the String
* String is not found, false is returned. * is not found, false is returned.
* *
* @param str * @param str
* @return * @return
*/ */
public boolean isSelected(String str) { public boolean isSelected(String str) {
if (stringToIndexHash == null) { // for some time efficiency... if (stringToIndexHash == null) { // for some time efficiency...
stringToIndexHash = new HashMap<String,Integer>(2*strObjects.length); stringToIndexHash = new HashMap<String, Integer>(2 * strObjects.length);
for (int i=0; i<strObjects.length; i++) { for (int i = 0; i < strObjects.length; i++) {
stringToIndexHash.put(strObjects[i], i); stringToIndexHash.put(strObjects[i], i);
} }
} }
Integer selIndex = stringToIndexHash.get(str); Integer selIndex = stringToIndexHash.get(str);
if (selIndex==null) { if (selIndex == null) {
System.err.println("Error, unknown string for StringSelection: " + str + ", selectable were " + BeanInspector.toString(getStrings())); System.err.println("Error, unknown string for StringSelection: " + str + ", selectable were " + BeanInspector.toString(getStrings()));
return false; return false;
} return isSelected(selIndex); }
return isSelected(selIndex);
// for (int i=0; i<strObjects.length; i++) { // for (int i=0; i<strObjects.length; i++) {
// if (strObjects[i].equals(str)) return isSelected(i); // if (strObjects[i].equals(str)) return isSelected(i);
// } // }
// return false; // return false;
} }
/** /**
* Return the ordinal of the given String within the StringSelection. If * Return the ordinal of the given String within the StringSelection. If the
* the string could not be found, -1 is returned. * string could not be found, -1 is returned.
* *
* @param str * @param str
* @return * @return
*/ */
public int stringToIndex(String str) { public int stringToIndex(String str) {
if (stringToIndexHash == null) { // for some time efficiency... if (stringToIndexHash == null) { // for some time efficiency...
stringToIndexHash = new HashMap<String,Integer>(2*strObjects.length); stringToIndexHash = new HashMap<String, Integer>(2 * strObjects.length);
for (int i=0; i<strObjects.length; i++) { for (int i = 0; i < strObjects.length; i++) {
stringToIndexHash.put(strObjects[i], i); stringToIndexHash.put(strObjects[i], i);
} }
} }
Integer selIndex = stringToIndexHash.get(str); Integer selIndex = stringToIndexHash.get(str);
if (selIndex==null) return -1; if (selIndex == null) {
else return selIndex.intValue(); return -1;
} } else {
return selIndex.intValue();
}
}
/** /**
* Set the selection state of a field denoted by a String value. If the * 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 * String is not represented within this instance, an error message is
* printed. * printed.
* *
* @param str * @param str
* @param v * @param v
*/ */
public void setSelected(String str, boolean v) { public void setSelected(String str, boolean v) {
int index = stringToIndex(str); int index = stringToIndex(str);
if (index>=0) { if (index >= 0) {
setSelected(index,v); setSelected(index, v);
} else { } else {
System.err.println("Error, unknown string " + str + " cant be selected in " + this.getClass()); 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. * Set the selection state of a field. The index must be valid.
* *
* @param i * @param i
* @param v * @param v
*/ */
public void setSelected(int i, boolean v) { public void setSelected(int i, boolean v) {
selStates[i]=v; selStates[i] = v;
} }
/** /**
* Toggle the selection state of a field. The index must be valid. * Toggle the selection state of a field. The index must be valid.
* *
* @param i * @param i
*/ */
public void toggleSelected(int i) { public void toggleSelected(int i) {
selStates[i]=!selStates[i]; selStates[i] = !selStates[i];
} }
/** /**
* Apply the selection state of the given instance to this instance. Compares * Apply the selection state of the given instance to this instance.
* Strings and takes over the selection state if they are equal. * Compares Strings and takes over the selection state if they are equal.
* *
* @param sel * @param sel
*/ */
public void takeOverSelection(StringSelection sel) { public void takeOverSelection(StringSelection sel) {
// try to apply the same selection for equivalent string (should be in same order) // try to apply the same selection for equivalent string (should be in same order)
int mismatchAt = -1; int mismatchAt = -1;
for (int i=0; i<sel.getLength() && i<getLength(); i++) { for (int i = 0; i < sel.getLength() && i < getLength(); i++) {
// hope that elements are aligned at the beginning and take over selection state // hope that elements are aligned at the beginning and take over selection state
if (sel.getElement(i).equals(getElement(i))) { if (sel.getElement(i).equals(getElement(i))) {
// System.out.println("Fit: " + getElement(i) + " / " + sel.getElement(i)); // System.out.println("Fit: " + getElement(i) + " / " + sel.getElement(i));
setSelected(i, sel.isSelected(i)); setSelected(i, sel.isSelected(i));
} else { } else {
// System.out.println(" - does not fit: " + getElement(i) + " vs " + sel.getElement(i)); // 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 mismatchAt = i; // if elements are not aligned, start double loop search at that point
break; break;
} }
} }
if (mismatchAt>=0) { if (mismatchAt >= 0) {
// double look search to find matching elements (equal strings) // double look search to find matching elements (equal strings)
for (int i=mismatchAt; i<getLength(); i++) { for (int i = mismatchAt; i < getLength(); i++) {
for (int j=mismatchAt; j<sel.getLength(); j++) { for (int j = mismatchAt; j < sel.getLength(); j++) {
if (sel.getElement(j).equals(getElement(i))) { if (sel.getElement(j).equals(getElement(i))) {
// if strings match, take over the selection state // if strings match, take over the selection state
// System.out.println("Fit: " + getElement(i) + " / " + sel.getElement(j)); // 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 a sub-list of the selected items.
* *
* @return * @return
*/ */
public String[] getSelected() { public String[] getSelected() {
ArrayList<String> ret = new ArrayList<String>(); ArrayList<String> ret = new ArrayList<String>();
for (int i=0; i<getLength(); i++) if (isSelected(i)) ret.add(getElement(i)); for (int i = 0; i < getLength(); i++) {
return ret.toArray(new String[ret.size()]); if (isSelected(i)) {
} ret.add(getElement(i));
}
}
return ret.toArray(new String[ret.size()]);
}
/** /**
* Return a sub-list of the selected items paired up with the respective index. * Return a sub-list of the selected items paired up with the respective
* * index.
* @return *
*/ * @return
public List<Pair<String,Integer>> getSelectedWithIndex() { */
ArrayList<Pair<String,Integer>> ret = new ArrayList<Pair<String,Integer>>(); public List<Pair<String, Integer>> getSelectedWithIndex() {
for (int i=0; i<getLength(); i++) if (isSelected(i)) ret.add(new Pair<String,Integer>(getElement(i), i)); ArrayList<Pair<String, Integer>> ret = new ArrayList<Pair<String, Integer>>();
return ret; for (int i = 0; i < getLength(); i++) {
} if (isSelected(i)) {
ret.add(new Pair<String, Integer>(getElement(i), i));
}
}
return ret;
}
/** /**
* Return only those selected fields which are members of the given enum. * Return only those selected fields which are members of the given enum.
* @param e *
* @return * @param e
*/ * @return
public Enum[] getSelectedEnum(Enum[] e) { */
LinkedList<Integer> selectedList = new LinkedList<Integer>(); public Enum[] getSelectedEnum(Enum[] e) {
for (int i=0; i<e.length; i++) { LinkedList<Integer> selectedList = new LinkedList<Integer>();
if (isSelected(e[i])) selectedList.add(i); for (int i = 0; i < e.length; i++) {
} if (isSelected(e[i])) {
Enum[] ret = (Enum[]) java.lang.reflect.Array.newInstance(e[0].getClass(), selectedList.size()); selectedList.add(i);
Iterator<Integer> iter = selectedList.iterator(); }
int i=0; }
while (iter.hasNext()) { Enum[] ret = (Enum[]) java.lang.reflect.Array.newInstance(e[0].getClass(), selectedList.size());
ret[i++]=e[iter.next()]; Iterator<Integer> iter = selectedList.iterator();
} int i = 0;
return ret; while (iter.hasNext()) {
} ret[i++] = e[iter.next()];
}
return ret;
}
/** /**
* Select all or deselect all items. * Select all or deselect all items.
* *
* @param selState * @param selState
*/ */
public void setAllSelectionStates(boolean selState) { public void setAllSelectionStates(boolean selState) {
for (int i=0; i<selStates.length; i++) { for (int i = 0; i < selStates.length; i++) {
selStates[i]=selState; selStates[i] = selState;
} }
} }
} }

View File

@ -786,7 +786,7 @@ public class DArea extends JComponent implements DParent, Printable {
System.out.println("DArea.setVisibleRectangle(DRectangle)"); System.out.println("DArea.setVisibleRectangle(DRectangle)");
if (rect.isEmpty()) if (rect.isEmpty())
throw new IllegalArgumentException( 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"); + "as the visible rectangle of an DArea");
if (!rect.equals(visible_rect) && rect.getWidth() > 0 if (!rect.equals(visible_rect) && rect.getWidth() > 0