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
*/
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();
}
});
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) {

View File

@ -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();

View File

@ -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) {

View File

@ -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<m_fields.length;i++) {
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);
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();
private static final Logger LOGGER = Logger.getLogger(GenericStatistics.class.getName());
//private Object m_target;
private int test;
private String[] propertyNames;
private boolean[] states;
private transient Field[] fields;
private DataViewerInterface viewer;
private Graph graph;
private static MainAdapterClient mainAdapterClient;
/**
*
*/
public static void setMainAdapterClient(MainAdapterClient adapter) {
mainAdapterClient = adapter;
}
}
/**
*
*/
public void setTest(int Test) {
m_Test = Test;
}
/**
*
*/
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++;
/**
*
*/
public GenericStatistics getClone() {
return new GenericStatistics(this);
}
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 void statechanged(Object target) {
int len=0;
for (int i=0;i<m_State.length;i++)
if (m_State[i]==true) len++;
if (len==0) return;
if (m_Viewer == null) initViewer();
double[] data = new double[len];
try {
m_fields = getDeclaredFields(target);
} catch (Exception ex) {
System.out.println("ERROR in GenericStatistics:"+ex.getMessage());
ex.printStackTrace();
}
int index =0;
for (int i=0;i<m_fields.length;i++) {
for (int n=0;n<m_PropertyNames.length;n++) {
if (this.m_State[n]==false)
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();
/**
*
*/
public GenericStatistics(Object target) {
//m_target = target;
//System.out.println("GenericStatistics-->");
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]);
}
}

View File

@ -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<String[]> 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();
}

View File

@ -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;
}

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) {
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<InterfaceAdditionalPopulationInformer> informerList) {

View File

@ -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<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() {
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<InterfaceAdditionalPopulationInformer> informerList) {
super.startOptPerformed(infoString, runNumber, goParams, informerList);
graphInfoString = infoString;
/**
*
*/
public synchronized void startOptPerformed(String infoString, int runNumber, Object goParams, List<InterfaceAdditionalPopulationInformer> 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<InterfaceAdditionalPopulationInformer> 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<description.get(0).length; i++) graphDesc.add(description.get(0)[i]);
} else {
graphDesc = null;
System.err.println("Error in StatisticsWithGUI.initPlots()!");
}
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 graphCount = graphDesc.size();
// System.out.println("Initializing " + graphCount + " plots (StatisticsWithGUI)");
fitnessFrame = new GraphWindow[windowCount];
for (int i = 0; i < fitnessFrame.length; i++) {
fitnessFrame[i] = GraphWindow.getInstance(mainAdapterClient, "Optimization " + i + " " + " on " + hostName, "function calls", "fitness");
}
fitnessGraph = new Graph[windowCount][];
// 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?
for (int i = 0; i < fitnessGraph.length; i++) {
fitnessGraph[i] = new Graph[graphCount];
for (int j = 0; j < fitnessGraph[i].length; j++) {
// String[] d = (String[]) description.get(i);
// this is where the column string for ascii export is created! Uah!
fitnessGraph[i][j] =
fitnessFrame[i].getNewGraph(graphDesc.get(j).head + "_"
+ graphInfoString);
fitnessGraph[i][j].jump();
}
}
if (m_StatsParams.getMultiRuns() > 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<InterfaceAdditionalPopulationInformer> 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<description.get(0).length; i++) graphDesc.add(description.get(0)[i]);
} else {
graphDesc = null;
System.err.println("Error in StatisticsWithGUI.initPlots()!");
}
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 graphCount = graphDesc.size();
// System.out.println("Initializing " + graphCount + " plots (StatisticsWithGUI)");
fitnessFrame = new GraphWindow[windowCount];
for (int i = 0; i < fitnessFrame.length; i++) {
fitnessFrame[i] = GraphWindow.getInstance(mainAdapterClient, "Optimization " + i + " " + " on " + hostName, "function calls", "fitness");
}
fitnessGraph = new Graph[windowCount][];
// 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?
for (int i = 0; i < fitnessGraph.length; i++) {
fitnessGraph[i] = new Graph[graphCount];
for (int j = 0; j < fitnessGraph[i].length; j++) {
// String[] d = (String[]) description.get(i);
// this is where the column string for ascii export is created! Uah!
fitnessGraph[i][j] =
fitnessFrame[i].getNewGraph(graphDesc.get(j).head + "_"
+ graphInfoString);
fitnessGraph[i][j].jump();
}
}
if (m_StatsParams.getMultiRuns() > 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<graphDesc.size(); i++) {
Integer colIndex = i+1; // always add one because the function calls are located in column zero
if (lastIsShowFull) colIndex = 1+graphDesc.get(i).tail;
// plot the column as indicated by the graph description
if (currentStatDoubleData[colIndex]!=null) plotFitnessPoint(0, subGraph++, functionCalls, currentStatDoubleData[colIndex]);
else {
for (int i = 0; i < graphDesc.size(); i++) {
Integer colIndex = i + 1; // always add one because the function calls are located in column zero
if (lastIsShowFull) {
colIndex = 1 + graphDesc.get(i).tail;
}
// 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.");
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
* define specific data. However its used by the ES module implementation.
*/
public void plotSpecificData(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informer) {
double[] specificData = pop.getSpecificData();
int calls = pop.getFunctionCalls();
ArrayList<String[]> description = new ArrayList<String[]>();
ArrayList<String> temp = new ArrayList<String>();
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<String>();
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<InterfaceAdditionalPopulationInformer> informer) {
double[] specificData = pop.getSpecificData();
int calls = pop.getFunctionCalls();
ArrayList<String[]> description = new ArrayList<String[]>();
ArrayList<String> temp = new ArrayList<String>();
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<String>();
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;
}
}

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 {
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;
/**
* 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<String> 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<String, Integer> stringToIndexHash = null;
private transient Class<? extends Enum> 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<String> 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<String,Integer>(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);
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<String, Integer>(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<strObjects.length; i++) {
// if (strObjects[i].equals(str)) return isSelected(i);
// }
// return false;
}
/**
* Return the ordinal of the given String within the StringSelection. If
* the string could not be found, -1 is returned.
*
* @param str
* @return
*/
public int stringToIndex(String str) {
if (stringToIndexHash == null) { // for some time efficiency...
stringToIndexHash = new HashMap<String,Integer>(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 + " 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<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))) {
/**
* Return the ordinal of the given String within the StringSelection. If the
* string could not be found, -1 is returned.
*
* @param str
* @return
*/
public int stringToIndex(String str) {
if (stringToIndexHash == null) { // for some time efficiency...
stringToIndexHash = new HashMap<String, Integer>(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<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
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 < 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<String> ret = new ArrayList<String>();
for (int i=0; i<getLength(); i++) 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
*/
public List<Pair<String,Integer>> getSelectedWithIndex() {
ArrayList<Pair<String,Integer>> ret = new ArrayList<Pair<String,Integer>>();
for (int i=0; i<getLength(); i++) if (isSelected(i)) ret.add(new Pair<String,Integer>(getElement(i), i));
return ret;
}
/**
* Return a sub-list of the selected items.
*
* @return
*/
public String[] getSelected() {
ArrayList<String> ret = new ArrayList<String>();
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<Integer> selectedList = new LinkedList<Integer>();
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<Integer> 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<Pair<String, Integer>> getSelectedWithIndex() {
ArrayList<Pair<String, Integer>> ret = new ArrayList<Pair<String, Integer>>();
for (int i = 0; i < getLength(); i++) {
if (isSelected(i)) {
ret.add(new Pair<String, Integer>(getElement(i), i));
}
}
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;
}
}
/**
* Return only those selected fields which are members of the given enum.
*
* @param e
* @return
*/
public Enum[] getSelectedEnum(Enum[] e) {
LinkedList<Integer> selectedList = new LinkedList<Integer>();
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<Integer> 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;
}
}
}

View File

@ -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