code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* RandomRBFGenerator.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.generators;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import java.io.Serializable;
import java.util.Random;
import moa.core.InstancesHeader;
import moa.core.MiscUtils;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.IntOption;
import moa.streams.InstanceStream;
import moa.tasks.TaskMonitor;
/**
* Stream generator for a random radial basis function stream.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class RandomRBFGenerator extends AbstractOptionHandler implements
InstanceStream {
@Override
public String getPurposeString() {
return "Generates a random radial basis function stream.";
}
private static final long serialVersionUID = 1L;
public IntOption modelRandomSeedOption = new IntOption("modelRandomSeed",
'r', "Seed for random generation of model.", 1);
public IntOption instanceRandomSeedOption = new IntOption(
"instanceRandomSeed", 'i',
"Seed for random generation of instances.", 1);
public IntOption numClassesOption = new IntOption("numClasses", 'c',
"The number of classes to generate.", 2, 2, Integer.MAX_VALUE);
public IntOption numAttsOption = new IntOption("numAtts", 'a',
"The number of attributes to generate.", 10, 0, Integer.MAX_VALUE);
public IntOption numCentroidsOption = new IntOption("numCentroids", 'n',
"The number of centroids in the model.", 50, 1, Integer.MAX_VALUE);
protected static class Centroid implements Serializable {
private static final long serialVersionUID = 1L;
public double[] centre;
public int classLabel;
public double stdDev;
}
protected InstancesHeader streamHeader;
protected Centroid[] centroids;
protected double[] centroidWeights;
protected Random instanceRandom;
@Override
public void prepareForUseImpl(TaskMonitor monitor,
ObjectRepository repository) {
monitor.setCurrentActivity("Preparing random RBF...", -1.0);
generateHeader();
generateCentroids();
restart();
}
@Override
public InstancesHeader getHeader() {
return this.streamHeader;
}
@Override
public long estimatedRemainingInstances() {
return -1;
}
@Override
public boolean hasMoreInstances() {
return true;
}
@Override
public boolean isRestartable() {
return true;
}
@Override
public void restart() {
this.instanceRandom = new Random(this.instanceRandomSeedOption.getValue());
}
@Override
public Instance nextInstance() {
Centroid centroid = this.centroids[MiscUtils.chooseRandomIndexBasedOnWeights(this.centroidWeights,
this.instanceRandom)];
int numAtts = this.numAttsOption.getValue();
double[] attVals = new double[numAtts + 1];
for (int i = 0; i < numAtts; i++) {
attVals[i] = (this.instanceRandom.nextDouble() * 2.0) - 1.0;
}
double magnitude = 0.0;
for (int i = 0; i < numAtts; i++) {
magnitude += attVals[i] * attVals[i];
}
magnitude = Math.sqrt(magnitude);
double desiredMag = this.instanceRandom.nextGaussian()
* centroid.stdDev;
double scale = desiredMag / magnitude;
for (int i = 0; i < numAtts; i++) {
attVals[i] = centroid.centre[i] + attVals[i] * scale;
}
Instance inst = new DenseInstance(1.0, attVals);
inst.setDataset(getHeader());
inst.setClassValue(centroid.classLabel);
return inst;
}
protected void generateHeader() {
FastVector attributes = new FastVector();
for (int i = 0; i < this.numAttsOption.getValue(); i++) {
attributes.addElement(new Attribute("att" + (i + 1)));
}
FastVector classLabels = new FastVector();
for (int i = 0; i < this.numClassesOption.getValue(); i++) {
classLabels.addElement("class" + (i + 1));
}
attributes.addElement(new Attribute("class", classLabels));
this.streamHeader = new InstancesHeader(new Instances(
getCLICreationString(InstanceStream.class), attributes, 0));
this.streamHeader.setClassIndex(this.streamHeader.numAttributes() - 1);
}
protected void generateCentroids() {
Random modelRand = new Random(this.modelRandomSeedOption.getValue());
this.centroids = new Centroid[this.numCentroidsOption.getValue()];
this.centroidWeights = new double[this.centroids.length];
for (int i = 0; i < this.centroids.length; i++) {
this.centroids[i] = new Centroid();
double[] randCentre = new double[this.numAttsOption.getValue()];
for (int j = 0; j < randCentre.length; j++) {
randCentre[j] = modelRand.nextDouble();
}
this.centroids[i].centre = randCentre;
this.centroids[i].classLabel = modelRand.nextInt(this.numClassesOption.getValue());
this.centroids[i].stdDev = modelRand.nextDouble();
this.centroidWeights[i] = modelRand.nextDouble();
}
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* LEDGenerator.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.generators;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import java.util.Random;
import moa.core.InstancesHeader;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.FlagOption;
import moa.options.IntOption;
import moa.streams.InstanceStream;
import moa.tasks.TaskMonitor;
/**
* Stream generator for the problem of predicting the digit displayed on a 7-segment LED display.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class LEDGenerator extends AbstractOptionHandler implements
InstanceStream {
@Override
public String getPurposeString() {
return "Generates a problem of predicting the digit displayed on a 7-segment LED display.";
}
private static final long serialVersionUID = 1L;
public static final int NUM_IRRELEVANT_ATTRIBUTES = 17;
protected static final int originalInstances[][] = {
{1, 1, 1, 0, 1, 1, 1}, {0, 0, 1, 0, 0, 1, 0},
{1, 0, 1, 1, 1, 0, 1}, {1, 0, 1, 1, 0, 1, 1},
{0, 1, 1, 1, 0, 1, 0}, {1, 1, 0, 1, 0, 1, 1},
{1, 1, 0, 1, 1, 1, 1}, {1, 0, 1, 0, 0, 1, 0},
{1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 0, 1, 1}};
public IntOption instanceRandomSeedOption = new IntOption(
"instanceRandomSeed", 'i',
"Seed for random generation of instances.", 1);
public IntOption noisePercentageOption = new IntOption("noisePercentage",
'n', "Percentage of noise to add to the data.", 10, 0, 100);
public FlagOption suppressIrrelevantAttributesOption = new FlagOption(
"suppressIrrelevantAttributes", 's',
"Reduce the data to only contain 7 relevant binary attributes.");
protected InstancesHeader streamHeader;
protected Random instanceRandom;
@Override
protected void prepareForUseImpl(TaskMonitor monitor,
ObjectRepository repository) {
// generate header
FastVector attributes = new FastVector();
FastVector binaryLabels = new FastVector();
binaryLabels.addElement("0");
binaryLabels.addElement("1");
int numAtts = 7;
if (!this.suppressIrrelevantAttributesOption.isSet()) {
numAtts += NUM_IRRELEVANT_ATTRIBUTES;
}
for (int i = 0; i < numAtts; i++) {
attributes.addElement(new Attribute("att" + (i + 1), binaryLabels));
}
FastVector classLabels = new FastVector();
for (int i = 0; i < 10; i++) {
classLabels.addElement(Integer.toString(i));
}
attributes.addElement(new Attribute("class", classLabels));
this.streamHeader = new InstancesHeader(new Instances(
getCLICreationString(InstanceStream.class), attributes, 0));
this.streamHeader.setClassIndex(this.streamHeader.numAttributes() - 1);
restart();
}
@Override
public long estimatedRemainingInstances() {
return -1;
}
@Override
public InstancesHeader getHeader() {
return this.streamHeader;
}
@Override
public boolean hasMoreInstances() {
return true;
}
@Override
public boolean isRestartable() {
return true;
}
@Override
public Instance nextInstance() {
InstancesHeader header = getHeader();
Instance inst = new DenseInstance(header.numAttributes());
inst.setDataset(header);
int selected = this.instanceRandom.nextInt(10);
for (int i = 0; i < 7; i++) {
if ((1 + (this.instanceRandom.nextInt(100))) <= this.noisePercentageOption.getValue()) {
inst.setValue(i, originalInstances[selected][i] == 0 ? 1 : 0);
} else {
inst.setValue(i, originalInstances[selected][i]);
}
}
if (!this.suppressIrrelevantAttributesOption.isSet()) {
for (int i = 0; i < NUM_IRRELEVANT_ATTRIBUTES; i++) {
inst.setValue(i + 7, this.instanceRandom.nextInt(2));
}
}
inst.setClassValue(selected);
return inst;
}
@Override
public void restart() {
this.instanceRandom = new Random(this.instanceRandomSeedOption.getValue());
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* MultilabelArffFileStream.java
* Copyright (C) 2010 University of Waikato, Hamilton, New Zealand
* @author Jesse Read (jmr30@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.generators.multilabel;
import moa.streams.ArffFileStream;
import moa.core.InstancesHeader;
import moa.core.MultilabelInstancesHeader;
import moa.options.IntOption;
/**
* Stream reader for ARFF files of multilabel data.
*
* @author Jesse Read (jmr30@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class MultilabelArffFileStream extends ArffFileStream {
@Override
public String getPurposeString() {
return "A stream read from an ARFF file.";
}
private static final long serialVersionUID = 1L;
public IntOption numLabelsOption = new IntOption("numLabels", 'l',
"The number of labels. e.g. n = 10 : the first 10 binary attributes are the labels; n = -10 the last 10 binary attributes are the labels.", -1, -1, Integer.MAX_VALUE);
public MultilabelArffFileStream() {
}
public MultilabelArffFileStream(String arffFileName, int numLabels) {
this.arffFileOption.setValue(arffFileName);
this.numLabelsOption.setValue(numLabels);
restart();
}
@Override
public InstancesHeader getHeader() {
return new MultilabelInstancesHeader(this.instances, numLabelsOption.getValue());
}
}
| Java |
/*
* MetaMultilabelGenerator.java
* Copyright (C) 2012 University of Waikato, Hamilton, New Zealand
* @author Jesse Read (jesse@tsc.uc3m.es)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.generators.multilabel;
import java.util.*;
import moa.core.InstancesHeader;
import moa.core.MultilabelInstancesHeader;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.ClassOption;
import moa.options.FloatOption;
import moa.options.IntOption;
import moa.streams.InstanceStream;
import moa.tasks.TaskMonitor;
import weka.core.*;
/**
* Stream generator for multilabel data.
*
* @author Jesse Read ((jesse@tsc.uc3m.es))
* @version $Revision: 7 $
*/
public class MetaMultilabelGenerator extends AbstractOptionHandler implements InstanceStream {
private static final long serialVersionUID = 1L;
public ClassOption binaryGeneratorOption = new ClassOption(
"binaryGenerator", 's', "Binary Generator (specify the number of attributes here, but only two classes!).", InstanceStream.class, "generators.RandomTreeGenerator");
public IntOption metaRandomSeedOption = new IntOption(
"metaRandomSeed", 'm', "Random seed (for the meta process). Use two streams with the same seed and r > 0.0 in the second stream if you wish to introduce drift to the label dependencies without changing the underlying concept.", 1);
public IntOption numLabelsOption = new IntOption(
"numLabels", 'c', "Number of labels.", 10, 2, Integer.MAX_VALUE);
public IntOption skewOption = new IntOption(
"skew", 'k', "Skewed label distribution: 1 (default) = yes; 0 = no (relatively uniform) @NOTE: not currently implemented.", 1, 0, 1);
public FloatOption labelCardinalityOption = new FloatOption(
"labelCardinality", 'z', "Desired label cardinality (average number of labels per example).", 1.5, 0.0, Integer.MAX_VALUE);
public FloatOption labelCardinalityVarOption = new FloatOption(
"labelCardinalityVar", 'v', "Desired label cardinality variance (variance of z) @NOTE: not currently implemented.", 1.0, 0.0, Integer.MAX_VALUE);
public FloatOption labelCardinalityRatioOption = new FloatOption(
"labelDependency", 'u', "Specifies how much label dependency from 0 (total independence) to 1 (full dependence).", 0.25, 0.0, 1.0);
public FloatOption labelDependencyChangeRatioOption = new FloatOption(
"labelDependencyRatioChange", 'r', "Each label-pair dependency has a 'r' chance of being modified. Use this option on the second of two streams with the same random seed (-m) to introduce label-dependence drift.", 0.0, 0.0, 1.0);
protected MultilabelInstancesHeader m_MultilabelInstancesHeader = null;
protected InstanceStream m_BinaryGenerator = null;
protected Instances multilabelStreamTemplate = null;
protected Random m_MetaRandom = new Random();
protected int m_L = 0, m_A = 0;
protected double priors[] = null, priors_norm[] = null;
protected double Conditional[][] = null;
protected HashSet m_TopCombinations[] = null;
@Override
public void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) {
this.restart();
}
@Override
public void restart() {
// The number of class labels L
this.m_L = numLabelsOption.getValue();
if (this.labelCardinalityOption.getValue() > m_L) {
System.err.println("Error: Label cardinality (z) cannot be greater than the number of labels (c)!");
System.exit(1);
}
// Initialise the chosen binary generator
this.m_BinaryGenerator = (InstanceStream) getPreparedClassOption(this.binaryGeneratorOption);
this.m_BinaryGenerator.restart();
// The number of attributes A (not including class-attributes)
this.m_A = this.m_BinaryGenerator.getHeader().numAttributes() - 1;
// Random seed
this.m_MetaRandom = new Random(this.metaRandomSeedOption.getValue());
// Set up a queue system
this.queue = new LinkedList[2];
for (int i = 0; i < this.queue.length; i++) {
this.queue[i] = new LinkedList<Instance>();
}
// Generate the multi-label header
this.m_MultilabelInstancesHeader = generateMultilabelHeader(this.m_BinaryGenerator.getHeader());
// Generate label prior distribution
this.priors = generatePriors(m_MetaRandom, m_L, labelCardinalityOption.getValue(), (skewOption.getValue() >= 1));
//printVector(this.priors);
// Generate the matrix marking the label-dependencies
boolean DependencyMatrix[][] = modifyDependencyMatrix(new boolean[m_L][m_L], labelCardinalityRatioOption.getValue(), m_MetaRandom);
// Modify the dependency matrix (and the priors) if they are to change in this stream
if (labelDependencyChangeRatioOption.getValue() > 0.0) {
priors = modifyPriorVector(priors, labelDependencyChangeRatioOption.getValue(), m_MetaRandom, (skewOption.getValue() >= 1));
modifyDependencyMatrix(DependencyMatrix, labelDependencyChangeRatioOption.getValue(), m_MetaRandom);
}
// Generate the conditional matrix, using this change matrix
this.Conditional = generateConditional(priors, DependencyMatrix);
//printMatrix(this.Conditional);
// Make a normalised version of the priors
this.priors_norm = Arrays.copyOf(priors, priors.length);
Utils.normalize(this.priors_norm);
// Create the feature-label mappings
m_TopCombinations = getTopCombinations(m_A);
}
/**
* GenerateMultilabelHeader.
*
* @param si single-label Instances
*/
protected MultilabelInstancesHeader generateMultilabelHeader(Instances si) {
Instances mi = new Instances(si, 0, 0);
mi.setClassIndex(-1);
mi.deleteAttributeAt(mi.numAttributes() - 1);
FastVector bfv = new FastVector();
bfv.addElement("0");
bfv.addElement("1");
for (int i = 0; i < this.m_L; i++) {
mi.insertAttributeAt(new Attribute("class" + i, bfv), i);
}
this.multilabelStreamTemplate = mi;
this.multilabelStreamTemplate.setRelationName("SYN_Z" + this.labelCardinalityOption.getValue() + "L" + this.m_L + "X" + m_A + "S" + metaRandomSeedOption.getValue() + ": -C " + this.m_L);
this.multilabelStreamTemplate.setClassIndex(this.m_L);
return new MultilabelInstancesHeader(multilabelStreamTemplate, m_L);
}
/**
* Generate Priors. Generate the label priors.
*
* @param L number of labels
* @param z desired label cardinality
* @param r random number generator
* @param skew whether to be very skewed or not (@NOTE not currently used)
* @return P label prior distribution
*/
private double[] generatePriors(Random r, int L, double z, boolean skew) {
double P[] = new double[L];
for (int i = 0; i < L; i++) {
P[i] = r.nextDouble();
//P[i] = 1.0; // @temp
}
// normalise to z
do {
double c = Utils.sum(P) / z;
for (int i = 0; i < L; i++) {
P[i] = Math.min(1.0, P[i] / c); // must be in [0,1]
}
} while (Utils.sum(P) < z);
return P;
}
/**
* GetNextWithBinary. Get the next instance with binary class i
*
* @param i the class to generate (0,1)
*/
LinkedList<Instance> queue[] = null;
private Instance getNextWithBinary(int i) {
int lim = 1000;
if (queue[i].size() <= 0) {
int c = -1;
while (lim-- > 0) {
Instance tinst = this.m_BinaryGenerator.nextInstance();
c = (int) Math.round(tinst.classValue());
if (i == c) {
return tinst;
} else if (queue[c].size() < 100) {
queue[c].add(tinst);
}
}
System.err.println("[Overflow] The binary stream is too skewed, could not get an example of class " + i + "");
System.exit(1);
return null;
} else {
return queue[i].remove();
}
}
/**
* GenerateML. Generates a multi-label example.
*/
@Override
public Instance nextInstance() {
return generateMLInstance(generateSet());
}
/**
* Generate Set.
*
* @return a label set Y
*/
private HashSet generateSet() {
int y[] = new int[m_L]; // [0,0,0]
int k = samplePMF(priors_norm); // k = 1 // y[k] ~ p(k==1)
y[k] = 1; // [0,1,0]
ArrayList<Integer> indices = getShuffledListToLWithoutK(m_L, k);
for (int j : indices) {
//y[j] ~ p(j==1|y)
y[j] = (joint(j, y) > m_MetaRandom.nextDouble()) ? 1 : 0;
}
return vector2set(y);
}
// P(y[] where y[k]==1)
private double joint(int k, int y[]) {
double p = 1.0; //priors[k];
for (int j = 0; j < y.length; j++) {
if (j != k && y[j] == 1) {
p *= Conditional[k][j];
}
}
return p;
}
/**
* GenerateMLInstance.
*
* @param Y a set of label [indices]
* @return a multit-labelled example
*/
private Instance generateMLInstance(HashSet<Integer> Y) {
// create a multi-label instance:
Instance x_ml = new SparseInstance(this.multilabelStreamTemplate.numAttributes());
x_ml.setDataset(this.multilabelStreamTemplate);
// set classes
for (int j = 0; j < m_L; j++) {
x_ml.setValue(j, 0.0);
}
for (int l : Y) {
x_ml.setValue(l, 1.0);
}
// generate binary instances
Instance x_0 = getNextWithBinary(0);
Instance x_1 = getNextWithBinary(1);
// Loop through each feature attribute @warning: assumes class is last index
for (int a = 0; a < m_A; a++) {
// The combination is present: use a positive value
if (Y.containsAll(m_TopCombinations[a])) {
x_ml.setValue(m_L + a, x_1.value(a));
//x_ml.setValue(m_L+a,1.0);
} // The combination is absent: use a negative value
else {
x_ml.setValue(m_L + a, x_0.value(a));
//x_ml.setValue(m_L+a,0.0);
}
}
return x_ml;
}
/**
* samplePMF.
*
* @param p a pmf
* @return an index i of p with probability p[i], and -1 with probability
* 1.0-p[i]
*/
private int samplePMF(double p[]) {
double r = m_MetaRandom.nextDouble();
double sum = 0.0;
for (int i = 0; i < p.length; i++) {
sum += p[i];
if (r < sum) {
return i;
}
}
return -1;
}
/**
* ModifyPriorVector. A certain number of values will be altered.
*
* @param P[] the prior distribution
* @param u the probability of changing P[j]
* @param r for random numbers
* @param skew NOTE not currently used
* @return the modified P
*/
protected double[] modifyPriorVector(double P[], double u, Random r, boolean skew) {
for (int j = 0; j < P.length; j++) {
if (r.nextDouble() < u) {
P[j] = r.nextDouble();
}
}
return P;
}
/**
* ModifyDependencyMatrix. A certain number of values will be altered. @NOTE
* a future improvement would be to detect cycles, since this may lead to
* inconsistencies. However, due to the rarity of this occurring, and the
* minimal problems it would cause (and considering that inconsistencies
* also occr in real datasets) we don't implement this.
*
* @param M[][] a boolean matrix
* @param u the probability of changing the relationship M[j][k]
* @param r for random numbers
* @return the modified M
*/
protected boolean[][] modifyDependencyMatrix(boolean M[][], double u, Random r) {
//List<int[]> L = new ArrayList<int[]>();
for (int j = 0; j < M.length; j++) {
for (int k = j + 1; k < M[j].length; k++) {
if (/*
* !hasCycle(L) &&
*/r.nextDouble() <= u) {
M[j][k] ^= true;
//L.add(new int[]{j,k});
}
}
}
return M;
}
/**
* GenerateConditional. Given the priors distribution and a matrix flagging
* dependencies, generate a conditional distribution matrix Q; such that:
* P(i) = Q[i][i] P(i|j) = Q[i][j]
*
* @param P prior distribution
* @param M dependency matrix (where 1 == dependency)
* @return Q conditional dependency matrix
*/
protected double[][] generateConditional(double P[], boolean M[][]) {
int L = P.length;
double Q[][] = new double[L][L];
// set priors
for (int j = 0; j < L; j++) {
Q[j][j] = P[j];
}
// create conditionals
for (int j = 0; j < Q.length; j++) {
for (int k = j + 1; k < Q[j].length; k++) {
// dependence
if (M[j][k]) {
// min = tending toward mutual exclusivity
// max = tending toward total co-occurence
// @NOTE it would also be an option to select in [min,max], but since
// we are approximating the joint distribution, we can take
// a stronger approach, and just take either min or max.
Q[j][k] = (m_MetaRandom.nextBoolean() ? min(P[j], P[k]) : max(P[j], P[k]));
Q[k][j] = (Q[j][k] * Q[j][j]) / Q[k][k]; // Bayes Rule
} // independence
else {
Q[j][k] = P[j];
Q[k][j] = (Q[j][k] * P[k]) / P[j]; // Bayes Rule
}
}
}
return Q;
}
/**
* GetTopCombinations. Calculating the full joint probability distribution
* is too complex. - sample from the approximate joint many times - record
* the the n most commonly ocurring Y and their frequencies - create a map
* based on these frequencies
*
* @param n the number of labelsets
* @return n labelsts
*/
private HashSet[] getTopCombinations(int n) {
final HashMap<HashSet, Integer> count = new HashMap<HashSet, Integer>();
HashMap<HashSet, Integer> isets = new HashMap<HashSet, Integer>();
int N = 100000;
double lc = 0.0;
for (int i = 0; i < N; i++) {
HashSet Y = generateSet();
lc += Y.size();
count.put(Y, count.get(Y) != null ? count.get(Y) + 1 : 1);
}
lc = lc / N;
// @TODO could generate closed frequent itemsets from 'count'
List<HashSet> top_set = new ArrayList<HashSet>(count.keySet());
// Sort the sets by their count
Collections.sort(top_set, new Comparator<HashSet>() {
@Override
public int compare(HashSet Y1, HashSet Y2) {
return count.get(Y2).compareTo(count.get(Y1));
}
});
System.err.println("The most common labelsets (from which we will build the map) will likely be: ");
HashSet map_set[] = new HashSet[n];
double weights[] = new double[n];
int idx = 0;
for (HashSet Y : top_set) {
System.err.println(" " + Y + " : " + (count.get(Y) * 100.0 / N) + "%");
weights[idx++] = count.get(Y);
if (idx == weights.length) {
break;
}
}
double sum = Utils.sum(weights);
System.err.println("Estimated Label Cardinality: " + lc + "\n\n");
System.err.println("Estimated % Unique Labelsets: " + (count.size() * 100.0 / N) + "%\n\n");
// normalize weights[]
Utils.normalize(weights);
// add sets to the map set, according to their weights
for (int i = 0, k = 0; i < top_set.size() && k < map_set.length; i++) { // i'th combination (pre)
int num = (int) Math.round(Math.max(weights[i] * map_set.length, 1.0)); // i'th weight
for (int j = 0; j < num && k < map_set.length; j++) {
map_set[k++] = top_set.get(i);
}
}
// shuffle
Collections.shuffle(Arrays.asList(map_set));
// return
return map_set;
}
@Override
public InstancesHeader getHeader() {
return m_MultilabelInstancesHeader;
}
@Override
public String getPurposeString() {
return "Generates a multi-label stream based on a binary random generator.";
}
@Override
public long estimatedRemainingInstances() {
return -1;
}
@Override
public boolean hasMoreInstances() {
return true;
}
@Override
public boolean isRestartable() {
return true;
}
@Override
public void getDescription(StringBuilder sb, int indent) {
}
// ------- following are private utility functions -----------
// convert set Y to an L-length vector y
private int[] set2vector(HashSet<Integer> Y, int L) {
int y[] = new int[L];
for (int j : Y) {
y[j] = 1;
}
return y;
}
// convert L-length vector y to set Y
private HashSet<Integer> vector2set(int y[]) {
HashSet<Integer> Y = new HashSet<Integer>();
for (int j = 0; j < y.length; j++) {
if (y[j] > 0) {
Y.add(j);
}
}
return Y;
}
// the highest possible prob. of P(A|B) given A and B
private double max(double A, double B) {
return Math.min(1.0, (B / A));
}
// the lowest possible prob. of P(A|B) given A and B
private double min(double A, double B) {
return Math.max(0.0, (-1.0 + A + B));
}
private ArrayList<Integer> getShuffledListToLWithoutK(int L, int k) {
ArrayList<Integer> list = new ArrayList<Integer>(L - 1);
for (int j = 0; j < L; j++) {
if (j != k) {
list.add(j);
}
}
Collections.shuffle(list);
return list;
}
// ------- following are private debugging functions -----------
public static void main(String args[]) {
// test routines
}
private void printMatrix(double M[][]) {
System.out.println("--- MATRIX ---");
for (int i = 0; i < M.length; i++) {
for (int j = 0; j < M[i].length; j++) {
System.out.print(" " + Utils.doubleToString(M[i][j], 5, 3));
}
System.out.println("");
}
}
private void printVector(double V[]) {
System.out.println("--- VECTOR ---");
for (int j = 0; j < V.length; j++) {
System.out.print(" " + Utils.doubleToString(V[j], 5, 3));
}
System.out.println("");
}
}
| Java |
/*
* WaveformGeneratorDrift.java
* Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
* @author Christophe Salperwyck
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.generators;
import weka.core.DenseInstance;
import weka.core.Instance;
import moa.core.InstancesHeader;
import moa.core.ObjectRepository;
import moa.options.IntOption;
import moa.tasks.TaskMonitor;
/**
* Stream generator for the problem of predicting one of three waveform types with drift.
*
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
* @version $Revision: 7 $
*/
public class WaveformGeneratorDrift extends WaveformGenerator {
private static final long serialVersionUID = 1L;
public IntOption numberAttributesDriftOption = new IntOption("numberAttributesDrift",
'd', "Number of attributes with drift.", 0, 0, TOTAL_ATTRIBUTES_INCLUDING_NOISE);
protected int[] numberAttribute;
@Override
public String getPurposeString() {
return "Generates a problem of predicting one of three waveform types with drift.";
}
@Override
protected void prepareForUseImpl(TaskMonitor monitor,
ObjectRepository repository) {
super.prepareForUseImpl(monitor, repository);
int numAtts = this.addNoiseOption.isSet() ? TOTAL_ATTRIBUTES_INCLUDING_NOISE
: NUM_BASE_ATTRIBUTES;
this.numberAttribute = new int[numAtts];
for (int i = 0; i < numAtts; i++) {
this.numberAttribute[i] = i;
}
//Change atributes
int randomInt = this.instanceRandom.nextInt(numAtts);
int offset = this.instanceRandom.nextInt(numAtts);
int swap;
for (int i = 0; i < this.numberAttributesDriftOption.getValue(); i++) {
swap = this.numberAttribute[(i + randomInt) % numAtts];
this.numberAttribute[(i + randomInt) % numAtts] = this.numberAttribute[(i + offset) % numAtts];
this.numberAttribute[(i + offset) % numAtts] = swap;
}
}
@Override
public Instance nextInstance() {
InstancesHeader header = getHeader();
Instance inst = new DenseInstance(header.numAttributes());
inst.setDataset(header);
int waveform = this.instanceRandom.nextInt(NUM_CLASSES);
int choiceA = 0, choiceB = 0;
switch (waveform) {
case 0:
choiceA = 0;
choiceB = 1;
break;
case 1:
choiceA = 0;
choiceB = 2;
break;
case 2:
choiceA = 1;
choiceB = 2;
break;
}
double multiplierA = this.instanceRandom.nextDouble();
double multiplierB = 1.0 - multiplierA;
for (int i = 0; i < NUM_BASE_ATTRIBUTES; i++) {
inst.setValue(this.numberAttribute[i], (multiplierA * hFunctions[choiceA][i])
+ (multiplierB * hFunctions[choiceB][i])
+ this.instanceRandom.nextGaussian());
}
if (this.addNoiseOption.isSet()) {
for (int i = NUM_BASE_ATTRIBUTES; i < TOTAL_ATTRIBUTES_INCLUDING_NOISE; i++) {
inst.setValue(this.numberAttribute[i], this.instanceRandom.nextGaussian());
}
}
inst.setClassValue(waveform);
return inst;
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* SEAGenerator.java
* Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.generators;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import java.util.Random;
import moa.core.InstancesHeader;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.FlagOption;
import moa.options.IntOption;
import moa.streams.InstanceStream;
import moa.tasks.TaskMonitor;
/**
* Stream generator for SEA concepts functions.
* Generator described in the paper:<br/>
* W. Nick Street and YongSeog Kim
* "A streaming ensemble algorithm (SEA) for large-scale classification",
* KDD '01: Proceedings of the seventh ACM SIGKDD international conference on Knowledge discovery and data mining
* 377-382 2001.<br/><br/>
*
* Notes:<br/>
* The built in functions are based on the paper.
*
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
* @version $Revision: 7 $
*/
public class SEAGenerator extends AbstractOptionHandler implements
InstanceStream {
@Override
public String getPurposeString() {
return "Generates SEA concepts functions.";
}
private static final long serialVersionUID = 1L;
public IntOption functionOption = new IntOption("function", 'f',
"Classification function used, as defined in the original paper.",
1, 1, 4);
public IntOption instanceRandomSeedOption = new IntOption(
"instanceRandomSeed", 'i',
"Seed for random generation of instances.", 1);
public FlagOption balanceClassesOption = new FlagOption("balanceClasses",
'b', "Balance the number of instances of each class.");
public IntOption numInstancesConcept = new IntOption("numInstancesConcept", 'n',
"The number of instances for each concept.", 0, 0, Integer.MAX_VALUE);
public IntOption noisePercentageOption = new IntOption("noisePercentage",
'n', "Percentage of noise to add to the data.", 10, 0, 100);
protected interface ClassFunction {
public int determineClass(double attrib1, double attrib2, double attrib3);
}
protected static ClassFunction[] classificationFunctions = {
// function 1
new ClassFunction() {
@Override
public int determineClass(double attrib1, double attrib2, double attrib3) {
return (attrib1 + attrib2 <= 8) ? 0 : 1;
}
},
// function 2
new ClassFunction() {
@Override
public int determineClass(double attrib1, double attrib2, double attrib3) {
return (attrib1 + attrib2 <= 9) ? 0 : 1;
}
},
// function 3
new ClassFunction() {
public int determineClass(double attrib1, double attrib2, double attrib3) {
return (attrib1 + attrib2 <= 7) ? 0 : 1;
}
},
// function 4
new ClassFunction() {
@Override
public int determineClass(double attrib1, double attrib2, double attrib3) {
return (attrib1 + attrib2 <= 9.5) ? 0 : 1;
}
}
};
protected InstancesHeader streamHeader;
protected Random instanceRandom;
protected boolean nextClassShouldBeZero;
@Override
protected void prepareForUseImpl(TaskMonitor monitor,
ObjectRepository repository) {
// generate header
FastVector attributes = new FastVector();
attributes.addElement(new Attribute("attrib1"));
attributes.addElement(new Attribute("attrib2"));
attributes.addElement(new Attribute("attrib3"));
FastVector classLabels = new FastVector();
classLabels.addElement("groupA");
classLabels.addElement("groupB");
attributes.addElement(new Attribute("class", classLabels));
this.streamHeader = new InstancesHeader(new Instances(
getCLICreationString(InstanceStream.class), attributes, 0));
this.streamHeader.setClassIndex(this.streamHeader.numAttributes() - 1);
restart();
}
@Override
public long estimatedRemainingInstances() {
return -1;
}
@Override
public InstancesHeader getHeader() {
return this.streamHeader;
}
@Override
public boolean hasMoreInstances() {
return true;
}
@Override
public boolean isRestartable() {
return true;
}
@Override
public Instance nextInstance() {
double attrib1 = 0, attrib2 = 0, attrib3 = 0;
int group = 0;
boolean desiredClassFound = false;
while (!desiredClassFound) {
// generate attributes
attrib1 = 10 * this.instanceRandom.nextDouble();
attrib2 = 10 * this.instanceRandom.nextDouble();
attrib3 = 10 * this.instanceRandom.nextDouble();
// determine class
group = classificationFunctions[this.functionOption.getValue() - 1].determineClass(attrib1, attrib2, attrib3);
if (!this.balanceClassesOption.isSet()) {
desiredClassFound = true;
} else {
// balance the classes
if ((this.nextClassShouldBeZero && (group == 0))
|| (!this.nextClassShouldBeZero && (group == 1))) {
desiredClassFound = true;
this.nextClassShouldBeZero = !this.nextClassShouldBeZero;
} // else keep searching
}
}
//Add Noise
if ((1 + (this.instanceRandom.nextInt(100))) <= this.noisePercentageOption.getValue()) {
group = (group == 0 ? 1 : 0);
}
// construct instance
InstancesHeader header = getHeader();
Instance inst = new DenseInstance(header.numAttributes());
inst.setValue(0, attrib1);
inst.setValue(1, attrib2);
inst.setValue(2, attrib3);
inst.setDataset(header);
inst.setClassValue(group);
return inst;
}
@Override
public void restart() {
this.instanceRandom = new Random(this.instanceRandomSeedOption.getValue());
this.nextClassShouldBeZero = false;
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* RandomRBFGeneratorDrift.java
* Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.generators;
import java.util.Random;
import moa.options.IntOption;
import moa.options.FloatOption;
import weka.core.Instance;
/**
* Stream generator for a random radial basis function stream with drift.
*
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
* @version $Revision: 7 $
*/
public class RandomRBFGeneratorDrift extends RandomRBFGenerator {
@Override
public String getPurposeString() {
return "Generates a random radial basis function stream with drift.";
}
private static final long serialVersionUID = 1L;
public FloatOption speedChangeOption = new FloatOption("speedChange", 's',
"Speed of change of centroids in the model.", 0, 0, Float.MAX_VALUE);
public IntOption numDriftCentroidsOption = new IntOption("numDriftCentroids", 'k',
"The number of centroids with drift.", 50, 0, Integer.MAX_VALUE);
protected double[][] speedCentroids;
@Override
public Instance nextInstance() {
//Update Centroids with drift
int len = this.numDriftCentroidsOption.getValue();
if (len > this.centroids.length) {
len = this.centroids.length;
}
for (int j = 0; j < len; j++) {
for (int i = 0; i < this.numAttsOption.getValue(); i++) {
this.centroids[j].centre[i] += this.speedCentroids[j][i] * this.speedChangeOption.getValue();
if (this.centroids[j].centre[i] > 1) {
this.centroids[j].centre[i] = 1;
this.speedCentroids[j][i] = -this.speedCentroids[j][i];
}
if (this.centroids[j].centre[i] < 0) {
this.centroids[j].centre[i] = 0;
this.speedCentroids[j][i] = -this.speedCentroids[j][i];
}
}
}
return super.nextInstance();
}
@Override
protected void generateCentroids() {
super.generateCentroids();
Random modelRand = new Random(this.modelRandomSeedOption.getValue());
int len = this.numDriftCentroidsOption.getValue();
if (len > this.centroids.length) {
len = this.centroids.length;
}
this.speedCentroids = new double[len][this.numAttsOption.getValue()];
for (int i = 0; i < len; i++) {
double[] randSpeed = new double[this.numAttsOption.getValue()];
double normSpeed = 0.0;
for (int j = 0; j < randSpeed.length; j++) {
randSpeed[j] = modelRand.nextDouble();
normSpeed += randSpeed[j] * randSpeed[j];
}
normSpeed = Math.sqrt(normSpeed);
for (int j = 0; j < randSpeed.length; j++) {
randSpeed[j] /= normSpeed;
}
this.speedCentroids[i] = randSpeed;
}
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* HyperplaneGenerator.java
* Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.generators;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import java.util.Random;
import moa.core.InstancesHeader;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.FloatOption;
import moa.options.IntOption;
import moa.streams.InstanceStream;
import moa.tasks.TaskMonitor;
/**
* Stream generator for Hyperplane data stream.
*
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
* @version $Revision: 7 $
*/
public class HyperplaneGenerator extends AbstractOptionHandler implements
InstanceStream {
@Override
public String getPurposeString() {
return "Generates a problem of predicting class of a rotating hyperplane.";
}
private static final long serialVersionUID = 1L;
public IntOption instanceRandomSeedOption = new IntOption(
"instanceRandomSeed", 'i',
"Seed for random generation of instances.", 1);
public IntOption numClassesOption = new IntOption("numClasses", 'c',
"The number of classes to generate.", 2, 2, Integer.MAX_VALUE);
public IntOption numAttsOption = new IntOption("numAtts", 'a',
"The number of attributes to generate.", 10, 0, Integer.MAX_VALUE);
public IntOption numDriftAttsOption = new IntOption("numDriftAtts", 'k',
"The number of attributes with drift.", 2, 0, Integer.MAX_VALUE);
public FloatOption magChangeOption = new FloatOption("magChange", 't',
"Magnitude of the change for every example", 0.0, 0.0, 1.0);
public IntOption noisePercentageOption = new IntOption("noisePercentage",
'n', "Percentage of noise to add to the data.", 5, 0, 100);
public IntOption sigmaPercentageOption = new IntOption("sigmaPercentage",
's', "Percentage of probability that the direction of change is reversed.", 10, 0, 100);
protected InstancesHeader streamHeader;
protected Random instanceRandom;
protected double[] weights;
protected int[] sigma;
public int numberInstance;
@Override
protected void prepareForUseImpl(TaskMonitor monitor,
ObjectRepository repository) {
monitor.setCurrentActivity("Preparing hyperplane...", -1.0);
generateHeader();
restart();
}
protected void generateHeader() {
FastVector attributes = new FastVector();
for (int i = 0; i < this.numAttsOption.getValue(); i++) {
attributes.addElement(new Attribute("att" + (i + 1)));
}
FastVector classLabels = new FastVector();
for (int i = 0; i < this.numClassesOption.getValue(); i++) {
classLabels.addElement("class" + (i + 1));
}
attributes.addElement(new Attribute("class", classLabels));
this.streamHeader = new InstancesHeader(new Instances(
getCLICreationString(InstanceStream.class), attributes, 0));
this.streamHeader.setClassIndex(this.streamHeader.numAttributes() - 1);
}
@Override
public long estimatedRemainingInstances() {
return -1;
}
@Override
public InstancesHeader getHeader() {
return this.streamHeader;
}
@Override
public boolean hasMoreInstances() {
return true;
}
@Override
public boolean isRestartable() {
return true;
}
@Override
public Instance nextInstance() {
int numAtts = this.numAttsOption.getValue();
double[] attVals = new double[numAtts + 1];
double sum = 0.0;
double sumWeights = 0.0;
for (int i = 0; i < numAtts; i++) {
attVals[i] = this.instanceRandom.nextDouble();
sum += this.weights[i] * attVals[i];
sumWeights += this.weights[i];
}
int classLabel;
if (sum >= sumWeights * 0.5) {
classLabel = 1;
} else {
classLabel = 0;
}
//Add Noise
if ((1 + (this.instanceRandom.nextInt(100))) <= this.noisePercentageOption.getValue()) {
classLabel = (classLabel == 0 ? 1 : 0);
}
Instance inst = new DenseInstance(1.0, attVals);
inst.setDataset(getHeader());
inst.setClassValue(classLabel);
addDrift();
return inst;
}
private void addDrift() {
for (int i = 0; i < this.numDriftAttsOption.getValue(); i++) {
this.weights[i] += (double) ((double) sigma[i]) * ((double) this.magChangeOption.getValue());
if (//this.weights[i] >= 1.0 || this.weights[i] <= 0.0 ||
(1 + (this.instanceRandom.nextInt(100))) <= this.sigmaPercentageOption.getValue()) {
this.sigma[i] *= -1;
}
}
}
@Override
public void restart() {
this.instanceRandom = new Random(this.instanceRandomSeedOption.getValue());
this.weights = new double[this.numAttsOption.getValue()];
this.sigma = new int[this.numAttsOption.getValue()];
for (int i = 0; i < this.numAttsOption.getValue(); i++) {
this.weights[i] = this.instanceRandom.nextDouble();
this.sigma[i] = (i < this.numDriftAttsOption.getValue() ? 1 : 0);
}
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* ArffFileStream.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import moa.core.InputStreamProgressMonitor;
import moa.core.InstancesHeader;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.FileOption;
import moa.options.IntOption;
import moa.tasks.TaskMonitor;
import weka.core.Instance;
import weka.core.Instances;
/**
* Stream reader of ARFF files.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class ArffFileStream extends AbstractOptionHandler implements
InstanceStream {
@Override
public String getPurposeString() {
return "A stream read from an ARFF file.";
}
private static final long serialVersionUID = 1L;
public FileOption arffFileOption = new FileOption("arffFile", 'f',
"ARFF file to load.", null, "arff", false);
public IntOption classIndexOption = new IntOption(
"classIndex",
'c',
"Class index of data. 0 for none or -1 for last attribute in file.",
-1, -1, Integer.MAX_VALUE);
protected Instances instances;
protected Reader fileReader;
protected boolean hitEndOfFile;
protected Instance lastInstanceRead;
protected int numInstancesRead;
protected InputStreamProgressMonitor fileProgressMonitor;
public ArffFileStream() {
}
public ArffFileStream(String arffFileName, int classIndex) {
this.arffFileOption.setValue(arffFileName);
this.classIndexOption.setValue(classIndex);
restart();
}
@Override
public void prepareForUseImpl(TaskMonitor monitor,
ObjectRepository repository) {
restart();
}
@Override
public InstancesHeader getHeader() {
return new InstancesHeader(this.instances);
}
@Override
public long estimatedRemainingInstances() {
double progressFraction = this.fileProgressMonitor.getProgressFraction();
if ((progressFraction > 0.0) && (this.numInstancesRead > 0)) {
return (long) ((this.numInstancesRead / progressFraction) - this.numInstancesRead);
}
return -1;
}
@Override
public boolean hasMoreInstances() {
return !this.hitEndOfFile;
}
@Override
public Instance nextInstance() {
Instance prevInstance = this.lastInstanceRead;
this.hitEndOfFile = !readNextInstanceFromFile();
return prevInstance;
}
@Override
public boolean isRestartable() {
return true;
}
@Override
public void restart() {
try {
if (this.fileReader != null) {
this.fileReader.close();
}
InputStream fileStream = new FileInputStream(this.arffFileOption.getFile());
this.fileProgressMonitor = new InputStreamProgressMonitor(
fileStream);
this.fileReader = new BufferedReader(new InputStreamReader(
this.fileProgressMonitor));
this.instances = new Instances(this.fileReader, 1);
if (this.classIndexOption.getValue() < 0) {
this.instances.setClassIndex(this.instances.numAttributes() - 1);
} else if (this.classIndexOption.getValue() > 0) {
this.instances.setClassIndex(this.classIndexOption.getValue() - 1);
}
this.numInstancesRead = 0;
this.lastInstanceRead = null;
this.hitEndOfFile = !readNextInstanceFromFile();
} catch (IOException ioe) {
throw new RuntimeException("ArffFileStream restart failed.", ioe);
}
}
protected boolean readNextInstanceFromFile() {
try {
if (this.instances.readInstance(this.fileReader)) {
this.lastInstanceRead = this.instances.instance(0);
this.instances.delete(); // keep instances clean
this.numInstancesRead++;
return true;
}
if (this.fileReader != null) {
this.fileReader.close();
this.fileReader = null;
}
return false;
} catch (IOException ioe) {
throw new RuntimeException(
"ArffFileStream failed to read instance from stream.", ioe);
}
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* ConceptDriftStream.java
* Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams;
import java.util.Random;
import moa.core.InstancesHeader;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.ClassOption;
import moa.options.FloatOption;
import moa.options.IntOption;
import moa.tasks.TaskMonitor;
import weka.core.Instance;
/**
* Stream generator that adds concept drift to examples in a stream.
*<br/><br/>
* Example:
*<br/><br/>
* <code>ConceptDriftStream -s (generators.AgrawalGenerator -f 7) <br/>
* -d (generators.AgrawalGenerator -f 2) -w 1000000 -p 900000</code>
*<br/><br/>
* s : Stream <br/>
* d : Concept drift Stream<br/>
* p : Central position of concept drift change<br/>
* w : Width of concept drift change<br/>
*
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
* @version $Revision: 7 $
*/
public class ConceptDriftStream extends AbstractOptionHandler implements
InstanceStream {
@Override
public String getPurposeString() {
return "Adds Concept Drift to examples in a stream.";
}
private static final long serialVersionUID = 1L;
public ClassOption streamOption = new ClassOption("stream", 's',
"Stream to add concept drift.", InstanceStream.class,
"generators.RandomTreeGenerator");
public ClassOption driftstreamOption = new ClassOption("driftstream", 'd',
"Concept drift Stream.", InstanceStream.class,
"generators.RandomTreeGenerator");
public FloatOption alphaOption = new FloatOption("alpha",
'a', "Angle alpha of change grade.", 0.0, 0.0, 90.0);
public IntOption positionOption = new IntOption("position",
'p', "Central position of concept drift change.", 0);
public IntOption widthOption = new IntOption("width",
'w', "Width of concept drift change.", 1000);
public IntOption randomSeedOption = new IntOption("randomSeed", 'r',
"Seed for random noise.", 1);
protected InstanceStream inputStream;
protected InstanceStream driftStream;
protected Random random;
protected int numberInstanceStream;
@Override
public void prepareForUseImpl(TaskMonitor monitor,
ObjectRepository repository) {
this.inputStream = (InstanceStream) getPreparedClassOption(this.streamOption);
this.driftStream = (InstanceStream) getPreparedClassOption(this.driftstreamOption);
this.random = new Random(this.randomSeedOption.getValue());
numberInstanceStream = 0;
if (this.alphaOption.getValue() != 0.0) {
this.widthOption.setValue((int) (1 / Math.tan(this.alphaOption.getValue() * Math.PI / 180)));
}
}
@Override
public long estimatedRemainingInstances() {
return this.inputStream.estimatedRemainingInstances() + this.driftStream.estimatedRemainingInstances();
}
@Override
public InstancesHeader getHeader() {
return this.inputStream.getHeader();
}
@Override
public boolean hasMoreInstances() {
return (this.inputStream.hasMoreInstances() || this.driftStream.hasMoreInstances());
}
@Override
public boolean isRestartable() {
return (this.inputStream.isRestartable() && this.driftStream.isRestartable());
}
@Override
public Instance nextInstance() {
numberInstanceStream++;
double x = -4.0 * (double) (numberInstanceStream - this.positionOption.getValue()) / (double) this.widthOption.getValue();
double probabilityDrift = 1.0 / (1.0 + Math.exp(x));
if (this.random.nextDouble() > probabilityDrift) {
return this.inputStream.nextInstance();
} else {
return this.driftStream.nextInstance();
}
}
@Override
public void restart() {
this.inputStream.restart();
this.driftStream.restart();
numberInstanceStream = 0;
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* InstanceStream.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams;
import moa.MOAObject;
import moa.core.InstancesHeader;
import weka.core.Instance;
/**
* Interface representing a data stream of instances.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public interface InstanceStream extends MOAObject {
/**
* Gets the header of this stream.
* This is useful to know attributes and classes.
* InstancesHeader is an extension of weka.Instances.
*
* @return the header of this stream
*/
public InstancesHeader getHeader();
/**
* Gets the estimated number of remaining instances in this stream
*
* @return the estimated number of instances to get from this stream
*/
public long estimatedRemainingInstances();
/**
* Gets whether this stream has more instances to output.
* This is useful when reading streams from files.
*
* @return true if this stream has more instances to output
*/
public boolean hasMoreInstances();
/**
* Gets the next instance from this stream.
*
* @return the next instance of this stream
*/
public Instance nextInstance();
/**
* Gets whether this stream can restart.
*
* @return true if this stream can restart
*/
public boolean isRestartable();
/**
* Restarts this stream. It must be similar to
* starting a new stream from scratch.
*
*/
public void restart();
}
| Java |
/*
* ConceptDriftRealStream.java
* Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
import java.util.Random;
import moa.core.InstancesHeader;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.ClassOption;
import moa.options.FloatOption;
import moa.options.IntOption;
import moa.tasks.TaskMonitor;
/**
* Stream generator that adds concept drift to examples in a stream with
* different classes and attributes. Example: real datasets.
*<br/><br/>
* Example:
*<br/><br/>
* <code>ConceptDriftRealStream -s (ArffFileStream -f covtype.arff) \ <br/>
* -d (ConceptDriftRealStream -s (ArffFileStream -f PokerOrig.arff) \<br/>
* -d (ArffFileStream -f elec.arff) -w 5000 -p 1000000 ) -w 5000 -p 581012</code>
*<br/><br/>
* s : Stream <br/>
* d : Concept drift Stream<br/>
* p : Central position of concept drift change<br/>
* w : Width of concept drift change<br/>
*
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
* @version $Revision: 7 $
*/
public class ConceptDriftRealStream extends AbstractOptionHandler implements
InstanceStream {
@Override
public String getPurposeString() {
return "Adds Concept Drift to examples in a stream.";
}
private static final long serialVersionUID = 1L;
public ClassOption streamOption = new ClassOption("stream", 's',
"Stream to add concept drift.", InstanceStream.class,
"generators.RandomTreeGenerator");
public ClassOption driftstreamOption = new ClassOption("driftstream", 'd',
"Concept drift Stream.", InstanceStream.class,
"generators.RandomTreeGenerator");
public FloatOption alphaOption = new FloatOption("alpha",
'a', "Angle alpha of change grade.", 0.0, 0.0, 90.0);
public IntOption positionOption = new IntOption("position",
'p', "Central position of concept drift change.", 0);
public IntOption widthOption = new IntOption("width",
'w', "Width of concept drift change.", 1000);
public IntOption randomSeedOption = new IntOption("randomSeed", 'r',
"Seed for random noise.", 1);
protected InstanceStream inputStream;
protected InstanceStream driftStream;
protected Random random;
protected int numberInstanceStream;
protected InstancesHeader streamHeader;
protected Instance inputInstance;
protected Instance driftInstance;
@Override
public void prepareForUseImpl(TaskMonitor monitor,
ObjectRepository repository) {
this.inputStream = (InstanceStream) getPreparedClassOption(this.streamOption);
this.driftStream = (InstanceStream) getPreparedClassOption(this.driftstreamOption);
this.random = new Random(this.randomSeedOption.getValue());
numberInstanceStream = 0;
if (this.alphaOption.getValue() != 0.0) {
this.widthOption.setValue((int) (1 / Math.tan(this.alphaOption.getValue() * Math.PI / 180)));
}
// generate header
Instances first = this.inputStream.getHeader();
Instances second = this.driftStream.getHeader();
FastVector newAttributes = new FastVector();
for (int i = 0; i < first.numAttributes() - 1; i++) {
newAttributes.addElement(first.attribute(i));
}
for (int i = 0; i < second.numAttributes() - 1; i++) {
newAttributes.addElement(second.attribute(i));
}
Attribute classLabels;
if (first.numClasses() < second.numClasses()) {
classLabels = second.classAttribute();
} else {
classLabels = first.classAttribute();
}
newAttributes.addElement(classLabels);
this.streamHeader = new InstancesHeader(new Instances(
getCLICreationString(InstanceStream.class), newAttributes, 0));
this.streamHeader.setClassIndex(this.streamHeader.numAttributes() - 1);
restart();
}
@Override
public long estimatedRemainingInstances() {
return -1;
}
@Override
public boolean hasMoreInstances() {
return true;
}
@Override
public InstancesHeader getHeader() {
return this.streamHeader;
}
@Override
public boolean isRestartable() {
return (this.inputStream.isRestartable() && this.driftStream.isRestartable());
}
@Override
public Instance nextInstance() {
numberInstanceStream++;
double numclass = 0.0;
double x = -4.0 * (double) (numberInstanceStream - this.positionOption.getValue()) / (double) this.widthOption.getValue();
double probabilityDrift = 1.0 / (1.0 + Math.exp(x));
if (this.random.nextDouble() > probabilityDrift) {
if (this.inputStream.hasMoreInstances() == false) {
this.inputStream.restart();
}
this.inputInstance = this.inputStream.nextInstance();
numclass = this.inputInstance.classValue();
} else {
if (this.driftStream.hasMoreInstances() == false) {
this.driftStream.restart();
}
this.driftInstance = this.driftStream.nextInstance();
numclass = this.driftInstance.classValue();
}
int m = 0;
double[] newVals = new double[this.inputInstance.numAttributes() + this.driftInstance.numAttributes() - 1];
for (int j = 0; j < this.inputInstance.numAttributes() - 1; j++, m++) {
newVals[m] = this.inputInstance.value(j);
}
for (int j = 0; j < this.driftInstance.numAttributes() - 1; j++, m++) {
newVals[m] = this.driftInstance.value(j);
}
newVals[m] = numclass;
//return new Instance(1.0, newVals);
Instance inst = new DenseInstance(1.0, newVals);
inst.setDataset(this.getHeader());
inst.setClassValue(numclass);
return inst;
}
@Override
public void restart() {
this.inputStream.restart();
this.driftStream.restart();
numberInstanceStream = 0;
this.inputInstance = this.inputStream.nextInstance();
this.driftInstance = this.driftStream.nextInstance();
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* CachedInstancesStream.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams;
import moa.AbstractMOAObject;
import moa.core.InstancesHeader;
import weka.core.Instance;
import weka.core.Instances;
/**
* Stream generator for representing a stream that is cached in memory.
* This generator is used with the task <code>CacheShuffledStream</code> that
* stores and shuffles examples in memory.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class CachedInstancesStream extends AbstractMOAObject implements
InstanceStream {
private static final long serialVersionUID = 1L;
protected Instances toStream;
protected int streamPos;
public CachedInstancesStream(Instances toStream) {
this.toStream = toStream;
}
@Override
public InstancesHeader getHeader() {
return new InstancesHeader(this.toStream);
}
@Override
public long estimatedRemainingInstances() {
return this.toStream.numInstances() - this.streamPos;
}
@Override
public boolean hasMoreInstances() {
return this.streamPos < this.toStream.numInstances();
}
@Override
public Instance nextInstance() {
return this.toStream.instance(this.streamPos++);
}
@Override
public boolean isRestartable() {
return true;
}
@Override
public void restart() {
this.streamPos = 0;
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* AddNoiseFilter.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.filters;
import java.util.Random;
import moa.core.AutoExpandVector;
import moa.core.DoubleVector;
import moa.core.GaussianEstimator;
import moa.core.InstancesHeader;
import moa.options.FloatOption;
import moa.options.IntOption;
import weka.core.Instance;
/**
* Filter for adding random noise to examples in a stream.
* Noise can be added to attribute values or to class labels.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class AddNoiseFilter extends AbstractStreamFilter {
@Override
public String getPurposeString() {
return "Adds random noise to examples in a stream.";
}
private static final long serialVersionUID = 1L;
public IntOption randomSeedOption = new IntOption("randomSeed", 'r',
"Seed for random noise.", 1);
public FloatOption attNoiseFractionOption = new FloatOption("attNoise",
'a', "The fraction of attribute values to disturb.", 0.1, 0.0, 1.0);
public FloatOption classNoiseFractionOption = new FloatOption("classNoise",
'c', "The fraction of class labels to disturb.", 0.1, 0.0, 1.0);
protected Random random;
protected AutoExpandVector<Object> attValObservers;
@Override
protected void restartImpl() {
this.random = new Random(this.randomSeedOption.getValue());
this.attValObservers = new AutoExpandVector<Object>();
}
@Override
public InstancesHeader getHeader() {
return this.inputStream.getHeader();
}
@Override
public Instance nextInstance() {
Instance inst = (Instance) this.inputStream.nextInstance().copy();
for (int i = 0; i < inst.numAttributes(); i++) {
double noiseFrac = i == inst.classIndex() ? this.classNoiseFractionOption.getValue()
: this.attNoiseFractionOption.getValue();
if (inst.attribute(i).isNominal()) {
DoubleVector obs = (DoubleVector) this.attValObservers.get(i);
if (obs == null) {
obs = new DoubleVector();
this.attValObservers.set(i, obs);
}
int originalVal = (int) inst.value(i);
if (!inst.isMissing(i)) {
obs.addToValue(originalVal, inst.weight());
}
if ((this.random.nextDouble() < noiseFrac)
&& (obs.numNonZeroEntries() > 1)) {
do {
inst.setValue(i, this.random.nextInt(obs.numValues()));
} while (((int) inst.value(i) == originalVal)
|| (obs.getValue((int) inst.value(i)) == 0.0));
}
} else {
GaussianEstimator obs = (GaussianEstimator) this.attValObservers.get(i);
if (obs == null) {
obs = new GaussianEstimator();
this.attValObservers.set(i, obs);
}
obs.addObservation(inst.value(i), inst.weight());
inst.setValue(i, inst.value(i) + this.random.nextGaussian()
* obs.getStdDev() * noiseFrac);
}
}
return inst;
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* ReplacingMissingValuesFilter.java
* Copyright (C) 2014 Manuel Martin Salvador
* @author Manuel Martin Salvador (draxus@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.filters;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import moa.core.InstancesHeader;
import moa.options.FloatOption;
import moa.options.MultiChoiceOption;
import moa.options.StringOption;
import weka.core.Instance;
/**
* Replaces the missing values with another value according to the selected
* strategy. Available strategies for numerical attributes are:
* 1. Nothing: Does nothing (doesn't replace missing values)
* 2. LastKnownValue: Replaces with the last non missing value
* 3. Mean: Replaces with mean of the processed instances so far
* 4. Max: Replaces with maximum of the processed instances so far
* 5. Min: Replaces with minimum of the processed instances so far
* 6. Constant: Replaces with a constant value (default: zero)
*
* Available strategies for nominal attributes are:
* 1. Nothing: Does nothing (doesn't replace missing values)
* 2. LastKnownValue: Replaces with the last non missing value
* 3. Mode: Replaces with the mode of the processed instances so far (most frequent value)
*
* Beware of numerical strategies 2 to 5: if no previous non-missing values were processed,
* missing values will be replaced by 0.
*
* @author Manuel Martin Salvador <draxus@gmail.com>
*
*/
public class ReplacingMissingValuesFilter extends AbstractStreamFilter {
private static final long serialVersionUID = 1470772215201414815L;
public MultiChoiceOption numericReplacementStrategyOption = new MultiChoiceOption(
"numericReplacementStrategy", 's', "Replacement strategy for numeric attributes",
new String[]{"Nothing", "LastKnownValue", "Mean", "Max", "Min", "Constant"},
new String[]{"Does nothing (doesn't replace missing values)",
"Replaces with the last non missing value",
"Replaces with mean of the processed instances so far",
"Replaces with maximum of the processed instances so far",
"Replaces with minimum of the processed instances so far",
"Replaces with a constant value (default: zero)"}
, 0);
public MultiChoiceOption nominalReplacementStrategyOption = new MultiChoiceOption(
"nominalReplacementStrategy", 't', "Replacement strategy for nominal attributes",
new String[]{"Nothing", "LastKnownValue", "Mode"},
new String[]{"Does nothing (doesn't replace missing values)",
"Replaces with the last non missing value",
"Replaces with the mode of the processed instances so far (most frequent value)"}
, 0);
public FloatOption numericalConstantValueOption = new FloatOption("numericalConstantValue", 'c',
"Value used to replace missing values during the numerical constant strategy", 0.0);
protected int numAttributes = -1;
protected double columnsStatistics[] = null;
protected long numberOfSamples[] = null;
protected String lastNominalValues[] = null;
protected HashMap<String, Integer> frequencies[] = null;
protected int numericalSelectedStrategy = 0;
protected int nominalSelectedStrategy = 0;
@Override
public String getPurposeString() {
return "Replaces the missing values with another value according to the selected strategy.";
}
@Override
public InstancesHeader getHeader() {
return this.inputStream.getHeader();
}
@Override
public Instance nextInstance() {
Instance inst = (Instance) this.inputStream.nextInstance().copy();
// Initialization
if (numAttributes < 0){
numAttributes = inst.numAttributes();
columnsStatistics = new double[numAttributes];
numberOfSamples = new long[numAttributes];
lastNominalValues = new String[numAttributes];
frequencies = new HashMap[numAttributes];
for(int i=0; i< inst.numAttributes(); i++){
if(inst.attribute(i).isNominal())
frequencies[i] = new HashMap<String, Integer>();
}
numericalSelectedStrategy = this.numericReplacementStrategyOption.getChosenIndex();
nominalSelectedStrategy = this.nominalReplacementStrategyOption.getChosenIndex();
}
for (int i = 0; i < numAttributes; i++) {
// ---- Numerical values ----
if (inst.attribute(i).isNumeric()) {
// Handle missing value
if (inst.isMissing(i)) {
switch(numericalSelectedStrategy){
case 0: // NOTHING
break;
case 1: // LAST KNOWN VALUE
case 2: // MEAN
case 3: // MAX
case 4: // MIN
inst.setValue(i, columnsStatistics[i]);
break;
case 5: // CONSTANT
inst.setValue(i, numericalConstantValueOption.getValue());
break;
default: continue;
}
}
// Update statistics with non-missing values
else{
switch(numericalSelectedStrategy){
case 1: // LAST KNOWN VALUE
columnsStatistics[i] = inst.value(i);
break;
case 2: // MEAN
numberOfSamples[i]++;
columnsStatistics[i] = columnsStatistics[i] + (inst.value(i) - columnsStatistics[i])/numberOfSamples[i];
break;
case 3: // MAX
columnsStatistics[i] = columnsStatistics[i] < inst.value(i) ? inst.value(i) : columnsStatistics[i];
break;
case 4: // MIN
columnsStatistics[i] = columnsStatistics[i] > inst.value(i) ? inst.value(i) : columnsStatistics[i];
break;
default: continue;
}
}
}
// ---- Nominal values ----
else if(inst.attribute(i).isNominal()){
// Handle missing value
if (inst.isMissing(i)) {
switch(nominalSelectedStrategy){
case 0: // NOTHING
break;
case 1: // LAST KNOWN VALUE
if(lastNominalValues[i] != null){
inst.setValue(i, lastNominalValues[i]);
}
break;
case 2: // MODE
if(!frequencies[i].isEmpty()){
// Sort the map to get the most frequent value
Map<String, Integer> sortedMap = MapUtil.sortByValue( frequencies[i] );
inst.setValue(i, sortedMap.entrySet().iterator().next().getKey());
}
break;
default: continue;
}
}
// Update statistics with non-missing values
else{
switch(nominalSelectedStrategy){
case 1: // LAST KNOWN VALUE
lastNominalValues[i] = inst.stringValue(i);
break;
case 2: // MODE
Integer previousCounter = frequencies[i].get(inst.stringValue(i));
if(previousCounter == null) previousCounter = 0;
frequencies[i].put(inst.stringValue(i), ++previousCounter);
break;
default: continue;
}
}
}
}
return inst;
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
@Override
protected void restartImpl() {
numAttributes = -1;
columnsStatistics = null;
numberOfSamples = null;
lastNominalValues = null;
frequencies = null;
}
// Solution from http://stackoverflow.com/a/2581754/2022620
public static class MapUtil {
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) {
return -(o1.getValue()).compareTo( o2.getValue() );
}
});
Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
}
}
| Java |
/*
* AbstractStreamFilter.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.filters;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.streams.InstanceStream;
import moa.tasks.TaskMonitor;
/**
* Abstract Stream Filter.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public abstract class AbstractStreamFilter extends AbstractOptionHandler
implements StreamFilter {
/** The input stream to this filter. */
protected InstanceStream inputStream;
@Override
public void setInputStream(InstanceStream stream) {
this.inputStream = stream;
prepareForUse();
}
@Override
public void prepareForUseImpl(TaskMonitor monitor,
ObjectRepository repository) {
restartImpl();
}
@Override
public long estimatedRemainingInstances() {
return this.inputStream.estimatedRemainingInstances();
}
@Override
public boolean hasMoreInstances() {
return this.inputStream.hasMoreInstances();
}
@Override
public boolean isRestartable() {
return this.inputStream.isRestartable();
}
@Override
public void restart() {
this.inputStream.restart();
restartImpl();
}
/**
* Restarts this filter. All instances that extends from
* <code>AbstractStreamFilter</code> must implement <code>restartImpl</code>.
* <code>restart</code> uses <code>restartImpl</code> in <code>AbstractStreamFilter</code>.
*/
protected abstract void restartImpl();
}
| Java |
/*
* StreamFilter.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.filters;
import moa.streams.InstanceStream;
/**
* Interface representing a stream filter.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public interface StreamFilter extends InstanceStream {
/**
* Sets the input stream to the filter
*
* @param stream the input stream to the filter
*/
public void setInputStream(InstanceStream stream);
}
| Java |
/*
* CacheFilter.java
* Copyright (C) 2013 University of Waikato, Hamilton, New Zealand
* @author Albert Bifet (abifet@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.streams.filters;
import moa.core.InstancesHeader;
import weka.core.Instance;
import weka.core.Instances;
/**
* Filter for representing a stream that is cached in memory.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class CacheFilter extends AbstractStreamFilter {
@Override
public String getPurposeString() {
return "Stores a dataset in memory.";
}
private static final long serialVersionUID = 1L;
protected Instances cache;
protected int indexCache;
protected int totalCacheInstances;
protected boolean isInitialized;
@Override
protected void restartImpl() {
this.isInitialized = false;
if (this.inputStream != null) {
this.init();
}
}
protected void init() {
this.cache = new Instances(this.inputStream.getHeader(), 0);
this.indexCache = 0;
this.totalCacheInstances = 0;
while (this.inputStream.hasMoreInstances()) {
cache.add(this.inputStream.nextInstance());
this.totalCacheInstances++;
}
this.isInitialized = true;
}
@Override
public InstancesHeader getHeader() {
return this.inputStream.getHeader();
}
@Override
public Instance nextInstance() {
Instance inst = null;
if (this.hasMoreInstances()) {
inst = (Instance) this.cache.get(indexCache);
this.indexCache++;
}
return inst;
}
@Override
public boolean hasMoreInstances() {
return (this.indexCache < this.totalCacheInstances);
}
@Override
public long estimatedRemainingInstances() {
return this.totalCacheInstances - this.indexCache;
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-ge nerated method stub
}
}
| Java |
/*
* Globals.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
/**
* Class for storing global information about current version of MOA.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class Globals {
public static final String workbenchTitle = "{M}assive {O}nline {A}nalysis";
public static final String versionString = "14.11 November 2014";
public static final String copyrightNotice = "(C) 2007-2014 University of Waikato, Hamilton, New Zealand";
public static final String webAddress = "http://moa.cms.waikato.ac.nz/";
public static String getWorkbenchInfoString() {
StringBuilder result = new StringBuilder();
result.append(workbenchTitle);
StringUtils.appendNewline(result);
result.append("Version: ");
result.append(versionString);
StringUtils.appendNewline(result);
result.append("Copyright: ");
result.append(copyrightNotice);
StringUtils.appendNewline(result);
result.append("Web: ");
result.append(webAddress);
return result.toString();
}
}
| Java |
/*
* TimingUtils.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
/**
* Class implementing some time utility methods.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class TimingUtils {
protected static boolean preciseThreadTimesAvailable = false;
public static boolean enablePreciseTiming() {
if (!preciseThreadTimesAvailable) {
try {
java.lang.management.ThreadMXBean tmxb = java.lang.management.ManagementFactory.getThreadMXBean();
if (tmxb.isCurrentThreadCpuTimeSupported()) {
tmxb.setThreadCpuTimeEnabled(true);
preciseThreadTimesAvailable = true;
}
} catch (Throwable e) {
// ignore problems, just resort to inaccurate timing
}
}
return preciseThreadTimesAvailable;
}
public static long getNanoCPUTimeOfCurrentThread() {
return getNanoCPUTimeOfThread(Thread.currentThread().getId());
}
public static long getNanoCPUTimeOfThread(long threadID) {
if (preciseThreadTimesAvailable) {
long time = java.lang.management.ManagementFactory.getThreadMXBean().getThreadCpuTime(threadID);
if (time != -1) {
return time;
}
}
return System.nanoTime();
}
public static double nanoTimeToSeconds(long nanoTime) {
return nanoTime / 1000000000.0;
}
}
| Java |
/*
* GaussianEstimator.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import moa.AbstractMOAObject;
/**
* Gaussian incremental estimator that uses incremental method that is more resistant to floating point imprecision.
* for more info see Donald Knuth's "The Art of Computer Programming, Volume 2: Seminumerical Algorithms", section 4.2.2.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class GaussianEstimator extends AbstractMOAObject {
private static final long serialVersionUID = 1L;
protected double weightSum;
protected double mean;
protected double varianceSum;
public static final double NORMAL_CONSTANT = Math.sqrt(2 * Math.PI);
public void addObservation(double value, double weight) {
if (Double.isInfinite(value) || Double.isNaN(value)) {
return;
}
if (this.weightSum > 0.0) {
this.weightSum += weight;
double lastMean = this.mean;
this.mean += weight * (value - lastMean) / this.weightSum;
this.varianceSum += weight * (value - lastMean) * (value - this.mean);
} else {
this.mean = value;
this.weightSum = weight;
}
}
public void addObservations(GaussianEstimator obs) {
// Follows Variance Combination Rule in Section 2 of
// Brian Babcock, Mayur Datar, Rajeev Motwani, Liadan O'Callaghan:
// Maintaining variance and k-medians over data stream windows. PODS 2003: 234-243
//
if ((this.weightSum > 0.0) && (obs.weightSum > 0.0)) {
double oldMean = this.mean;
this.mean = (this.mean * (this.weightSum / (this.weightSum + obs.weightSum)))
+ (obs.mean * (obs.weightSum / (this.weightSum + obs.weightSum)));
this.varianceSum += obs.varianceSum + (this.weightSum * obs.weightSum / (this.weightSum + obs.weightSum) *
Math.pow(obs.mean-oldMean, 2));
this.weightSum += obs.weightSum;
}
}
public double getTotalWeightObserved() {
return this.weightSum;
}
public double getMean() {
return this.mean;
}
public double getStdDev() {
return Math.sqrt(getVariance());
}
public double getVariance() {
return this.weightSum > 1.0 ? this.varianceSum / (this.weightSum - 1.0)
: 0.0;
}
public double probabilityDensity(double value) {
if (this.weightSum > 0.0) {
double stdDev = getStdDev();
if (stdDev > 0.0) {
double diff = value - getMean();
return (1.0 / (NORMAL_CONSTANT * stdDev))
* Math.exp(-(diff * diff / (2.0 * stdDev * stdDev)));
}
return value == getMean() ? 1.0 : 0.0;
}
return 0.0;
}
public double[] estimatedWeight_LessThan_EqualTo_GreaterThan_Value(
double value) {
double equalToWeight = probabilityDensity(value) * this.weightSum;
double stdDev = getStdDev();
double lessThanWeight = stdDev > 0.0 ? weka.core.Statistics.normalProbability((value - getMean()) / stdDev)
* this.weightSum - equalToWeight
: (value < getMean() ? this.weightSum - equalToWeight : 0.0);
double greaterThanWeight = this.weightSum - equalToWeight
- lessThanWeight;
if (greaterThanWeight < 0.0) {
greaterThanWeight = 0.0;
}
return new double[]{lessThanWeight, equalToWeight, greaterThanWeight};
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* SizeOf.java
* Copyright (C) 2009 University of Waikato, Hamilton, New Zealand
*/
package moa.core;
import sizeof.agent.SizeOfAgent;
/**
* Helper class for <a href="http://www.jroller.com/maxim/entry/again_about_determining_size_of" target="_blank">Maxim Zakharenkov's SizeOf agent</a>.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class SizeOf {
/** whether the agent is present. */
protected static Boolean m_Present;
/**
* Checks whteher the agent is present.
*
* @return true if the agent is present, false otherwise
*/
protected static synchronized boolean isPresent() {
if (m_Present == null) {
try {
SizeOfAgent.fullSizeOf(new Integer(1));
m_Present = true;
} catch (Throwable t) {
m_Present = false;
}
}
return m_Present;
}
/**
* Returns the size of the object.
*
* @param o the object to get the size for
* @return the size of the object, or if the agent isn't present -1
*/
public static long sizeOf(Object o) {
if (isPresent()) {
return SizeOfAgent.sizeOf(o);
} else {
return -1;
}
}
/**
* Returns the full size of the object.
*
* @param o the object to get the size for
* @return the size of the object, or if the agent isn't present -1
*/
public static long fullSizeOf(Object o) {
if (isPresent()) {
return SizeOfAgent.fullSizeOf(o);
} else {
return -1;
}
}
}
| Java |
/*
* AutoClassDiscovery.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Class for discovering classes via reflection in the java class path.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class AutoClassDiscovery {
protected static final Map<String, String[]> cachedClassNames = new HashMap<String, String[]>();
public static String[] findClassNames(String packageNameToSearch) {
String[] cached = cachedClassNames.get(packageNameToSearch);
if (cached == null) {
HashSet<String> classNames = new HashSet<String>();
/*StringTokenizer pathTokens = new StringTokenizer(System
.getProperty("java.class.path"), File.pathSeparator);*/
String packageDirName = packageNameToSearch.replace('.',
File.separatorChar);
String packageJarName = packageNameToSearch.length() > 0 ? (packageNameToSearch.replace('.', '/') + "/")
: "";
String part = "";
AutoClassDiscovery adc = new AutoClassDiscovery();
URLClassLoader sysLoader = (URLClassLoader) adc.getClass().getClassLoader();
URL[] cl_urls = sysLoader.getURLs();
for (int i = 0; i < cl_urls.length; i++) {
part = cl_urls[i].toString();
if (part.startsWith("file:")) {
part = part.replace(" ", "%20");
try {
File temp = new File(new java.net.URI(part));
part = temp.getAbsolutePath();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
// find classes
ArrayList<File> files = new ArrayList<File>();
File dir = new File(part);
if (dir.isDirectory()) {
File root = new File(dir.toString() + File.separatorChar + packageDirName);
String[] names = findClassesInDirectoryRecursive(root, "");
classNames.addAll(Arrays.asList(names));
} else {
try {
JarFile jar = new JarFile(part);
Enumeration<JarEntry> jarEntries = jar.entries();
while (jarEntries.hasMoreElements()) {
String jarEntry = jarEntries.nextElement().getName();
if (jarEntry.startsWith(packageJarName)) {
String relativeName = jarEntry.substring(packageJarName.length());
if (relativeName.endsWith(".class")) {
relativeName = relativeName.replace('/',
'.');
classNames.add(relativeName.substring(0,
relativeName.length()
- ".class".length()));
}
}
}
} catch (IOException ignored) {
// ignore unreadable files
}
}
}
/*while (pathTokens.hasMoreElements()) {
String pathToSearch = pathTokens.nextElement().toString();
if (pathToSearch.endsWith(".jar")) {
try {
JarFile jar = new JarFile(pathToSearch);
Enumeration<JarEntry> jarEntries = jar.entries();
while (jarEntries.hasMoreElements()) {
String jarEntry = jarEntries.nextElement()
.getName();
if (jarEntry.startsWith(packageJarName)) {
String relativeName = jarEntry
.substring(packageJarName.length());
if (relativeName.endsWith(".class")) {
relativeName = relativeName.replace('/',
'.');
classNames.add(relativeName.substring(0,
relativeName.length()
- ".class".length()));
}
}
}
} catch (IOException ignored) {
// ignore unreadable files
}
} else {
File root = new File(pathToSearch + File.separatorChar
+ packageDirName);
String[] names = findClassesInDirectoryRecursive(root, "");
for (String name : names) {
classNames.add(name);
}
}
} */
cached = classNames.toArray(new String[classNames.size()]);
Arrays.sort(cached);
cachedClassNames.put(packageNameToSearch, cached);
}
return cached;
}
protected static String[] findClassesInDirectoryRecursive(File root,
String packagePath) {
HashSet<String> classNames = new HashSet<String>();
if (root.isDirectory()) {
String[] list = root.list();
for (String string : list) {
if (string.endsWith(".class")) {
classNames.add(packagePath
+ string.substring(0, string.length()
- ".class".length()));
} else {
File testDir = new File(root.getPath() + File.separatorChar
+ string);
if (testDir.isDirectory()) {
String[] names = findClassesInDirectoryRecursive(
testDir, packagePath + string + ".");
classNames.addAll(Arrays.asList(names));
}
}
}
}
return classNames.toArray(new String[classNames.size()]);
}
public static Class[] findClassesOfType(String packageNameToSearch,
Class<?> typeDesired) {
ArrayList<Class<?>> classesFound = new ArrayList<Class<?>>();
String[] classNames = findClassNames(packageNameToSearch);
for (String className : classNames) {
String fullName = packageNameToSearch.length() > 0 ? (packageNameToSearch
+ "." + className)
: className;
if (isPublicConcreteClassOfType(fullName, typeDesired)) {
try {
classesFound.add(Class.forName(fullName));
} catch (Exception ignored) {
// ignore classes that we cannot instantiate
}
}
}
return classesFound.toArray(new Class[classesFound.size()]);
}
public static boolean isPublicConcreteClassOfType(String className,
Class<?> typeDesired) {
Class<?> testClass = null;
try {
testClass = Class.forName(className);
} catch (Exception e) {
return false;
}
int classModifiers = testClass.getModifiers();
return (java.lang.reflect.Modifier.isPublic(classModifiers)
&& !java.lang.reflect.Modifier.isAbstract(classModifiers)
&& typeDesired.isAssignableFrom(testClass) && hasEmptyConstructor(testClass));
}
public static boolean hasEmptyConstructor(Class<?> type) {
try {
type.getConstructor();
return true;
} catch (Exception ignored) {
return false;
}
}
}
| Java |
/*
* StringUtils.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import java.text.DecimalFormat;
/**
* Class implementing some string utility methods.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class StringUtils {
public static final String newline = System.getProperty("line.separator");
public static String doubleToString(double value, int fractionDigits) {
return doubleToString(value, 0, fractionDigits);
}
public static String doubleToString(double value, int minFractionDigits,
int maxFractionDigits) {
DecimalFormat numberFormat = new DecimalFormat();
numberFormat.setMinimumFractionDigits(minFractionDigits);
numberFormat.setMaximumFractionDigits(maxFractionDigits);
return numberFormat.format(value);
}
public static void appendNewline(StringBuilder out) {
out.append(newline);
}
public static void appendIndent(StringBuilder out, int indent) {
for (int i = 0; i < indent; i++) {
out.append(' ');
}
}
public static void appendIndented(StringBuilder out, int indent, String s) {
appendIndent(out, indent);
out.append(s);
}
public static void appendNewlineIndented(StringBuilder out, int indent,
String s) {
appendNewline(out);
appendIndented(out, indent, s);
}
public static String secondsToDHMSString(double seconds) {
if (seconds < 60) {
return doubleToString(seconds, 2, 2) + 's';
}
long secs = (int) (seconds);
long mins = secs / 60;
long hours = mins / 60;
long days = hours / 24;
secs %= 60;
mins %= 60;
hours %= 24;
StringBuilder result = new StringBuilder();
if (days > 0) {
result.append(days);
result.append('d');
}
if ((hours > 0) || (days > 0)) {
result.append(hours);
result.append('h');
}
if ((hours > 0) || (days > 0) || (mins > 0)) {
result.append(mins);
result.append('m');
}
result.append(secs);
result.append('s');
return result.toString();
}
}
| Java |
/*
* EvalUtils.java
* Copyright (C) 2012 University of Waikato, Hamilton, New Zealand
* @author Jesse Read (jesse@tsc.uc3m.es)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import weka.core.Instance;
import weka.core.Utils;
/**
* Evaluation Utilities.
*
* @author Jesse Read (jesse@tsc.uc3m.es)
* @version $Revision: 1 $
*/
public abstract class EvalUtils {
/**
* Convert Instance to bit array. Returns the labels of this instance as an
* int array relevance representation.
*/
public static final int[] toIntArray(Instance x, int L) {
int y[] = new int[L];
for (int j = 0; j < L; j++) {
y[j] = (int) Math.round(x.value(j));
}
return y;
}
/**
* Calibrate a threshold. Based upon a supplied label cardinality from the
* training set.
*/
public static double calibrateThreshold(ArrayList<double[]> Y, double LC_train) {
int N = Y.size();
ArrayList<Double> big = new ArrayList<Double>();
for (double y[] : Y) {
for (double y_ : y) {
big.add(y_);
}
}
Collections.sort(big);
int i = big.size() - (int) Math.round(LC_train * (double) N);
return Math.max(((double) (big.get(i) + big.get(Math.max(i + 1, N - 1)))) / 2.0, 0.00001);
}
/**
* Calibrate thresholds. One threshold for each label, based on training-set
* label cardinality. Assumes that each double[] in Y is of length
* LC_train.length;
*/
public static double[] calibrateThresholds(ArrayList<double[]> Y, double LC_train[]) {
int L = LC_train.length;
double t[] = new double[L];
ArrayList<double[]> Y_[] = new ArrayList[Y.size()];
for (double y[] : Y) {
for (int j = 0; j < y.length; j++) {
Y_[j].add(y);
}
}
for (int j = 0; j < L; j++) {
t[j] = calibrateThreshold(Y_[j], LC_train[j]);
}
return t;
}
/**
* Calculate Performance Measures. Given a threshold t on a batch of
* predicted Distributions and their corresponding TrueRelevances.
* (Rankings.size() must equal Actuals.size()).
*/
public static HashMap<String, Double> evaluateMultiLabel(ArrayList<double[]> Distributions, ArrayList<int[]> TrueRelevances, double t) {
double N = Distributions.size();
int L = Distributions.iterator().next().length;
int fp = 0, tp = 0, tn = 0, fn = 0;
int p_sum_total = 0, r_sum_total = 0;
double log_loss_D = 0.0, log_loss_L = 0.0;
int set_empty_total = 0, set_inter_total = 0;
int exact_match = 0, one_error = 0, coverage = 0;
double accuracy = 0.0, f1_macro_D = 0.0, f1_macro_L = 0.0;
int hloss_total = 0;
int[] o_tp = new int[L], o_fp = new int[L], o_fn = new int[L], o_tn = new int[L];
int[] d_tp = new int[(int) N], d_fp = new int[(int) N], d_fn = new int[(int) N], d_tn = new int[(int) N];
//double average_accuracy_online = 0.0;
for (int i = 0; i < N; i++) {
double ranking[] = Distributions.get(i);
int actual[] = TrueRelevances.get(i);
int pred[] = new int[actual.length];
for (int j = 0; j < L; j++) {
pred[j] = (ranking[j] >= t) ? 1 : 0;
}
// calculate
int p_sum = 0, r_sum = 0;
int set_union = 0;
int set_inter = 0;
int doc_inter = 0;
int doc_union = 0;
for (int j = 0; j < L; j++) {
int p = pred[j];
int R = actual[j];
if (p == 1) {
p_sum++;
// predt 1, real 1
if (R == 1) {
r_sum++;
tp++;
o_tp[j]++; // f1 macro (L)
d_tp[i]++; // f1 macro (D)
set_inter++;
set_union++;
} // predt 1, real 0
else {
fp++;
o_fp[j]++; // f1 macro (L)
d_fp[i]++; // f1 macro (D)
hloss_total++;
set_union++;
}
} else {
// predt 0, real 1
if (R == 1) {
r_sum++;
fn++;
o_fn[j]++; // f1 macro (L)
d_fn[i]++; // f1 macro (D)
hloss_total++;
set_union++;
} // predt 0, real 0
else {
tn++;
o_tn[j]++; // f1 macro (L)
d_tn[i]++; // f1 macro (D)
}
}
// log losses:
log_loss_D += calcLogLoss((double) R, ranking[j], Math.log(N));
log_loss_L += calcLogLoss((double) R, ranking[j], Math.log(L));
}
set_inter_total += set_inter;
p_sum_total += p_sum;
r_sum_total += r_sum;
if (set_union > 0) //avoid NaN
{
accuracy += ((double) set_inter / (double) set_union);
}
//System.out.println(""+set_inter+","+set_union);
if (p_sum <= 0) //empty set
{
set_empty_total++;
}
// exact match (eval. by example)
if (set_inter == set_union) {
exact_match++;
}
// f1 macro average by example
if (p_sum > 0 && r_sum > 0 && set_inter > 0) {
double prec = (double) set_inter / (double) p_sum;
double rec = (double) set_inter / (double) r_sum;
if (prec > 0 || rec > 0) {
f1_macro_D += ((2.0 * prec * rec) / (prec + rec));
}
}
//one error: how many times the top ranked label is NOT in the label set
if (actual[Utils.maxIndex(ranking)] <= 0) {
one_error++;
}
}
double fms[] = new double[L];
for (int j = 0; j < L; j++) {
// micro average
if (o_tp[j] <= 0) {
fms[j] = 0.0;
} else {
double prec = (double) o_tp[j] / ((double) o_tp[j] + (double) o_fp[j]);
double recall = (double) o_tp[j] / ((double) o_tp[j] + (double) o_fn[j]);
fms[j] = 2 * ((prec * recall) / (prec + recall));
}
}
double precision = (double) set_inter_total / (double) p_sum_total;
double recall = (double) set_inter_total / (double) r_sum_total;
HashMap<String, Double> results = new HashMap<String, Double>();
results.put("N", N);
results.put("L", (double) L);
results.put("Accuracy", (accuracy / N));
results.put("F1_micro", (2.0 * precision * recall) / (precision + recall));
results.put("F1_macro_D", (f1_macro_D / N));
results.put("F1_macro_L", (Utils.sum(fms) / (double) L));
results.put("H_loss", ((double) hloss_total / ((double) N * (double) L)));
results.put("H_acc", 1.0 - ((double) hloss_total / ((double) N * (double) L)));
results.put("LCard_pred", (double) p_sum_total / N);
results.put("LCard_real", (double) r_sum_total / N);
results.put("LCard_diff", Math.abs((((double) p_sum_total / N) - (double) r_sum_total / N)));
results.put("Coverage", ((double) coverage / N));
results.put("One_error", ((double) one_error / N));
results.put("Exact_match", ((double) exact_match / N));
results.put("ZeroOne_loss", 1.0 - ((double) exact_match / N));
results.put("LogLossD", (log_loss_D / N));
results.put("LogLossL", (log_loss_L / N));
results.put("Empty", (double) set_empty_total / (double) N);
results.put("EmptyAccuracy", (accuracy / (N - set_empty_total)));
results.put("EmptyMacroF1", f1_macro_D / (N - (double) set_empty_total));
//results.put("Build_time" ,s.vals.get("Build_time"));
//results.put("Test_time" ,s.vals.get("Test_time"));
//results.put("Total_time" ,s.vals.get("Build_time") + s.vals.get("Test_time"));
results.put("TPR", (double) tp / (double) (tp + fn));
results.put("FPR", (double) fp / (double) (fp + tn));
results.put("Precision", precision);
results.put("Recall", recall);
results.put("Threshold", t);
return results;
}
/**
* Calculate Log Loss. See Jesse Read. <i>Scalable Multi-label
* Classification</i>. PhD thesis, University of Waikato, 2010.
*/
public static double calcLogLoss(double R, double P, double C) {
double ans = Math.min(Utils.eq(R, P) ? 0.0 : -((R * Math.log(P)) + ((1.0 - R) * Math.log(1.0 - P))), C);
return (Double.isNaN(ans) ? 0.0 : ans);
}
}
| Java |
/*
* Converter.java
* Copyright (C) 2012 University of Waikato, Hamilton, New Zealand
* @author Jesse Read (jesse@tsc.uc3m.es)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core.utils;
import java.util.LinkedList;
import java.util.List;
import moa.AbstractMOAObject;
import weka.core.Instance;
import weka.core.Instances;
/**
* Converter. This class can be used to convert a multi-label instance into a
* single-label instance.
*
* @author Jesse Read (jesse@tsc.uc3m.es)
* @version $Revision: 1 $
*/
public class Converter extends AbstractMOAObject {
protected Instances m_InstancesTemplate = null;
protected int m_L = -1;
public int getL() {
return this.m_L;
}
public Converter() {
}
public Converter(int n) {
m_L = n;
}
public Instances createTemplate(Instances i) {
this.m_InstancesTemplate = new Instances(i, 0, 0);
return this.m_InstancesTemplate;
}
public Instance formatInstance(Instance original) {
//Copy the original instance
Instance converted = (Instance) original.copy();
converted.setDataset(null);
//Delete all class attributes
for (int j = 0; j < m_L; j++) {
converted.deleteAttributeAt(0);
}
//Add one of those class attributes at the begginning
converted.insertAttributeAt(0);
//Hopefully setting the dataset will configure that attribute properly
converted.setDataset(m_InstancesTemplate);
return converted;
}
public List<Integer> getRelevantLabels(Instance x) {
List<Integer> classValues = new LinkedList<Integer>();
//get all class attributes
for (int j = 0; j < m_L; j++) {
if (x.value(j) > 0.0) {
classValues.add(j);
}
}
return classValues;
}
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* MiscUtils.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author Bernhard Pfahringer (bernhard@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Random;
import weka.core.Utils;
/**
* Class implementing some utility methods.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author Bernhard Pfahringer (bernhard@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class MiscUtils {
public static int chooseRandomIndexBasedOnWeights(double[] weights,
Random random) {
double probSum = Utils.sum(weights);
double val = random.nextDouble() * probSum;
int index = 0;
double sum = 0.0;
while ((sum <= val) && (index < weights.length)) {
sum += weights[index++];
}
return index - 1;
}
public static int poisson(double lambda, Random r) {
if (lambda < 100.0) {
double product = 1.0;
double sum = 1.0;
double threshold = r.nextDouble() * Math.exp(lambda);
int i = 1;
int max = Math.max(100, 10 * (int) Math.ceil(lambda));
while ((i < max) && (sum <= threshold)) {
product *= (lambda / i);
sum += product;
i++;
}
return i - 1;
}
double x = lambda + Math.sqrt(lambda) * r.nextGaussian();
if (x < 0.0) {
return 0;
}
return (int) Math.floor(x);
}
public static String getStackTraceString(Exception ex) {
StringWriter stackTraceWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stackTraceWriter));
return "*** STACK TRACE ***\n" + stackTraceWriter.toString();
}
}
| Java |
/*
* MultilabelInstance.java
* Copyright (C) 2010 University of Waikato, Hamilton, New Zealand
* @author Jesse Read (jmr30@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import weka.core.SparseInstance;
/**
* Multilabel instance.
*
* @author Jesse Read (jmr30@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class MultilabelInstance extends SparseInstance {
int L = -1;
public void setNumLabels(int n) {
this.L = n;
}
public int getNumLabels() {
return this.L;
}
}
| Java |
/*
* SerializeUtils.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Class implementing some serialize utility methods.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class SerializeUtils {
public static class ByteCountingOutputStream extends OutputStream {
protected int numBytesWritten = 0;
public int getNumBytesWritten() {
return this.numBytesWritten;
}
@Override
public void write(int b) throws IOException {
this.numBytesWritten++;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.numBytesWritten += len;
}
@Override
public void write(byte[] b) throws IOException {
this.numBytesWritten += b.length;
}
}
public static void writeToFile(File file, Serializable obj)
throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new GZIPOutputStream(
new BufferedOutputStream(new FileOutputStream(file))));
out.writeObject(obj);
out.flush();
out.close();
}
public static Object readFromFile(File file) throws IOException,
ClassNotFoundException {
ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(
new BufferedInputStream(new FileInputStream(file))));
Object obj = in.readObject();
in.close();
return obj;
}
public static Object copyObject(Serializable obj) throws Exception {
ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(baoStream));
out.writeObject(obj);
out.flush();
out.close();
byte[] byteArray = baoStream.toByteArray();
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(
new ByteArrayInputStream(byteArray)));
Object copy = in.readObject();
in.close();
return copy;
}
public static int measureObjectByteSize(Serializable obj) throws Exception {
ByteCountingOutputStream bcoStream = new ByteCountingOutputStream();
ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(bcoStream));
out.writeObject(obj);
out.flush();
out.close();
return bcoStream.getNumBytesWritten();
}
}
| Java |
/*
* Measurement.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import java.util.ArrayList;
import java.util.List;
import moa.AbstractMOAObject;
/**
* Class for storing an evaluation measurement.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class Measurement extends AbstractMOAObject {
private static final long serialVersionUID = 1L;
protected String name;
protected double value;
public Measurement(String name, double value) {
this.name = name;
this.value = value;
}
public String getName() {
return this.name;
}
public double getValue() {
return this.value;
}
public static Measurement getMeasurementNamed(String name,
Measurement[] measurements) {
for (Measurement measurement : measurements) {
if (name.equals(measurement.getName())) {
return measurement;
}
}
return null;
}
public static void getMeasurementsDescription(Measurement[] measurements,
StringBuilder out, int indent) {
if (measurements.length > 0) {
StringUtils.appendIndented(out, indent, measurements[0].toString());
for (int i = 1; i < measurements.length; i++) {
StringUtils.appendNewlineIndented(out, indent, measurements[i].toString());
}
}
}
public static Measurement[] averageMeasurements(Measurement[][] toAverage) {
List<String> measurementNames = new ArrayList<String>();
for (Measurement[] measurements : toAverage) {
for (Measurement measurement : measurements) {
if (measurementNames.indexOf(measurement.getName()) < 0) {
measurementNames.add(measurement.getName());
}
}
}
GaussianEstimator[] estimators = new GaussianEstimator[measurementNames.size()];
for (int i = 0; i < estimators.length; i++) {
estimators[i] = new GaussianEstimator();
}
for (Measurement[] measurements : toAverage) {
for (Measurement measurement : measurements) {
estimators[measurementNames.indexOf(measurement.getName())].addObservation(measurement.getValue(), 1.0);
}
}
List<Measurement> averagedMeasurements = new ArrayList<Measurement>();
for (int i = 0; i < measurementNames.size(); i++) {
String mName = measurementNames.get(i);
GaussianEstimator mEstimator = estimators[i];
if (mEstimator.getTotalWeightObserved() > 1.0) {
averagedMeasurements.add(new Measurement("[avg] " + mName,
mEstimator.getMean()));
averagedMeasurements.add(new Measurement("[err] " + mName,
mEstimator.getStdDev()
/ Math.sqrt(mEstimator.getTotalWeightObserved())));
}
}
return averagedMeasurements.toArray(new Measurement[averagedMeasurements.size()]);
}
@Override
public void getDescription(StringBuilder sb, int indent) {
sb.append(getName());
sb.append(" = ");
if (getValue()>.001) {
sb.append(StringUtils.doubleToString(getValue(),3));
} else {
sb.append(getValue());
}
}
}
| Java |
/*
* ObjectRepository.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
/**
* Interface for object repositories.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public interface ObjectRepository {
Object getObjectNamed(String string);
}
| Java |
/*
* DoubleVector.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import moa.AbstractMOAObject;
/**
* Vector of double numbers with some utilities.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class DoubleVector extends AbstractMOAObject {
private static final long serialVersionUID = 1L;
protected double[] array;
public DoubleVector() {
this.array = new double[0];
}
public DoubleVector(double[] toCopy) {
this.array = new double[toCopy.length];
System.arraycopy(toCopy, 0, this.array, 0, toCopy.length);
}
public DoubleVector(DoubleVector toCopy) {
this(toCopy.getArrayRef());
}
public int numValues() {
return this.array.length;
}
public void setValue(int i, double v) {
if (i >= this.array.length) {
setArrayLength(i + 1);
}
this.array[i] = v;
}
public void addToValue(int i, double v) {
if (i >= this.array.length) {
setArrayLength(i + 1);
}
this.array[i] += v;
}
public void addValues(DoubleVector toAdd) {
addValues(toAdd.getArrayRef());
}
public void addValues(double[] toAdd) {
if (toAdd.length > this.array.length) {
setArrayLength(toAdd.length);
}
for (int i = 0; i < toAdd.length; i++) {
this.array[i] += toAdd[i];
}
}
public void subtractValues(DoubleVector toSubtract) {
subtractValues(toSubtract.getArrayRef());
}
public void subtractValues(double[] toSubtract) {
if (toSubtract.length > this.array.length) {
setArrayLength(toSubtract.length);
}
for (int i = 0; i < toSubtract.length; i++) {
this.array[i] -= toSubtract[i];
}
}
public void addToValues(double toAdd) {
for (int i = 0; i < this.array.length; i++) {
this.array[i] = this.array[i] + toAdd;
}
}
public void scaleValues(double multiplier) {
for (int i = 0; i < this.array.length; i++) {
this.array[i] = this.array[i] * multiplier;
}
}
// returns 0.0 for values outside of range
public double getValue(int i) {
return ((i >= 0) && (i < this.array.length)) ? this.array[i] : 0.0;
}
public double sumOfValues() {
double sum = 0.0;
for (double element : this.array) {
sum += element;
}
return sum;
}
public int maxIndex() {
int max = -1;
for (int i = 0; i < this.array.length; i++) {
if ((max < 0) || (this.array[i] > this.array[max])) {
max = i;
}
}
return max;
}
public void normalize() {
scaleValues(1.0 / sumOfValues());
}
public int numNonZeroEntries() {
int count = 0;
for (double element : this.array) {
if (element != 0.0) {
count++;
}
}
return count;
}
public double minWeight() {
if (this.array.length > 0) {
double min = this.array[0];
for (int i = 1; i < this.array.length; i++) {
if (this.array[i] < min) {
min = this.array[i];
}
}
return min;
}
return 0.0;
}
public double[] getArrayCopy() {
double[] aCopy = new double[this.array.length];
System.arraycopy(this.array, 0, aCopy, 0, this.array.length);
return aCopy;
}
public double[] getArrayRef() {
return this.array;
}
protected void setArrayLength(int l) {
double[] newArray = new double[l];
int numToCopy = this.array.length;
if (numToCopy > l) {
numToCopy = l;
}
System.arraycopy(this.array, 0, newArray, 0, numToCopy);
this.array = newArray;
}
public void getSingleLineDescription(StringBuilder out) {
getSingleLineDescription(out, numValues());
}
public void getSingleLineDescription(StringBuilder out, int numValues) {
out.append("{");
for (int i = 0; i < numValues; i++) {
if (i > 0) {
out.append("|");
}
out.append(StringUtils.doubleToString(getValue(i), 3));
}
out.append("}");
}
@Override
public void getDescription(StringBuilder sb, int indent) {
getSingleLineDescription(sb);
}
}
| Java |
/*
* InputStreamProgressMonitor.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Class for monitoring the progress of reading an input stream.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class InputStreamProgressMonitor extends FilterInputStream {
/** The number of bytes to read in total */
protected int inputByteSize;
/** The number of bytes read so far */
protected int inputBytesRead;
public InputStreamProgressMonitor(InputStream in) {
super(in);
try {
this.inputByteSize = in.available();
} catch (IOException ioe) {
this.inputByteSize = 0;
}
this.inputBytesRead = 0;
}
public int getBytesRead() {
return this.inputBytesRead;
}
public int getBytesRemaining() {
return this.inputByteSize - this.inputBytesRead;
}
public double getProgressFraction() {
return ((double) this.inputBytesRead / (double) this.inputByteSize);
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#read()
*/
@Override
public int read() throws IOException {
int c = this.in.read();
if (c > 0) {
this.inputBytesRead++;
}
return c;
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#read(byte[])
*/
@Override
public int read(byte[] b) throws IOException {
int numread = this.in.read(b);
if (numread > 0) {
this.inputBytesRead += numread;
}
return numread;
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#read(byte[], int, int)
*/
@Override
public int read(byte[] b, int off, int len) throws IOException {
int numread = this.in.read(b, off, len);
if (numread > 0) {
this.inputBytesRead += numread;
}
return numread;
}
/*
* (non-Javadoc)
*
* @see java.io.InputStream#skip(long)
*/
@Override
public long skip(long n) throws IOException {
long numskip = this.in.skip(n);
if (numskip > 0) {
this.inputBytesRead += numskip;
}
return numskip;
}
/*
* (non-Javadoc)
*
* @see java.io.FilterInputStream#reset()
*/
@Override
public synchronized void reset() throws IOException {
this.in.reset();
this.inputBytesRead = this.inputByteSize - this.in.available();
}
}
| Java |
/*
* MultilabelInstancesHeader.java
* Copyright (C) 2010 University of Waikato, Hamilton, New Zealand
* @author Jesse Read (jmr30@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import weka.core.Instances;
/**
* Class for storing the header or context of a multilabel data stream.
* It allows to know the number of attributes and class labels.
*
* @author Jesse Read (jmr30@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class MultilabelInstancesHeader extends InstancesHeader {
private int m_NumLabels = -1;
public MultilabelInstancesHeader(Instances i, int numLabels) {
super(i);
m_NumLabels = numLabels;
}
public int getNumClassLabels() {
return m_NumLabels;
}
}
| Java |
/*
* GreenwaldKhannaQuantileSummary.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import java.io.Serializable;
import java.util.ArrayList;
import moa.AbstractMOAObject;
/**
* Class for representing summaries of Greenwald and Khanna quantiles.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class GreenwaldKhannaQuantileSummary extends AbstractMOAObject {
private static final long serialVersionUID = 1L;
protected static class Tuple implements Serializable {
private static final long serialVersionUID = 1L;
public double v;
public long g;
public long delta;
public Tuple(double v, long g, long delta) {
this.v = v;
this.g = g;
this.delta = delta;
}
public Tuple(double v) {
this(v, 1, 0);
}
}
protected Tuple[] summary;
protected int numTuples = 0;
protected long numObservations = 0;
public GreenwaldKhannaQuantileSummary(int maxTuples) {
this.summary = new Tuple[maxTuples];
}
public void insert(double val) {
int i = findIndexOfTupleGreaterThan(val);
Tuple nextT = this.summary[i];
if (nextT == null) {
insertTuple(new Tuple(val, 1, 0), i);
} else {
insertTuple(new Tuple(val, 1, nextT.g + nextT.delta - 1), i);
}
if (this.numTuples == this.summary.length) {
// use method 1
deleteMergeableTupleMostFull();
// if (mergeMethod == 1) {
// deleteMergeableTupleMostFull();
// } else if (mergeMethod == 2) {
// deleteTupleMostFull();
// } else {
// long maxDelta = findMaxDelta();
// compress(maxDelta);
// while (numTuples == summary.length) {
// maxDelta++;
// compress(maxDelta);
// }
// }
}
this.numObservations++;
}
protected void insertTuple(Tuple t, int index) {
System.arraycopy(this.summary, index, this.summary, index + 1,
this.numTuples - index);
this.summary[index] = t;
this.numTuples++;
}
protected void deleteTuple(int index) {
this.summary[index] = new Tuple(this.summary[index + 1].v,
this.summary[index].g + this.summary[index + 1].g,
this.summary[index + 1].delta);
System.arraycopy(this.summary, index + 2, this.summary, index + 1,
this.numTuples - index - 2);
this.summary[this.numTuples - 1] = null;
this.numTuples--;
}
protected void deleteTupleMostFull() {
long leastFullness = Long.MAX_VALUE;
int leastFullIndex = 0;
for (int i = 1; i < this.numTuples - 1; i++) {
long fullness = this.summary[i].g + this.summary[i + 1].g
+ this.summary[i + 1].delta;
if (fullness < leastFullness) {
leastFullness = fullness;
leastFullIndex = i;
}
}
if (leastFullIndex > 0) {
deleteTuple(leastFullIndex);
}
}
protected void deleteMergeableTupleMostFull() {
long leastFullness = Long.MAX_VALUE;
int leastFullIndex = 0;
for (int i = 1; i < this.numTuples - 1; i++) {
long fullness = this.summary[i].g + this.summary[i + 1].g
+ this.summary[i + 1].delta;
if ((this.summary[i].delta >= this.summary[i + 1].delta)
&& (fullness < leastFullness)) {
leastFullness = fullness;
leastFullIndex = i;
}
}
if (leastFullIndex > 0) {
deleteTuple(leastFullIndex);
}
}
public long getWorstError() {
long mostFullness = 0;
for (int i = 1; i < this.numTuples - 1; i++) {
long fullness = this.summary[i].g + this.summary[i].delta;
if (fullness > mostFullness) {
mostFullness = fullness;
}
}
return mostFullness;
}
public long findMaxDelta() {
long maxDelta = 0;
for (int i = 0; i < this.numTuples; i++) {
if (this.summary[i].delta > maxDelta) {
maxDelta = this.summary[i].delta;
}
}
return maxDelta;
}
public void compress(long maxDelta) {
long[] bandBoundaries = computeBandBoundaries(maxDelta);
for (int i = this.numTuples - 2; i >= 0; i--) {
if (this.summary[i].delta >= this.summary[i + 1].delta) {
int band = 0;
while (this.summary[i].delta < bandBoundaries[band]) {
band++;
}
long belowBandThreshold = Long.MAX_VALUE;
if (band > 0) {
belowBandThreshold = bandBoundaries[band - 1];
}
long mergeG = this.summary[i + 1].g + this.summary[i].g;
int childI = i - 1;
while (((mergeG + this.summary[i + 1].delta) < maxDelta)
&& (childI >= 0)
&& (this.summary[childI].delta >= belowBandThreshold)) {
mergeG += this.summary[childI].g;
childI--;
}
if (mergeG + this.summary[i + 1].delta < maxDelta) {
// merge
int numDeleted = i - childI;
this.summary[childI + 1] = new Tuple(this.summary[i + 1].v,
mergeG, this.summary[i + 1].delta);
// todo complete & test this multiple delete
System.arraycopy(this.summary, i + 2, this.summary,
childI + 2, this.numTuples - (i + 2));
for (int j = this.numTuples - numDeleted; j < this.numTuples; j++) {
this.summary[j] = null;
}
this.numTuples -= numDeleted;
i = childI + 1;
}
}
}
}
public double getQuantile(double quant) {
long r = (long) Math.ceil(quant * this.numObservations);
long currRank = 0;
for (int i = 0; i < this.numTuples - 1; i++) {
currRank += this.summary[i].g;
if (currRank + this.summary[i + 1].g > r) {
return this.summary[i].v;
}
}
return this.summary[this.numTuples - 1].v;
}
public long getTotalCount() {
return this.numObservations;
}
public double getPropotionBelow(double cutpoint) {
return (double) getCountBelow(cutpoint) / (double) this.numObservations;
}
public long getCountBelow(double cutpoint) {
long rank = 0;
for (int i = 0; i < this.numTuples; i++) {
if (this.summary[i].v > cutpoint) {
break;
}
rank += this.summary[i].g;
}
return rank;
}
public double[] getSuggestedCutpoints() {
double[] cutpoints = new double[this.numTuples];
for (int i = 0; i < this.numTuples; i++) {
cutpoints[i] = this.summary[i].v;
}
return cutpoints;
}
protected int findIndexOfTupleGreaterThan(double val) {
int high = this.numTuples, low = -1, probe;
while (high - low > 1) {
probe = (high + low) / 2;
if (this.summary[probe].v > val) {
high = probe;
} else {
low = probe;
}
}
return high;
}
public static long[] computeBandBoundaries(long maxDelta) {
ArrayList<Long> boundaryList = new ArrayList<Long>();
boundaryList.add(new Long(maxDelta));
int alpha = 1;
while (true) {
long boundary = (maxDelta - (2 << (alpha - 1)) - (maxDelta % (2 << (alpha - 1))));
if (boundary >= 0) {
boundaryList.add(new Long(boundary + 1));
} else {
break;
}
alpha++;
}
boundaryList.add(new Long(0));
long[] boundaries = new long[boundaryList.size()];
for (int i = 0; i < boundaries.length; i++) {
boundaries[i] = boundaryList.get(i).longValue();
}
return boundaries;
}
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* AutoExpandVector.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import java.util.ArrayList;
import java.util.Collection;
import moa.AbstractMOAObject;
import moa.MOAObject;
/**
* Vector with the capability of automatic expansion.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class AutoExpandVector<T> extends ArrayList<T> implements MOAObject {
private static final long serialVersionUID = 1L;
public AutoExpandVector() {
super(0);
}
public AutoExpandVector(int size) {
super(size);
}
@Override
public void add(int pos, T obj) {
if (pos > size()) {
while (pos > size()) {
add(null);
}
trimToSize();
}
super.add(pos, obj);
}
@Override
public T get(int pos) {
return ((pos >= 0) && (pos < size())) ? super.get(pos) : null;
}
@Override
public T set(int pos, T obj) {
if (pos >= size()) {
add(pos, obj);
return null;
}
return super.set(pos, obj);
}
@Override
public boolean add(T arg0) {
boolean result = super.add(arg0);
trimToSize();
return result;
}
@Override
public boolean addAll(Collection<? extends T> arg0) {
boolean result = super.addAll(arg0);
trimToSize();
return result;
}
@Override
public boolean addAll(int arg0, Collection<? extends T> arg1) {
boolean result = super.addAll(arg0, arg1);
trimToSize();
return result;
}
@Override
public void clear() {
super.clear();
trimToSize();
}
@Override
public T remove(int arg0) {
T result = super.remove(arg0);
trimToSize();
return result;
}
@Override
public boolean remove(Object arg0) {
boolean result = super.remove(arg0);
trimToSize();
return result;
}
@Override
protected void removeRange(int arg0, int arg1) {
super.removeRange(arg0, arg1);
trimToSize();
}
@Override
public MOAObject copy() {
return AbstractMOAObject.copy(this);
}
@Override
public int measureByteSize() {
return AbstractMOAObject.measureByteSize(this);
}
@Override
public void getDescription(StringBuilder sb, int indent) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* PropertiesReader.java
* Copyright (C) 1999-2004 University of Waikato, Hamilton, New Zealand
*
*/
package moa.core;
import weka.core.Utils;
import java.util.Properties;
import java.io.File;
import java.io.FileInputStream;
/**
* Class implementing some properties reader utility methods.
*
* @author Eibe Frank
* @author Yong Wang
* @author Len Trigg
* @author Julien Prados
* @version $Revision: 6681 $
*/
public final class PropertiesReader {
/**
* Reads properties that inherit from three locations. Properties
* are first defined in the system resource location (i.e. in the
* CLASSPATH). These default properties must exist. Properties
* defined in the users home directory (optional) override default
* settings. Properties defined in the current directory (optional)
* override all these settings.
*
* @param resourceName the location of the resource that should be
* loaded. e.g.: "weka/core/Utils.props". (The use of hardcoded
* forward slashes here is OK - see
* jdk1.1/docs/guide/misc/resources.html) This routine will also
* look for the file (in this case) "Utils.props" in the users home
* directory and the current directory.
* @return the Properties
* @exception Exception if no default properties are defined, or if
* an error occurs reading the properties files.
*/
public static Properties readProperties(String resourceName)
throws Exception {
Properties defaultProps = new Properties();
try {
// Apparently hardcoded slashes are OK here
// jdk1.1/docs/guide/misc/resources.html
// defaultProps.load(ClassLoader.getSystemResourceAsStream(resourceName));
defaultProps.load((new Utils()).getClass().getClassLoader().getResourceAsStream(resourceName));
} catch (Exception ex) {
/* throw new Exception("Problem reading default properties: "
+ ex.getMessage()); */
System.err.println("Warning, unable to load properties file from "
+ "system resource (Utils.java)");
}
// Hardcoded slash is OK here
// eg: see jdk1.1/docs/guide/misc/resources.html
int slInd = resourceName.lastIndexOf('/');
if (slInd != -1) {
resourceName = resourceName.substring(slInd + 1);
}
// Allow a properties file in the home directory to override
Properties userProps = new Properties(defaultProps);
File propFile = new File(System.getProperties().getProperty("user.home")
+ File.separatorChar
+ resourceName);
if (propFile.exists()) {
try {
userProps.load(new FileInputStream(propFile));
} catch (Exception ex) {
throw new Exception("Problem reading user properties: " + propFile);
}
}
// Allow a properties file in the current directory to override
Properties localProps = new Properties(userProps);
propFile = new File(resourceName);
if (propFile.exists()) {
try {
localProps.load(new FileInputStream(propFile));
} catch (Exception ex) {
throw new Exception("Problem reading local properties: " + propFile);
}
}
return localProps;
}
}
| Java |
/*
* InstancesHeader.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.core;
import java.io.IOException;
import java.io.Reader;
import weka.core.Instance;
import weka.core.Instances;
/**
* Class for storing the header or context of a data stream. It allows to know the number of attributes and classes.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class InstancesHeader extends Instances {
private static final long serialVersionUID = 1L;
public InstancesHeader(Instances i) {
super(i, 0);
}
@Override
public boolean add(Instance i) {
throw new UnsupportedOperationException();
}
@Override
public boolean readInstance(Reader r) throws IOException {
throw new UnsupportedOperationException();
}
public static String getClassNameString(InstancesHeader context) {
if (context == null) {
return "[class]";
}
return "[class:" + context.classAttribute().name() + "]";
}
public static String getClassLabelString(InstancesHeader context,
int classLabelIndex) {
if ((context == null) || (classLabelIndex >= context.numClasses())) {
return "<class " + (classLabelIndex + 1) + ">";
}
return "<class " + (classLabelIndex + 1) + ":"
+ context.classAttribute().value(classLabelIndex) + ">";
}
// is impervious to class index changes - attIndex is true attribute index
// regardless of class position
public static String getAttributeNameString(InstancesHeader context,
int attIndex) {
if ((context == null) || (attIndex >= context.numAttributes())) {
return "[att " + (attIndex + 1) + "]";
}
int instAttIndex = attIndex < context.classIndex() ? attIndex
: attIndex + 1;
return "[att " + (attIndex + 1) + ":"
+ context.attribute(instAttIndex).name() + "]";
}
// is impervious to class index changes - attIndex is true attribute index
// regardless of class position
public static String getNominalValueString(InstancesHeader context,
int attIndex, int valIndex) {
if (context != null) {
int instAttIndex = attIndex < context.classIndex() ? attIndex
: attIndex + 1;
if ((instAttIndex < context.numAttributes())
&& (valIndex < context.attribute(instAttIndex).numValues())) {
return "{val " + (valIndex + 1) + ":"
+ context.attribute(instAttIndex).value(valIndex) + "}";
}
}
return "{val " + (valIndex + 1) + "}";
}
// is impervious to class index changes - attIndex is true attribute index
// regardless of class position
public static String getNumericValueString(InstancesHeader context,
int attIndex, double value) {
if (context != null) {
int instAttIndex = attIndex < context.classIndex() ? attIndex
: attIndex + 1;
if (instAttIndex < context.numAttributes()) {
if (context.attribute(instAttIndex).isDate()) {
return context.attribute(instAttIndex).formatDate(value);
}
}
}
return Double.toString(value);
}
}
| Java |
/*
* ClusteringSetupTab.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.clustertab;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JFileChooser;
import moa.clusterers.AbstractClusterer;
import moa.evaluation.MeasureCollection;
import moa.gui.FileExtensionFilter;
import moa.gui.TextViewerPanel;
import moa.streams.clustering.ClusteringStream;
public class ClusteringSetupTab extends javax.swing.JPanel {
private ClusteringTabPanel clusteringTab;
private String lastfile;
/** Creates new form ClusteringSetupTab */
public ClusteringSetupTab() {
initComponents();
clusteringAlgoPanel0.renderAlgoPanel();
}
public AbstractClusterer getClusterer0(){
return clusteringAlgoPanel0.getClusterer0();
}
public AbstractClusterer getClusterer1(){
return clusteringAlgoPanel0.getClusterer1();
}
public ClusteringStream getStream0(){
return clusteringAlgoPanel0.getStream();
}
public MeasureCollection[] getMeasures(){
return clusteringEvalPanel1.getSelectedMeasures();
}
public TextViewerPanel getLogPanel(){
return logPanel;
}
public void addButtonActionListener(ActionListener l){
buttonWeka.addActionListener(l);
buttonWeka.setActionCommand("weka export");
buttonExport.addActionListener(l);
buttonExport.setActionCommand("csv export");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
clusteringAlgoPanel0 = new moa.gui.clustertab.ClusteringAlgoPanel();
clusteringEvalPanel1 = new moa.gui.clustertab.ClusteringEvalPanel();
buttonStart = new javax.swing.JButton();
buttonStop = new javax.swing.JButton();
buttonExport = new javax.swing.JButton();
buttonWeka = new javax.swing.JButton();
buttonImportSettings = new javax.swing.JButton();
buttonExportSettings = new javax.swing.JButton();
logPanel = new moa.gui.TextViewerPanel();
setLayout(new java.awt.GridBagLayout());
clusteringAlgoPanel0.setMinimumSize(new java.awt.Dimension(335, 150));
clusteringAlgoPanel0.setPanelTitle("Cluster Algorithm Setup");
clusteringAlgoPanel0.setPreferredSize(new java.awt.Dimension(335, 150));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(clusteringAlgoPanel0, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(clusteringEvalPanel1, gridBagConstraints);
buttonStart.setText("Start");
buttonStart.setPreferredSize(new java.awt.Dimension(80, 23));
buttonStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonStartActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonStart, gridBagConstraints);
buttonStop.setText("Stop");
buttonStop.setEnabled(false);
buttonStop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonStopActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonStop, gridBagConstraints);
buttonExport.setText("Export CSV");
buttonExport.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonExport, gridBagConstraints);
buttonWeka.setText("Weka Explorer");
buttonWeka.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonWeka, gridBagConstraints);
buttonImportSettings.setText("Import");
buttonImportSettings.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonImportSettingsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 75, 4, 4);
add(buttonImportSettings, gridBagConstraints);
buttonExportSettings.setText("Export");
buttonExportSettings.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonExportSettingsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonExportSettings, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(logPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void buttonImportSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonImportSettingsActionPerformed
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(new FileExtensionFilter("txt"));
if(lastfile!=null)
fileChooser.setSelectedFile(new File(lastfile));
if (fileChooser.showOpenDialog(this.buttonImportSettings) == JFileChooser.APPROVE_OPTION) {
lastfile = fileChooser.getSelectedFile().getPath();
loadOptionsFromFile(fileChooser.getSelectedFile().getPath());
}
}//GEN-LAST:event_buttonImportSettingsActionPerformed
private void buttonExportSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExportSettingsActionPerformed
StringBuffer sb = new StringBuffer();
sb.append(clusteringAlgoPanel0.getStreamValueAsCLIString()+"\n");
sb.append(clusteringAlgoPanel0.getAlgorithm0ValueAsCLIString()+"\n");
sb.append(clusteringAlgoPanel0.getAlgorithm1ValueAsCLIString()+"\n");
System.out.println(sb);
logPanel.addText(sb.toString());
}//GEN-LAST:event_buttonExportSettingsActionPerformed
private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStartActionPerformed
toggle(true);
}//GEN-LAST:event_buttonStartActionPerformed
private void buttonStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStopActionPerformed
stop(true);
}//GEN-LAST:event_buttonStopActionPerformed
private void loadOptionsFromFile(String filepath){
try {
BufferedReader in = new BufferedReader(new FileReader(filepath));
String stream0 = in.readLine();
clusteringAlgoPanel0.setStreamValueAsCLIString(stream0);
String algo0 = in.readLine();
clusteringAlgoPanel0.setAlgorithm0ValueAsCLIString(algo0);
String algo1 = in.readLine();
clusteringAlgoPanel0.setAlgorithm1ValueAsCLIString(algo1);
System.out.println("Loading settings from "+filepath);
logPanel.addText("Loading settings from "+filepath);
} catch (Exception e) {
System.out.println("Bad option file:"+e.getMessage());
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonExport;
private javax.swing.JButton buttonExportSettings;
private javax.swing.JButton buttonImportSettings;
private javax.swing.JButton buttonStart;
private javax.swing.JButton buttonStop;
private javax.swing.JButton buttonWeka;
private moa.gui.clustertab.ClusteringAlgoPanel clusteringAlgoPanel0;
private moa.gui.clustertab.ClusteringEvalPanel clusteringEvalPanel1;
private moa.gui.TextViewerPanel logPanel;
// End of variables declaration//GEN-END:variables
void setClusteringTab(ClusteringTabPanel clusteringTab) {
this.clusteringTab = clusteringTab;
}
public void toggleRunMode(){
toggle(false);
}
public void stopRun(){
stop(false);
}
private void toggle(boolean internal) {
setStateConfigButtons(false);
if(buttonStart.getText().equals("Pause")){
buttonStart.setText("Resume");
buttonWeka.setEnabled(true);
buttonExport.setEnabled(true);
}
else{
buttonStart.setText("Pause");
buttonWeka.setEnabled(false);
buttonExport.setEnabled(false);
}
//push event forward to the cluster tab
if(internal)
clusteringTab.toggle();
}
private void stop(boolean internal) {
buttonStart.setEnabled(true);
buttonStart.setText("Start");
buttonStop.setEnabled(false);
buttonWeka.setEnabled(false);
buttonExport.setEnabled(false);
setStateConfigButtons(true);
//push event forward to the cluster tab
if(internal)
clusteringTab.stop();
}
private void setStateConfigButtons(boolean state){
buttonStop.setEnabled(!state);
buttonExportSettings.setEnabled(state);
buttonImportSettings.setEnabled(state);
}
}
| Java |
/*
* ClusteringVisualEvalPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.clustertab;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import moa.evaluation.MeasureCollection;
public class ClusteringVisualEvalPanel extends javax.swing.JPanel{
private ArrayList<JLabel> names;
private ArrayList<JLabel> values;
private ArrayList<JRadioButton> radiobuttons;
private MeasureCollection[] measures0;
private MeasureCollection[] measures1;
private ButtonGroup radioGroup;
private JLabel labelDummy;
private JLabel labelMeasure;
private JLabel labelCurrent0;
private JLabel labelMean0;
/** Creates new form ClusteringEvalPanel */
public ClusteringVisualEvalPanel() {
initComponents();
radioGroup = new ButtonGroup();
}
public void setMeasures(MeasureCollection[] measures0, MeasureCollection[] measures1, ActionListener listener){
this.measures0 = measures0;
this.measures1 = measures1;
names = new ArrayList<JLabel>();
values = new ArrayList<JLabel>();
radiobuttons = new ArrayList<JRadioButton>();
for (int i = 0; i < measures0.length; i++) {
for (int j = 0; j < measures0[i].getNumMeasures(); j++) {
if(measures0[i].isEnabled(j)){
names.add(new JLabel(measures0[i].getName(j)));
}
}
}
setLayout(new java.awt.GridBagLayout());
GridBagConstraints gb;
//Radiobuttons
radioGroup = new ButtonGroup();
gb = new GridBagConstraints();
gb.gridx=0;
for (int i = 0; i < names.size(); i++) {
JRadioButton rb = new JRadioButton();
rb.setActionCommand(Integer.toString(i));
rb.addActionListener(listener);
radiobuttons.add(rb);
gb.gridy = i+1;
contentPanel.add(rb, gb);
radioGroup.add(rb);
}
radiobuttons.get(0).setSelected(true);
//name labels
gb = new GridBagConstraints();
gb.gridx=1;
for (int i = 0; i < names.size(); i++) {
names.get(i).setPreferredSize(new Dimension(40, 14));
gb.anchor = GridBagConstraints.WEST;
gb.insets = new java.awt.Insets(4, 7, 4, 7);
gb.gridy = i+1;
contentPanel.add(names.get(i), gb);
}
int counter = 0;
for (int i = 0; i < measures0.length; i++) {
for (int j = 0; j < measures0[i].getNumMeasures(); j++) {
if(!measures0[i].isEnabled(j)) continue;
for (int k = 0; k < 4; k++) {
String tooltip ="";
Color color = Color.black;
switch(k){
case 0:
tooltip = "current value";
color = Color.red;
break;
case 1:
tooltip = "current value";
color = Color.blue;
break;
case 2:
tooltip = "mean";
color = Color.black;
break;
case 3:
tooltip = "mean";
color = Color.black;
break;
}
JLabel l = new JLabel("-");
l.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
l.setPreferredSize(new java.awt.Dimension(50, 14));
l.setToolTipText(measures0[i].getName(j)+" "+tooltip);
l.setForeground(color);
values.add(l);
gb = new GridBagConstraints();
gb.gridy = 1 + counter;
gb.gridx = 2 + k;
gb.weightx = 1.0;
contentPanel.add(l, gb);
}
counter++;
}
}
//dummy label to align the labels at the top
gb = new GridBagConstraints();
gb.gridx = 0;
gb.gridy = names.size()+2;
gb.gridwidth = 6;
gb.weighty = 1.0;
JLabel fill = new JLabel();
contentPanel.add(fill, gb);
addLabels();
contentPanel.setPreferredSize(new Dimension(250, names.size()*(14+8)+20));
}
private void addLabels(){
labelMeasure = new javax.swing.JLabel("Measure");
labelCurrent0 = new JLabel("Current");
labelMean0 = new javax.swing.JLabel("Mean");
labelDummy = new javax.swing.JLabel();
GridBagConstraints gb = new GridBagConstraints();
gb.gridy = 0;
gb.gridx = 0;
contentPanel.add(labelDummy, gb);
gb.gridx = 1;
contentPanel.add(labelMeasure, gb);
gb = new GridBagConstraints();
gb.gridy = 0;
gb.gridx = 2;
gb.gridwidth = 2;
contentPanel.add(labelCurrent0, gb);
gb = new GridBagConstraints();
gb.gridy = 0;
gb.gridx=4;
gb.gridwidth = 2;
contentPanel.add(labelMean0, gb);
}
public void update(){
DecimalFormat d = new DecimalFormat("0.00");
if(measures0!=null){
int counter = 0;
for (MeasureCollection m : measures0) {
for (int i = 0; i < m.getNumMeasures(); i++) {
if(!m.isEnabled(i)) continue;
if(Double.isNaN(m.getLastValue(i)))
values.get(counter*4).setText("-");
else
values.get(counter*4).setText(d.format(m.getLastValue(i)));
if(Double.isNaN(m.getMean(i)))
values.get(counter*4+2).setText("-");
else
values.get(counter*4+2).setText(d.format(m.getMean(i)));
counter++;
}
}
}
if(measures1!=null){
int counter = 0;
for (MeasureCollection m : measures1) {
for (int i = 0; i < m.getNumMeasures(); i++) {
if(!m.isEnabled(i)) continue;
if(Double.isNaN(m.getLastValue(i)))
values.get(counter*4+1).setText("-");
else
values.get(counter*4+1).setText(d.format(m.getLastValue(i)));
if(Double.isNaN(m.getMean(i)))
values.get(counter*4+3).setText("-");
else
values.get(counter*4+3).setText(d.format(m.getMean(i)));
counter++;
}
}
}
}
@Override
//this is soooooo bad, but freaking gridbag somehow doesnt kick in...???
protected void paintComponent(Graphics g) {
scrollPane.setPreferredSize(new Dimension(getWidth()-20, getHeight()-30));
super.paintComponent(g);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
scrollPane = new javax.swing.JScrollPane();
contentPanel = new javax.swing.JPanel();
setBorder(javax.swing.BorderFactory.createTitledBorder("Values"));
setPreferredSize(new java.awt.Dimension(250, 115));
setLayout(new java.awt.GridBagLayout());
scrollPane.setBorder(null);
scrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setPreferredSize(new java.awt.Dimension(270, 180));
contentPanel.setPreferredSize(new java.awt.Dimension(100, 105));
contentPanel.setLayout(new java.awt.GridBagLayout());
scrollPane.setViewportView(contentPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(scrollPane, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel contentPanel;
private javax.swing.JScrollPane scrollPane;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* ClusteringAlgoPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.clustertab;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import moa.clusterers.AbstractClusterer;
import moa.clusterers.Clusterer;
import moa.gui.GUIUtils;
import moa.gui.OptionEditComponent;
import moa.options.ClassOption;
import moa.options.Option;
import moa.streams.clustering.ClusteringStream;
import moa.streams.generators.RandomRBFGenerator;
public class ClusteringAlgoPanel extends javax.swing.JPanel implements ActionListener{
protected List<OptionEditComponent> editComponents = new LinkedList<OptionEditComponent>();
private ClassOption streamOption = new ClassOption("Stream", 's',
"", ClusteringStream.class,
"RandomRBFGeneratorEvents");
private ClassOption algorithmOption0 = new ClassOption("Algorithm0", 'a',
"Algorithm to use.", Clusterer.class, "ClusterGenerator");
private ClassOption algorithmOption1 = new ClassOption("Algorithm1", 'c',
"Comparison algorithm", Clusterer.class, "", "clustream.WithKmeans");
public ClusteringAlgoPanel() {
initComponents();
}
public void renderAlgoPanel(){
setLayout(new BorderLayout());
ArrayList<Option> options = new ArrayList<Option>();
options.add(streamOption);
options.add(algorithmOption0);
options.add(algorithmOption1);
JPanel optionsPanel = new JPanel();
GridBagLayout gbLayout = new GridBagLayout();
optionsPanel.setLayout(gbLayout);
//Create generic label constraints
GridBagConstraints gbcLabel = new GridBagConstraints();
gbcLabel.gridx = 0;
gbcLabel.fill = GridBagConstraints.NONE;
gbcLabel.anchor = GridBagConstraints.EAST;
gbcLabel.weightx = 0;
gbcLabel.insets = new Insets(5, 5, 5, 5);
//Create generic editor constraints
GridBagConstraints gbcOption = new GridBagConstraints();
gbcOption.gridx = 1;
gbcOption.fill = GridBagConstraints.HORIZONTAL;
gbcOption.anchor = GridBagConstraints.CENTER;
gbcOption.weightx = 1;
gbcOption.insets = new Insets(5, 5, 5, 0);
//Stream Option
JLabel labelStream = new JLabel("Stream");
labelStream.setToolTipText("Stream to use.");
optionsPanel.add(labelStream, gbcLabel);
JComponent editorStream = streamOption.getEditComponent();
labelStream.setLabelFor(editorStream);
editComponents.add((OptionEditComponent) editorStream);
optionsPanel.add(editorStream, gbcOption);
//Algorithm0 Option
JLabel labelAlgo0 = new JLabel("Algorithm1");
labelAlgo0.setToolTipText("Algorithm to use.");
optionsPanel.add(labelAlgo0, gbcLabel);
JComponent editorAlgo0 = algorithmOption0.getEditComponent();
labelAlgo0.setLabelFor(editorAlgo0);
editComponents.add((OptionEditComponent) editorAlgo0);
optionsPanel.add(editorAlgo0, gbcOption);
//Algorithm1 Option
JLabel labelAlgo1 = new JLabel("Algorithm2");
labelAlgo1.setToolTipText("Comparison algorithm to use.");
optionsPanel.add(labelAlgo1, gbcLabel);
JComponent editorAlgo1 = algorithmOption1.getEditComponent();
labelAlgo1.setLabelFor(editorAlgo1);
editComponents.add((OptionEditComponent) editorAlgo1);
optionsPanel.add(editorAlgo1, gbcOption);
//use comparison Algorithm Option
GridBagConstraints gbcClearButton = new GridBagConstraints();
gbcClearButton.gridx = 2;
gbcClearButton.gridy = 2;
gbcClearButton.fill = GridBagConstraints.NONE;
gbcClearButton.anchor = GridBagConstraints.CENTER;
gbcClearButton.insets = new Insets(5, 0, 5, 5);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setActionCommand("clear");
optionsPanel.add(clearButton, gbcClearButton);
add(optionsPanel);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("clear")){
algorithmOption1.setValueViaCLIString("None");
editComponents.get(2).setEditState("None");
}
}
public AbstractClusterer getClusterer0(){
AbstractClusterer c = null;
applyChanges();
try {
c = (AbstractClusterer) ClassOption.cliStringToObject(algorithmOption0.getValueAsCLIString(), Clusterer.class, null);
} catch (Exception ex) {
Logger.getLogger(ClusteringAlgoPanel.class.getName()).log(Level.SEVERE, null, ex);
}
return c;
}
public AbstractClusterer getClusterer1(){
AbstractClusterer c = null;
applyChanges();
if(!algorithmOption1.getValueAsCLIString().equals("None")){
try {
c = (AbstractClusterer) ClassOption.cliStringToObject(algorithmOption1.getValueAsCLIString(), Clusterer.class, null);
} catch (Exception ex) {
Logger.getLogger(ClusteringAlgoPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
return c;
}
public ClusteringStream getStream(){
ClusteringStream s = null;
applyChanges();
try {
s = (ClusteringStream) ClassOption.cliStringToObject(streamOption.getValueAsCLIString(), ClusteringStream.class, null);
} catch (Exception ex) {
Logger.getLogger(ClusteringAlgoPanel.class.getName()).log(Level.SEVERE, null, ex);
}
return s;
}
public String getStreamValueAsCLIString(){
applyChanges();
return streamOption.getValueAsCLIString();
}
public String getAlgorithm0ValueAsCLIString(){
applyChanges();
return algorithmOption0.getValueAsCLIString();
}
public String getAlgorithm1ValueAsCLIString(){
applyChanges();
return algorithmOption1.getValueAsCLIString();
}
/* We need to fetch the right item from editComponents list, index needs to match GUI order */
public void setStreamValueAsCLIString(String s){
streamOption.setValueViaCLIString(s);
editComponents.get(0).setEditState(streamOption.getValueAsCLIString());
}
public void setAlgorithm0ValueAsCLIString(String s){
algorithmOption0.setValueViaCLIString(s);
editComponents.get(1).setEditState(algorithmOption0.getValueAsCLIString());
}
public void setAlgorithm1ValueAsCLIString(String s){
algorithmOption1.setValueViaCLIString(s);
editComponents.get(2).setEditState(algorithmOption1.getValueAsCLIString());
}
public void applyChanges() {
for (OptionEditComponent editor : this.editComponents) {
try {
editor.applyState();
} catch (Exception ex) {
GUIUtils.showExceptionDialog(this, "Problem with option "
+ editor.getEditedOption().getName(), ex);
}
}
}
public void setPanelTitle(String title){
setBorder(javax.swing.BorderFactory.createTitledBorder(null,title, javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Cluster Algorithm Setup", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
setLayout(new java.awt.GridBagLayout());
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* ClusteringTabPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.clustertab;
import moa.gui.AbstractTabPanel;
public class ClusteringTabPanel extends AbstractTabPanel{
/** Creates new form ClusterTab */
public ClusteringTabPanel() {
initComponents();
clusteringVisualTab.setClusteringSetupTab(clusteringSetupTab);
clusteringSetupTab.addButtonActionListener(clusteringVisualTab);
clusteringSetupTab.setClusteringTab(this);
}
void toggle() {
clusteringVisualTab.toggleVisualizer(false);
}
void stop() {
clusteringVisualTab.stopVisualizer();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
clusteringSetupTab = new moa.gui.clustertab.ClusteringSetupTab();
clusteringVisualTab = new moa.gui.clustertab.ClusteringVisualTab();
setLayout(new java.awt.BorderLayout());
jTabbedPane1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTabbedPane1MouseClicked(evt);
}
});
jTabbedPane1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTabbedPane1FocusGained(evt);
}
});
jTabbedPane1.addTab("Setup", clusteringSetupTab);
jTabbedPane1.addTab("Visualization", clusteringVisualTab);
add(jTabbedPane1, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void jTabbedPane1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTabbedPane1FocusGained
}//GEN-LAST:event_jTabbedPane1FocusGained
private void jTabbedPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTabbedPane1MouseClicked
}//GEN-LAST:event_jTabbedPane1MouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private moa.gui.clustertab.ClusteringSetupTab clusteringSetupTab;
private moa.gui.clustertab.ClusteringVisualTab clusteringVisualTab;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration//GEN-END:variables
//returns the string to display as title of the tab
public String getTabTitle() {
return "Clustering";
}
//a short description (can be used as tool tip) of the tab, or contributor, etc.
public String getDescription(){
return "MOA Clustering";
}
}
| Java |
/*
* ClusteringEvalPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.clustertab;
import java.awt.GridBagConstraints;
import java.util.ArrayList;
import java.util.logging.Logger;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import moa.core.AutoClassDiscovery;
import moa.core.AutoExpandVector;
import moa.evaluation.ClassificationMeasureCollection;
import moa.evaluation.MeasureCollection;
public class ClusteringEvalPanel extends javax.swing.JPanel {
Class<?>[] measure_classes = null;
ArrayList<JLabel> labels = null;
ArrayList<JCheckBox> checkboxes = null;
/** Creates new form ClusteringEvalPanel */
public ClusteringEvalPanel() {
initComponents();
measure_classes = findMeasureClasses();
labels = new ArrayList<JLabel>();
checkboxes = new ArrayList<JCheckBox>();
addComponents();
}
private void addComponents() {
GridBagConstraints gb = new GridBagConstraints();
gb.insets = new java.awt.Insets(4, 7, 4, 7);
int counter = 0;
for (int i = 0; i < measure_classes.length; i++) {
try {
MeasureCollection m = (MeasureCollection) measure_classes[i].newInstance();
for (int j = 0; j < m.getNumMeasures(); j++) {
String t = m.getName(j);
JLabel l = new JLabel(m.getName(j));
l.setPreferredSize(new java.awt.Dimension(100, 14));
//labels[i].setToolTipText("");
gb.gridx = 0;
gb.gridy = counter;
labels.add(l);
contentPanel.add(l, gb);
JCheckBox cb = new JCheckBox();
if (m.isEnabled(j)) {
cb.setSelected(true);
} else {
cb.setSelected(false);
}
gb.gridx = 1;
checkboxes.add(cb);
contentPanel.add(cb, gb);
counter++;
}
} catch (Exception ex) {
Logger.getLogger("Couldn't create Instance for " + measure_classes[i].getName());
ex.printStackTrace();
}
}
JLabel dummy = new JLabel();
gb.gridx = 0;
gb.gridy++;
gb.gridwidth = 3;
gb.weightx = 1;
gb.weighty = 1;
add(dummy, gb);
}
private Class<?>[] findMeasureClasses() {
AutoExpandVector<Class<?>> finalClasses = new AutoExpandVector<Class<?>>();
Class<?>[] classesFound = AutoClassDiscovery.findClassesOfType("moa.evaluation",
MeasureCollection.class);
for (Class<?> foundClass : classesFound) {
//Not add ClassificationMeasureCollection
boolean noClassificationMeasures = true;
for (Class cl: foundClass.getInterfaces()) {
if (cl.toString().contains("moa.evaluation.ClassificationMeasureCollection")){
noClassificationMeasures = false;
}
}
if (noClassificationMeasures ) {
finalClasses.add(foundClass);
}
}
return finalClasses.toArray(new Class<?>[finalClasses.size()]);
}
public MeasureCollection[] getSelectedMeasures() {
ArrayList<MeasureCollection> measuresSelect = new ArrayList<MeasureCollection>();
int counter = 0;
for (int i = 0; i < measure_classes.length; i++) {
try {
MeasureCollection m = (MeasureCollection) measure_classes[i].newInstance();
boolean addMeasure = false;
for (int j = 0; j < m.getNumMeasures(); j++) {
boolean selected = checkboxes.get(counter).isSelected();
m.setEnabled(j, selected);
if (selected) {
addMeasure = true;
}
counter++;
}
if (addMeasure) {
measuresSelect.add(m);
}
} catch (Exception ex) {
Logger.getLogger("Couldn't create Instance for " + measure_classes[i].getName());
ex.printStackTrace();
}
}
MeasureCollection[] measures = new MeasureCollection[measuresSelect.size()];
for (int i = 0; i < measures.length; i++) {
measures[i] = measuresSelect.get(i);
}
return measures;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
scrollPane = new javax.swing.JScrollPane();
contentPanel = new javax.swing.JPanel();
setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Evaluation Measures", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
setLayout(new java.awt.GridBagLayout());
scrollPane.setBorder(null);
scrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
if(java.awt.Toolkit.getDefaultToolkit().getScreenSize().getHeight() > 650) {
scrollPane.setPreferredSize(new java.awt.Dimension(100, 225));
} else {
scrollPane.setPreferredSize(new java.awt.Dimension(100, 115));
}
contentPanel.setLayout(new java.awt.GridBagLayout());
scrollPane.setViewportView(contentPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(scrollPane, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel contentPanel;
private javax.swing.JScrollPane scrollPane;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* ClusteringVisualTab.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.clustertab;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.ToolTipManager;
import moa.gui.FileExtensionFilter;
import moa.gui.visualization.GraphCanvas;
import moa.gui.visualization.RunVisualizer;
import moa.gui.visualization.StreamPanel;
public class ClusteringVisualTab extends javax.swing.JPanel implements ActionListener{
private RunVisualizer visualizer = null;
private Thread visualizerThread = null;
private Boolean running = false;
private ClusteringSetupTab clusteringSetupTab = null;
private String exportFile;
private String screenshotFilebase;
/** Creates new form ClusteringVisualTab */
public ClusteringVisualTab() {
resetComponents();
}
private void resetComponents(){
initComponents();
comboY.setSelectedIndex(1);
graphCanvas.setViewport(graphScrollPanel.getViewport());
//TODO this needs to only affect the visual Panel
ToolTipManager.sharedInstance().setDismissDelay(20000);
ToolTipManager.sharedInstance().setInitialDelay(100);
}
public void setClusteringSetupTab(ClusteringSetupTab clusteringSetupTab){
this.clusteringSetupTab = clusteringSetupTab;
}
private void createVisualiterThread(){
visualizer = new RunVisualizer(this, clusteringSetupTab);
visualizerThread = new Thread(visualizer);
}
public void setDimensionComobBoxes(int numDimensions){
String[] dimensions = new String[numDimensions];
for (int i = 0; i < dimensions.length; i++) {
dimensions[i] = "Dim "+(i+1);
}
comboX.setModel(new javax.swing.DefaultComboBoxModel(dimensions));
comboY.setModel(new javax.swing.DefaultComboBoxModel(dimensions));
comboY.setSelectedIndex(1);
}
public StreamPanel getLeftStreamPanel(){
return streamPanel0;
}
public StreamPanel getRightStreamPanel(){
return streamPanel1;
}
public GraphCanvas getGraphCanvas(){
return graphCanvas;
}
public ClusteringVisualEvalPanel getEvalPanel(){
return clusteringVisualEvalPanel1;
}
public boolean isEnabledDrawPoints(){
return checkboxDrawPoints.isSelected();
}
public boolean isEnabledDrawGroundTruth(){
return checkboxDrawGT.isSelected();
}
public boolean isEnabledDrawMicroclustering(){
return checkboxDrawMicro.isSelected();
}
public boolean isEnabledDrawClustering(){
return checkboxDrawClustering.isSelected();
}
public void setProcessedPointsCounter(int value){
label_processed_points_value.setText(Integer.toString(value));
}
public int getPauseInterval(){
return Integer.parseInt(numPauseAfterPoints.getText());
}
public void setPauseInterval(int pause){
numPauseAfterPoints.setText(Integer.toString(pause));
}
@Override
public void repaint() {
if(splitVisual!=null)
splitVisual.setDividerLocation(splitVisual.getWidth()/2);
super.repaint();
}
public void toggleVisualizer(boolean internal){
if(visualizer == null)
createVisualiterThread();
if(!visualizerThread.isAlive()){
visualizerThread.start();
}
//pause
if(running){
running = false;
visualizer.pause();
buttonRun.setText("Resume");
}
else{
running = true;
visualizer.resume();
buttonRun.setText("Pause");
}
if(internal)
clusteringSetupTab.toggleRunMode();
}
public void stopVisualizer(){
visualizer.stop();
running = false;
visualizer = null;
visualizerThread = null;
removeAll();
resetComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jSplitPane1 = new javax.swing.JSplitPane();
topWrapper = new javax.swing.JPanel();
panelVisualWrapper = new javax.swing.JPanel();
splitVisual = new javax.swing.JSplitPane();
scrollPane1 = new javax.swing.JScrollPane();
streamPanel1 = new moa.gui.visualization.StreamPanel();
scrollPane0 = new javax.swing.JScrollPane();
streamPanel0 = new moa.gui.visualization.StreamPanel();
panelControl = new javax.swing.JPanel();
buttonRun = new javax.swing.JButton();
buttonStop = new javax.swing.JButton();
buttonScreenshot = new javax.swing.JButton();
speedSlider = new javax.swing.JSlider();
jLabel1 = new javax.swing.JLabel();
comboX = new javax.swing.JComboBox();
labelX = new javax.swing.JLabel();
comboY = new javax.swing.JComboBox();
labelY = new javax.swing.JLabel();
checkboxDrawPoints = new javax.swing.JCheckBox();
checkboxDrawGT = new javax.swing.JCheckBox();
checkboxDrawMicro = new javax.swing.JCheckBox();
checkboxDrawClustering = new javax.swing.JCheckBox();
label_processed_points = new javax.swing.JLabel();
label_processed_points_value = new javax.swing.JLabel();
labelNumPause = new javax.swing.JLabel();
numPauseAfterPoints = new javax.swing.JTextField();
panelEvalOutput = new javax.swing.JPanel();
clusteringVisualEvalPanel1 = new moa.gui.clustertab.ClusteringVisualEvalPanel();
graphPanel = new javax.swing.JPanel();
graphPanelControlTop = new javax.swing.JPanel();
buttonZoomInY = new javax.swing.JButton();
buttonZoomOutY = new javax.swing.JButton();
labelEvents = new javax.swing.JLabel();
graphScrollPanel = new javax.swing.JScrollPane();
graphCanvas = new moa.gui.visualization.GraphCanvas();
graphPanelControlBottom = new javax.swing.JPanel();
buttonZoomInX = new javax.swing.JButton();
buttonZoomOutX = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
jSplitPane1.setDividerLocation(400);
jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
topWrapper.setPreferredSize(new java.awt.Dimension(688, 500));
topWrapper.setLayout(new java.awt.GridBagLayout());
panelVisualWrapper.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
panelVisualWrapper.setLayout(new java.awt.BorderLayout());
splitVisual.setDividerLocation(403);
splitVisual.setResizeWeight(1.0);
streamPanel1.setPreferredSize(new java.awt.Dimension(400, 250));
javax.swing.GroupLayout streamPanel1Layout = new javax.swing.GroupLayout(streamPanel1);
streamPanel1.setLayout(streamPanel1Layout);
streamPanel1Layout.setHorizontalGroup(
streamPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 428, Short.MAX_VALUE)
);
streamPanel1Layout.setVerticalGroup(
streamPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 339, Short.MAX_VALUE)
);
scrollPane1.setViewportView(streamPanel1);
splitVisual.setRightComponent(scrollPane1);
scrollPane0.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
scrollPane0MouseWheelMoved(evt);
}
});
streamPanel0.setPreferredSize(new java.awt.Dimension(400, 250));
javax.swing.GroupLayout streamPanel0Layout = new javax.swing.GroupLayout(streamPanel0);
streamPanel0.setLayout(streamPanel0Layout);
streamPanel0Layout.setHorizontalGroup(
streamPanel0Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
streamPanel0Layout.setVerticalGroup(
streamPanel0Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 339, Short.MAX_VALUE)
);
scrollPane0.setViewportView(streamPanel0);
splitVisual.setLeftComponent(scrollPane0);
panelVisualWrapper.add(splitVisual, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = java.awt.GridBagConstraints.RELATIVE;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.ipadx = 400;
gridBagConstraints.ipady = 200;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
topWrapper.add(panelVisualWrapper, gridBagConstraints);
panelControl.setMinimumSize(new java.awt.Dimension(600, 76));
panelControl.setPreferredSize(new java.awt.Dimension(2000, 76));
panelControl.setLayout(new java.awt.GridBagLayout());
buttonRun.setText("Start");
buttonRun.setPreferredSize(new java.awt.Dimension(70, 33));
buttonRun.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
buttonRunMouseClicked(evt);
}
});
buttonRun.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRunActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(3, 5, 1, 5);
panelControl.add(buttonRun, gridBagConstraints);
buttonStop.setText("Stop");
buttonStop.setPreferredSize(new java.awt.Dimension(70, 33));
buttonStop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonStopActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(1, 5, 1, 5);
panelControl.add(buttonStop, gridBagConstraints);
buttonScreenshot.setText("Screenshot");
buttonScreenshot.setPreferredSize(new java.awt.Dimension(90, 23));
buttonScreenshot.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
buttonScreenshotMouseClicked(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(3, 5, 1, 5);
// ### panelControl.add(buttonScreenshot, gridBagConstraints);
speedSlider.setValue(100);
speedSlider.setBorder(javax.swing.BorderFactory.createTitledBorder("Visualisation Speed"));
speedSlider.setMinimumSize(new java.awt.Dimension(150, 68));
speedSlider.setPreferredSize(new java.awt.Dimension(160, 68));
speedSlider.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
speedSliderMouseDragged(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 6;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.insets = new java.awt.Insets(0, 16, 1, 5);
panelControl.add(speedSlider, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 9;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
panelControl.add(jLabel1, gridBagConstraints);
comboX.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Dim 1", "Dim 2", "Dim 3", "Dim 4" }));
comboX.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboXActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
panelControl.add(comboX, gridBagConstraints);
labelX.setText("X");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 14, 0, 5);
panelControl.add(labelX, gridBagConstraints);
comboY.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Dim 1", "Dim 2", "Dim 3", "Dim 4" }));
comboY.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboYActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
panelControl.add(comboY, gridBagConstraints);
labelY.setText("Y");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(0, 14, 0, 5);
panelControl.add(labelY, gridBagConstraints);
checkboxDrawPoints.setSelected(true);
checkboxDrawPoints.setText("Points");
checkboxDrawPoints.setMargin(new java.awt.Insets(0, 0, 0, 0));
checkboxDrawPoints.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkboxDrawPointsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 4);
panelControl.add(checkboxDrawPoints, gridBagConstraints);
checkboxDrawGT.setSelected(true);
checkboxDrawGT.setText("Ground truth");
checkboxDrawGT.setMargin(new java.awt.Insets(0, 0, 0, 0));
checkboxDrawGT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkboxDrawGTActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
panelControl.add(checkboxDrawGT, gridBagConstraints);
checkboxDrawMicro.setSelected(true);
checkboxDrawMicro.setText("Microclustering");
checkboxDrawMicro.setMargin(new java.awt.Insets(0, 0, 0, 0));
checkboxDrawMicro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkboxDrawMicroActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 4);
panelControl.add(checkboxDrawMicro, gridBagConstraints);
checkboxDrawClustering.setSelected(true);
checkboxDrawClustering.setText("Clustering");
checkboxDrawClustering.setMargin(new java.awt.Insets(0, 0, 0, 0));
checkboxDrawClustering.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkboxDrawClusteringActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
panelControl.add(checkboxDrawClustering, gridBagConstraints);
label_processed_points.setText("Processed:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
panelControl.add(label_processed_points, gridBagConstraints);
label_processed_points_value.setText("0");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 8;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
panelControl.add(label_processed_points_value, gridBagConstraints);
labelNumPause.setText("Pause in:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
panelControl.add(labelNumPause, gridBagConstraints);
numPauseAfterPoints.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
numPauseAfterPoints.setText(Integer.toString(RunVisualizer.initialPauseInterval));
numPauseAfterPoints.setMinimumSize(new java.awt.Dimension(70, 25));
numPauseAfterPoints.setPreferredSize(new java.awt.Dimension(70, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 8;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
panelControl.add(numPauseAfterPoints, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
topWrapper.add(panelControl, gridBagConstraints);
jSplitPane1.setLeftComponent(topWrapper);
panelEvalOutput.setBorder(javax.swing.BorderFactory.createTitledBorder("Evaluation"));
panelEvalOutput.setLayout(new java.awt.GridBagLayout());
clusteringVisualEvalPanel1.setMinimumSize(new java.awt.Dimension(280, 118));
clusteringVisualEvalPanel1.setPreferredSize(new java.awt.Dimension(290, 115));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weighty = 1.0;
panelEvalOutput.add(clusteringVisualEvalPanel1, gridBagConstraints);
graphPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Plot"));
graphPanel.setPreferredSize(new java.awt.Dimension(530, 115));
graphPanel.setLayout(new java.awt.GridBagLayout());
graphPanelControlTop.setLayout(new java.awt.GridBagLayout());
buttonZoomInY.setText("Zoom in Y");
buttonZoomInY.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomInYActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
graphPanelControlTop.add(buttonZoomInY, gridBagConstraints);
buttonZoomOutY.setText("Zoom out Y");
buttonZoomOutY.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomOutYActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
graphPanelControlTop.add(buttonZoomOutY, gridBagConstraints);
labelEvents.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
graphPanelControlTop.add(labelEvents, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
graphPanel.add(graphPanelControlTop, gridBagConstraints);
graphCanvas.setPreferredSize(new java.awt.Dimension(500, 111));
javax.swing.GroupLayout graphCanvasLayout = new javax.swing.GroupLayout(graphCanvas);
graphCanvas.setLayout(graphCanvasLayout);
graphCanvasLayout.setHorizontalGroup(
graphCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 515, Short.MAX_VALUE)
);
graphCanvasLayout.setVerticalGroup(
graphCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 128, Short.MAX_VALUE)
);
graphScrollPanel.setViewportView(graphCanvas);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
graphPanel.add(graphScrollPanel, gridBagConstraints);
buttonZoomInX.setText("Zoom in X");
buttonZoomInX.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomInXActionPerformed(evt);
}
});
graphPanelControlBottom.add(buttonZoomInX);
buttonZoomOutX.setText("Zoom out X");
buttonZoomOutX.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomOutXActionPerformed(evt);
}
});
graphPanelControlBottom.add(buttonZoomOutX);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
graphPanel.add(graphPanelControlBottom, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 2.0;
gridBagConstraints.weighty = 1.0;
panelEvalOutput.add(graphPanel, gridBagConstraints);
jSplitPane1.setRightComponent(panelEvalOutput);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jSplitPane1, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void buttonScreenshotMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonScreenshotMouseClicked
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
if(screenshotFilebase!=null)
fileChooser.setSelectedFile(new File(screenshotFilebase));
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
screenshotFilebase = fileChooser.getSelectedFile().getPath();
streamPanel0.screenshot(screenshotFilebase+"_"+label_processed_points_value.getText()+"_0", true, true);
streamPanel1.screenshot(screenshotFilebase+"_"+label_processed_points_value.getText()+"_1", true, true);
}
}//GEN-LAST:event_buttonScreenshotMouseClicked
private void buttonRunMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonRunMouseClicked
toggleVisualizer(true);
}//GEN-LAST:event_buttonRunMouseClicked
private void speedSliderMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_speedSliderMouseDragged
visualizer.setSpeed((int)(speedSlider.getValue()/(100.0/15.0)));
}//GEN-LAST:event_speedSliderMouseDragged
private void scrollPane0MouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_scrollPane0MouseWheelMoved
streamPanel0.setZoom(evt.getX(),evt.getY(),(-1)*evt.getWheelRotation(),scrollPane0);
}//GEN-LAST:event_scrollPane0MouseWheelMoved
private void buttonZoomInXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomInXActionPerformed
graphCanvas.scaleXResolution(false);
}//GEN-LAST:event_buttonZoomInXActionPerformed
private void buttonZoomOutYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomOutYActionPerformed
graphCanvas.setSize(new Dimension(graphCanvas.getWidth(), (int)(graphCanvas.getHeight()*0.8)));
graphCanvas.setPreferredSize(new Dimension(graphCanvas.getWidth(), (int)(graphCanvas.getHeight()*0.8)));
}//GEN-LAST:event_buttonZoomOutYActionPerformed
private void buttonZoomOutXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomOutXActionPerformed
graphCanvas.scaleXResolution(true);
}//GEN-LAST:event_buttonZoomOutXActionPerformed
private void buttonZoomInYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomInYActionPerformed
graphCanvas.setSize(new Dimension(graphCanvas.getWidth(), (int)(graphCanvas.getHeight()*1.2)));
graphCanvas.setPreferredSize(new Dimension(graphCanvas.getWidth(), (int)(graphCanvas.getHeight()*1.2)));
}//GEN-LAST:event_buttonZoomInYActionPerformed
private void checkboxDrawPointsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkboxDrawPointsActionPerformed
visualizer.setPointLayerVisibility(checkboxDrawPoints.isSelected());
}//GEN-LAST:event_checkboxDrawPointsActionPerformed
private void checkboxDrawMicroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkboxDrawMicroActionPerformed
//visualizer.redrawClusterings();
visualizer.setMicroLayerVisibility(checkboxDrawMicro.isSelected());
}//GEN-LAST:event_checkboxDrawMicroActionPerformed
private void checkboxDrawGTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkboxDrawGTActionPerformed
//visualizer.redrawClusterings();
visualizer.setGroundTruthVisibility(checkboxDrawGT.isSelected());
}//GEN-LAST:event_checkboxDrawGTActionPerformed
private void checkboxDrawClusteringActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkboxDrawClusteringActionPerformed
//visualizer.redrawClusterings();
visualizer.setMacroVisibility(checkboxDrawClustering.isSelected());
}//GEN-LAST:event_checkboxDrawClusteringActionPerformed
private void comboXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboXActionPerformed
JComboBox cb = (JComboBox)evt.getSource();
int dim = cb.getSelectedIndex();
streamPanel0.setActiveXDim(dim);
streamPanel1.setActiveXDim(dim);
if(visualizer!=null)
visualizer.redraw();
}//GEN-LAST:event_comboXActionPerformed
private void comboYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboYActionPerformed
JComboBox cb = (JComboBox)evt.getSource();
int dim = cb.getSelectedIndex();
streamPanel0.setActiveYDim(dim);
streamPanel1.setActiveYDim(dim);
if(visualizer!=null)
visualizer.redraw();
}//GEN-LAST:event_comboYActionPerformed
private void buttonStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStopActionPerformed
stopVisualizer();
clusteringSetupTab.stopRun();
}//GEN-LAST:event_buttonStopActionPerformed
private void buttonRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRunActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_buttonRunActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonRun;
private javax.swing.JButton buttonScreenshot;
private javax.swing.JButton buttonStop;
private javax.swing.JButton buttonZoomInX;
private javax.swing.JButton buttonZoomInY;
private javax.swing.JButton buttonZoomOutX;
private javax.swing.JButton buttonZoomOutY;
private javax.swing.JCheckBox checkboxDrawClustering;
private javax.swing.JCheckBox checkboxDrawGT;
private javax.swing.JCheckBox checkboxDrawMicro;
private javax.swing.JCheckBox checkboxDrawPoints;
private moa.gui.clustertab.ClusteringVisualEvalPanel clusteringVisualEvalPanel1;
private javax.swing.JComboBox comboX;
private javax.swing.JComboBox comboY;
private moa.gui.visualization.GraphCanvas graphCanvas;
private javax.swing.JPanel graphPanel;
private javax.swing.JPanel graphPanelControlBottom;
private javax.swing.JPanel graphPanelControlTop;
private javax.swing.JScrollPane graphScrollPanel;
private javax.swing.JLabel jLabel1;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JLabel labelEvents;
private javax.swing.JLabel labelNumPause;
private javax.swing.JLabel labelX;
private javax.swing.JLabel labelY;
private javax.swing.JLabel label_processed_points;
private javax.swing.JLabel label_processed_points_value;
private javax.swing.JTextField numPauseAfterPoints;
private javax.swing.JPanel panelControl;
private javax.swing.JPanel panelEvalOutput;
private javax.swing.JPanel panelVisualWrapper;
private javax.swing.JScrollPane scrollPane0;
private javax.swing.JScrollPane scrollPane1;
private javax.swing.JSlider speedSlider;
private javax.swing.JSplitPane splitVisual;
private moa.gui.visualization.StreamPanel streamPanel0;
private moa.gui.visualization.StreamPanel streamPanel1;
private javax.swing.JPanel topWrapper;
// End of variables declaration//GEN-END:variables
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JButton){
if(e.getActionCommand().equals("csv export")){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(new FileExtensionFilter("csv"));
if(exportFile!=null)
fileChooser.setSelectedFile(new File(exportFile));
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
exportFile = fileChooser.getSelectedFile().getPath();
visualizer.exportCSV(exportFile);
}
}
if(e.getActionCommand().equals("weka export")){
visualizer.weka();
}
}
}
}
| Java |
/*
* LineGraphViewPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.table.AbstractTableModel;
import moa.evaluation.LearningCurve;
/**
* This panel displays an evaluation learning curve.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class LineGraphViewPanel extends JPanel {
private static final long serialVersionUID = 1L;
static final BasicStroke lineStroke = new BasicStroke(3.0f);
protected class PlotLine {
public LearningCurve curve;
public Color colour;
public int xAxisIndex;
public int yAxisIndex;
public double xMin;
public double xMax;
public double yMin;
public double yMax;
public float convertX(double x) {
return (float) ((x - this.xMin) / (this.xMax - this.xMin));
}
public float convertY(double y) {
return (float) ((y - this.yMin) / (this.yMax - this.yMin));
}
public Shape getShapeToPlot() {
GeneralPath path = new GeneralPath();
if (this.curve.numEntries() > 0) {
path.moveTo(convertX(this.curve.getMeasurement(0,
this.xAxisIndex)), convertY(this.curve.getMeasurement(
0, this.yAxisIndex)));
for (int i = 1; i < this.curve.numEntries(); i++) {
path.lineTo(convertX(this.curve.getMeasurement(i,
this.xAxisIndex)), convertY(this.curve.getMeasurement(i, this.yAxisIndex)));
}
}
return path;
}
}
protected class PlotPanel extends JPanel {
private static final long serialVersionUID = 1L;
@Override
public void paint(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
Graphics2D g2 = (Graphics2D) g;
g2.scale(getWidth(), getHeight());
g2.setStroke(lineStroke);
for (PlotLine plotLine : LineGraphViewPanel.this.plotLines) {
g2.setPaint(plotLine.colour);
g2.draw(plotLine.getShapeToPlot());
}
}
}
protected class PlotTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
@Override
public String getColumnName(int col) {
switch (col) {
case 0:
return "source";
case 1:
return "colour";
case 2:
return "x-axis";
case 3:
return "y-axis";
case 4:
return "x-min";
case 5:
return "x-max";
case 6:
return "y-min";
case 7:
return "y-max";
}
return null;
}
@Override
public int getColumnCount() {
return 8;
}
@Override
public int getRowCount() {
return LineGraphViewPanel.this.plotLines.size();
}
@Override
public Object getValueAt(int row, int col) {
PlotLine plotLine = LineGraphViewPanel.this.plotLines.get(row);
switch (col) {
case 0:
return plotLine.curve;
case 1:
return plotLine.colour;
case 2:
return plotLine.curve.getMeasurementName(plotLine.xAxisIndex);
case 3:
return plotLine.curve.getMeasurementName(plotLine.yAxisIndex);
case 4:
return plotLine.xMin;
case 5:
return plotLine.xMax;
case 6:
return plotLine.yMin;
case 7:
return plotLine.yMax;
}
return null;
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
protected List<PlotLine> plotLines = new ArrayList<PlotLine>();
}
| Java |
/*
* TaskLauncher.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* The old main class for the MOA gui, now the main class is <code>GUI</code>.
* Lets the user configure
* tasks, learners, streams, and perform data stream analysis.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class TaskLauncher extends JPanel {
private static final long serialVersionUID = 1L;
protected TaskManagerPanel taskManagerPanel;
protected PreviewPanel previewPanel;
public TaskLauncher() {
this.taskManagerPanel = new TaskManagerPanel();
this.previewPanel = new PreviewPanel();
this.taskManagerPanel.setPreviewPanel(this.previewPanel);
setLayout(new BorderLayout());
add(this.taskManagerPanel, BorderLayout.NORTH);
add(this.previewPanel, BorderLayout.CENTER);
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("MOA Task Launcher");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JPanel panel = new TaskLauncher();
panel.setOpaque(true); // content panes must be opaque
frame.setContentPane(panel);
// Display the window.
frame.pack();
frame.setSize(640, 480);
frame.setVisible(true);
}
public static void main(String[] args) {
try {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
/*
* ClassOptionEditComponent.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import moa.options.ClassOption;
import moa.options.Option;
/**
* An OptionEditComponent that lets the user edit a class option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class ClassOptionEditComponent extends JPanel implements
OptionEditComponent {
private static final long serialVersionUID = 1L;
protected ClassOption editedOption;
protected JTextField textField = new JTextField();
protected JButton editButton = new JButton("Edit");
/** listeners that listen to changes to the chosen option. */
protected HashSet<ChangeListener> changeListeners = new HashSet<ChangeListener>();
public ClassOptionEditComponent(ClassOption option) {
this.editedOption = option;
this.textField.setEditable(false);
this.textField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e) {
notifyChangeListeners();
}
@Override
public void insertUpdate(DocumentEvent e) {
notifyChangeListeners();
}
@Override
public void changedUpdate(DocumentEvent e) {
notifyChangeListeners();
}
});
setLayout(new BorderLayout());
add(this.textField, BorderLayout.CENTER);
add(this.editButton, BorderLayout.EAST);
this.editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
editObject();
}
});
setEditState(this.editedOption.getValueAsCLIString());
}
@Override
public void applyState() {
this.editedOption.setValueViaCLIString(this.textField.getText());
}
@Override
public Option getEditedOption() {
return this.editedOption;
}
@Override
public void setEditState(String cliString) {
this.textField.setText(cliString);
}
public void editObject() {
setEditState(ClassOptionSelectionPanel.showSelectClassDialog(this,
"Editing option: " + this.editedOption.getName(),
this.editedOption.getRequiredType(), this.textField.getText(),
this.editedOption.getNullString()));
}
/**
* Adds the listener to the internal set of listeners. Gets notified when
* the option string changes.
*
* @param l the listener to add
*/
public void addChangeListener(ChangeListener l) {
changeListeners.add(l);
}
/**
* Removes the listener from the internal set of listeners.
*
* @param l the listener to remove
*/
public void removeChangeListener(ChangeListener l) {
changeListeners.remove(l);
}
/**
* Notifies all registered change listeners that the options have changed.
*/
protected void notifyChangeListeners() {
ChangeEvent e = new ChangeEvent(this);
for (ChangeListener l : changeListeners) {
l.stateChanged(e);
}
}
}
| Java |
/*
* TextViewerPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
* This panel displays text. Used to output the results of tasks.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class TextViewerPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static String exportFileExtension = "txt";
protected JTextArea textArea;
protected JScrollPane scrollPane;
protected JButton exportButton;
public TextViewerPanel() {
this.textArea = new JTextArea();
this.textArea.setEditable(false);
this.textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
this.exportButton = new JButton("Export as .txt file...");
this.exportButton.setEnabled(false);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 2));
buttonPanel.add(this.exportButton);
setLayout(new BorderLayout());
this.scrollPane = new JScrollPane(this.textArea);
add(this.scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
this.exportButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(new FileExtensionFilter(
exportFileExtension));
if (fileChooser.showSaveDialog(TextViewerPanel.this) == JFileChooser.APPROVE_OPTION) {
File chosenFile = fileChooser.getSelectedFile();
String fileName = chosenFile.getPath();
if (!chosenFile.exists()
&& !fileName.endsWith(exportFileExtension)) {
fileName = fileName + "." + exportFileExtension;
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(fileName)));
out.write(TextViewerPanel.this.textArea.getText());
out.close();
} catch (IOException ioe) {
GUIUtils.showExceptionDialog(
TextViewerPanel.this.exportButton,
"Problem saving file " + fileName, ioe);
}
}
}
});
}
public void setText(String newText) {
Point p = this.scrollPane.getViewport().getViewPosition();
this.textArea.setText(newText);
this.scrollPane.getViewport().setViewPosition(p);
this.exportButton.setEnabled(newText != null);
}
public void addText(String newText) {
String text = textArea.getText();
text += (!text.isEmpty()) ? "\n" : "";
text += newText;
setText(text);
}
}
| Java |
/*
* RegressionTabPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import moa.gui.PreviewPanel.TypePanel;
/**
* This panel allows the user to select and configure a task, and run it.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class RegressionTabPanel extends AbstractTabPanel {
private static final long serialVersionUID = 1L;
protected RegressionTaskManagerPanel taskManagerPanel;
protected PreviewPanel previewPanel;
public RegressionTabPanel() {
this.taskManagerPanel = new RegressionTaskManagerPanel();
this.previewPanel = new PreviewPanel(TypePanel.REGRESSION);
this.taskManagerPanel.setPreviewPanel(this.previewPanel);
setLayout(new BorderLayout());
add(this.taskManagerPanel, BorderLayout.NORTH);
add(this.previewPanel, BorderLayout.CENTER);
}
//returns the string to display as title of the tab
@Override
public String getTabTitle() {
return "Regression";
}
//a short description (can be used as tool tip) of the tab, or contributor, etc.
@Override
public String getDescription(){
return "MOA Regression";
}
}
| Java |
/*
* OptionsConfigurationPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import moa.classifiers.trees.HoeffdingTree;
import moa.options.Option;
import moa.options.OptionHandler;
import moa.options.Options;
/**
* This panel displays an options configuration.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class OptionsConfigurationPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static final int FIXED_PANEL_WIDTH = 400;
public static final int MAX_PANEL_HEIGHT = 300;
protected Options options;
protected List<OptionEditComponent> editComponents = new LinkedList<OptionEditComponent>();
protected JButton helpButton = new JButton("Help");
protected JButton resetButton = new JButton("Reset to defaults");
public OptionsConfigurationPanel(String purposeString, Options options) {
this.options = options;
setLayout(new BorderLayout());
if (purposeString != null) {
JTextArea purposeTextArea = new JTextArea(purposeString, 3, 0);
purposeTextArea.setEditable(false);
purposeTextArea.setLineWrap(true);
purposeTextArea.setWrapStyleWord(true);
purposeTextArea.setEnabled(false);
purposeTextArea.setBorder(BorderFactory.createTitledBorder("Purpose"));
purposeTextArea.setBackground(getBackground());
JScrollPane scrollPanePurpose = new JScrollPane(purposeTextArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPanePurpose.setBorder(null);
add(scrollPanePurpose, BorderLayout.NORTH);
}
JPanel optionsPanel = createLabelledOptionComponentListPanel(options.getOptionArray(), this.editComponents);
JScrollPane scrollPane = new JScrollPane(optionsPanel,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(null);
int optionPanelHeight = (int) optionsPanel.getPreferredSize().getHeight();
int scrollPaneHeight = (int) scrollPane.getPreferredSize().getHeight();
scrollPane.setPreferredSize(new Dimension(FIXED_PANEL_WIDTH,
scrollPaneHeight > MAX_PANEL_HEIGHT ? MAX_PANEL_HEIGHT
: scrollPaneHeight));
optionsPanel.setPreferredSize(new Dimension(0, optionPanelHeight));
add(scrollPane, BorderLayout.CENTER);
JPanel lowerButtons = new JPanel();
lowerButtons.setLayout(new FlowLayout());
lowerButtons.add(this.helpButton);
lowerButtons.add(this.resetButton);
add(lowerButtons, BorderLayout.SOUTH);
this.helpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
showHelpDialog();
}
});
this.resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
resetToDefaults();
}
});
}
public static boolean showEditOptionsDialog(Component parent, String title,
OptionHandler optionHandler) {
OptionsConfigurationPanel panel = new OptionsConfigurationPanel(
optionHandler.getPurposeString(), optionHandler.getOptions());
if (JOptionPane.showOptionDialog(parent, panel, title,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null,
null, null) == JOptionPane.OK_OPTION) {
panel.applyChanges();
return true;
}
return false;
}
public String getHelpText() {
return this.options.getHelpString();
}
public void showHelpDialog() {
JTextArea helpTextArea = new JTextArea(getHelpText(), 20, 80);
helpTextArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
helpTextArea.setEditable(false);
JOptionPane.showMessageDialog(this, new JScrollPane(helpTextArea),
"Options Help", JOptionPane.INFORMATION_MESSAGE);
}
public void resetToDefaults() {
for (OptionEditComponent editor : this.editComponents) {
editor.setEditState(editor.getEditedOption().getDefaultCLIString());
}
}
public void applyChanges() {
for (OptionEditComponent editor : this.editComponents) {
try {
editor.applyState();
} catch (Exception ex) {
GUIUtils.showExceptionDialog(this, "Problem with option "
+ editor.getEditedOption().getName(), ex);
}
}
}
protected static JPanel createLabelledOptionComponentListPanel(
Option[] options, List<OptionEditComponent> editComponents) {
JPanel panel = new JPanel();
if ((options != null) && (options.length > 0)) {
GridBagLayout gbLayout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
panel.setLayout(gbLayout);
for (int i = 0; i < options.length; i++) {
JLabel label = new JLabel(options[i].getName());
label.setToolTipText(options[i].getPurpose());
gbc.gridx = 0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
gbc.weightx = 0;
gbc.insets = new Insets(5, 5, 5, 5);
gbLayout.setConstraints(label, gbc);
panel.add(label);
JComponent editor = options[i].getEditComponent();
label.setLabelFor(editor);
if (editComponents != null) {
editComponents.add((OptionEditComponent) editor);
}
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 1;
gbc.insets = new Insets(5, 5, 5, 5);
gbLayout.setConstraints(editor, gbc);
panel.add(editor);
}
} else {
panel.add(new JLabel("No options."));
}
return panel;
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
Options options = new HoeffdingTree().getOptions();
JPanel panel = new OptionsConfigurationPanel(null, options);
// createLabelledOptionComponentListPanel(options
// .getOptionArray(), null);
panel.setOpaque(true); // content panes must be opaque
frame.setContentPane(panel);
// Display the window.
frame.pack();
// frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
/*
* AWTRenderable.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
/**
* Interface representing a component that is renderable
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public interface AWTRenderable {
public AWTRenderer getAWTRenderer();
}
| Java |
/*
* PreviewPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import moa.core.StringUtils;
import moa.evaluation.Accuracy;
import moa.evaluation.ChangeDetectionMeasures;
import moa.evaluation.MeasureCollection;
import moa.evaluation.RegressionAccuracy;
import moa.gui.conceptdrift.CDTaskManagerPanel;
import moa.tasks.ResultPreviewListener;
import moa.tasks.TaskThread;
/**
* This panel displays the running task preview text and buttons.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class PreviewPanel extends JPanel implements ResultPreviewListener {
private static final long serialVersionUID = 1L;
public static final String[] autoFreqStrings = {"never", "every second",
"every 5 seconds", "every 10 seconds", "every 30 seconds",
"every minute"};
public static final int[] autoFreqTimeSecs = {0, 1, 5, 10, 30, 60};
protected TaskThread previewedThread;
protected JLabel previewLabel = new JLabel("No preview available");
protected JButton refreshButton = new JButton("Refresh");
protected JLabel autoRefreshLabel = new JLabel("Auto refresh: ");
protected JComboBox autoRefreshComboBox = new JComboBox(autoFreqStrings);
protected TaskTextViewerPanel textViewerPanel; // = new TaskTextViewerPanel();
protected javax.swing.Timer autoRefreshTimer;
public enum TypePanel {
CLASSIFICATION(new Accuracy()),
REGRESSION(new RegressionAccuracy()),
CONCEPT_DRIFT(new ChangeDetectionMeasures());
private final MeasureCollection measureCollection;
//Constructor
TypePanel(MeasureCollection measureCollection){
this.measureCollection = measureCollection;
}
public MeasureCollection getMeasureCollection(){
return (MeasureCollection) this.measureCollection.copy();
}
}
public PreviewPanel() {
this(TypePanel.CLASSIFICATION, null);
}
public PreviewPanel(TypePanel typePanel) {
this(typePanel, null);
}
public PreviewPanel(TypePanel typePanel, CDTaskManagerPanel taskManagerPanel) {
this.textViewerPanel = new TaskTextViewerPanel(typePanel,taskManagerPanel);
this.autoRefreshComboBox.setSelectedIndex(1); // default to 1 sec
JPanel controlPanel = new JPanel();
controlPanel.add(this.previewLabel);
controlPanel.add(this.refreshButton);
controlPanel.add(this.autoRefreshLabel);
controlPanel.add(this.autoRefreshComboBox);
setLayout(new BorderLayout());
add(controlPanel, BorderLayout.NORTH);
add(this.textViewerPanel, BorderLayout.CENTER);
this.refreshButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
refresh();
}
});
this.autoRefreshTimer = new javax.swing.Timer(1000,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
refresh();
}
});
this.autoRefreshComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
updateAutoRefreshTimer();
}
});
setTaskThreadToPreview(null);
}
public void refresh() {
if (this.previewedThread != null) {
if (this.previewedThread.isComplete()) {
setLatestPreview(null);
disableRefresh();
} else {
this.previewedThread.getPreview(PreviewPanel.this);
}
}
}
public void setTaskThreadToPreview(TaskThread thread) {
this.previewedThread = thread;
setLatestPreview(thread != null ? thread.getLatestResultPreview()
: null);
if (thread == null) {
disableRefresh();
} else if (!thread.isComplete()) {
enableRefresh();
}
}
public void setLatestPreview(Object preview) {
if ((this.previewedThread != null) && this.previewedThread.isComplete()) {
this.previewLabel.setText("Final result");
Object finalResult = this.previewedThread.getFinalResult();
this.textViewerPanel.setText(finalResult != null ? finalResult.toString() : null);
disableRefresh();
} else {
double grabTime = this.previewedThread != null ? this.previewedThread.getLatestPreviewGrabTimeSeconds()
: 0.0;
String grabString = grabTime > 0.0 ? (" ("
+ StringUtils.secondsToDHMSString(grabTime) + ")") : "";
this.textViewerPanel.setText(preview != null ? preview.toString()
: null);
if (preview == null) {
this.previewLabel.setText("No preview available" + grabString);
} else {
this.previewLabel.setText("Preview" + grabString);
}
}
}
public void updateAutoRefreshTimer() {
int autoDelay = autoFreqTimeSecs[this.autoRefreshComboBox.getSelectedIndex()];
if (autoDelay > 0) {
if (this.autoRefreshTimer.isRunning()) {
this.autoRefreshTimer.stop();
}
this.autoRefreshTimer.setDelay(autoDelay * 1000);
this.autoRefreshTimer.start();
} else {
this.autoRefreshTimer.stop();
}
}
public void disableRefresh() {
this.refreshButton.setEnabled(false);
this.autoRefreshLabel.setEnabled(false);
this.autoRefreshComboBox.setEnabled(false);
this.autoRefreshTimer.stop();
}
public void enableRefresh() {
this.refreshButton.setEnabled(true);
this.autoRefreshLabel.setEnabled(true);
this.autoRefreshComboBox.setEnabled(true);
updateAutoRefreshTimer();
}
@Override
public void latestPreviewChanged() {
setTaskThreadToPreview(this.previewedThread);
}
}
| Java |
/*
* FileOptionEditComponent.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;
import moa.options.FileOption;
import moa.options.Option;
/**
* An OptionEditComponent that lets the user edit a file option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class FileOptionEditComponent extends JPanel implements
OptionEditComponent {
private static final long serialVersionUID = 1L;
protected FileOption editedOption;
protected JTextField textField = new JTextField();
protected JButton browseButton = new JButton("Browse");
public FileOptionEditComponent(FileOption option) {
this.editedOption = option;
setLayout(new BorderLayout());
add(this.textField, BorderLayout.CENTER);
add(this.browseButton, BorderLayout.EAST);
this.browseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
browseForFile();
}
});
setEditState(this.editedOption.getValueAsCLIString());
}
@Override
public void applyState() {
this.editedOption.setValueViaCLIString(this.textField.getText().length() > 0 ? this.textField.getText() : null);
}
@Override
public Option getEditedOption() {
return this.editedOption;
}
@Override
public void setEditState(String cliString) {
this.textField.setText(cliString);
}
public void browseForFile() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
String extension = this.editedOption.getDefaultFileExtension();
if (extension != null) {
fileChooser.addChoosableFileFilter(new FileExtensionFilter(
extension));
}
fileChooser.setSelectedFile(new File(this.textField.getText()));
if (this.editedOption.isOutputFile()) {
if (fileChooser.showSaveDialog(this.browseButton) == JFileChooser.APPROVE_OPTION) {
File chosenFile = fileChooser.getSelectedFile();
String fileName = chosenFile.getPath();
if (!chosenFile.exists()) {
if ((extension != null) && !fileName.endsWith(extension)) {
fileName = fileName + "." + extension;
}
}
this.textField.setText(fileName);
}
} else {
if (fileChooser.showOpenDialog(this.browseButton) == JFileChooser.APPROVE_OPTION) {
this.textField.setText(fileChooser.getSelectedFile().getPath());
}
}
}
}
| Java |
/*
* WEKAClassOptionEditComponent.java
* Copyright (C) 2009 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import weka.core.Utils;
import weka.gui.GenericObjectEditor;
import weka.gui.PropertyDialog;
import weka.gui.GenericObjectEditor.GOEPanel;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import moa.options.Option;
import moa.options.WEKAClassOption;
/**
* An OptionEditComponent that lets the user edit a WEKA class option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class WEKAClassOptionEditComponent
extends JPanel
implements OptionEditComponent {
private static final long serialVersionUID = 1L;
protected WEKAClassOption editedOption;
protected JTextField textField = new JTextField();
protected JButton editButton = new JButton("Edit");
public WEKAClassOptionEditComponent(WEKAClassOption option) {
this.editedOption = option;
this.textField.setEditable(false);
setLayout(new BorderLayout());
add(this.textField, BorderLayout.CENTER);
add(this.editButton, BorderLayout.EAST);
this.editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
editObject();
}
});
setEditState(this.editedOption.getValueAsCLIString());
}
@Override
public void applyState() {
this.editedOption.setValueViaCLIString(this.textField.getText());
}
@Override
public Option getEditedOption() {
return this.editedOption;
}
@Override
public void setEditState(String cliString) {
this.textField.setText(cliString);
}
public void editObject() {
final GenericObjectEditor goe = new GenericObjectEditor(true);
goe.setClassType(editedOption.getRequiredType());
try {
String[] options = Utils.splitOptions(editedOption.getValueAsCLIString());
String classname = options[0];
options[0] = "";
Object obj = Class.forName(classname).newInstance();
if (obj instanceof weka.core.OptionHandler) {
((weka.core.OptionHandler) obj).setOptions(options);
}
goe.setValue(obj);
((GOEPanel) goe.getCustomEditor()).addOkListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object obj = goe.getValue();
String s = obj.getClass().getName();
if (obj instanceof weka.core.OptionHandler) {
s += " " + Utils.joinOptions(((weka.core.OptionHandler) obj).getOptions());
}
setEditState(s.trim());
}
});
PropertyDialog dialog;
if (PropertyDialog.getParentDialog(this) != null) {
dialog = new PropertyDialog(PropertyDialog.getParentDialog(this), goe);
} else {
dialog = new PropertyDialog(PropertyDialog.getParentFrame(this), goe);
}
dialog.setModal(true);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
/*
* AWTRenderer.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.Graphics;
/**
* Interface representing a component to edit an option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public interface AWTRenderer {
public void renderAWTBox(Graphics g, int minPixelX, int minPixelY,
int maxPixelX, int maxPixelY);
}
| Java |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* GUIDefaults.java
* Copyright (C) 2006 University of Waikato, Hamilton, New Zealand
*/
package moa.gui;
import moa.core.PropertiesReader;
import weka.core.Utils;
import java.io.Serializable;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
/**
* This class offers get methods for the default GUI settings in
* the props file <code>moa/gui/GUI.props</code>.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision: 6103 $
*/
public class GUIDefaults
implements Serializable {
/** for serialization. */
private static final long serialVersionUID = 4954795757927524225L;
/** The name of the properties file. */
public final static String PROPERTY_FILE = "moa/gui/GUI.props";
/** Properties associated with the GUI options. */
protected static Properties PROPERTIES;
static {
try {
PROPERTIES = PropertiesReader.readProperties(PROPERTY_FILE);
} catch (Exception e) {
System.err.println("Problem reading properties. Fix before continuing.");
e.printStackTrace();
PROPERTIES = new Properties();
}
}
/**
* returns the value for the specified property, if non-existent then the
* default value.
*
* @param property the property to retrieve the value for
* @param defaultValue the default value for the property
* @return the value of the specified property
*/
public static String get(String property, String defaultValue) {
return PROPERTIES.getProperty(property, defaultValue);
}
/**
* returns the associated properties file.
*
* @return the props file
*/
public final static Properties getProperties() {
return PROPERTIES;
}
/**
* Tries to instantiate the class stored for this property, optional
* options will be set as well. Returns null if unsuccessful.
*
* @param property the property to get the object for
* @param defaultValue the default object spec string
* @return if successful the fully configured object, null
* otherwise
*/
protected static Object getObject(String property, String defaultValue) {
return getObject(property, defaultValue, Object.class);
}
/**
* Tries to instantiate the class stored for this property, optional
* options will be set as well. Returns null if unsuccessful.
*
* @param property the property to get the object for
* @param defaultValue the default object spec string
* @param cls the class the object must be derived from
* @return if successful the fully configured object, null
* otherwise
*/
protected static Object getObject(String property, String defaultValue, Class cls) {
Object result;
String tmpStr;
String[] tmpOptions;
result = null;
try {
tmpStr = get(property, defaultValue);
tmpOptions = Utils.splitOptions(tmpStr);
if (tmpOptions.length != 0) {
tmpStr = tmpOptions[0];
tmpOptions[0] = "";
result = Utils.forName(cls, tmpStr, tmpOptions);
}
} catch (Exception e) {
e.printStackTrace();
result = null;
}
return result;
}
/**
* returns an array with the classnames of all the additional panels to
* display as tabs in the GUI.
*
* @return the classnames
*/
public static String[] getTabs() {
String[] result;
String tabs;
// read and split on comma
tabs = get("Tabs", "moa.gui.ClassificationTabPanel,moa.gui.RegressionTabPanel,moa.gui.clustertab.ClusteringTabPanel,moa.gui.outliertab.OutlierTabPanel,moa.gui.ConceptDriftTabPanel");
result = tabs.split(",");
return result;
}
/**
* Returns the initial directory for the file chooser used for opening
* datasets.
* <p/>
* The following placeholders are recognized:
* <pre>
* %t - the temp directory
* %h - the user's home directory
* %c - the current directory
* %% - gets replaced by a single percentage sign
* </pre>
*
* @return the default directory
*/
public static String getInitialDirectory() {
String result;
result = get("InitialDirectory", "%c");
result = result.replaceAll("%t", System.getProperty("java.io.tmpdir"));
result = result.replaceAll("%h", System.getProperty("user.home"));
result = result.replaceAll("%c", System.getProperty("user.dir"));
result = result.replaceAll("%%", System.getProperty("%"));
return result;
}
/**
* only for testing - prints the content of the props file.
*
* @param args commandline parameters - ignored
*/
public static void main(String[] args) {
Enumeration names;
String name;
Vector sorted;
System.out.println("\nMOA defaults:");
names = PROPERTIES.propertyNames();
// sort names
sorted = new Vector();
while (names.hasMoreElements()) {
sorted.add(names.nextElement());
}
Collections.sort(sorted);
names = sorted.elements();
// output
while (names.hasMoreElements()) {
name = names.nextElement().toString();
System.out.println("- " + name + ": " + PROPERTIES.getProperty(name, ""));
}
System.out.println();
}
}
| Java |
/*
* AWTInteractiveRenderer.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
// not used?
public interface AWTInteractiveRenderer extends AWTRenderer {
public void mouseClicked(int pixelX, int pixelY);
}
| Java |
/*
* ClassificationTabPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
/**
* This panel allows the user to select and configure a task, and run it.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class ClassificationTabPanel extends AbstractTabPanel {
private static final long serialVersionUID = 1L;
protected TaskManagerPanel taskManagerPanel;
protected PreviewPanel previewPanel;
public ClassificationTabPanel() {
this.taskManagerPanel = new TaskManagerPanel();
this.previewPanel = new PreviewPanel();
this.taskManagerPanel.setPreviewPanel(this.previewPanel);
setLayout(new BorderLayout());
add(this.taskManagerPanel, BorderLayout.NORTH);
add(this.previewPanel, BorderLayout.CENTER);
}
//returns the string to display as title of the tab
@Override
public String getTabTitle() {
return "Classification";
}
//a short description (can be used as tool tip) of the tab, or contributor, etc.
@Override
public String getDescription(){
return "MOA Classification";
}
}
| Java |
/*
* IntOptionEditComponent.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import moa.options.IntOption;
import moa.options.Option;
/**
* An OptionEditComponent that lets the user edit an integer option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class IntOptionEditComponent extends JPanel implements
OptionEditComponent {
private static final long serialVersionUID = 1L;
protected IntOption editedOption;
protected JSpinner spinner;
protected JSlider slider;
public IntOptionEditComponent(IntOption option) {
this.editedOption = option;
int minVal = option.getMinValue();
int maxVal = option.getMaxValue();
setLayout(new GridLayout(1, 0));
this.spinner = new JSpinner(new SpinnerNumberModel(option.getValue(),
minVal, maxVal, 1));
add(this.spinner);
if ((minVal > Integer.MIN_VALUE) && (maxVal < Integer.MAX_VALUE)) {
this.slider = new JSlider(minVal, maxVal, option.getValue());
add(this.slider);
this.slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
IntOptionEditComponent.this.spinner.setValue(IntOptionEditComponent.this.slider.getValue());
}
});
this.spinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
IntOptionEditComponent.this.slider.setValue(((Integer) IntOptionEditComponent.this.spinner.getValue()).intValue());
}
});
}
}
@Override
public void applyState() {
this.editedOption.setValue(((Integer) this.spinner.getValue()).intValue());
}
@Override
public Option getEditedOption() {
return this.editedOption;
}
@Override
public void setEditState(String cliString) {
this.spinner.setValue(IntOption.cliStringToInt(cliString));
}
}
| Java |
/*
* CDTaskManagerPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author Manuel Martín (msalvador@bournemouth.ac.uk)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui.conceptdrift;
import moa.gui.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import moa.core.StringUtils;
import moa.options.ClassOption;
import moa.options.OptionHandler;
import moa.tasks.ConceptDriftMainTask;
import moa.tasks.EvaluateConceptDrift;
import moa.tasks.Task;
import moa.tasks.TaskThread;
/**
* This panel displays the running tasks.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class CDTaskManagerPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static final int MILLISECS_BETWEEN_REFRESH = 600;
public static String exportFileExtension = "log";
public class ProgressCellRenderer extends JProgressBar implements
TableCellRenderer {
private static final long serialVersionUID = 1L;
public ProgressCellRenderer() {
super(SwingConstants.HORIZONTAL, 0, 10000);
setBorderPainted(false);
setStringPainted(true);
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
double frac = -1.0;
if (value instanceof Double) {
frac = ((Double) value).doubleValue();
}
if (frac >= 0.0) {
setIndeterminate(false);
setValue((int) (frac * 10000.0));
setString(StringUtils.doubleToString(frac * 100.0, 2, 2));
} else {
setValue(0);
//setIndeterminate(true);
//setString("?");
}
return this;
}
@Override
public void validate() {
}
@Override
public void revalidate() {
}
@Override
protected void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
}
@Override
public void firePropertyChange(String propertyName, boolean oldValue,
boolean newValue) {
}
}
public class TaskTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
@Override
public String getColumnName(int col) {
switch (col) {
case 0:
return "command";
case 1:
return "status";
case 2:
return "time elapsed";
case 3:
return "current activity";
case 4:
return "% complete";
}
return null;
}
@Override
public int getColumnCount() {
return 5;
}
@Override
public int getRowCount() {
return CDTaskManagerPanel.this.taskList.size();
}
@Override
public Object getValueAt(int row, int col) {
TaskThread thread = CDTaskManagerPanel.this.taskList.get(row);
switch (col) {
case 0:
return ((OptionHandler) thread.getTask()).getCLICreationString(ConceptDriftMainTask.class);
case 1:
return thread.getCurrentStatusString();
case 2:
return StringUtils.secondsToDHMSString(thread.getCPUSecondsElapsed());
case 3:
return thread.getCurrentActivityString();
case 4:
return new Double(thread.getCurrentActivityFracComplete());
}
return null;
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
protected ConceptDriftMainTask currentTask = new EvaluateConceptDrift();//LearnModel();
protected List<TaskThread> taskList = new ArrayList<TaskThread>();
protected JButton configureTaskButton = new JButton("Configure");
protected JTextField taskDescField = new JTextField();
protected JButton runTaskButton = new JButton("Run");
protected TaskTableModel taskTableModel;
protected JTable taskTable;
protected JButton pauseTaskButton = new JButton("Pause");
protected JButton resumeTaskButton = new JButton("Resume");
protected JButton cancelTaskButton = new JButton("Cancel");
protected JButton deleteTaskButton = new JButton("Delete");
protected PreviewPanel previewPanel;
private Preferences prefs;
private final String PREF_NAME = "currentTask";
public CDTaskManagerPanel() {
// Read current task preference
prefs = Preferences.userRoot().node(this.getClass().getName());
currentTask = new EvaluateConceptDrift();
String taskText = this.currentTask.getCLICreationString(ConceptDriftMainTask.class);
String propertyValue = prefs.get(PREF_NAME, taskText);
//this.taskDescField.setText(propertyValue);
setTaskString(propertyValue, false); //Not store preference
this.taskDescField.setEditable(false);
final Component comp = this.taskDescField;
this.taskDescField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 1) {
if ((evt.getButton() == MouseEvent.BUTTON3)
|| ((evt.getButton() == MouseEvent.BUTTON1) && evt.isAltDown() && evt.isShiftDown())) {
JPopupMenu menu = new JPopupMenu();
JMenuItem item;
item = new JMenuItem("Copy configuration to clipboard");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyClipBoardConfiguration();
}
});
menu.add(item);
item = new JMenuItem("Save selected tasks to file");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
saveLogSelectedTasks();
}
});
menu.add(item);
item = new JMenuItem("Enter configuration...");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String newTaskString = JOptionPane.showInputDialog("Insert command line");
if (newTaskString != null) {
setTaskString(newTaskString);
}
}
});
menu.add(item);
menu.show(comp, evt.getX(), evt.getY());
}
}
}
});
JPanel configPanel = new JPanel();
configPanel.setLayout(new BorderLayout());
configPanel.add(this.configureTaskButton, BorderLayout.WEST);
configPanel.add(this.taskDescField, BorderLayout.CENTER);
configPanel.add(this.runTaskButton, BorderLayout.EAST);
this.taskTableModel = new TaskTableModel();
this.taskTable = new JTable(this.taskTableModel);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
this.taskTable.getColumnModel().getColumn(1).setCellRenderer(
centerRenderer);
this.taskTable.getColumnModel().getColumn(2).setCellRenderer(
centerRenderer);
this.taskTable.getColumnModel().getColumn(4).setCellRenderer(
new ProgressCellRenderer());
JPanel controlPanel = new JPanel();
controlPanel.add(this.pauseTaskButton);
controlPanel.add(this.resumeTaskButton);
controlPanel.add(this.cancelTaskButton);
controlPanel.add(this.deleteTaskButton);
setLayout(new BorderLayout());
add(configPanel, BorderLayout.NORTH);
add(new JScrollPane(this.taskTable), BorderLayout.CENTER);
add(controlPanel, BorderLayout.SOUTH);
this.taskTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
taskSelectionChanged();
}
});
this.configureTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String newTaskString = ClassOptionSelectionPanel.showSelectClassDialog(CDTaskManagerPanel.this,
"Configure task", ConceptDriftMainTask.class,
CDTaskManagerPanel.this.currentTask.getCLICreationString(ConceptDriftMainTask.class),
null);
setTaskString(newTaskString);
}
});
this.runTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
runTask((Task) CDTaskManagerPanel.this.currentTask.copy());
}
});
this.pauseTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
pauseSelectedTasks();
}
});
this.resumeTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
resumeSelectedTasks();
}
});
this.cancelTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
cancelSelectedTasks();
}
});
this.deleteTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
deleteSelectedTasks();
}
});
javax.swing.Timer updateListTimer = new javax.swing.Timer(
MILLISECS_BETWEEN_REFRESH, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CDTaskManagerPanel.this.taskTable.repaint();
}
});
updateListTimer.start();
setPreferredSize(new Dimension(0, 200));
}
public void setPreviewPanel(PreviewPanel previewPanel) {
this.previewPanel = previewPanel;
}
public void setTaskString(String cliString) {
setTaskString(cliString, true);
}
public void setTaskString(String cliString, boolean storePreference) {
try {
this.currentTask = (ConceptDriftMainTask) ClassOption.cliStringToObject(
cliString, ConceptDriftMainTask.class, null);
String taskText = this.currentTask.getCLICreationString(ConceptDriftMainTask.class);
this.taskDescField.setText(taskText);
if (storePreference == true){
//Save task text as a preference
prefs.put(PREF_NAME, taskText);
}
} catch (Exception ex) {
GUIUtils.showExceptionDialog(this, "Problem with task", ex);
}
}
public void runTask(Task task) {
TaskThread thread = new TaskThread(task);
this.taskList.add(0, thread);
this.taskTableModel.fireTableDataChanged();
this.taskTable.setRowSelectionInterval(0, 0);
thread.start();
}
public void taskSelectionChanged() {
TaskThread[] selectedTasks = getSelectedTasks();
if (selectedTasks.length == 1) {
setTaskString(((OptionHandler) selectedTasks[0].getTask()).getCLICreationString(ConceptDriftMainTask.class));
if (this.previewPanel != null) {
this.previewPanel.setTaskThreadToPreview(selectedTasks[0]);
}
} else {
this.previewPanel.setTaskThreadToPreview(null);
}
}
public TaskThread[] getSelectedTasks() {
int[] selectedRows = this.taskTable.getSelectedRows();
TaskThread[] selectedTasks = new TaskThread[selectedRows.length];
for (int i = 0; i < selectedRows.length; i++) {
selectedTasks[i] = this.taskList.get(selectedRows[i]);
}
return selectedTasks;
}
public void pauseSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.pauseTask();
}
}
public void resumeSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.resumeTask();
}
}
public void cancelSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.cancelTask();
}
}
public void deleteSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.cancelTask();
this.taskList.remove(thread);
}
this.taskTableModel.fireTableDataChanged();
}
public void copyClipBoardConfiguration() {
StringSelection selection = new StringSelection(this.taskDescField.getText().trim());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
}
public void saveLogSelectedTasks() {
String tasksLog = "";
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
tasksLog += ((OptionHandler) thread.getTask()).getCLICreationString(ConceptDriftMainTask.class) + "\n";
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(new FileExtensionFilter(
exportFileExtension));
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File chosenFile = fileChooser.getSelectedFile();
String fileName = chosenFile.getPath();
if (!chosenFile.exists()
&& !fileName.endsWith(exportFileExtension)) {
fileName = fileName + "." + exportFileExtension;
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(fileName)));
out.write(tasksLog);
out.close();
} catch (IOException ioe) {
GUIUtils.showExceptionDialog(
this,
"Problem saving file " + fileName, ioe);
}
}
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JPanel panel = new CDTaskManagerPanel();
panel.setOpaque(true); // content panes must be opaque
frame.setContentPane(panel);
// Display the window.
frame.pack();
// frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
//Added for stream events
public ConceptDriftMainTask getCurrenTask() {
return (ConceptDriftMainTask) this.currentTask; //this.getSelectedTasks()[0].getTask();//this.currentTask;
}
//Added for stream events
public ConceptDriftMainTask getSelectedCurrenTask() {
if (this.getSelectedTasks().length > 0) {
return (ConceptDriftMainTask) this.getSelectedTasks()[0].getTask();//this.currentTask;
}
else {
return getCurrenTask();
}
}
}
| Java |
/*
* GUIUtils.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import moa.core.MiscUtils;
/**
* This class offers util methods for displaying dialogs showing errors or exceptions.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class GUIUtils {
public static void showErrorDialog(Component parent, String title,
String message) {
JTextArea messagePanel = new JTextArea(message);
JScrollPane messageScroll = new JScrollPane(messagePanel);
messageScroll.setPreferredSize(new Dimension(400, 100));
JOptionPane.showMessageDialog(parent, messageScroll, title,
JOptionPane.ERROR_MESSAGE);
}
public static void showExceptionDialog(Component parent, String title,
Exception ex) {
showErrorDialog(parent, title, ex.getMessage() + "\n\n"
+ MiscUtils.getStackTraceString(ex));
}
}
| Java |
/*
* GUI.java
* Copyright (C) 2010 University of Waikato, Hamilton, New Zealand
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import moa.DoTask;
/**
* The main class for the MOA gui. Lets the user configure
* tasks, learners, streams, and perform data stream analysis.
*
* @author Albert Bifet (abifet at cs dot waikato dot ac dot nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision: 7 $
*/
public class GUI extends JPanel {
private static final long serialVersionUID = 1L;
private javax.swing.JTabbedPane panel;
public GUI() {
initGUI();
}
private void initGUI() {
setLayout(new BorderLayout());
// Create and set up tabs
panel = new javax.swing.JTabbedPane();
add(panel, BorderLayout.CENTER);
// initialize additional panels
String[] tabs = GUIDefaults.getTabs();
for (int i = 0; i < tabs.length; i++) {
try {
// determine classname
String[] optionsStr = tabs[i].split(":");
String classname = optionsStr[0];
// setup panel
AbstractTabPanel tabPanel = (AbstractTabPanel) Class.forName(classname).newInstance();
panel.addTab(tabPanel.getTabTitle(), null, (JPanel) tabPanel, tabPanel.getDescription());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
if (DoTask.isJavaVersionOK() == false || DoTask.isWekaVersionOK() == false) {
return;
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Create and set up the window.
JFrame frame = new JFrame("MOA Graphical User Interface");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
try {
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception ex) {
}
}
GUI gui = new GUI();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(gui);
// Display the window.
frame.pack();
frame.setVisible(true);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
/*
* ConceptDriftTabPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import moa.gui.PreviewPanel.TypePanel;
import moa.gui.conceptdrift.CDTaskManagerPanel;
/**
* This panel allows the user to select and configure a task, and run it.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class ConceptDriftTabPanel extends AbstractTabPanel {
private static final long serialVersionUID = 1L;
protected CDTaskManagerPanel taskManagerPanel;
protected PreviewPanel previewPanel;
public ConceptDriftTabPanel() {
this.taskManagerPanel = new CDTaskManagerPanel();
this.previewPanel = new PreviewPanel(TypePanel.CONCEPT_DRIFT, this.taskManagerPanel);
this.taskManagerPanel.setPreviewPanel(this.previewPanel);
setLayout(new BorderLayout());
add(this.taskManagerPanel, BorderLayout.NORTH);
add(this.previewPanel, BorderLayout.CENTER);
}
//returns the string to display as title of the tab
@Override
public String getTabTitle() {
return "Concept Drift";
}
//a short description (can be used as tool tip) of the tab, or contributor, etc.
@Override
public String getDescription(){
return "MOA Concept Drift";
}
}
| Java |
/*
* OptionEditComponent.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import moa.options.Option;
/**
* Interface representing a component to edit an option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public interface OptionEditComponent {
/**
* Gets the option of this component
*
* @return the option of this component
*/
public Option getEditedOption();
/**
* Sets the state of the component
*
* @param cliString the state of the component
*/
public void setEditState(String cliString);
/**
* This method applies the state
*
*/
public void applyState();
}
| Java |
/*
* FlagOptionEditComponent.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import javax.swing.JCheckBox;
import moa.options.FlagOption;
import moa.options.Option;
/**
* An OptionEditComponent that lets the user edit a flag option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class FlagOptionEditComponent extends JCheckBox implements
OptionEditComponent {
private static final long serialVersionUID = 1L;
protected FlagOption editedOption;
public FlagOptionEditComponent(FlagOption option) {
this.editedOption = option;
setEditState(this.editedOption.getValueAsCLIString());
}
@Override
public Option getEditedOption() {
return this.editedOption;
}
@Override
public void setEditState(String cliString) {
setSelected(cliString != null);
}
@Override
public void applyState() {
this.editedOption.setValue(isSelected());
}
}
| Java |
/*
* TaskTextViewerPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author Jansen (moa@cs.rwth-aachen.de)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import moa.evaluation.Accuracy;
import moa.evaluation.MeasureCollection;
import moa.evaluation.RegressionAccuracy;
import moa.gui.PreviewPanel.TypePanel;
import moa.gui.conceptdrift.CDTaskManagerPanel;
import moa.streams.clustering.ClusterEvent;
import moa.tasks.ConceptDriftMainTask;
/**
* This panel displays text. Used to output the results of tasks.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class TaskTextViewerPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
public static String exportFileExtension = "txt";
protected JTextArea textArea;
protected JScrollPane scrollPane;
protected JButton exportButton;
private javax.swing.JPanel topWrapper;
private javax.swing.JSplitPane jSplitPane1;
//Added for stream events
protected CDTaskManagerPanel taskManagerPanel;
protected TypePanel typePanel;
public void initVisualEvalPanel() {
acc1[0] = getNewMeasureCollection();
acc2[0] = getNewMeasureCollection();
if (clusteringVisualEvalPanel1 != null) {
panelEvalOutput.remove(clusteringVisualEvalPanel1);
}
clusteringVisualEvalPanel1 = new moa.gui.clustertab.ClusteringVisualEvalPanel();
clusteringVisualEvalPanel1.setMeasures(acc1, acc2, this);
this.graphCanvas.setGraph(acc1[0], acc2[0], 0, 1000);
this.graphCanvas.forceAddEvents();
clusteringVisualEvalPanel1.setMinimumSize(new java.awt.Dimension(280, 118));
clusteringVisualEvalPanel1.setPreferredSize(new java.awt.Dimension(290, 115));
panelEvalOutput.add(clusteringVisualEvalPanel1, gridBagConstraints);
}
public TaskTextViewerPanel() {
this(TypePanel.CLASSIFICATION, null);
}
public java.awt.GridBagConstraints gridBagConstraints;
public TaskTextViewerPanel(PreviewPanel.TypePanel typePanel, CDTaskManagerPanel taskManagerPanel) {
this.typePanel = typePanel;
this.taskManagerPanel = taskManagerPanel;
jSplitPane1 = new javax.swing.JSplitPane();
topWrapper = new javax.swing.JPanel();
this.textArea = new JTextArea();
this.textArea.setEditable(false);
this.textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
this.exportButton = new JButton("Export as .txt file...");
this.exportButton.setEnabled(false);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 2));
buttonPanel.add(this.exportButton);
topWrapper.setLayout(new BorderLayout());
this.scrollPane = new JScrollPane(this.textArea);
topWrapper.add(this.scrollPane, BorderLayout.CENTER);
topWrapper.add(buttonPanel, BorderLayout.SOUTH);
this.exportButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(new FileExtensionFilter(
exportFileExtension));
if (fileChooser.showSaveDialog(TaskTextViewerPanel.this) == JFileChooser.APPROVE_OPTION) {
File chosenFile = fileChooser.getSelectedFile();
String fileName = chosenFile.getPath();
if (!chosenFile.exists()
&& !fileName.endsWith(exportFileExtension)) {
fileName = fileName + "." + exportFileExtension;
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(fileName)));
out.write(TaskTextViewerPanel.this.textArea.getText());
out.close();
} catch (IOException ioe) {
GUIUtils.showExceptionDialog(
TaskTextViewerPanel.this.exportButton,
"Problem saving file " + fileName, ioe);
}
}
}
});
//topWrapper.add(this.scrollPane);
//topWrapper.add(buttonPanel);
panelEvalOutput = new javax.swing.JPanel();
//clusteringVisualEvalPanel1 = new moa.gui.clustertab.ClusteringVisualEvalPanel();
graphPanel = new javax.swing.JPanel();
graphPanelControlTop = new javax.swing.JPanel();
buttonZoomInY = new javax.swing.JButton();
buttonZoomOutY = new javax.swing.JButton();
labelEvents = new javax.swing.JLabel();
graphScrollPanel = new javax.swing.JScrollPane();
graphCanvas = new moa.gui.visualization.GraphCanvas();
// New EventClusters
//clusterEvents = new ArrayList<ClusterEvent>();
//clusterEvents.add(new ClusterEvent(this,100,"Change", "Drift"));
//graphCanvas.setClusterEventsList(clusterEvents);
graphPanelControlBottom = new javax.swing.JPanel();
buttonZoomInX = new javax.swing.JButton();
buttonZoomOutX = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
jSplitPane1.setDividerLocation(200);
jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
//topWrapper.setPreferredSize(new java.awt.Dimension(688, 500));
//topWrapper.setLayout(new java.awt.GridBagLayout());
jSplitPane1.setLeftComponent(topWrapper);
panelEvalOutput.setBorder(javax.swing.BorderFactory.createTitledBorder("Evaluation"));
panelEvalOutput.setLayout(new java.awt.GridBagLayout());
//clusteringVisualEvalPanel1.setMinimumSize(new java.awt.Dimension(280, 118));
//clusteringVisualEvalPanel1.setPreferredSize(new java.awt.Dimension(290, 115));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weighty = 1.0;
//panelEvalOutput.add(clusteringVisualEvalPanel1, gridBagConstraints);
initVisualEvalPanel();
graphPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Plot"));
graphPanel.setPreferredSize(new java.awt.Dimension(530, 115));
graphPanel.setLayout(new java.awt.GridBagLayout());
graphPanelControlTop.setLayout(new java.awt.GridBagLayout());
buttonZoomInY.setText("Zoom in Y");
buttonZoomInY.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomInYActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
graphPanelControlTop.add(buttonZoomInY, gridBagConstraints);
buttonZoomOutY.setText("Zoom out Y");
buttonZoomOutY.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomOutYActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
graphPanelControlTop.add(buttonZoomOutY, gridBagConstraints);
labelEvents.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
graphPanelControlTop.add(labelEvents, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
graphPanel.add(graphPanelControlTop, gridBagConstraints);
graphCanvas.setPreferredSize(new java.awt.Dimension(500, 111));
javax.swing.GroupLayout graphCanvasLayout = new javax.swing.GroupLayout(graphCanvas);
graphCanvas.setLayout(graphCanvasLayout);
graphCanvasLayout.setHorizontalGroup(
graphCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 515, Short.MAX_VALUE));
graphCanvasLayout.setVerticalGroup(
graphCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 128, Short.MAX_VALUE));
graphScrollPanel.setViewportView(graphCanvas);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
graphPanel.add(graphScrollPanel, gridBagConstraints);
buttonZoomInX.setText("Zoom in X");
buttonZoomInX.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomInXActionPerformed(evt);
}
});
graphPanelControlBottom.add(buttonZoomInX);
buttonZoomOutX.setText("Zoom out X");
buttonZoomOutX.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomOutXActionPerformed(evt);
}
});
graphPanelControlBottom.add(buttonZoomOutX);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
graphPanel.add(graphPanelControlBottom, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 2.0;
gridBagConstraints.weighty = 1.0;
panelEvalOutput.add(graphPanel, gridBagConstraints);
jSplitPane1.setRightComponent(panelEvalOutput);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jSplitPane1, gridBagConstraints);
// acc1[0] = getNewMeasureCollection();
//acc2[0] = getNewMeasureCollection();
//clusteringVisualEvalPanel1.setMeasures(acc1, acc2, this);
//this.graphCanvas.setGraph(acc1[0], acc2[0], 0, 1000);
}
public void setText(String newText) {
Point p = this.scrollPane.getViewport().getViewPosition();
this.textArea.setText(newText);
this.scrollPane.getViewport().setViewPosition(p);
this.exportButton.setEnabled(newText != null);
setGraph(newText);
}
protected MeasureCollection[] acc1 = new MeasureCollection[1];
protected MeasureCollection[] acc2 = new MeasureCollection[1];
protected String secondLine = "";
protected double round(double d) {
return Math.abs(Math.rint(d * 100) / 100);
}
protected MeasureCollection getNewMeasureCollection() {
/*if (this.taskManagerPanel != null) {
return new ChangeDetectionMeasures();
} else {
return new Accuracy();
}*/
return this.typePanel.getMeasureCollection();
}
public void setGraph(String preview) {
//Change the graph when there is change in the text
double processFrequency = 1000;
if (preview != null && !preview.equals("")) {
MeasureCollection oldAccuracy = acc1[0];
acc1[0] = getNewMeasureCollection();
Scanner scanner = new Scanner(preview);
String firstLine = scanner.nextLine();
boolean isSecondLine = true;
boolean isPrequential = firstLine.startsWith("learning evaluation instances,evaluation time");
boolean isHoldOut = firstLine.startsWith("evaluation instances,to");
int accuracyColumn = 6;
int kappaColumn = 4;
int RamColumn = 2;
int timeColumn = 1;
int memoryColumn = 9;
int kappaTempColumn = 5;
if (this.taskManagerPanel instanceof CDTaskManagerPanel) {
accuracyColumn = 6;
kappaColumn = 4;
RamColumn = 2;
timeColumn = 1;
memoryColumn = 9;
} else if (isPrequential || isHoldOut) {
accuracyColumn = 4;
kappaColumn = 5;
RamColumn = 2;
timeColumn = 1;
memoryColumn = 7;
kappaTempColumn = 5;
String[] tokensFirstLine = firstLine.split(",");
int i = 0;
for (String s : tokensFirstLine) {
if (s.equals("classifications correct (percent)")) {
accuracyColumn = i;
} else if (s.equals("Kappa Statistic (percent)")) {
kappaColumn = i;
} else if (s.equals("Kappa Temporal Statistic (percent)")) {
kappaTempColumn = i;
} else if (s.equals("model cost (RAM-Hours)")) {
RamColumn = i;
} else if (s.equals("evaluation time (cpu seconds)")
|| s.equals("total train time")) {
timeColumn = i;
} else if (s.equals("model serialized size (bytes)")) {
memoryColumn = i;
}
i++;
}
}
if (isPrequential || isHoldOut || this.taskManagerPanel instanceof CDTaskManagerPanel) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] tokens = line.split(",");
this.acc1[0].addValue(0, round(parseDouble(tokens[accuracyColumn])));
this.acc1[0].addValue(1, round(parseDouble(tokens[kappaColumn])));
this.acc1[0].addValue(2, round(parseDouble(tokens[kappaTempColumn])));
if (!isHoldOut) {
this.acc1[0].addValue(3, Math.abs(parseDouble(tokens[RamColumn])));
}
this.acc1[0].addValue(4, round(parseDouble(tokens[timeColumn])));
this.acc1[0].addValue(5, round(parseDouble(tokens[memoryColumn]) / (1024 * 1024)));
if (isSecondLine == true) {
processFrequency = Math.abs(parseDouble(tokens[0]));
isSecondLine = false;
if (acc1[0].getValue(0, 0) != oldAccuracy.getValue(0, 0)) { //(!line.equals(secondLine)) {
//If we are in a new task, compare with the previous
secondLine = line;
if (processFrequency == this.graphCanvas.getProcessFrequency()) {
acc2[0] = oldAccuracy;
}
}
}
}
} else {
this.acc2[0] = getNewMeasureCollection();
}
} else {
this.acc1[0] = getNewMeasureCollection();
this.acc2[0] = getNewMeasureCollection();
}
if (this.taskManagerPanel instanceof CDTaskManagerPanel) {
ConceptDriftMainTask cdTask = this.taskManagerPanel.getSelectedCurrenTask();
ArrayList<ClusterEvent> clusterEvents = cdTask.getEventsList();
this.graphCanvas.setClusterEventsList(clusterEvents);
}
this.graphCanvas.setGraph(acc1[0], acc2[0], this.graphCanvas.getMeasureSelected(), (int) processFrequency);
this.graphCanvas.updateCanvas(true);
this.graphCanvas.forceAddEvents();
this.clusteringVisualEvalPanel1.update();
}
private double parseDouble(String s) {
double ret = 0;
if (s.equals("?") == false) {
ret = Double.parseDouble(s);
}
return ret;
}
private void scrollPane0MouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_scrollPane0MouseWheelMoved
streamPanel0.setZoom(evt.getX(), evt.getY(), (-1) * evt.getWheelRotation(), scrollPane0);
}//GEN-LAST:event_scrollPane0MouseWheelMoved
private void buttonZoomInXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomInXActionPerformed
graphCanvas.scaleXResolution(false);
}//GEN-LAST:event_buttonZoomInXActionPerformed
private void buttonZoomOutYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomOutYActionPerformed
graphCanvas.setSize(new Dimension(graphCanvas.getWidth(), (int) (graphCanvas.getHeight() * 0.8)));
graphCanvas.setPreferredSize(new Dimension(graphCanvas.getWidth(), (int) (graphCanvas.getHeight() * 0.8)));
this.graphCanvas.updateCanvas(true);
}//GEN-LAST:event_buttonZoomOutYActionPerformed
private void buttonZoomOutXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomOutXActionPerformed
graphCanvas.scaleXResolution(true);
}//GEN-LAST:event_buttonZoomOutXActionPerformed
private void buttonZoomInYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomInYActionPerformed
graphCanvas.setSize(new Dimension(graphCanvas.getWidth(), (int) (graphCanvas.getHeight() * 1.2)));
graphCanvas.setPreferredSize(new Dimension(graphCanvas.getWidth(), (int) (graphCanvas.getHeight() * 1.2)));
this.graphCanvas.updateCanvas(true);
}//GEN-LAST:event_buttonZoomInYActionPerformed
private void buttonRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRunActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_buttonRunActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonRun;
private javax.swing.JButton buttonScreenshot;
private javax.swing.JButton buttonStop;
private javax.swing.JButton buttonZoomInX;
private javax.swing.JButton buttonZoomInY;
private javax.swing.JButton buttonZoomOutX;
private javax.swing.JButton buttonZoomOutY;
private javax.swing.JCheckBox checkboxDrawClustering;
private javax.swing.JCheckBox checkboxDrawGT;
private javax.swing.JCheckBox checkboxDrawMicro;
private javax.swing.JCheckBox checkboxDrawPoints;
private moa.gui.clustertab.ClusteringVisualEvalPanel clusteringVisualEvalPanel1;
private javax.swing.JComboBox comboX;
private javax.swing.JComboBox comboY;
private moa.gui.visualization.GraphCanvas graphCanvas;
private javax.swing.JPanel graphPanel;
private javax.swing.JPanel graphPanelControlBottom;
private javax.swing.JPanel graphPanelControlTop;
private javax.swing.JScrollPane graphScrollPanel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel labelEvents;
private javax.swing.JLabel labelNumPause;
private javax.swing.JLabel labelX;
private javax.swing.JLabel labelY;
private javax.swing.JLabel label_processed_points;
private javax.swing.JLabel label_processed_points_value;
private javax.swing.JTextField numPauseAfterPoints;
private javax.swing.JPanel panelControl;
private javax.swing.JPanel panelEvalOutput;
private javax.swing.JPanel panelVisualWrapper;
private javax.swing.JScrollPane scrollPane0;
private javax.swing.JScrollPane scrollPane1;
private javax.swing.JSlider speedSlider;
private javax.swing.JSplitPane splitVisual;
private moa.gui.visualization.StreamPanel streamPanel0;
private moa.gui.visualization.StreamPanel streamPanel1;
@Override
public void actionPerformed(ActionEvent e) {
//reacte on graph selection and find out which measure was selected
int selected = Integer.parseInt(e.getActionCommand());
int counter = selected;
int m_select = 0;
int m_select_offset = 0;
boolean found = false;
for (int i = 0; i < acc1.length; i++) {
for (int j = 0; j < acc1[i].getNumMeasures(); j++) {
if (acc1[i].isEnabled(j)) {
counter--;
if (counter < 0) {
m_select = i;
m_select_offset = j;
found = true;
break;
}
}
}
if (found) {
break;
}
}
this.graphCanvas.setGraph(acc1[m_select], acc2[m_select], m_select_offset, this.graphCanvas.getProcessFrequency());
this.graphCanvas.forceAddEvents();
}
}
| Java |
/*
* ClassOptionSelectionPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import moa.core.AutoClassDiscovery;
import moa.core.AutoExpandVector;
import moa.options.ClassOption;
import moa.options.OptionHandler;
import moa.tasks.Task;
/**
* Creates a panel that displays the classes available, letting the user select
* a class.
*
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class ClassOptionSelectionPanel extends JPanel {
// TODO: idea - why not retain matching options between classes when the
// class type is changed
// e.g. if user switches from LearnModel to EvaluateLearner, retain whatever
// the 'stream' option was set to
private static final long serialVersionUID = 1L;
protected JComboBox classChoiceBox;
protected JComponent chosenObjectEditor;
protected Object chosenObject;
public ClassOptionSelectionPanel(Class<?> requiredType,
String initialCLIString, String nullString) {
// Class<?>[] classesFound = AutoClassDiscovery.findClassesOfType("moa",
// requiredType);
Class<?>[] classesFound = findSuitableClasses(requiredType);
this.classChoiceBox = new JComboBox(classesFound);
setLayout(new BorderLayout());
add(this.classChoiceBox, BorderLayout.NORTH);
Object initialObject = null;
try {
initialObject = ClassOption.cliStringToObject(initialCLIString,
requiredType, null);
} catch (Exception ignored) {
// ignore exception
}
if (initialObject != null) {
this.classChoiceBox.setSelectedItem(initialObject.getClass());
classChoiceChanged(initialObject);
} else {
try {
Object chosen = ((Class<?>) ClassOptionSelectionPanel.this.classChoiceBox.getSelectedItem()).newInstance();
classChoiceChanged(chosen);
} catch (Exception ex) {
GUIUtils.showExceptionDialog(ClassOptionSelectionPanel.this,
"Problem", ex);
}
}
this.classChoiceBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
try {
Object chosen = ((Class<?>) ClassOptionSelectionPanel.this.classChoiceBox.getSelectedItem()).newInstance();
classChoiceChanged(chosen);
} catch (Exception ex) {
GUIUtils.showExceptionDialog(
ClassOptionSelectionPanel.this, "Problem", ex);
}
}
});
}
public Class<?>[] findSuitableClasses(Class<?> requiredType) {
AutoExpandVector<Class<?>> finalClasses = new AutoExpandVector<Class<?>>();
Class<?>[] classesFound = AutoClassDiscovery.findClassesOfType("moa",
requiredType);
for (Class<?> foundClass : classesFound) {
finalClasses.add(foundClass);
}
Class<?>[] tasksFound = AutoClassDiscovery.findClassesOfType("moa",
Task.class);
for (Class<?> foundTask : tasksFound) {
try {
Task task = (Task) foundTask.newInstance();
if (requiredType.isAssignableFrom(task.getTaskResultType())) {
finalClasses.add(foundTask);
}
} catch (Exception e) {
// ignore
}
}
return finalClasses.toArray(new Class<?>[finalClasses.size()]);
}
public static String showSelectClassDialog(Component parent, String title,
Class<?> requiredType, String initialCLIString, String nullString) {
ClassOptionSelectionPanel panel = new ClassOptionSelectionPanel(
requiredType, initialCLIString, nullString);
if (JOptionPane.showOptionDialog(parent, panel, title,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null,
null, null) == JOptionPane.OK_OPTION) {
return panel.getChosenObjectCLIString(requiredType);
}
return initialCLIString;
}
public String getChosenObjectCLIString(Class<?> requiredType) {
if (this.chosenObjectEditor instanceof OptionsConfigurationPanel) {
((OptionsConfigurationPanel) this.chosenObjectEditor).applyChanges();
}
return ClassOption.objectToCLIString(this.chosenObject, requiredType);
}
public void classChoiceChanged(Object chosen) {
this.chosenObject = chosen;
JComponent newChosenObjectEditor = null;
if (this.chosenObject instanceof OptionHandler) {
OptionHandler chosenOptionHandler = (OptionHandler) this.chosenObject;
newChosenObjectEditor = new OptionsConfigurationPanel(
chosenOptionHandler.getPurposeString(), chosenOptionHandler.getOptions());
}
if (this.chosenObjectEditor != null) {
remove(this.chosenObjectEditor);
}
this.chosenObjectEditor = newChosenObjectEditor;
if (this.chosenObjectEditor != null) {
add(this.chosenObjectEditor, BorderLayout.CENTER);
}
Component component = this;
while ((component != null) && !(component instanceof JDialog)) {
component = component.getParent();
}
if (component != null) {
Window window = (Window) component;
window.pack();
}
}
}
| Java |
/*
* StringOptionEditComponent.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import javax.swing.JTextField;
import moa.options.Option;
/**
* An OptionEditComponent that lets the user edit a string option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class StringOptionEditComponent extends JTextField implements
OptionEditComponent {
private static final long serialVersionUID = 1L;
protected Option editedOption;
public StringOptionEditComponent(Option option) {
this.editedOption = option;
setEditState(this.editedOption.getValueAsCLIString());
}
@Override
public Option getEditedOption() {
return this.editedOption;
}
@Override
public void setEditState(String cliString) {
setText(cliString);
}
@Override
public void applyState() {
this.editedOption.setValueViaCLIString(getText().length() > 0 ? getText() : null);
}
}
| Java |
/*
* AbstractTabPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author FracPete (fracpete at waikato dot ac dot nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
/**
* Abstract Tab Panel.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision: 7 $
*/
public abstract class AbstractTabPanel extends javax.swing.JPanel {
/**
* Returns the string to display as title of the tab.
*
* @return the string to display as title of the tab
*/
public abstract String getTabTitle();
/**
* Returns a short description (can be used as tool tip) of the tab, or contributor, etc.
*
* @return a short description of this tab panel.
*/
public abstract String getDescription();
}
| Java |
/*
* FloatOptionEditComponent.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import moa.options.FloatOption;
import moa.options.Option;
/**
* An OptionEditComponent that lets the user edit a float option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class FloatOptionEditComponent extends JPanel implements
OptionEditComponent {
private static final long serialVersionUID = 1L;
public static final int SLIDER_RESOLUTION = 100000;
protected FloatOption editedOption;
protected JSpinner spinner;
protected JSlider slider;
public FloatOptionEditComponent(FloatOption option) {
this.editedOption = option;
double minVal = option.getMinValue();
double maxVal = option.getMaxValue();
setLayout(new GridLayout(1, 0));
this.spinner = new JSpinner(new SpinnerNumberModel(option.getValue(),
minVal, maxVal, 0.001));
add(this.spinner);
if ((minVal > Double.NEGATIVE_INFINITY)
&& (maxVal < Double.POSITIVE_INFINITY)) {
this.slider = new JSlider(0, SLIDER_RESOLUTION,
floatValueToSliderValue(option.getValue()));
add(this.slider);
this.slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
FloatOptionEditComponent.this.spinner.setValue(sliderValueToFloatValue(FloatOptionEditComponent.this.slider.getValue()));
}
});
this.spinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
FloatOptionEditComponent.this.slider.setValue(floatValueToSliderValue(((Double) FloatOptionEditComponent.this.spinner.getValue()).doubleValue()));
}
});
}
}
protected int floatValueToSliderValue(double floatValue) {
double minVal = this.editedOption.getMinValue();
double maxVal = this.editedOption.getMaxValue();
return (int) Math.round((floatValue - minVal) / (maxVal - minVal)
* SLIDER_RESOLUTION);
}
protected double sliderValueToFloatValue(int sliderValue) {
double minVal = this.editedOption.getMinValue();
double maxVal = this.editedOption.getMaxValue();
return minVal
+ (((double) sliderValue / SLIDER_RESOLUTION) * (maxVal - minVal));
}
@Override
public void applyState() {
this.editedOption.setValue(((Double) this.spinner.getValue()).doubleValue());
// this.editedOption.setValue(Double.parseDouble(this.spinner.getValue().toString()));
}
@Override
public Option getEditedOption() {
return this.editedOption;
}
@Override
public void setEditState(String cliString) {
this.spinner.setValue(FloatOption.cliStringToDouble(cliString));
}
}
| Java |
/*
* MultiChoiceOptionEditComponent.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import javax.swing.JComboBox;
import moa.options.MultiChoiceOption;
import moa.options.Option;
/**
* An OptionEditComponent that lets the user edit a multi choice option.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class MultiChoiceOptionEditComponent extends JComboBox implements
OptionEditComponent {
private static final long serialVersionUID = 1L;
protected MultiChoiceOption editedOption;
public MultiChoiceOptionEditComponent(MultiChoiceOption option) {
super(option.getOptionLabels());
this.editedOption = option;
setSelectedIndex(option.getChosenIndex());
}
@Override
public void applyState() {
this.editedOption.setChosenIndex(getSelectedIndex());
}
@Override
public Option getEditedOption() {
return this.editedOption;
}
@Override
public void setEditState(String cliString) {
MultiChoiceOption tempOpt = (MultiChoiceOption) this.editedOption.copy();
tempOpt.setValueViaCLIString(cliString);
setSelectedIndex(tempOpt.getChosenIndex());
}
}
| Java |
/*
* TaskManagerPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author Manuel Martín (msalvador@bournemouth.ac.uk)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import moa.core.StringUtils;
import moa.options.ClassOption;
import moa.options.OptionHandler;
import moa.tasks.EvaluatePrequential;
import moa.tasks.MainTask;
import moa.tasks.Task;
import moa.tasks.TaskThread;
/**
* This panel displays the running tasks.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class TaskManagerPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static final int MILLISECS_BETWEEN_REFRESH = 600;
public static String exportFileExtension = "log";
public class ProgressCellRenderer extends JProgressBar implements
TableCellRenderer {
private static final long serialVersionUID = 1L;
public ProgressCellRenderer() {
super(SwingConstants.HORIZONTAL, 0, 10000);
setBorderPainted(false);
setStringPainted(true);
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
double frac = -1.0;
if (value instanceof Double) {
frac = ((Double) value).doubleValue();
}
if (frac >= 0.0) {
setIndeterminate(false);
setValue((int) (frac * 10000.0));
setString(StringUtils.doubleToString(frac * 100.0, 2, 2));
} else {
setValue(0);
//setIndeterminate(true);
//setString("?");
}
return this;
}
@Override
public void validate() {
}
@Override
public void revalidate() {
}
@Override
protected void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
}
@Override
public void firePropertyChange(String propertyName, boolean oldValue,
boolean newValue) {
}
}
protected class TaskTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
@Override
public String getColumnName(int col) {
switch (col) {
case 0:
return "command";
case 1:
return "status";
case 2:
return "time elapsed";
case 3:
return "current activity";
case 4:
return "% complete";
}
return null;
}
@Override
public int getColumnCount() {
return 5;
}
@Override
public int getRowCount() {
return TaskManagerPanel.this.taskList.size();
}
@Override
public Object getValueAt(int row, int col) {
TaskThread thread = TaskManagerPanel.this.taskList.get(row);
switch (col) {
case 0:
return ((OptionHandler) thread.getTask()).getCLICreationString(MainTask.class);
case 1:
return thread.getCurrentStatusString();
case 2:
return StringUtils.secondsToDHMSString(thread.getCPUSecondsElapsed());
case 3:
return thread.getCurrentActivityString();
case 4:
return new Double(thread.getCurrentActivityFracComplete());
}
return null;
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
protected MainTask currentTask = new EvaluatePrequential();//LearnModel();
protected List<TaskThread> taskList = new ArrayList<TaskThread>();
protected JButton configureTaskButton = new JButton("Configure");
protected JTextField taskDescField = new JTextField();
protected JButton runTaskButton = new JButton("Run");
protected TaskTableModel taskTableModel;
protected JTable taskTable;
protected JButton pauseTaskButton = new JButton("Pause");
protected JButton resumeTaskButton = new JButton("Resume");
protected JButton cancelTaskButton = new JButton("Cancel");
protected JButton deleteTaskButton = new JButton("Delete");
protected PreviewPanel previewPanel;
private Preferences prefs;
private final String PREF_NAME = "currentTask";
public TaskManagerPanel() {
// Read current task preference
prefs = Preferences.userRoot().node(this.getClass().getName());
currentTask = new EvaluatePrequential();
String taskText = this.currentTask.getCLICreationString(MainTask.class);
String propertyValue = prefs.get(PREF_NAME, taskText);
//this.taskDescField.setText(propertyValue);
setTaskString(propertyValue, false); //Not store preference
this.taskDescField.setEditable(false);
final Component comp = this.taskDescField;
this.taskDescField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 1) {
if ((evt.getButton() == MouseEvent.BUTTON3)
|| ((evt.getButton() == MouseEvent.BUTTON1) && evt.isAltDown() && evt.isShiftDown())) {
JPopupMenu menu = new JPopupMenu();
JMenuItem item;
item = new JMenuItem("Copy configuration to clipboard");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyClipBoardConfiguration();
}
});
menu.add(item);
item = new JMenuItem("Save selected tasks to file");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
saveLogSelectedTasks();
}
});
menu.add(item);
item = new JMenuItem("Enter configuration...");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String newTaskString = JOptionPane.showInputDialog("Insert command line");
if (newTaskString != null) {
setTaskString(newTaskString);
}
}
});
menu.add(item);
menu.show(comp, evt.getX(), evt.getY());
}
}
}
});
JPanel configPanel = new JPanel();
configPanel.setLayout(new BorderLayout());
configPanel.add(this.configureTaskButton, BorderLayout.WEST);
configPanel.add(this.taskDescField, BorderLayout.CENTER);
configPanel.add(this.runTaskButton, BorderLayout.EAST);
this.taskTableModel = new TaskTableModel();
this.taskTable = new JTable(this.taskTableModel);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
this.taskTable.getColumnModel().getColumn(1).setCellRenderer(
centerRenderer);
this.taskTable.getColumnModel().getColumn(2).setCellRenderer(
centerRenderer);
this.taskTable.getColumnModel().getColumn(4).setCellRenderer(
new ProgressCellRenderer());
JPanel controlPanel = new JPanel();
controlPanel.add(this.pauseTaskButton);
controlPanel.add(this.resumeTaskButton);
controlPanel.add(this.cancelTaskButton);
controlPanel.add(this.deleteTaskButton);
setLayout(new BorderLayout());
add(configPanel, BorderLayout.NORTH);
add(new JScrollPane(this.taskTable), BorderLayout.CENTER);
add(controlPanel, BorderLayout.SOUTH);
this.taskTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
taskSelectionChanged();
}
});
this.configureTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String newTaskString = ClassOptionSelectionPanel.showSelectClassDialog(TaskManagerPanel.this,
"Configure task", MainTask.class,
TaskManagerPanel.this.currentTask.getCLICreationString(MainTask.class),
null);
setTaskString(newTaskString);
}
});
this.runTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
runTask((Task) TaskManagerPanel.this.currentTask.copy());
}
});
this.pauseTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
pauseSelectedTasks();
}
});
this.resumeTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
resumeSelectedTasks();
}
});
this.cancelTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
cancelSelectedTasks();
}
});
this.deleteTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
deleteSelectedTasks();
}
});
javax.swing.Timer updateListTimer = new javax.swing.Timer(
MILLISECS_BETWEEN_REFRESH, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TaskManagerPanel.this.taskTable.repaint();
}
});
updateListTimer.start();
setPreferredSize(new Dimension(0, 200));
}
public void setPreviewPanel(PreviewPanel previewPanel) {
this.previewPanel = previewPanel;
}
public void setTaskString(String cliString) {
setTaskString(cliString, true);
}
public void setTaskString(String cliString, boolean storePreference) {
try {
this.currentTask = (MainTask) ClassOption.cliStringToObject(
cliString, MainTask.class, null);
String taskText = this.currentTask.getCLICreationString(MainTask.class);
this.taskDescField.setText(taskText);
if (storePreference == true){
//Save task text as a preference
prefs.put(PREF_NAME, taskText);
}
} catch (Exception ex) {
GUIUtils.showExceptionDialog(this, "Problem with task", ex);
}
}
public void runTask(Task task) {
TaskThread thread = new TaskThread(task);
this.taskList.add(0, thread);
this.taskTableModel.fireTableDataChanged();
this.taskTable.setRowSelectionInterval(0, 0);
thread.start();
}
public void taskSelectionChanged() {
TaskThread[] selectedTasks = getSelectedTasks();
if (selectedTasks.length == 1) {
setTaskString(((OptionHandler) selectedTasks[0].getTask()).getCLICreationString(MainTask.class));
if (this.previewPanel != null) {
this.previewPanel.setTaskThreadToPreview(selectedTasks[0]);
}
} else {
this.previewPanel.setTaskThreadToPreview(null);
}
}
public TaskThread[] getSelectedTasks() {
int[] selectedRows = this.taskTable.getSelectedRows();
TaskThread[] selectedTasks = new TaskThread[selectedRows.length];
for (int i = 0; i < selectedRows.length; i++) {
selectedTasks[i] = this.taskList.get(selectedRows[i]);
}
return selectedTasks;
}
public void pauseSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.pauseTask();
}
}
public void resumeSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.resumeTask();
}
}
public void cancelSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.cancelTask();
}
}
public void deleteSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.cancelTask();
this.taskList.remove(thread);
}
this.taskTableModel.fireTableDataChanged();
}
public void copyClipBoardConfiguration() {
StringSelection selection = new StringSelection(this.taskDescField.getText().trim());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
}
public void saveLogSelectedTasks() {
String tasksLog = "";
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
tasksLog += ((OptionHandler) thread.getTask()).getCLICreationString(MainTask.class) + "\n";
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(new FileExtensionFilter(
exportFileExtension));
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File chosenFile = fileChooser.getSelectedFile();
String fileName = chosenFile.getPath();
if (!chosenFile.exists()
&& !fileName.endsWith(exportFileExtension)) {
fileName = fileName + "." + exportFileExtension;
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(fileName)));
out.write(tasksLog);
out.close();
} catch (IOException ioe) {
GUIUtils.showExceptionDialog(
this,
"Problem saving file " + fileName, ioe);
}
}
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JPanel panel = new TaskManagerPanel();
panel.setOpaque(true); // content panes must be opaque
frame.setContentPane(panel);
// Display the window.
frame.pack();
// frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
/**
* [ClassOptionWithNamesEditComponent.java]
*
* ClassOptionWithNames: Editing window
*
* @author Yunsu Kim
* based on the implementation of Richard Kirkby
* Data Management and Data Exploration Group, RWTH Aachen University
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import moa.options.ClassOptionWithNames;
import moa.options.Option;
public class ClassOptionWithNamesEditComponent extends JPanel implements OptionEditComponent {
private static final long serialVersionUID = 1L;
protected ClassOptionWithNames editedOption;
protected JTextField textField = new JTextField();
protected JButton editButton = new JButton("Edit");
/** listeners that listen to changes to the chosen option. */
protected HashSet<ChangeListener> changeListeners = new HashSet<ChangeListener>();
public ClassOptionWithNamesEditComponent(ClassOptionWithNames option) {
this.editedOption = option;
this.textField.setEditable(false);
this.textField.getDocument().addDocumentListener(new DocumentListener() {
public void removeUpdate(DocumentEvent e) {
notifyChangeListeners();
}
public void insertUpdate(DocumentEvent e) {
notifyChangeListeners();
}
public void changedUpdate(DocumentEvent e) {
notifyChangeListeners();
}
});
setLayout(new BorderLayout());
add(this.textField, BorderLayout.CENTER);
add(this.editButton, BorderLayout.EAST);
this.editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
editObject();
}
});
setEditState(this.editedOption.getValueAsCLIString());
}
public void applyState() {
this.editedOption.setValueViaCLIString(this.textField.getText());
}
public Option getEditedOption() {
return this.editedOption;
}
public void setEditState(String cliString) {
this.textField.setText(cliString);
}
public void editObject() {
setEditState(ClassOptionWithNamesSelectionPanel.showSelectClassDialog(this,
"Editing option: " + this.editedOption.getName(),
this.editedOption.getRequiredType(), this.textField.getText(),
this.editedOption.getNullString(), this.editedOption.getClassNames()));
}
/**
* Adds the listener to the internal set of listeners. Gets notified when
* the option string changes.
*
* @param l the listener to add
*/
public void addChangeListener(ChangeListener l) {
changeListeners.add(l);
}
/**
* Removes the listener from the internal set of listeners.
*
* @param l the listener to remove
*/
public void removeChangeListener(ChangeListener l) {
changeListeners.remove(l);
}
/**
* Notifies all registered change listeners that the options have changed.
*/
protected void notifyChangeListeners() {
ChangeEvent e = new ChangeEvent(this);
for (ChangeListener l : changeListeners) {
l.stateChanged(e);
}
}
}
| Java |
/**
* BatchCmd.java
*
* @author Timm Jansen (moa@cs.rwth-aachen.de)
* @editor Yunsu Kim
*
* Last edited: 2013/06/02
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import moa.cluster.Clustering;
import moa.clusterers.AbstractClusterer;
import moa.clusterers.ClusterGenerator;
import moa.clusterers.clustream.WithKmeans;
import moa.evaluation.EntropyCollection;
import moa.evaluation.F1;
import moa.evaluation.General;
import moa.evaluation.MeasureCollection;
import moa.evaluation.SSQ;
import moa.evaluation.SilhouetteCoefficient;
import moa.evaluation.StatisticalCollection;
import moa.gui.visualization.DataPoint;
import moa.gui.visualization.RunVisualizer;
import moa.streams.clustering.ClusterEvent;
import moa.streams.clustering.ClusterEventListener;
import moa.streams.clustering.ClusteringStream;
import moa.streams.clustering.RandomRBFGeneratorEvents;
import weka.core.DenseInstance;
import weka.core.Instance;
public class BatchCmd implements ClusterEventListener{
private ArrayList<ClusterEvent> clusterEvents;
private AbstractClusterer clusterer;
private ClusteringStream stream;
private MeasureCollection[] measures;
private int totalInstances;
public boolean useMicroGT = false;
public BatchCmd(AbstractClusterer clusterer, ClusteringStream stream, MeasureCollection[] measures, int totalInstances){
this.clusterer = clusterer;
this.stream = stream;
this.totalInstances = totalInstances;
this.measures = measures;
if(stream instanceof RandomRBFGeneratorEvents){
((RandomRBFGeneratorEvents)stream).addClusterChangeListener(this);
clusterEvents = new ArrayList<ClusterEvent>();
}
else{
clusterEvents = null;
}
stream.prepareForUse();
clusterer.prepareForUse();
}
private ArrayList<ClusterEvent> getEventList(){
return clusterEvents;
}
@SuppressWarnings("unchecked")
private static ArrayList<Class> getMeasureSelection(int selection){
ArrayList<Class>mclasses = new ArrayList<Class>();
mclasses.add(EntropyCollection.class);
mclasses.add(F1.class);
mclasses.add(General.class);
mclasses.add(SSQ.class);
mclasses.add(SilhouetteCoefficient.class);
mclasses.add(StatisticalCollection.class);
return mclasses;
}
/* TODO read args from command line */
public static void main(String[] args){
RandomRBFGeneratorEvents stream = new RandomRBFGeneratorEvents();
AbstractClusterer clusterer = new WithKmeans();
int measureCollectionType = 0;
int amountInstances = 20000;
String testfile = "d:\\data\\test.csv";
runBatch(stream, clusterer, measureCollectionType, amountInstances, testfile);
}
public static void runBatch(ClusteringStream stream, AbstractClusterer clusterer,
int measureCollectionType, int amountInstances, String outputFile){
// create the measure collection
MeasureCollection[] measures = getMeasures(getMeasureSelection(measureCollectionType));
// run the batch job
BatchCmd batch = new BatchCmd(clusterer, stream, measures, amountInstances);
batch.run();
// read events and horizon
ArrayList<ClusterEvent> clusterEvents = batch.getEventList();
int horizon = stream.decayHorizonOption.getValue();
// write results to file
exportCSV(outputFile, clusterEvents, measures, horizon);
}
public void run(){
ArrayList<DataPoint> pointBuffer0 = new ArrayList<DataPoint>();
int m_timestamp = 0;
int decayHorizon = stream.getDecayHorizon();
double decay_threshold = stream.getDecayThreshold();
double decay_rate = (-1*Math.log(decay_threshold)/decayHorizon);
int counter = decayHorizon;
while(m_timestamp < totalInstances && stream.hasMoreInstances()){
m_timestamp++;
counter--;
Instance next = stream.nextInstance();
DataPoint point0 = new DataPoint(next,m_timestamp);
pointBuffer0.add(point0);
Instance traininst0 = new DenseInstance(point0);
if(clusterer instanceof ClusterGenerator)
traininst0.setDataset(point0.dataset());
else
traininst0.deleteAttributeAt(point0.classIndex());
clusterer.trainOnInstanceImpl(traininst0);
if(counter <= 0){
// if(m_timestamp%(totalInstances/10) == 0)
// System.out.println("Thread"+threadID+":"+(m_timestamp*100/totalInstances)+"% ");
for(DataPoint p:pointBuffer0)
p.updateWeight(m_timestamp, decay_rate);
Clustering gtClustering0;
Clustering clustering0 = null;
gtClustering0 = new Clustering(pointBuffer0);
if(useMicroGT && stream instanceof RandomRBFGeneratorEvents){
gtClustering0 = ((RandomRBFGeneratorEvents)stream).getMicroClustering();
}
clustering0 = clusterer.getClusteringResult();
if(clusterer.implementsMicroClusterer()){
if(clusterer instanceof ClusterGenerator
&& stream instanceof RandomRBFGeneratorEvents){
((ClusterGenerator)clusterer).setSourceClustering(((RandomRBFGeneratorEvents)stream).getMicroClustering());
}
Clustering microC = clusterer.getMicroClusteringResult();
if(clusterer.evaluateMicroClusteringOption.isSet()){
clustering0 = microC;
}
else{
if(clustering0 == null && microC != null)
clustering0 = moa.clusterers.KMeans.gaussianMeans(gtClustering0, microC);
}
}
//evaluate
for (int i = 0; i < measures.length; i++) {
try {
/*double sec =*/ measures[i].evaluateClusteringPerformance(clustering0, gtClustering0, pointBuffer0);
//System.out.println("Eval of "+measures[i].getClass().getSimpleName()+" at "+m_timestamp+" took "+sec);
} catch (Exception ex) { ex.printStackTrace(); }
}
pointBuffer0.clear();
counter = decayHorizon;
}
}
}
@SuppressWarnings("unchecked")
private static MeasureCollection[] getMeasures(ArrayList<Class> measure_classes){
MeasureCollection[] measures = new MeasureCollection[measure_classes.size()];
for (int i = 0; i < measure_classes.size(); i++) {
try {
MeasureCollection m = (MeasureCollection)measure_classes.get(i).newInstance();
measures[i] = m;
} catch (Exception ex) {
Logger.getLogger("Couldn't create Instance for "+measure_classes.get(i).getName());
ex.printStackTrace();
}
}
return measures;
}
public void changeCluster(ClusterEvent e) {
if(clusterEvents!=null) clusterEvents.add(e);
}
public static void exportCSV(String filepath, ArrayList<ClusterEvent> clusterEvents, MeasureCollection[] measures, int horizon) {
PrintWriter out = null;
try {
// Prepare an output file
if (!filepath.endsWith(".csv")) {
filepath += ".csv";
}
out = new PrintWriter(new BufferedWriter(new FileWriter(filepath)));
String delimiter = ";";
// Header
int numValues = 0;
out.write("Nr" + delimiter);
out.write("Event" + delimiter);
for (int m = 0; m < 1; m++) { // TODO: Multiple group of measures
for (int i = 0; i < measures.length; i++) {
for (int j = 0; j < measures[i].getNumMeasures(); j++) {
if (measures[i].isEnabled(j)) {
out.write(measures[i].getName(j) + delimiter);
numValues = measures[i].getNumberOfValues(j);
}
}
}
}
out.write("\n");
// Rows
Iterator<ClusterEvent> eventIt = null;
ClusterEvent event = null;
if (clusterEvents != null) {
if (clusterEvents.size() > 0) {
eventIt = clusterEvents.iterator();
event = eventIt.next();
}
}
for (int v = 0; v < numValues; v++){
// Nr
out.write(v + delimiter);
// Events
if (event != null && event.getTimestamp() <= horizon) {
out.write(event.getType() + delimiter);
if (eventIt != null && eventIt.hasNext()) {
event = eventIt.next();
} else {
event = null;
}
} else {
out.write(delimiter);
}
// Values
for (int m = 0; m < 1; m++) { // TODO: Multiple group of measures
for (int i = 0; i < measures.length; i++) {
for (int j = 0; j < measures[i].getNumMeasures(); j++) {
if (measures[i].isEnabled(j)) {
out.write(measures[i].getValue(j, v) + delimiter);
}
}
}
}
out.write("\n");
}
out.close();
} catch (IOException ex) {
Logger.getLogger(RunVisualizer.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
}
| Java |
/*
* RegressionTaskManagerPanel.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author Manuel Martín (msalvador@bournemouth.ac.uk)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import moa.core.StringUtils;
import moa.options.ClassOption;
import moa.options.OptionHandler;
import moa.tasks.EvaluatePrequentialRegression;
import moa.tasks.RegressionMainTask;
import moa.tasks.Task;
import moa.tasks.TaskThread;
/**
* This panel displays the running tasks.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class RegressionTaskManagerPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static final int MILLISECS_BETWEEN_REFRESH = 600;
public static String exportFileExtension = "log";
public class ProgressCellRenderer extends JProgressBar implements
TableCellRenderer {
private static final long serialVersionUID = 1L;
public ProgressCellRenderer() {
super(SwingConstants.HORIZONTAL, 0, 10000);
setBorderPainted(false);
setStringPainted(true);
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
double frac = -1.0;
if (value instanceof Double) {
frac = ((Double) value).doubleValue();
}
if (frac >= 0.0) {
setIndeterminate(false);
setValue((int) (frac * 10000.0));
setString(StringUtils.doubleToString(frac * 100.0, 2, 2));
} else {
setValue(0);
//setIndeterminate(true);
//setString("?");
}
return this;
}
@Override
public void validate() {
}
@Override
public void revalidate() {
}
@Override
protected void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
}
@Override
public void firePropertyChange(String propertyName, boolean oldValue,
boolean newValue) {
}
}
protected class TaskTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
@Override
public String getColumnName(int col) {
switch (col) {
case 0:
return "command";
case 1:
return "status";
case 2:
return "time elapsed";
case 3:
return "current activity";
case 4:
return "% complete";
}
return null;
}
@Override
public int getColumnCount() {
return 5;
}
@Override
public int getRowCount() {
return RegressionTaskManagerPanel.this.taskList.size();
}
@Override
public Object getValueAt(int row, int col) {
TaskThread thread = RegressionTaskManagerPanel.this.taskList.get(row);
switch (col) {
case 0:
return ((OptionHandler) thread.getTask()).getCLICreationString(RegressionMainTask.class);
case 1:
return thread.getCurrentStatusString();
case 2:
return StringUtils.secondsToDHMSString(thread.getCPUSecondsElapsed());
case 3:
return thread.getCurrentActivityString();
case 4:
return new Double(thread.getCurrentActivityFracComplete());
}
return null;
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
}
protected RegressionMainTask currentTask = new EvaluatePrequentialRegression();//LearnModel();
protected List<TaskThread> taskList = new ArrayList<TaskThread>();
protected JButton configureTaskButton = new JButton("Configure");
protected JTextField taskDescField = new JTextField();
protected JButton runTaskButton = new JButton("Run");
protected TaskTableModel taskTableModel;
protected JTable taskTable;
protected JButton pauseTaskButton = new JButton("Pause");
protected JButton resumeTaskButton = new JButton("Resume");
protected JButton cancelTaskButton = new JButton("Cancel");
protected JButton deleteTaskButton = new JButton("Delete");
protected PreviewPanel previewPanel;
private Preferences prefs;
private final String PREF_NAME = "currentTask";
public RegressionTaskManagerPanel() {
// Read current task preference
prefs = Preferences.userRoot().node(this.getClass().getName());
currentTask = new EvaluatePrequentialRegression();
String taskText = this.currentTask.getCLICreationString(RegressionMainTask.class);
String propertyValue = prefs.get(PREF_NAME, taskText);
//this.taskDescField.setText(propertyValue);
setTaskString(propertyValue, false); //Not store preference
this.taskDescField.setEditable(false);
final Component comp = this.taskDescField;
this.taskDescField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 1) {
if ((evt.getButton() == MouseEvent.BUTTON3)
|| ((evt.getButton() == MouseEvent.BUTTON1) && evt.isAltDown() && evt.isShiftDown())) {
JPopupMenu menu = new JPopupMenu();
JMenuItem item;
item = new JMenuItem("Copy configuration to clipboard");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
copyClipBoardConfiguration();
}
});
menu.add(item);
item = new JMenuItem("Save selected tasks to file");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
saveLogSelectedTasks();
}
});
menu.add(item);
item = new JMenuItem("Enter configuration...");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String newTaskString = JOptionPane.showInputDialog("Insert command line");
if (newTaskString != null) {
setTaskString(newTaskString);
}
}
});
menu.add(item);
menu.show(comp, evt.getX(), evt.getY());
}
}
}
});
JPanel configPanel = new JPanel();
configPanel.setLayout(new BorderLayout());
configPanel.add(this.configureTaskButton, BorderLayout.WEST);
configPanel.add(this.taskDescField, BorderLayout.CENTER);
configPanel.add(this.runTaskButton, BorderLayout.EAST);
this.taskTableModel = new TaskTableModel();
this.taskTable = new JTable(this.taskTableModel);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
this.taskTable.getColumnModel().getColumn(1).setCellRenderer(
centerRenderer);
this.taskTable.getColumnModel().getColumn(2).setCellRenderer(
centerRenderer);
this.taskTable.getColumnModel().getColumn(4).setCellRenderer(
new ProgressCellRenderer());
JPanel controlPanel = new JPanel();
controlPanel.add(this.pauseTaskButton);
controlPanel.add(this.resumeTaskButton);
controlPanel.add(this.cancelTaskButton);
controlPanel.add(this.deleteTaskButton);
setLayout(new BorderLayout());
add(configPanel, BorderLayout.NORTH);
add(new JScrollPane(this.taskTable), BorderLayout.CENTER);
add(controlPanel, BorderLayout.SOUTH);
this.taskTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
taskSelectionChanged();
}
});
this.configureTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String newTaskString = ClassOptionSelectionPanel.showSelectClassDialog(RegressionTaskManagerPanel.this,
"Configure task", RegressionMainTask.class,
RegressionTaskManagerPanel.this.currentTask.getCLICreationString(RegressionMainTask.class),
null);
setTaskString(newTaskString);
}
});
this.runTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
runTask((Task) RegressionTaskManagerPanel.this.currentTask.copy());
}
});
this.pauseTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
pauseSelectedTasks();
}
});
this.resumeTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
resumeSelectedTasks();
}
});
this.cancelTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
cancelSelectedTasks();
}
});
this.deleteTaskButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
deleteSelectedTasks();
}
});
javax.swing.Timer updateListTimer = new javax.swing.Timer(
MILLISECS_BETWEEN_REFRESH, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RegressionTaskManagerPanel.this.taskTable.repaint();
}
});
updateListTimer.start();
setPreferredSize(new Dimension(0, 200));
}
public void setPreviewPanel(PreviewPanel previewPanel) {
this.previewPanel = previewPanel;
}
public void setTaskString(String cliString) {
setTaskString(cliString, true);
}
public void setTaskString(String cliString, boolean storePreference) {
try {
this.currentTask = (RegressionMainTask) ClassOption.cliStringToObject(
cliString, RegressionMainTask.class, null);
String taskText = this.currentTask.getCLICreationString(RegressionMainTask.class);
this.taskDescField.setText(taskText);
if (storePreference == true){
//Save task text as a preference
prefs.put(PREF_NAME, taskText);
}
} catch (Exception ex) {
GUIUtils.showExceptionDialog(this, "Problem with task", ex);
}
}
public void runTask(Task task) {
TaskThread thread = new TaskThread(task);
this.taskList.add(0, thread);
this.taskTableModel.fireTableDataChanged();
this.taskTable.setRowSelectionInterval(0, 0);
thread.start();
}
public void taskSelectionChanged() {
TaskThread[] selectedTasks = getSelectedTasks();
if (selectedTasks.length == 1) {
setTaskString(((OptionHandler) selectedTasks[0].getTask()).getCLICreationString(RegressionMainTask.class));
if (this.previewPanel != null) {
this.previewPanel.setTaskThreadToPreview(selectedTasks[0]);
}
} else {
this.previewPanel.setTaskThreadToPreview(null);
}
}
public TaskThread[] getSelectedTasks() {
int[] selectedRows = this.taskTable.getSelectedRows();
TaskThread[] selectedTasks = new TaskThread[selectedRows.length];
for (int i = 0; i < selectedRows.length; i++) {
selectedTasks[i] = this.taskList.get(selectedRows[i]);
}
return selectedTasks;
}
public void pauseSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.pauseTask();
}
}
public void resumeSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.resumeTask();
}
}
public void cancelSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.cancelTask();
}
}
public void deleteSelectedTasks() {
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
thread.cancelTask();
this.taskList.remove(thread);
}
this.taskTableModel.fireTableDataChanged();
}
public void copyClipBoardConfiguration() {
StringSelection selection = new StringSelection(this.taskDescField.getText().trim());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
}
public void saveLogSelectedTasks() {
String tasksLog = "";
TaskThread[] selectedTasks = getSelectedTasks();
for (TaskThread thread : selectedTasks) {
tasksLog += ((OptionHandler) thread.getTask()).getCLICreationString(RegressionMainTask.class) + "\n";
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(new FileExtensionFilter(
exportFileExtension));
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File chosenFile = fileChooser.getSelectedFile();
String fileName = chosenFile.getPath();
if (!chosenFile.exists()
&& !fileName.endsWith(exportFileExtension)) {
fileName = fileName + "." + exportFileExtension;
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(fileName)));
out.write(tasksLog);
out.close();
} catch (IOException ioe) {
GUIUtils.showExceptionDialog(
this,
"Problem saving file " + fileName, ioe);
}
}
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JPanel panel = new RegressionTaskManagerPanel();
panel.setOpaque(true); // content panes must be opaque
frame.setContentPane(panel);
// Display the window.
frame.pack();
// frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
/**
* [ClassOptionWithNamesSelectionPanel.java]
*
* ClassOptionWithNames: Selection panel
*
* @author Yunsu Kim
* based on the implementation of Richard Kirkby
* Data Management and Data Exploration Group, RWTH Aachen University
*/
package moa.gui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import moa.core.AutoClassDiscovery;
import moa.core.AutoExpandVector;
import moa.options.ClassOption;
import moa.options.OptionHandler;
import moa.tasks.Task;
public class ClassOptionWithNamesSelectionPanel extends JPanel {
private static final long serialVersionUID = 1L;
private boolean debug = false;
protected JComboBox classChoiceBox;
protected JComponent chosenObjectEditor;
protected Object chosenObject;
public ClassOptionWithNamesSelectionPanel(Class<?> requiredType,
String initialCLIString, String nullString, String[] classNames) {
Class<?>[] classesFound = findSuitableClasses(requiredType, classNames);
if (debug) {
System.out.print("[ClassOptionWithNamesSelectionPanel] classNames = ");
for (String s : classNames) {
System.out.print(s + ", ");
}
System.out.println();
System.out.print("[ClassOptionWithNamesSelectionPanel] classesFound = ");
for (Class<?> cl : classesFound) {
System.out.print(cl.getSimpleName() + ", ");
}
System.out.println();
}
this.classChoiceBox = new JComboBox(classesFound);
setLayout(new BorderLayout());
add(this.classChoiceBox, BorderLayout.NORTH);
Object initialObject = null;
try {
initialObject = ClassOption.cliStringToObject(initialCLIString,
requiredType, null);
} catch (Exception ignored) {
// ignore exception
}
if (initialObject != null) {
this.classChoiceBox.setSelectedItem(initialObject.getClass());
classChoiceChanged(initialObject);
} else {
try {
Object chosen = ((Class<?>) ClassOptionWithNamesSelectionPanel.this.classChoiceBox.getSelectedItem()).newInstance();
classChoiceChanged(chosen);
} catch (Exception ex) {
GUIUtils.showExceptionDialog(ClassOptionWithNamesSelectionPanel.this,
"Problem", ex);
}
}
this.classChoiceBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Object chosen = ((Class<?>) ClassOptionWithNamesSelectionPanel.this.classChoiceBox.getSelectedItem()).newInstance();
classChoiceChanged(chosen);
} catch (Exception ex) {
GUIUtils.showExceptionDialog(
ClassOptionWithNamesSelectionPanel.this, "Problem", ex);
}
}
});
}
public Class<?>[] findSuitableClasses(Class<?> requiredType, String[] classNames) {
AutoExpandVector<Class<?>> finalClasses = new AutoExpandVector<Class<?>>();
Class<?>[] classesFound = AutoClassDiscovery.findClassesOfType("moa",
requiredType);
for (Class<?> cl : classesFound) {
for (int i = 0; i < classNames.length; i++) {
if (cl.getSimpleName().contains(classNames[i])) {
finalClasses.add(cl);
break;
}
}
}
Class<?>[] tasksFound = AutoClassDiscovery.findClassesOfType("moa",
Task.class);
for (Class<?> foundTask : tasksFound) {
try {
Task task = (Task) foundTask.newInstance();
if (requiredType.isAssignableFrom(task.getTaskResultType())) {
for (int i = 0; i < classNames.length; i++) {
if (foundTask.getSimpleName().contains(classNames[i])) {
finalClasses.add(foundTask);
break;
}
}
}
} catch (Exception e) {
// ignore
}
}
return finalClasses.toArray(new Class<?>[finalClasses.size()]);
}
public static String showSelectClassDialog(Component parent, String title,
Class<?> requiredType, String initialCLIString, String nullString, String[] classNames) {
ClassOptionWithNamesSelectionPanel panel = new ClassOptionWithNamesSelectionPanel(
requiredType, initialCLIString, nullString, classNames);
if (JOptionPane.showOptionDialog(parent, panel, title,
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null,
null, null) == JOptionPane.OK_OPTION) {
return panel.getChosenObjectCLIString(requiredType);
}
return initialCLIString;
}
public String getChosenObjectCLIString(Class<?> requiredType) {
if (this.chosenObjectEditor instanceof OptionsConfigurationPanel) {
((OptionsConfigurationPanel) this.chosenObjectEditor).applyChanges();
}
return ClassOption.objectToCLIString(this.chosenObject, requiredType);
}
public void classChoiceChanged(Object chosen) {
this.chosenObject = chosen;
JComponent newChosenObjectEditor = null;
if (this.chosenObject instanceof OptionHandler) {
OptionHandler chosenOptionHandler = (OptionHandler) this.chosenObject;
newChosenObjectEditor = new OptionsConfigurationPanel(
chosenOptionHandler.getPurposeString(), chosenOptionHandler.getOptions());
}
if (this.chosenObjectEditor != null) {
remove(this.chosenObjectEditor);
}
this.chosenObjectEditor = newChosenObjectEditor;
if (this.chosenObjectEditor != null) {
add(this.chosenObjectEditor, BorderLayout.CENTER);
}
Component component = this;
while ((component != null) && !(component instanceof JDialog)) {
component = component.getParent();
}
if (component != null) {
Window window = (Window) component;
window.pack();
}
}
}
| Java |
/*
* WekaExplorer.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
*
* Copy of main() from weka.gui.Explorer to start the Explorer with the
* processed data already loaded
*
*/
package moa.gui.visualization;
import weka.gui.explorer.Explorer;
import weka.core.Memory;
//import weka.gui.LookAndFeel;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import weka.core.Instances;
public class WekaExplorer {
private static Explorer m_explorer;
/** for monitoring the Memory consumption */
private static Memory m_Memory = new Memory(true);
public WekaExplorer(Instances instances) {
//weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, "Logging started");
try {
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {}
try {
// uncomment to disable the memory management:
//m_Memory.setEnabled(false);
m_explorer = new Explorer();
final JFrame jf = new JFrame("Weka Explorer");
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(m_explorer, BorderLayout.CENTER);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
jf.dispose();
}
});
jf.pack();
jf.setSize(800, 600);
jf.setVisible(true);
Image icon = Toolkit.getDefaultToolkit().
getImage(ClassLoader.getSystemResource("weka/gui/weka_icon.gif"));
jf.setIconImage(icon);
if(instances !=null){
m_explorer.getPreprocessPanel().setInstances(instances);
}
Thread memMonitor = new Thread() {
public void run() {
while (true) {
try {
//System.out.println("Before sleeping.");
this.sleep(4000);
System.gc();
if (m_Memory.isOutOfMemory()) {
// clean up
jf.dispose();
m_explorer = null;
System.gc();
// stop threads
m_Memory.stopThreads();
// display error
System.err.println("\ndisplayed message:");
m_Memory.showOutOfMemory();
System.err.println("\nexiting");
System.exit(-1);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
};
memMonitor.setPriority(Thread.MAX_PRIORITY);
memMonitor.start();
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}
| Java |
/*
* OutlierPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import javax.swing.*;
import moa.cluster.SphereCluster;
import moa.clusterers.outliers.MyBaseOutlierDetector;
import moa.clusterers.outliers.MyBaseOutlierDetector.Outlier;
public class OutlierPanel extends JPanel {
private boolean bAntiAlias = false;
private MyBaseOutlierDetector myOutlierDetector;
private Outlier myOutlier;
private SphereCluster cluster;
JDialog frameInfo = null;
private double[] center;
private final static int DRAW_SIZE = 4;
protected double decay_rate;
protected int x_dim = 0;
protected int y_dim = 1;
protected Color col;
protected Color default_color = Color.BLACK;
protected StreamOutlierPanel streamPanel;
protected int panel_size;
protected int window_size;
protected boolean highligted = false;
private double r;
/** Creates new form ObjectPanel */
public OutlierPanel(MyBaseOutlierDetector myOutlierDetector, Outlier outlier, SphereCluster cluster, Color color, StreamOutlierPanel sp) {
this.myOutlierDetector = myOutlierDetector;
this.myOutlier = outlier;
this.cluster = cluster;
center = cluster.getCenter();
r = cluster.getRadius();
streamPanel = sp;
default_color = col = color;
setVisible(true);
setOpaque(false);
setSize(new Dimension(1,1));
setLocation(0,0);
initComponents();
}
public void setDirection(double[] direction){
}
public void updateLocation(){
x_dim = streamPanel.getActiveXDim();
y_dim = streamPanel.getActiveYDim();
if ((cluster != null) && (center == null)) {
getParent().remove(this);
} else {
//size of the parent
window_size = Math.min(streamPanel.getWidth(), streamPanel.getHeight());
panel_size = DRAW_SIZE + 1;
setSize(new Dimension(panel_size, panel_size));
int x = (int) Math.round(center[x_dim] * window_size);
int y = (int) Math.round(center[y_dim] * window_size);
setLocation((int)(x - (panel_size / 2)), (int)(y - (panel_size / 2)));
}
}
public void updateTooltip(){
/*setToolTipText(cluster.getInfo());
ToolTipManager.sharedInstance().registerComponent(this);
ToolTipManager.sharedInstance().setInitialDelay(0);*/
}
@Override
public boolean contains(int x, int y) {
//only react on the hull of the cluster
double dist = Math.sqrt(Math.pow(x-panel_size/2,2)+Math.pow(y-panel_size/2,2));
if(panel_size/2 - 5 < dist && dist < panel_size/2 + 5)
return true;
else
return false;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 296, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 266, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
streamPanel.setHighlightedOutlierPanel(this);
showInfo();
streamPanel.setHighlightedOutlierPanel(null);
}//GEN-LAST:event_formMouseClicked
public String getInfo() {
return myOutlierDetector.getObjectInfo(myOutlier.obj);
}
private void showInfo() {
String title = "Outlier information";
JLabel comp = new JLabel();
comp.setText(getInfo());
JOptionPane pane = new JOptionPane(comp);
pane.setOptionType(JOptionPane.DEFAULT_OPTION);
pane.setMessageType(JOptionPane.PLAIN_MESSAGE);
PointerInfo pointerInfo = MouseInfo.getPointerInfo();
Point mousePoint = pointerInfo.getLocation();
JDialog dialog = pane.createDialog(this, title);
dialog.setLocation(mousePoint);
dialog.setVisible(true);
}
@Override
protected void paintComponent(Graphics g) {
if (bAntiAlias) {
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
updateLocation();
if (highligted){
g.setColor(Color.ORANGE);
}
else{
g.setColor(default_color);
}
int drawSize = DRAW_SIZE;
int drawStart = 0;
g.fillOval(drawStart, drawStart, drawSize, drawSize);
g.drawOval(drawStart, drawStart, drawSize, drawSize);
}
public void highlight(boolean enabled){
highligted = enabled;
repaint();
}
public boolean isValidCluster(){
return (center!=null);
}
public int getClusterID(){
return (int)cluster.getId();
}
public int getClusterLabel(){
return (int)cluster.getGroundTruth();
}
public String getSVGString(int width){
StringBuffer out = new StringBuffer();
int x = (int)(center[x_dim]*window_size);
int y = (int)(center[y_dim]*window_size);
int radius = panel_size/2;
out.append("<circle ");
out.append("cx='"+x+"' cy='"+y+"' r='"+radius+"'");
out.append(" stroke='green' stroke-width='1' fill='white' fill-opacity='0' />");
out.append("\n");
return out.toString();
}
public void drawOnCanvas(Graphics2D imageGraphics){
int x = (int)(center[x_dim]*window_size-(panel_size/2));
int y = (int)(center[y_dim]*window_size-(panel_size/2));
int radius = panel_size;
imageGraphics.drawOval(x, y, radius, radius);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* GraphAxes.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.text.DecimalFormat;
public class GraphAxes extends javax.swing.JPanel {
private final int x_offset_left = 35;
private final int x_offset_right = 5;
private final int y_offset_bottom = 20;
private final int y_offset_top = 20;
private int height;
private int width;
private double x_resolution; //how many pixels per 1px
private int processFrequency;
private double min_value = 0;
private double max_value = 1;
private int max_x_value;
/** Creates new form GraphAxes */
public GraphAxes() {
initComponents();
}
public void setXMaxValue(int max) {
max_x_value = max;
}
public void setXResolution(double resolution){
x_resolution = resolution;
}
public void setProcessFrequency(int frequency){
processFrequency = frequency;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//stream not started yet
if(processFrequency == 0) return;
height = getHeight()-y_offset_bottom-y_offset_top;
width = getWidth()-x_offset_left-x_offset_right;
//System.out.println(width);
g.setColor(new Color(236,233,216));
g.fillRect(0, 0, getWidth(), getHeight());
//draw background
g.setColor(Color.WHITE);
g.fillRect(x_offset_left, y_offset_top, width, height);
g.setFont(new Font("Tahoma", 0, 11));
xAxis(g);
yAxis(g);
}
private void xAxis(Graphics g){
g.setColor(Color.BLACK);
//x-achsis
g.drawLine(x_offset_left, calcY(0), width+x_offset_left, calcY(0));
//x achsis labels
int w = 100;
for (int i = 0; w*i < width-x_offset_right; i++) {
g.drawLine(w*i+x_offset_left, height+y_offset_top, w*i+x_offset_left, height+y_offset_top+5);
String label = Integer.toString((int)(w*i*processFrequency*x_resolution));
int str_length = g.getFontMetrics().stringWidth(label);
g.drawString(label,w*i+x_offset_left-str_length/2,height+y_offset_top+18);
}
}
private void yAxis(Graphics g){
//y-achsis
g.setColor(Color.BLACK);
g.drawLine(x_offset_left, calcY(0), x_offset_left, y_offset_top);
//center horizontal line
g.setColor(new Color(220,220,220));
g.drawLine(x_offset_left, height/2+y_offset_top, getWidth(), height/2+y_offset_top);
//3 y-achsis markers + labels
g.setColor(Color.BLACK);
DecimalFormat d = new DecimalFormat("0.00");
int digits_y = (int)(Math.log10(max_value))-1;
double upper = Math.ceil(max_value/Math.pow(10,digits_y));
if(digits_y < 0) upper*=Math.pow(10,digits_y);
if(Double.isNaN(upper)) upper =1.0;
g.drawString(d.format(0.0), 3, height+y_offset_top+5);
g.drawString(d.format(upper/2), 3, height/2+y_offset_top + 5);
g.drawString(d.format(upper), 3, y_offset_top + 5);
g.drawLine(x_offset_left-5, height+y_offset_top, x_offset_left,height+y_offset_top);
g.drawLine(x_offset_left-5, height/2+y_offset_top, x_offset_left,height/2+y_offset_top);
g.drawLine(x_offset_left-5, y_offset_top, x_offset_left,y_offset_top);
}
public void setYMinMaxValues(double min, double max){
min_value = min;
max_value = max;
}
public void setMaxXValue(int max){
max_x_value = max;
}
private int calcY(double value){
return (int)(height-(value/max_value)*height)+y_offset_top;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* ClusterPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
import moa.cluster.SphereCluster;
public class ClusterPanel extends JPanel {
private SphereCluster cluster;
private double[] center;
private final static int MIN_SIZE = 5;
protected double decay_rate;
protected int x_dim = 0;
protected int y_dim = 1;
protected Color col;
protected Color default_color = Color.BLACK;
protected double[] direction = null;
protected StreamPanel streamPanel;
protected int panel_size;
protected int window_size;
protected boolean highligted = false;
private double r;
/** Creates new form ObjectPanel */
public ClusterPanel(SphereCluster cluster, Color color, StreamPanel sp) {
this.cluster = cluster;
center = cluster.getCenter();
r = cluster.getRadius();
streamPanel = sp;
default_color = col = color;
setVisible(true);
setOpaque(false);
setSize(new Dimension(1,1));
setLocation(0,0);
initComponents();
}
public void setDirection(double[] direction){
this.direction = direction;
}
public void updateLocation(){
x_dim = streamPanel.getActiveXDim();
y_dim = streamPanel.getActiveYDim();
if(cluster!=null && center==null)
getParent().remove(this);
else{
//size of the parent
window_size = Math.min(streamPanel.getWidth(),streamPanel.getHeight());
//scale down to diameter
panel_size = (int) (2* r * window_size);
if(panel_size < MIN_SIZE)
panel_size = MIN_SIZE;
setSize(new Dimension(panel_size+1,panel_size+1));
setLocation((int)(center[x_dim]*window_size-(panel_size/2)),(int)(center[y_dim]*window_size-(panel_size/2)));
}
}
public void updateTooltip(){
setToolTipText(cluster.getInfo());
}
@Override
public boolean contains(int x, int y) {
//only react on the hull of the cluster
double dist = Math.sqrt(Math.pow(x-panel_size/2,2)+Math.pow(y-panel_size/2,2));
if(panel_size/2 - 5 < dist && dist < panel_size/2 + 5)
return true;
else
return false;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 296, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 266, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
streamPanel.setHighlightedClusterPanel(this);
}//GEN-LAST:event_formMouseClicked
@Override
protected void paintComponent(Graphics g) {
updateLocation();
if(highligted){
g.setColor(Color.BLUE);
}
else{
g.setColor(default_color);
}
int c = (int)(panel_size/2);
if(cluster.getId()>=0)
g.drawString("C"+(int)cluster.getId(),c,c);
g.drawOval(0, 0, panel_size, panel_size);
if(direction!=null){
double length = Math.sqrt(Math.pow(direction[0], 2) + Math.pow(direction[1], 2));
g.drawLine(c, c, c+(int)((direction[0]/length)*panel_size), c+(int)((direction[1]/length)*panel_size));
}
updateTooltip();
}
public void highlight(boolean enabled){
highligted = enabled;
repaint();
}
public boolean isValidCluster(){
return (center!=null);
}
public int getClusterID(){
return (int)cluster.getId();
}
public int getClusterLabel(){
return (int)cluster.getGroundTruth();
}
public String getSVGString(int width){
StringBuffer out = new StringBuffer();
int x = (int)(center[x_dim]*window_size);
int y = (int)(center[y_dim]*window_size);
int radius = panel_size/2;
out.append("<circle ");
out.append("cx='"+x+"' cy='"+y+"' r='"+radius+"'");
out.append(" stroke='green' stroke-width='1' fill='white' fill-opacity='0' />");
out.append("\n");
return out.toString();
}
public void drawOnCanvas(Graphics2D imageGraphics){
int x = (int)(center[x_dim]*window_size-(panel_size/2));
int y = (int)(center[y_dim]*window_size-(panel_size/2));
int radius = panel_size;
imageGraphics.drawOval(x, y, radius, radius);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* RunVisualizer.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
/*
* todo:
* hide clusters when drawing
* pause fix
* show always clusters...
*/
package moa.gui.visualization;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.TreeSet;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import moa.cluster.Cluster;
import moa.cluster.Clustering;
import moa.clusterers.outliers.MyBaseOutlierDetector;
import moa.clusterers.outliers.MyBaseOutlierDetector.Outlier;
import moa.clusterers.outliers.MyBaseOutlierDetector.OutlierNotifier;
import moa.clusterers.outliers.MyBaseOutlierDetector.PrintMsg;
import moa.evaluation.MeasureCollection;
import moa.evaluation.OutlierPerformance;
import moa.gui.TextViewerPanel;
import moa.gui.clustertab.ClusteringVisualEvalPanel;
import moa.gui.outliertab.OutlierSetupTab;
import moa.gui.outliertab.OutlierVisualEvalPanel;
import moa.gui.outliertab.OutlierVisualTab;
import moa.streams.clustering.ClusterEvent;
import moa.streams.clustering.ClusterEventListener;
import moa.streams.clustering.ClusteringStream;
import moa.streams.clustering.RandomRBFGeneratorEvents;
import weka.core.*;
public class RunOutlierVisualizer implements Runnable, ActionListener, ClusterEventListener{
/** the pause interval, being read from the gui at startup */
public static final int initialPauseInterval = 1000;
/** factor to control the speed */
private int m_wait_frequency = 100;
private int m_drawOutliersInterval = 100;
/** after how many instances do we repaint the streampanel?
* the GUI becomes very slow with small values
* */
private int m_redrawInterval = 100;
private int m_eventsInterval = 20;
private int m_eventsDecay = 100;
// interval for measurement of processing time per object
private int m_MeasureInterval = 1000;
/* flags to control the run behavior */
private static boolean bWork;
private boolean bStop = false;
/* total amount of processed instances */
private static int timestamp;
/* amount of instances to process in one step*/
private int m_pauseInterval;
private boolean m_bWaitWinFull;
/* the stream that delivers the instances */
private final ClusteringStream m_stream0;
/* amount of relevant instances; older instances will be dropped;
creates the 'sliding window' over the stream;
is strongly connected to the decay rate and decay threshold*/
private int m_stream0_decayHorizon;
/* the decay threshold defines the minimum weight of an instance to be relevant */
private double m_stream0_decay_threshold;
/* the decay rate of the stream, often reffered to as lambda;
is being calculated from the horizion and the threshold
as these are more intuitive to define */
private double m_stream0_decay_rate;
private static final int ALGORITHM_1 = 0;
private static final int ALGORITHM_2 = 1;
private static final int MAX_ALGORITHMS = 2;
boolean bUseAlgorithm2 = false;
/* the outlier detector */
public MyBaseOutlierDetector m_outlier[] = new MyBaseOutlierDetector[MAX_ALGORITHMS];
/* the measure collections contain all the measures */
private MeasureCollection[] m_measures[] = new MeasureCollection[MAX_ALGORITHMS][];
/* left and right stream panel that datapoints and clusterings will be drawn to */
private StreamOutlierPanel m_streampanel[] = new StreamOutlierPanel[MAX_ALGORITHMS];
private TreeSet<OutlierEvent> eventBuffer[] = new TreeSet[MAX_ALGORITHMS];
/* panel that shows the evaluation results */
private OutlierVisualEvalPanel m_evalPanel;
/* panel to hold the graph */
private GraphCanvas m_graphcanvas;
/* reference to the visual panel */
private OutlierVisualTab m_visualPanel;
/* points of window */
private LinkedList<DataPoint> pointBuffer0;
//private boolean bRedrawPointImg = true;
int nProcessed;
Long m_timePreObjSum[] = new Long[MAX_ALGORITHMS];
int m_timePreObjInterval = 100;
/* reference to the log panel */
private final TextViewerPanel m_logPanel;
private class LogPanelPrintMsg implements PrintMsg {
@Override
public void println(String s) {
m_logPanel.addText(s);
}
@Override
public void print(String s) {
m_logPanel.addText(s);
}
@Override
public void printf(String fmt, Object... args) {
m_logPanel.addText(String.format(fmt, args));
}
}
private class MyOutlierNotifier extends OutlierNotifier {
int idxAlgorithm;
public MyOutlierNotifier(int idxAlgorithm) {
this.idxAlgorithm = idxAlgorithm;
}
@Override
public void OnOutlier(Outlier outlier) {
DataPoint point = new DataPoint(outlier.inst, (int)outlier.id);
OutlierEvent oe = new OutlierEvent(point, true, new Long(timestamp));
if (!eventBuffer[idxAlgorithm].add(oe)) {
// there is a previous such event, override it
eventBuffer[idxAlgorithm].remove(oe);
eventBuffer[idxAlgorithm].add(oe);
}
// System.out.println("OnOutlier outlier.id " + outlier.id + " timestamp " + timestamp);
}
@Override
public void OnInlier(Outlier outlier) {
DataPoint point = new DataPoint(outlier.inst, (int)outlier.id);
OutlierEvent oe = new OutlierEvent(point, false, new Long(timestamp));
if (!eventBuffer[idxAlgorithm].add(oe)) {
// there is a previous such event, override it
eventBuffer[idxAlgorithm].remove(oe);
eventBuffer[idxAlgorithm].add(oe);
}
// System.out.println("OnInlier outlier.id " + outlier.id + " timestamp " + timestamp);
}
}
public RunOutlierVisualizer(OutlierVisualTab visualPanel, OutlierSetupTab outlierSetupTab){
m_outlier[ALGORITHM_1] = outlierSetupTab.getOutlierer0();
m_outlier[ALGORITHM_1].prepareForUse();
// show algorithm output to log-panel
m_outlier[ALGORITHM_1].SetUserInfo(false, false, new LogPanelPrintMsg(), 2000);
m_outlier[ALGORITHM_1].outlierNotifier = new MyOutlierNotifier(ALGORITHM_1);
m_outlier[ALGORITHM_2] = outlierSetupTab.getOutlierer1();
bUseAlgorithm2 = (m_outlier[ALGORITHM_2] != null);
if (bUseAlgorithm2) {
m_outlier[ALGORITHM_2].prepareForUse();
// show algorithm output to log-panel
m_outlier[ALGORITHM_2].SetUserInfo(false, false, new LogPanelPrintMsg(), 2000);
m_outlier[ALGORITHM_2].outlierNotifier = new MyOutlierNotifier(ALGORITHM_2);
}
m_visualPanel = visualPanel;
m_streampanel[ALGORITHM_1] = visualPanel.getLeftStreamPanel();
m_streampanel[ALGORITHM_1].setVisualizer(this);
m_streampanel[ALGORITHM_1].setOutlierDetector(m_outlier[ALGORITHM_1]);
if (bUseAlgorithm2) {
m_streampanel[ALGORITHM_2] = visualPanel.getRightStreamPanel();
m_streampanel[ALGORITHM_2].setVisualizer(this);
m_streampanel[ALGORITHM_2].setOutlierDetector(m_outlier[ALGORITHM_2]);
}
m_logPanel = outlierSetupTab.getLogPanel();
m_graphcanvas = visualPanel.getGraphCanvas();
m_evalPanel = visualPanel.getEvalPanel();
m_stream0 = outlierSetupTab.getStream0();
m_stream0_decayHorizon = m_stream0.getDecayHorizon();
m_stream0_decay_threshold = m_stream0.getDecayThreshold();
m_stream0_decay_rate = (Math.log(1.0/m_stream0_decay_threshold)/Math.log(2)/m_stream0_decayHorizon);
eventBuffer[ALGORITHM_1] = new TreeSet<OutlierEvent>();
eventBuffer[ALGORITHM_2] = new TreeSet<OutlierEvent>();
timestamp = 0;
bWork = true;
if (m_stream0 instanceof RandomRBFGeneratorEvents) {
// ((RandomRBFGeneratorEvents)m_stream0).addClusterChangeListener(this);
}
m_stream0.prepareForUse();
// clear log
m_logPanel.setText("");
// init measures
m_measures[ALGORITHM_1] = outlierSetupTab.getMeasures();
m_measures[ALGORITHM_2] = outlierSetupTab.getMeasures();
// show as default process time per object
m_graphcanvas.setGraph(m_measures[ALGORITHM_1][0], m_measures[ALGORITHM_2][0], 0, 100);
updateSettings();
// get those values from the generator
if (m_stream0 instanceof moa.streams.clustering.FileStream) {
// manually set last value to be the class
m_stream0.numAttsOption.setValue(m_stream0.numAttsOption.getValue() - 1);
}
int dims = m_stream0.numAttsOption.getValue();
visualPanel.setDimensionComobBoxes(dims);
}
private void updateSettings() {
m_pauseInterval = m_visualPanel.getPauseInterval();
m_wait_frequency = m_visualPanel.GetSpeed();
setPointsVisibility(m_visualPanel.getPointVisibility());
setOutliersVisibility(m_visualPanel.getOutliersVisibility());
m_bWaitWinFull = m_visualPanel.getWaitWinFull();
}
@Override
public void run() {
nProcessed = 0;
m_timePreObjSum[ALGORITHM_1] = 0L;
m_timePreObjSum[ALGORITHM_2] = 0L;
pointBuffer0 = new LinkedList<DataPoint>();
while (!bStop) {
if (!bWork || CanPause()) {
updateSettings();
drawOutliers();
showOutliers(true);
m_streampanel[ALGORITHM_1].repaint();
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].repaint();
//redraw();
work_pause();
if (bStop) break;
updateSettings();
showOutliers(false);
m_streampanel[ALGORITHM_1].setHighlightedOutlierPanel(null);
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].setHighlightedOutlierPanel(null);
}
synchronized(this) {
processData();
}
}
}
private void MeasuredProcessStreamObj(int idxAlgorithm, Instance newInst) {
m_outlier[idxAlgorithm].processNewInstanceImpl(newInst);
if (nProcessed % m_timePreObjInterval == 0) {
UpdateTimePerObj(idxAlgorithm, m_outlier[idxAlgorithm].getTimePerObj());
}
}
private void processData() {
if (m_stream0.hasMoreInstances()) {
timestamp++;
nProcessed++;
if (timestamp % 100 == 0)
m_visualPanel.setProcessedPointsCounter(timestamp);
Instance nextStreamObj0 = m_stream0.nextInstance();
DataPoint point0 = new DataPoint(nextStreamObj0,timestamp);
pointBuffer0.add(point0);
while (pointBuffer0.size() > m_stream0_decayHorizon) {
pointBuffer0.removeFirst();
}
MeasuredProcessStreamObj(ALGORITHM_1, nextStreamObj0);
if (bUseAlgorithm2)
MeasuredProcessStreamObj(ALGORITHM_2, nextStreamObj0);
// draw new point
m_streampanel[ALGORITHM_1].drawPoint(point0, false, false);
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].drawPoint(point0, false, false);
// apply decay at points
if (nProcessed % m_redrawInterval == 0) {
float f;
if (m_stream0_decayHorizon <= m_redrawInterval)
f = 1;
else
f = ((float)m_redrawInterval) / ((float)m_stream0_decayHorizon);
m_streampanel[ALGORITHM_1].applyDrawDecay(f, false);
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].applyDrawDecay(f, false);
}
// draw events
//if (nProcessed % m_eventsInterval == 0) {
drawEvents();
// redraw point layer
m_streampanel[ALGORITHM_1].RedrawPointLayer();
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].RedrawPointLayer();
/*if (nProcessed % m_drawOutliersInterval == 0)
drawOutliers();*/
if (CanPause()) {
// automatically pause each m_pauseInterval objects
//updatePointsWeight();
showOutliers(true);
drawOutliers();
m_visualPanel.toggleVisualizer(true);
}
} else {
System.out.println("DONE");
pause();
return;
}
simulateVisualSpeed(); // simulate visualization speed
}
private void UpdateTimePerObj(int idxAlgorithm, double t) {
double ms = t / (1000.0 * 1000.0);
OutlierPerformance op = (OutlierPerformance) m_measures[idxAlgorithm][0];
op.addTimePerObject(ms);
//m_evalPanel.update();
m_graphcanvas.updateCanvas();
m_logPanel.addText("Algorithm " + idxAlgorithm + ", process time per object (ms): " + String.format("%.3f", ms));
}
private void ShowStatistics() {
synchronized(this) {
m_logPanel.addText(" ");
m_logPanel.addText("Algorithm1 " + m_outlier[ALGORITHM_1].getStatistics());
if (bUseAlgorithm2)
m_logPanel.addText("Algorithm2 " + m_outlier[ALGORITHM_2].getStatistics());
}
}
private boolean CanPause() {
if (m_pauseInterval != 0) {
return (nProcessed % m_pauseInterval == 0);
}
return false;
}
private void simulateVisualSpeed() {
int iMaxWaitFreq = 100;
int iSleepMS = iMaxWaitFreq - m_wait_frequency;
if (iSleepMS < 0) iSleepMS = 0;
if (iSleepMS > iMaxWaitFreq) iSleepMS = iMaxWaitFreq;
//System.out.println("iSleepMS="+iSleepMS + ", m_wait_frequency="+m_wait_frequency);
if (iSleepMS > 0)
Sleep(iSleepMS);
}
private void updatePointsWeight() {
for(DataPoint p : pointBuffer0)
p.updateWeight(timestamp, m_stream0_decay_rate);
}
public void setWaitWinFull(boolean b) {
m_bWaitWinFull = b;
}
private boolean CanShowOutliers() {
return (!m_bWaitWinFull || (nProcessed >= m_stream0_decayHorizon));
}
private void drawOutliers(){
drawOutliers(ALGORITHM_1);
if (bUseAlgorithm2)
drawOutliers(ALGORITHM_2);
}
private void drawOutliers(int idxAlgorithm){
Vector<MyBaseOutlierDetector.Outlier> outliers = m_outlier[idxAlgorithm].getOutliersResult();
if ((outliers != null) && (outliers.size() > 0) && CanShowOutliers())
m_streampanel[idxAlgorithm].drawOutliers(outliers, Color.RED);
}
private void deleteExpiredEvents(int idxAlgorithm) {
// delete expired events older than m_eventsDecay
boolean b = true;
while (b) {
b = false;
if (eventBuffer[idxAlgorithm].size() > 0) {
OutlierEvent ev = eventBuffer[idxAlgorithm].first();
if (timestamp > ev.timestamp + m_eventsDecay) {
eventBuffer[idxAlgorithm].remove(ev);
b = true;
}
}
}
}
private void drawEvents() {
drawEvents(ALGORITHM_1);
if (bUseAlgorithm2)
drawEvents(ALGORITHM_2);
}
private void drawEvents(int idxAlgorithm) {
m_streampanel[idxAlgorithm].clearEvents();
// System.out.println("Alg " + idxAlgorithm + " events " + eventBuffer[idxAlgorithm].size());
deleteExpiredEvents(idxAlgorithm);
if (CanShowOutliers()) {
for (OutlierEvent ev : eventBuffer[idxAlgorithm]) {
m_streampanel[idxAlgorithm].drawEvent(ev, false);
}
}
//m_streampanel[idxAlgorithm].RedrawPointLayer();
}
private void drawPoints() {
drawPoints(ALGORITHM_1);
if (bUseAlgorithm2)
drawPoints(ALGORITHM_2);
}
private void drawPoints(int idxAlgorithm) {
m_streampanel[idxAlgorithm].clearPoints();
for (DataPoint point0 : pointBuffer0) {
point0.updateWeight(timestamp, m_stream0_decay_rate);
m_streampanel[idxAlgorithm].drawPoint(point0, true, false);
}
m_streampanel[idxAlgorithm].RedrawPointLayer();
}
private void showOutliers(boolean bShow) {
showOutliers(ALGORITHM_1, bShow);
if (bUseAlgorithm2)
showOutliers(ALGORITHM_2, bShow);
}
private void showOutliers(int idxAlgorithm, boolean bShow) {
if (!bWork && m_visualPanel.isEnabledDrawOutliers() && CanShowOutliers()) {
m_streampanel[idxAlgorithm].setOutliersVisibility(bShow);
}
else {
m_streampanel[idxAlgorithm].setOutliersVisibility(false);
}
}
private void _redraw() {
m_streampanel[ALGORITHM_1].clearPoints();
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].clearPoints();
drawPoints();
drawEvents();
showOutliers(true);
// drawClusterings();
m_streampanel[ALGORITHM_1].repaint();
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].repaint();
}
public void redraw() {
synchronized(this) {
_redraw();
}
}
private void _redrawOnResize() {
m_streampanel[ALGORITHM_1].clearPoints();
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].clearPoints();
drawPoints();
drawEvents();
showOutliers(true);
drawOutliers();
m_streampanel[ALGORITHM_1].repaint();
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].repaint();
}
public void redrawOnResize() {
synchronized(this) {
_redrawOnResize();
}
}
public static int getCurrentTimestamp(){
return timestamp;
}
private void work_pause(){
while(!bWork && !bStop){
Sleep(200);
}
}
private void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ex) { }
}
public static void pause(){
bWork = false;
}
public static void resume(){
bWork = true;
}
public void stop(){
bWork = false;
bStop = true;
ShowStatistics();
}
public void setSpeed(int speed) {
m_wait_frequency = speed;
}
@Override
public void actionPerformed(ActionEvent e) {
}
public void setPointsVisibility(boolean selected) {
m_streampanel[ALGORITHM_1].setPointsVisibility(selected);
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].setPointsVisibility(selected);
}
public void setOutliersVisibility(boolean selected) {
m_streampanel[ALGORITHM_1].setOutliersVisibility(selected);
if (bUseAlgorithm2)
m_streampanel[ALGORITHM_2].setOutliersVisibility(selected);
}
@Override
public void changeCluster(ClusterEvent e) {
System.out.println(e.getType()+": "+e.getMessage());
}
public void exportCSV(String filepath) {
PrintWriter out = null;
try {
if(!filepath.endsWith(".csv"))
filepath+=".csv";
out = new PrintWriter(new BufferedWriter(new FileWriter(filepath)));
out.write("\n");
out.close();
} catch (IOException ex) {
Logger.getLogger(RunVisualizer.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
public void weka() {
try{
Class.forName("weka.gui.Logger");
}
catch (Exception e){
m_logPanel.addText("Please add weka.jar to the classpath to use the Weka explorer.");
return;
}
Clustering wekaClustering;
wekaClustering = null;
if(wekaClustering == null || wekaClustering.size()==0){
m_logPanel.addText("Empty Clustering");
return;
}
int dims = wekaClustering.get(0).getCenter().length;
FastVector attributes = new FastVector();
for(int i = 0; i < dims; i++)
attributes.addElement( new Attribute("att" + i) );
Instances instances = new Instances("trainset",attributes,0);
for(int c = 0; c < wekaClustering.size(); c++){
Cluster cluster = wekaClustering.get(c);
Instance inst = new DenseInstance(cluster.getWeight(), cluster.getCenter());
inst.setDataset(instances);
instances.add(inst);
}
WekaExplorer explorer = new WekaExplorer(instances);
}
}
| Java |
/*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
/**
*
* @author mits
*/
class OutlierEvent implements Comparable<OutlierEvent> {
public DataPoint point;
public boolean outlier;
public Long timestamp;
public OutlierEvent(DataPoint point, boolean outlier, Long timestamp) {
this.point = point;
this.outlier = outlier;
this.timestamp = timestamp;
}
@Override
public int compareTo(OutlierEvent o) {
if (this.timestamp > o.timestamp)
return 1;
else if (this.timestamp < o.timestamp)
return -1;
else {
if (this.point.timestamp > o.point.timestamp)
return 1;
else if (this.point.timestamp < o.point.timestamp)
return -1;
}
return 0;
}
@Override
public boolean equals(Object o) {
return ( (this.timestamp == ((OutlierEvent) o).timestamp) &&
(this.point.timestamp == ((OutlierEvent) o).point.timestamp) );
}
}
| Java |
/**
* StreamPanel.java
*
* @author Timm Jansen (moa@cs.rwth-aachen.de)
* @editor Yunsu Kim
*
* Last edited: 2013/06/02
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import moa.cluster.Cluster;
import moa.cluster.Clustering;
import moa.cluster.SphereCluster;
import moa.clusterers.macro.NonConvexCluster;
public class StreamPanel extends JPanel implements ComponentListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private ClusterPanel highlighted_cluster = null;
private double zoom_factor = 0.2;
private int zoom = 1;
private int width_org;
private int height_org;
private int activeXDim = 0;
private int activeYDim = 1;
private JPanel layerPoints;
private JPanel layerMicro;
private JPanel layerMacro;
private JPanel layerGroundTruth;
//Buffered Image stuff
private BufferedImage pointCanvas;
private pointCanvasPanel layerPointCanvas;
private boolean pointsVisible = true;
private boolean ANTIALIAS = false;
class pointCanvasPanel extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
BufferedImage image = null;
public void setImage(BufferedImage image){
setSize(image.getWidth(), image.getWidth());
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
if(image!=null)
g2.drawImage(image, null, 0, 0);
}
}
/** Creates new form StreamPanel */
public StreamPanel() {
initComponents();
layerPoints = getNewLayer();
layerPoints.setOpaque(true);
layerPoints.setBackground(Color.white);
layerMicro = getNewLayer();
layerMacro = getNewLayer();
layerGroundTruth = getNewLayer();
add(layerMacro);
add(layerMicro);
add(layerGroundTruth);
add(layerPoints);
layerPointCanvas = new pointCanvasPanel();
add(layerPointCanvas);
addComponentListener(this);
}
private JPanel getNewLayer(){
JPanel layer = new JPanel();
layer.setOpaque(false);
layer.setLayout(null);
return layer;
}
public void drawMicroClustering(Clustering clustering, List<DataPoint> points, Color color){
drawClustering(layerMicro, clustering, points, color);
}
public void drawMacroClustering(Clustering clustering, List<DataPoint> points, Color color){
drawClustering(layerMacro, clustering, points, color);
}
public void drawGTClustering(Clustering clustering, List<DataPoint> points, Color color){
drawClustering(layerGroundTruth, clustering, points, color);
}
public void setMicroLayerVisibility(boolean visibility){
layerMicro.setVisible(visibility);
}
public void setMacroLayerVisibility(boolean visibility){
layerMacro.setVisible(visibility);
}
public void setGroundTruthLayerVisibility(boolean visibility){
layerGroundTruth.setVisible(visibility);
}
public void setPointVisibility(boolean visibility){
pointsVisible = visibility;
layerPoints.setVisible(visibility);
if(!visibility)
layerPointCanvas.setVisible(false);
}
void drawPointPanels(ArrayList<DataPoint> points, int timestamp, double decay_rate, double decay_threshold) {
for(int p = 0; p < points.size(); p++){
PointPanel pointPanel = new PointPanel(points.get(p), this, decay_rate, decay_threshold);
layerPoints.add(pointPanel);
pointPanel.updateLocation();
}
layerPointCanvas.setVisible(false);
layerPoints.setVisible(pointsVisible);
}
public void drawPoint(DataPoint point){
layerPointCanvas.setVisible(pointsVisible);
layerPoints.setVisible(false);
if(!pointsVisible)
return;
Graphics2D imageGraphics = (Graphics2D) pointCanvas.createGraphics();
if (ANTIALIAS) {
imageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
int size = Math.min(getWidth(), getHeight());
int x = (int) Math.round(point.value(getActiveXDim()) * size);
int y = (int) Math.round(point.value(getActiveYDim()) * size);
Color c = PointPanel.getPointColorbyClass(point, 10);
imageGraphics.setColor(c);
int psize = PointPanel.POINTSIZE;
int poffset = 2;
imageGraphics.drawOval(x - poffset, y - poffset, psize, psize);
imageGraphics.fillOval(x - poffset, y - poffset, psize, psize);
layerPointCanvas.repaint();
}
private void drawClusteringsOnCanvas(JPanel layer, Graphics2D imageGraphics){
for(Component comp :layer.getComponents()){
if(comp instanceof ClusterPanel){
ClusterPanel cp = (ClusterPanel)comp;
cp.drawOnCanvas(imageGraphics);
}
}
}
public void applyDrawDecay(float factor){
RescaleOp brightenOp = new RescaleOp(1f, 150f/factor, null);
pointCanvas = brightenOp.filter(pointCanvas, null);
layerPointCanvas.setImage(pointCanvas);
layerPointCanvas.repaint();
}
private void drawClustering(JPanel layer, Clustering clustering, List<DataPoint> points, Color color){
if (clustering.get(0) instanceof NonConvexCluster) {
drawNonConvexClustering(layer, clustering, points, color);
} else {
layer.removeAll();
for (int c = 0; c < clustering.size(); c++) {
SphereCluster cluster = (SphereCluster)clustering.get(c);
ClusterPanel clusterpanel = new ClusterPanel(cluster, color, this);
layer.add(clusterpanel);
clusterpanel.updateLocation();
}
if(layer.isVisible() && pointsVisible){
Graphics2D imageGraphics = (Graphics2D) pointCanvas.createGraphics();
imageGraphics.setColor(color);
drawClusteringsOnCanvas(layer, imageGraphics);
layerPointCanvas.repaint();
}
layer.repaint();
}
}
private void drawNonConvexClustering(JPanel layer, Clustering clustering, List<DataPoint> points, Color color) {
layerMacro.removeAll();
List<Cluster> foundClusters = clustering.getClustering();
double inclusionProbabilityThreshold = 0.5;
for (DataPoint p : points) {
for (int i = 0; i < foundClusters.size(); i++) {
Cluster fc = foundClusters.get(i);
if (fc.getInclusionProbability(p) >= inclusionProbabilityThreshold) {
PointPanel pointPanel = new PointPanel(p, this, color);
layerMacro.add(pointPanel);
pointPanel.updateLocation();
}
}
}
if (layerMacro.isVisible() && pointsVisible) { // Points & Macro together
Graphics2D imageGraphics = (Graphics2D) pointCanvas.createGraphics();
imageGraphics.setColor(color);
drawClusteringsOnCanvas(layerMacro, imageGraphics);
layerPointCanvas.repaint();
}
layerMacro.repaint();
}
public void screenshot(String filename, boolean svg, boolean png){
if(layerPoints.getComponentCount()==0 && layerMacro.getComponentCount()==0 && layerMicro.getComponentCount()==0)
return;
BufferedImage image = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_RGB);
if(png){
synchronized(getTreeLock()){
Graphics g = image.getGraphics();
paintAll(g);
try {
ImageIO.write(image, "png", new File(filename+".png"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
if(svg){
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename+".svg")));
int width = 500;
out.write("<?xml version=\"1.0\"?>\n");
out.write("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
out.write("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\""+width+"\" height=\""+width+"\">\n");
if(layerMicro.isVisible()){
for(Component comp :layerMicro.getComponents()){
if(comp instanceof ClusterPanel)
out.write(((ClusterPanel)comp).getSVGString(width));
}
}
if(layerMacro.isVisible()){
for(Component comp :layerMacro.getComponents()){
if(comp instanceof ClusterPanel)
out.write(((ClusterPanel)comp).getSVGString(width));
}
}
if(layerGroundTruth.isVisible()){
for(Component comp :layerGroundTruth.getComponents()){
if(comp instanceof ClusterPanel)
out.write(((ClusterPanel)comp).getSVGString(width));
}
}
if(layerPoints.isVisible()){
for(Component comp :layerPoints.getComponents()){
if(comp instanceof PointPanel){
PointPanel pp = (PointPanel) comp;
out.write(pp.getSVGString(width));
}
}
}
out.write("</svg>");
out.close();
} catch (IOException ex) {
Logger.getLogger(StreamPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public ClusterPanel getHighlightedClusterPanel(){
return highlighted_cluster;
}
public void setHighlightedClusterPanel(ClusterPanel clusterpanel){
highlighted_cluster = clusterpanel;
repaint();
}
public void setZoom(int x, int y, int zoom_delta, JScrollPane scrollPane){
if(zoom ==1){
width_org = getWidth();
height_org = getHeight();
}
zoom+=zoom_delta;
if(zoom<1) zoom = 1;
else{
int size = (int)(Math.min(width_org, height_org)*zoom_factor*zoom);
setSize(new Dimension(size*zoom, size*zoom));
setPreferredSize(new Dimension(size*zoom, size*zoom));
scrollPane.getViewport().setViewPosition(new Point((int)(x*zoom_factor*zoom+x),(int)( y*zoom_factor*zoom+y)));
}
}
public int getActiveXDim() {
return activeXDim;
}
public void setActiveXDim(int activeXDim) {
this.activeXDim = activeXDim;
}
public int getActiveYDim() {
return activeYDim;
}
public void setActiveYDim(int activeYDim) {
this.activeYDim = activeYDim;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setBackground(new java.awt.Color(255, 255, 255));
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
if(highlighted_cluster!=null){
highlighted_cluster.highlight(false);
highlighted_cluster=null;
}
}//GEN-LAST:event_formMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
public void componentHidden(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
}
public void componentResized(ComponentEvent e) {
//System.out.println(e.getComponent().getClass().getName() + " --- Resized ");
int size = Math.min(getWidth(), getHeight());
layerMicro.setSize(new Dimension(size,size));
layerMacro.setSize(new Dimension(size,size));
layerGroundTruth.setSize(new Dimension(size,size));
layerPoints.setSize(new Dimension(size,size));
pointCanvas = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
layerPointCanvas.setSize(new Dimension(size,size));
layerPointCanvas.setImage(pointCanvas);
Graphics2D imageGraphics = (Graphics2D) pointCanvas.getGraphics();
imageGraphics.setColor(Color.white);
imageGraphics.fillRect(0, 0, getWidth(), getHeight());
imageGraphics.dispose();
}
public void componentShown(ComponentEvent e) {
}
}
| Java |
/**
* PointPanel.java
*
* @author Timm Jansen (moa@cs.rwth-aachen.de)
* @editor Yunsu Kim
*
* Last edited: 2013/06/02
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import javax.swing.JPanel;
public class PointPanel extends JPanel{
private static final long serialVersionUID = 1L;
static final int POINTSIZE = 4;
DataPoint point;
protected int x_dim = 0;
protected int y_dim = 1;
protected Color col;
protected Color default_color = Color.BLACK;
protected int panel_size;
protected int window_size;
protected boolean highligted = false;
protected double decayRate;
protected double decayThreshold;
protected int type;
protected final int TYPE_PLAIN = 0;
protected final int TYPE_CLUSTERED = 1;
protected StreamPanel sp;
/**
* Type 1: Possibly be decayed, colored by class label.
*
* @param point
* @param streamPanel
* @param decayRate
* @param decayThreshold
*/
public PointPanel(DataPoint point, StreamPanel streamPanel, double decayRate, double decayThreshold) {
this.point = point;
this.panel_size = POINTSIZE;
this.decayRate = decayRate;
this.decayThreshold = decayThreshold;
this.col = default_color;
this.sp = streamPanel;
this.type = TYPE_PLAIN;
setVisible(true);
setOpaque(false);
setSize(new Dimension(1, 1));
setLocation(0, 0);
initComponents();
}
/**
* Type 2: Never be decayed, single color.
*
* @param point
* @param streamPanel
* @param color
*/
public PointPanel(DataPoint point, StreamPanel streamPanel, Color color) {
this.point = point;
this.panel_size = POINTSIZE;
this.decayRate = 0; // Never be decayed
this.decayThreshold = 0;
this.col = color;
this.sp = streamPanel;
this.type = TYPE_CLUSTERED;
setVisible(true);
setOpaque(false);
setSize(new Dimension(1, 1));
setLocation(0,0);
initComponents();
}
public void updateLocation(){
window_size = Math.min(sp.getWidth(), sp.getHeight());
x_dim = sp.getActiveXDim();
y_dim = sp.getActiveYDim();
setSize(new Dimension(panel_size + 1, panel_size + 1));
setLocation((int)(point.value(x_dim) * window_size - (panel_size / 2)), (int)(point.value(y_dim) * window_size - (panel_size / 2)));
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 296, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 266, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
@Override
protected void paintComponent(Graphics g) {
if (type == TYPE_PLAIN) {
point.updateWeight(RunVisualizer.getCurrentTimestamp(), decayRate);
if (point.weight() < decayThreshold) {
getParent().remove(this);
return;
}
}
Color color = getColor();
//Color errcolor = getErrorColor();
//if (errcolor == null) {
// errcolor = color;
panel_size = POINTSIZE;
//} else {
// panel_size = POINTSIZE + 2;
//}
updateLocation();
/*g.setColor(errcolor);
g.drawOval(0, 0, panel_size, panel_size);
g.setColor(color);
g.fillOval(0, 0, panel_size, panel_size);*/
if (type == TYPE_PLAIN) {
g.setColor(color);
if (point.isNoise()) {
g.setFont(g.getFont().deriveFont(9.0f));
g.drawChars(new char[] {'x'}, 0, 1, 0, panel_size);
} else {
g.drawOval(0, 0, panel_size, panel_size);
g.setColor(color);
g.fillOval(0, 0, panel_size, panel_size);
}
} else if (type == TYPE_CLUSTERED) {
g.setColor(color);
g.drawOval(0, 0, panel_size, panel_size);
}
setToolTipText(point.getInfo(x_dim, y_dim));
}
private Color getErrorColor(){
String cmdvalue = point.getMeasureValue("CMM");
Color color = null;
if(!cmdvalue.equals("")){
double err = Double.parseDouble(cmdvalue);
if(err > 0.00001){
if(err > 0.7) err = 1;
int alpha = (int)(100+155*err);
color = new Color(255, 0, 0, alpha);
}
if(err == 0.00001){
color = new Color(255, 0, 0,100);
}
}
return color;
}
private Color getColor(){
Color color = null;
if (type == TYPE_PLAIN) {
ClusterPanel cp = sp.getHighlightedClusterPanel();
if (cp != null) {
if (cp.getClusterLabel() == point.classValue()) {
color = Color.BLUE;
}
}
if (color == null) {
int alpha = (int)(point.weight() * 200 + 55);
float numCl = 10;
Color c;
if (point.isNoise()) {
c = Color.GRAY;
} else {
c = getPointColorbyClass(point, numCl);
}
color = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha);
}
} else if (type == TYPE_CLUSTERED) {
color = this.col;
}
return color;
}
public static Color getPointColorbyClass(DataPoint point, float numClasses){
Color c;
int classValue = (int)point.classValue();
if (classValue != point.noiseLabel) {
c = new Color(Color.HSBtoRGB((float)((classValue+1)/numClasses), 1f, 240f/240));
} else {
c = Color.GRAY;
}
return c;
}
public void highlight(boolean enabled){
highligted = enabled;
repaint();
}
public String getObjectInfo(){
return point.getInfo(x_dim, y_dim);
}
@Override
public String getToolTipText() {
return super.getToolTipText();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
public String getSVGString(int width){
StringBuffer out = new StringBuffer();
int x = (int)(point.value(x_dim)*window_size);
int y = (int)(point.value(y_dim)*window_size);
int radius = panel_size/2;
//radius = 1;
Color c = getColor();
String color = "rgb("+c.getRed()+","+c.getGreen()+","+c.getBlue()+")";
double trans = c.getAlpha()/255.0;
out.append("<circle ");
out.append("cx='"+x+"' cy='"+y+"' r='"+radius+"'");
out.append(" stroke='"+color+"' stroke-width='0' fill='"+color+"' fill-opacity='"+trans+"' stroke-opacity='"+trans+"'/>");
out.append("\n");
return out.toString();
}
public void drawOnCanvas(Graphics2D imageGraphics) {
Point location = getLocation();
if (type == TYPE_PLAIN) {
imageGraphics.drawOval(location.x, location.y, panel_size, panel_size);
imageGraphics.fillOval(location.x, location.y, panel_size, panel_size);
} else if (type == TYPE_CLUSTERED) {
imageGraphics.drawOval(location.x, location.y, panel_size, panel_size);
}
}
}
| Java |
/*
* GraphCanvas.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JViewport;
import moa.evaluation.MeasureCollection;
import moa.streams.clustering.ClusterEvent;
public class GraphCanvas extends JPanel {
private MeasureCollection measure0 = null;
private MeasureCollection measure1 = null;
int measureSelected = 0;
private ArrayList<ClusterEvent> clusterEvents;
private ArrayList<JLabel> eventLabelList;
private GraphAxes axesPanel;
private GraphCurve curvePanel;
private JPanel eventPanel;
private int eventCounter = 0;
private final int x_offset_left = 35;
private final int x_offset_right = 5;
private final int y_offset_bottom = 20;
private final int y_offset_top = 20;
private int processFrequency;
//default values to start with;
private double min_y_value = 0;
private double max_y_value = 1;
private double max_x_value = 250;
private double x_resolution = 0.5; //how many pixels per 1px
private double y_resolution = 1; //full min to max scale
private JViewport viewport;
/** Creates new form GraphCanvas */
public GraphCanvas() {
addComponents();
eventLabelList = new ArrayList<JLabel>();
}
public void scaleXResolution(boolean scaleUp) {
if (scaleUp) {
x_resolution *= 2;
} else {
x_resolution /= 2;
}
updateCanvas(true);
}
public void scaleYResolution(boolean scaleUp) {
if (scaleUp) {
y_resolution *= 2;
} else {
y_resolution /= 2;
}
updateCanvas(true);
}
public int getMeasureSelected() {
return measureSelected;
}
public int getProcessFrequency() {
return this.processFrequency;
}
public void setGraph(MeasureCollection measure0, MeasureCollection measure1, int mSelect, int processFrequency) {
this.measure0 = measure0;
this.measure1 = measure1;
measureSelected = mSelect;
this.processFrequency = processFrequency;
axesPanel.setProcessFrequency(processFrequency);
curvePanel.setProcessFrequency(processFrequency);
curvePanel.setGraph(measure0, measure1, mSelect);
updateCanvas();
}
public void updateCanvas() {
updateCanvas(false);
}
public void updateCanvas(boolean force) {
//check for new min max values first so we know if we have to do some resizing
if (updateMinMaxValues() || force) {
int maxLabel = (int) Math.ceil(max_x_value / x_resolution / 500);
int width = (int) (maxLabel * 500);
setSize(width, getHeight());
setPreferredSize(new Dimension(width, getHeight()));
axesPanel.setXMaxValue(maxLabel);
updateXResolution();
updateYValues();
updateSize();
axesPanel.repaint();
}
//check for new events
addEvents();
//add the latest plot point through repaint
//TODO: somehow realize incremental painting? (real heavyweight canvas: update())
curvePanel.repaint();
}
//returns true when values have changed
private boolean updateMinMaxValues() {
double min_y_value_new = min_y_value;
double max_y_value_new = max_y_value;
double max_x_value_new = max_x_value;
if (measure0 != null && measure1 != null) {
min_y_value_new = Math.min(measure0.getMinValue(measureSelected), measure1.getMinValue(measureSelected));
max_y_value_new = Math.max(measure0.getMaxValue(measureSelected), measure1.getMaxValue(measureSelected));
max_x_value_new = Math.max(measure0.getNumberOfValues(measureSelected), max_x_value);
} else {
if (measure0 != null) {
min_y_value_new = measure0.getMinValue(measureSelected);
max_y_value_new = measure0.getMaxValue(measureSelected);
max_x_value_new = Math.max(measure0.getNumberOfValues(measureSelected), max_x_value);
}
}
//resizing needed?
if (max_x_value_new != max_x_value || max_y_value_new != max_y_value || min_y_value_new != min_y_value) {
min_y_value = min_y_value_new;
max_y_value = max_y_value_new;
max_x_value = max_x_value_new;
return true;
}
return false;
}
private void updateXResolution() {
axesPanel.setXResolution(x_resolution);
curvePanel.setXResolution(x_resolution);
}
private void updateYValues() {
axesPanel.setYMinMaxValues(min_y_value, max_y_value);
curvePanel.setYMinMaxValues(min_y_value, max_y_value);
}
private void updateSize() {
axesPanel.setSize(getWidth(), getHeight());
//axesPanel.setPreferredSize(new Dimension(getWidth(), getHeight()));
curvePanel.setSize(getWidth() - x_offset_left - x_offset_right, getHeight() - y_offset_bottom - y_offset_top);
eventPanel.setSize(getWidth() - x_offset_left - x_offset_right, y_offset_top);
if (clusterEvents != null) {
//update Label positions
for (int i = 0; i < clusterEvents.size(); i++) {
int x = (int) (clusterEvents.get(i).getTimestamp() / processFrequency / x_resolution);
if (i < eventLabelList.size()) {
eventLabelList.get(i).setLocation(x - 10, 0);
}
}
}
}
//check if there are any new events in the event list and add them to the plot
private void addEvents() {
if (clusterEvents != null && clusterEvents.size() > eventCounter) {
ClusterEvent ev = clusterEvents.get(eventCounter);
eventCounter++;
JLabel eventMarker = new JLabel(ev.getType().substring(0, 1));
eventMarker.setPreferredSize(new Dimension(20, y_offset_top));
eventMarker.setSize(new Dimension(20, y_offset_top));
eventMarker.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
int x = (int) (ev.getTimestamp() / processFrequency / x_resolution);
eventMarker.setLocation(x - 10, 0);
eventMarker.setToolTipText(ev.getType() + " at " + ev.getTimestamp() + ": " + ev.getMessage());
eventPanel.add(eventMarker);
eventLabelList.add(eventMarker);
eventPanel.repaint();
}
}
//check if there are any new events in the event list and add them to the plot
public void forceAddEvents() {
if (clusterEvents != null) {
eventPanel.removeAll();
for (int i = 0; i < clusterEvents.size(); i++) {
ClusterEvent ev = clusterEvents.get(i);
JLabel eventMarker = new JLabel(ev.getType().substring(0, 1));
eventMarker.setPreferredSize(new Dimension(20, y_offset_top));
eventMarker.setSize(new Dimension(20, y_offset_top));
eventMarker.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
int x = (int) (ev.getTimestamp() / processFrequency / x_resolution);
eventMarker.setLocation(x - 10, 0);
eventMarker.setToolTipText(ev.getType() + " at " + ev.getTimestamp() + ": " + ev.getMessage());
eventPanel.add(eventMarker);
eventLabelList.add(eventMarker);
eventPanel.repaint();
}
}
}
@Override
protected void paintComponent(Graphics g) {
//needed in case parent component gets resized
//TODO doesn't fully work yet when reducing height
updateSize();
super.paintComponent(g);
}
private void addComponents() {
axesPanel = new GraphAxes();
curvePanel = new GraphCurve();
eventPanel = new JPanel();
curvePanel.setLocation(x_offset_left + 1, y_offset_top);
eventPanel.setLocation(x_offset_left + 1, 0);
eventPanel.setLayout(null);
add(axesPanel);
axesPanel.add(curvePanel);
axesPanel.add(eventPanel);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setLayout(new java.awt.GridBagLayout());
}// </editor-fold>//GEN-END:initComponents
public void setClusterEventsList(ArrayList<ClusterEvent> clusterEvents) {
this.clusterEvents = clusterEvents;
curvePanel.setClusterEventsList(clusterEvents);
}
public void setViewport(JViewport viewport) {
this.viewport = viewport;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* InfoPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import javax.swing.JFrame;
public class InfoPanel extends javax.swing.JPanel {
private JFrame infoFrame = null;
/** Creates new form InfoPanel */
public InfoPanel(JFrame infoFrame) {
this.infoFrame = infoFrame;
initComponents();
}
public void updateInfo(String text){
infoFrame.setVisible(true);
jTextPane1.setText(text);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextPane1 = new javax.swing.JTextPane();
setLayout(new java.awt.GridLayout(1, 0));
jTextPane1.setEditable(false);
add(jTextPane1);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextPane jTextPane1;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* GraphCurve.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import moa.evaluation.MeasureCollection;
import moa.streams.clustering.ClusterEvent;
public class GraphCurve extends javax.swing.JPanel {
private double min_value = 0;
private double max_value = 1;
private MeasureCollection measure0 = null;
private MeasureCollection measure1 = null;
private int measureSelected = 0;
private double x_resolution;
private int processFrequency;
private ArrayList<ClusterEvent> clusterEvents;
/** Creates new form GraphCurve */
public GraphCurve() {
initComponents();
}
public void setGraph(MeasureCollection measure0, MeasureCollection measure1, int selection){
this.measure0 = measure0;
this.measure1 = measure1;
this.measureSelected = selection;
repaint();
}
void setProcessFrequency(int processFrequency) {
this.processFrequency = processFrequency;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
if(measure0!=null && measure1!=null){
paintFullCurve(g, measure0, measureSelected, Color.red);
paintFullCurve(g, measure1, measureSelected, Color.blue);
}
else{
if(measure0!=null){
paintFullCurve(g, measure0, measureSelected, Color.red);
}
}
paintEvents(g);
}
private void paintFullCurve(Graphics g, MeasureCollection m, int mSelect, Color color){
if (m.getNumberOfValues(mSelect)==0) return;
boolean corrupted = false;
int height = getHeight();
int width = getWidth();
int n = m.getNumberOfValues(mSelect);
if(x_resolution > 1)
n = (int)(n / (int)x_resolution);
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < n; i ++) {
if(x_resolution > 1){
//we need to compress the values
double sum_y = 0;
int counter = 0;
for (int j = 0; j < x_resolution; j++) {
if((i)*x_resolution+j<m.getNumberOfValues(mSelect)){
sum_y+= m.getValue(mSelect,i);
counter++;
}
sum_y/=counter;
}
x[i] = i;
y[i] = (int)(height-(sum_y/max_value)*height);
}
else{
//spreading one value
x[i] = (i)*(int)(1/x_resolution)+(int)(1/x_resolution/2);
double value = m.getValue(mSelect,i);
if(Double.isNaN(value)){
corrupted = true;
break;
}
y[i] = (int)(height-(value/max_value)*height);
}
}
if(!corrupted){
g.setColor(color);
g.drawPolyline(x, y, n);
}
}
private void paintEvents(Graphics g){
if(clusterEvents!=null){
g.setColor(Color.DARK_GRAY);
for (int i = 0; i < clusterEvents.size(); i++) {
int x = (int)(clusterEvents.get(i).getTimestamp()/processFrequency/x_resolution);
g.drawLine(x, 0, x, getHeight());
}
}
}
public void setYMinMaxValues(double min, double max){
min_value = min;
max_value = max;
}
void setClusterEventsList(ArrayList<ClusterEvent> clusterEvents) {
this.clusterEvents = clusterEvents;
}
@Override
public Dimension getPreferredSize() {
return super.getPreferredSize();
}
void setXResolution(double x_resolution) {
this.x_resolution = x_resolution;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setOpaque(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 1000, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* StreamPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import moa.cluster.SphereCluster;
import moa.clusterers.outliers.MyBaseOutlierDetector;
import moa.clusterers.outliers.MyBaseOutlierDetector.Outlier;
public class StreamOutlierPanel extends JPanel implements ComponentListener {
private OutlierPanel highlighted_outlier = null;
private double zoom_factor = 0.2;
private int zoom = 1;
private int width_org;
private int height_org;
private int activeXDim = 0;
private int activeYDim = 1;
private JPanel layerOutliers;
private LabelAlgorithmPanel layerAlgorithmTitle;
private RunOutlierVisualizer m_visualizer = null;
private MyBaseOutlierDetector m_outlierDetector = null;
//Buffered Image stuff
private BufferedImage pointImg;
private BufferedImage canvasImg;
private ImgPanel layerCanvas;
private boolean bAntiAlias = false;
private int EVENTSIZE = 10;
class ImgPanel extends JPanel{
public BufferedImage image = null;
public void setImage(BufferedImage image){
setSize(image.getWidth(), image.getWidth());
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
if(image!=null)
g2.drawImage(image, null, 0, 0);
}
}
class LabelAlgorithmPanel extends JPanel{
public Color color;
public LabelAlgorithmPanel() {
setOpaque(true);
setLayout(null);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(color);
g2.fillRect(0, 0, getWidth(), getHeight());
}
}
public StreamOutlierPanel(Color colorAlgorithmTitle) {
initComponents();
layerAlgorithmTitle = new LabelAlgorithmPanel();
layerAlgorithmTitle.color = colorAlgorithmTitle;
add(layerAlgorithmTitle);
layerOutliers = getNewLayer();
add(layerOutliers);
layerCanvas = new ImgPanel();
add(layerCanvas);
addComponentListener(this);
}
private JPanel getNewLayer(){
JPanel layer = new JPanel();
layer.setOpaque(false);
layer.setLayout(null);
return layer;
}
public void drawOutliers(Vector<Outlier> outliers, Color color){
drawOutliers(layerOutliers, outliers, color);
}
public void repaintOutliers() {
layerOutliers.repaint();
}
public void setOutliersVisibility(boolean visibility){
layerOutliers.setVisible(visibility);
layerOutliers.repaint();
}
public void setPointsVisibility(boolean visibility){
layerCanvas.setVisible(visibility);
layerCanvas.repaint();
}
public void clearPoints() {
Graphics2D imageGraphics = (Graphics2D) pointImg.createGraphics();
imageGraphics.setColor(Color.WHITE);
imageGraphics.setPaint(Color.WHITE);
imageGraphics.fill(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
ApplyToCanvas(pointImg);
RedrawPointLayer();
}
public void clearEvents() {
ApplyToCanvas(pointImg);
//RedrawPointLayer();
}
public void ApplyToCanvas(BufferedImage img) {
Graphics2D g = (Graphics2D) canvasImg.createGraphics();
g.drawImage(img, 0, 0, this);
}
public void RedrawPointLayer() {
//System.out.println("print?");
layerCanvas.setImage(canvasImg);
layerCanvas.repaint();
}
private void drawPoint(
DataPoint point,
boolean bShowDecay,
Color c,
boolean bFill,
boolean bRedrawPointImg)
{
Graphics2D imageGraphics = (Graphics2D) pointImg.createGraphics();
if (bAntiAlias) {
imageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
int size = Math.min(getWidth(), getHeight());
int x = (int) Math.round(point.value(getActiveXDim()) * size);
int y = (int) Math.round(point.value(getActiveYDim()) * size);
//System.out.println("drawPoint: size="+size+" x="+x+" y="+y);
if (c == null) {
// fixed color of points
c = Color.GRAY;
// get a color by class of point
// Color c = PointPanel.getPointColorbyClass((int)point.classValue(), 10);
}
if (bShowDecay) {
int minValue = 40; // 20
double w = point.weight();
int alpha = (int) (255 * w + minValue);
if (alpha > 255) alpha = 255;
//System.out.println("alpha="+alpha+"w="+w);
c = new Color(c.getRed(),c.getGreen(),c.getBlue(),alpha);
}
imageGraphics.setColor(c);
int psize = PointPanel.POINTSIZE;
int poffset = 2;
imageGraphics.drawOval(x - poffset, y - poffset, psize, psize);
if (bFill) imageGraphics.fillOval(x - poffset, y - poffset, psize, psize);
if (bRedrawPointImg) {
ApplyToCanvas(pointImg);
RedrawPointLayer();
}
}
public void drawPoint(DataPoint point, boolean bShowDecay, boolean bRedrawPointImg){
drawPoint(point, bShowDecay, null, true, bRedrawPointImg);
}
/*public static BufferedImage duplicateImage(BufferedImage image) {
if (image == null) {
throw new NullPointerException();
}
BufferedImage j = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
j.setData(image.getData());
return j;
}*/
public void drawEvent(OutlierEvent outlierEvent, boolean bRedrawPointImg)
{
Graphics2D imageGraphics = (Graphics2D) canvasImg.createGraphics();
if (bAntiAlias) {
imageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
int size = Math.min(getWidth(), getHeight());
int x = (int) Math.round(outlierEvent.point.value(getActiveXDim()) * size);
int y = (int) Math.round(outlierEvent.point.value(getActiveYDim()) * size);
//System.out.println("drawPoint: size="+size+" x="+x+" y="+y);
Color c = outlierEvent.outlier ? Color.RED : Color.BLACK;
imageGraphics.setColor(c);
int psize = EVENTSIZE;
int poffset = EVENTSIZE / 2;
imageGraphics.drawOval(x - poffset, y - poffset, psize, psize);
if (bRedrawPointImg) {
RedrawPointLayer();
}
}
public void applyDrawDecay(float factor, boolean bRedrawPointImg){
//System.out.println("applyDrawDecay: factor="+factor);
// 1)
int v = Color.GRAY.getRed();
//System.out.println("applyDrawDecay: v="+v);
RescaleOp brightenOp = new RescaleOp(1f, (255-v)*factor, null);
// 2)
//RescaleOp brightenOp = new RescaleOp(1f + factor, 0, null);
// 3)
//RescaleOp brightenOp = new RescaleOp(1f, (255)*factor, null);
pointImg = brightenOp.filter(pointImg, null);
if (bRedrawPointImg) {
ApplyToCanvas(pointImg);
RedrawPointLayer();
}
}
private void drawOutliers(JPanel layer, Vector<Outlier> outliers, Color color){
layer.removeAll();
for (Outlier outlier : outliers) {
double[] center = new double[outlier.inst.numValues() - 1]; // last value is the class
for (int i = 0; i < outlier.inst.numValues() - 1; i++) {
center[i] = outlier.inst.value(i);
}
SphereCluster cluster = new SphereCluster(center, 0);
OutlierPanel outlierpanel = new OutlierPanel(m_outlierDetector, outlier, cluster, color, this);
layer.add(outlierpanel);
outlierpanel.updateLocation();
}
layer.repaint();
}
public void screenshot(String filename, boolean svg, boolean png){
if(layerOutliers.getComponentCount() == 0)
return;
BufferedImage image = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_RGB);
if(png){
synchronized(getTreeLock()){
Graphics g = image.getGraphics();
paintAll(g);
try {
ImageIO.write(image, "png", new File(filename+".png"));
} catch (Exception e) { }
}
}
if(svg){
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename+".svg")));
int width = 500;
out.write("<?xml version=\"1.0\"?>\n");
out.write("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
out.write("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\""+width+"\" height=\""+width+"\">\n");
if(layerOutliers.isVisible()){
for(Component comp :layerOutliers.getComponents()){
if(comp instanceof ClusterPanel)
out.write(((ClusterPanel)comp).getSVGString(width));
}
}
out.write("</svg>");
out.close();
} catch (IOException ex) {
Logger.getLogger(StreamPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public OutlierPanel getHighlightedOutlierPanel(){
return highlighted_outlier;
}
public void setHighlightedOutlierPanel(OutlierPanel outlierpanel){
//if (highlighted_outlier == outlierpanel)
// return;
//System.out.println("setHighlightedOutlierPanel");
// restore previous highlighted outlier
if (highlighted_outlier != null)
highlighted_outlier.highlight(false);
highlighted_outlier = outlierpanel;
if (highlighted_outlier != null)
highlighted_outlier.highlight(true);
repaint();
}
public void setZoom(int x, int y, int zoom_delta, JScrollPane scrollPane){
if(zoom ==1){
width_org = getWidth();
height_org = getHeight();
}
zoom+=zoom_delta;
if(zoom<1) zoom = 1;
else{
int size = (int)(Math.min(width_org, height_org)*zoom_factor*zoom);
setSize(new Dimension(size*zoom, size*zoom));
setPreferredSize(new Dimension(size*zoom, size*zoom));
scrollPane.getViewport().setViewPosition(new Point((int)(x*zoom_factor*zoom+x),(int)( y*zoom_factor*zoom+y)));
}
}
public int getActiveXDim() {
return activeXDim;
}
public void setActiveXDim(int activeXDim) {
this.activeXDim = activeXDim;
}
public int getActiveYDim() {
return activeYDim;
}
public void setActiveYDim(int activeYDim) {
this.activeYDim = activeYDim;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setBackground(new java.awt.Color(255, 255, 255));
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
if (highlighted_outlier != null){
highlighted_outlier.highlight(false);
highlighted_outlier = null;
}
}//GEN-LAST:event_formMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
public void setVisualizer(RunOutlierVisualizer v) {
m_visualizer = v;
}
public void setOutlierDetector(MyBaseOutlierDetector outlierDetector) {
m_outlierDetector = outlierDetector;
}
@Override
public void componentHidden(ComponentEvent e) {
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentResized(ComponentEvent e) {
//System.out.println("componentResized");
int heightAlgorithmTitle = 2;
int size = Math.min(getWidth(), getHeight() - heightAlgorithmTitle);
layerOutliers.setBounds(0, heightAlgorithmTitle, size, size);
layerAlgorithmTitle.setBounds(0, 0, getWidth(), heightAlgorithmTitle);
pointImg = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
canvasImg = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
layerCanvas.setBounds(0, heightAlgorithmTitle, size, size);
Graphics2D imageGraphics = (Graphics2D) pointImg.getGraphics();
imageGraphics.setColor(Color.white);
imageGraphics.fillRect(0, 0, getWidth(), getHeight());
imageGraphics.dispose();
ApplyToCanvas(pointImg);
RedrawPointLayer();
if (m_visualizer != null) {
m_visualizer.redrawOnResize();
}
}
@Override
public void componentShown(ComponentEvent e) {
}
}
| Java |
/**
* [DataPoint.java]
*
* @author Timm Jansen (moa@cs.rwth-aachen.de)
* @editor Yunsu Kim
*
* Last edited: 2013/06/02
* Data Management and Data Exploration Group, RWTH Aachen University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
public class DataPoint extends DenseInstance{
private static final long serialVersionUID = 1L;
protected int timestamp;
private HashMap<String, String> measure_values;
protected int noiseLabel;
public DataPoint(Instance nextInstance, Integer timestamp) {
super(nextInstance);
this.setDataset(nextInstance.dataset());
this.timestamp = timestamp;
measure_values = new HashMap<String, String>();
Attribute classLabel = dataset().classAttribute();
noiseLabel = classLabel.indexOfValue("noise"); // -1 returned if there is no noise
}
public void updateWeight(int cur_timestamp, double decay_rate){
setWeight(Math.pow(2,(-1.0)*decay_rate*(cur_timestamp-timestamp)));
}
public void setMeasureValue(String measureKey, double value){
synchronized(measure_values){
measure_values.put(measureKey, Double.toString(value));
}
}
public void setMeasureValue(String measureKey,String value){
synchronized(measure_values){
measure_values.put(measureKey, value);
}
}
public String getMeasureValue(String measureKey){
if(measure_values.containsKey(measureKey))
synchronized(measure_values){
return measure_values.get(measureKey);
}
else
return "";
}
public int getTimestamp(){
return timestamp;
}
public String getInfo(int x_dim, int y_dim) {
StringBuffer sb = new StringBuffer();
sb.append("<html><table>");
sb.append("<tr><td>Point</td><td>"+timestamp+"</td></tr>");
for (int i = 0; i < m_AttValues.length-1; i++) {
String label = "Dim "+i;
if(i == x_dim)
label = "<b>X</b>";
if(i == y_dim)
label = "<b>Y</b>";
sb.append("<tr><td>"+label+"</td><td>"+value(i)+"</td></tr>");
}
sb.append("<tr><td>Decay</td><td>"+weight()+"</td></tr>");
sb.append("<tr><td>True cluster</td><td>"+classValue()+"</td></tr>");
sb.append("</table>");
sb.append("<br>");
sb.append("<b>Evaluation</b><br>");
sb.append("<table>");
TreeSet<String> sortedset;
synchronized(measure_values){
sortedset = new TreeSet<String>(measure_values.keySet());
}
Iterator miterator = sortedset.iterator();
while(miterator.hasNext()) {
String key = (String)miterator.next();
sb.append("<tr><td>"+key+"</td><td>"+measure_values.get(key)+"</td></tr>");
}
sb.append("</table></html>");
return sb.toString();
}
public double getDistance(DataPoint other){
double distance = 0.0;
int numDims = numAttributes();
if(classIndex()!=0) numDims--;
for (int i = 0; i < numDims; i++) {
double d = value(i) - other.value(i);
distance += d * d;
}
return Math.sqrt(distance);
}
public boolean isNoise() {
return (int)classValue() == noiseLabel;
}
public double getNoiseLabel() {
return noiseLabel;
}
}
| Java |
/*
* RunVisualizer.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.visualization;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import moa.cluster.Cluster;
import moa.cluster.Clustering;
import moa.clusterers.AbstractClusterer;
import moa.clusterers.ClusterGenerator;
import moa.evaluation.MeasureCollection;
import moa.gui.TextViewerPanel;
import moa.gui.clustertab.ClusteringSetupTab;
import moa.gui.clustertab.ClusteringVisualEvalPanel;
import moa.gui.clustertab.ClusteringVisualTab;
import moa.streams.clustering.ClusterEvent;
import moa.streams.clustering.ClusterEventListener;
import moa.streams.clustering.ClusteringStream;
import moa.streams.clustering.RandomRBFGeneratorEvents;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
public class RunVisualizer implements Runnable, ActionListener, ClusterEventListener{
/** the pause interval, being read from the gui at startup */
public static final int initialPauseInterval = 5000;
/** factor to control the speed */
private int m_wait_frequency = 1000;
/** after how many instances do we repaint the streampanel?
* the GUI becomes very slow with small values
* */
private int m_redrawInterval = 100;
/* flags to control the run behavior */
private static boolean work;
private boolean stop = false;
/* total amount of processed instances */
private static int timestamp;
private static int lastPauseTimestamp;
/* amount of instances to process in one step*/
private int m_processFrequency;
/* the stream that delivers the instances */
private final ClusteringStream m_stream0;
/* amount of relevant instances; older instances will be dropped;
creates the 'sliding window' over the stream;
is strongly connected to the decay rate and decay threshold*/
private int m_stream0_decayHorizon;
/* the decay threshold defines the minimum weight of an instance to be relevant */
private double m_stream0_decay_threshold;
/* the decay rate of the stream, often reffered to as lambda;
is being calculated from the horizion and the threshold
as these are more intuitive to define */
private double m_stream0_decay_rate;
/* the clusterer */
private AbstractClusterer m_clusterer0;
private AbstractClusterer m_clusterer1;
/* the measure collections contain all the measures */
private MeasureCollection[] m_measures0 = null;
private MeasureCollection[] m_measures1 = null;
/* left and right stream panel that datapoints and clusterings will be drawn to */
private StreamPanel m_streampanel0;
private StreamPanel m_streampanel1;
/* panel that shows the evaluation results */
private ClusteringVisualEvalPanel m_evalPanel;
/* panel to hold the graph */
private GraphCanvas m_graphcanvas;
/* reference to the visual panel */
private ClusteringVisualTab m_visualPanel;
/* all possible clusterings */
//not pretty to have all the clusterings, but otherwise we can't just redraw clusterings
private Clustering gtClustering0 = null;
private Clustering gtClustering1 = null;
private Clustering macro0 = null;
private Clustering macro1 = null;
private Clustering micro0 = null;
private Clustering micro1 = null;
/* holds all the events that have happend, if the stream supports events */
private ArrayList<ClusterEvent> clusterEvents;
/* reference to the log panel */
private final TextViewerPanel m_logPanel;
public RunVisualizer(ClusteringVisualTab visualPanel, ClusteringSetupTab clusteringSetupTab){
m_visualPanel = visualPanel;
m_streampanel0 = visualPanel.getLeftStreamPanel();
m_streampanel1 = visualPanel.getRightStreamPanel();
m_graphcanvas = visualPanel.getGraphCanvas();
m_evalPanel = visualPanel.getEvalPanel();
m_logPanel = clusteringSetupTab.getLogPanel();
m_stream0 = clusteringSetupTab.getStream0();
m_stream0_decayHorizon = m_stream0.getDecayHorizon();
m_stream0_decay_threshold = m_stream0.getDecayThreshold();
m_stream0_decay_rate = (Math.log(1.0/m_stream0_decay_threshold)/Math.log(2)/m_stream0_decayHorizon);
timestamp = 0;
lastPauseTimestamp = 0;
work = true;
if(m_stream0 instanceof RandomRBFGeneratorEvents){
((RandomRBFGeneratorEvents)m_stream0).addClusterChangeListener(this);
clusterEvents = new ArrayList<ClusterEvent>();
m_graphcanvas.setClusterEventsList(clusterEvents);
}
m_stream0.prepareForUse();
m_clusterer0 = clusteringSetupTab.getClusterer0();
m_clusterer0.prepareForUse();
m_clusterer1 = clusteringSetupTab.getClusterer1();
if(m_clusterer1!=null){
m_clusterer1.prepareForUse();
}
m_measures0 = clusteringSetupTab.getMeasures();
m_measures1 = clusteringSetupTab.getMeasures();
/* TODO this option needs to move from the stream panel to the setup panel */
m_processFrequency = m_stream0.getEvaluationFrequency();
//get those values from the generator
int dims = m_stream0.numAttsOption.getValue();
visualPanel.setDimensionComobBoxes(dims);
visualPanel.setPauseInterval(initialPauseInterval);
m_evalPanel.setMeasures(m_measures0, m_measures1, this);
m_graphcanvas.setGraph(m_measures0[0], m_measures1[0],0,m_processFrequency);
}
public void run() {
runVisual();
}
public void runVisual() {
int processCounter = 0;
int speedCounter = 0;
LinkedList<DataPoint> pointBuffer0 = new LinkedList<DataPoint>();
LinkedList<DataPoint> pointBuffer1 = new LinkedList<DataPoint>();
ArrayList<DataPoint> pointarray0 = null;
ArrayList<DataPoint> pointarray1 = null;
while(work || processCounter!=0){
if (m_stream0.hasMoreInstances()) {
timestamp++;
speedCounter++;
processCounter++;
if(timestamp%100 == 0){
m_visualPanel.setProcessedPointsCounter(timestamp);
}
Instance next0 = m_stream0.nextInstance();
DataPoint point0 = new DataPoint(next0,timestamp);
pointBuffer0.add(point0);
while(pointBuffer0.size() > m_stream0_decayHorizon){
pointBuffer0.removeFirst();
}
DataPoint point1 = null;
if(m_clusterer1!=null){
point1 = new DataPoint(next0,timestamp);
pointBuffer1.add(point1);
while(pointBuffer1.size() > m_stream0_decayHorizon){
pointBuffer1.removeFirst();
}
}
if(m_visualPanel.isEnabledDrawPoints()){
m_streampanel0.drawPoint(point0);
if(m_clusterer1!=null)
m_streampanel1.drawPoint(point1);
if(processCounter%m_redrawInterval==0){
m_streampanel0.applyDrawDecay(m_stream0_decayHorizon/(float)(m_redrawInterval));
if(m_clusterer1!=null)
m_streampanel1.applyDrawDecay(m_stream0_decayHorizon/(float)(m_redrawInterval));
}
}
Instance traininst0 = new DenseInstance(point0);
if(m_clusterer0.keepClassLabel())
traininst0.setDataset(point0.dataset());
else
traininst0.deleteAttributeAt(point0.classIndex());
m_clusterer0.trainOnInstanceImpl(traininst0);
if(m_clusterer1!=null){
Instance traininst1 = new DenseInstance(point1);
if(m_clusterer1.keepClassLabel())
traininst1.setDataset(point1.dataset());
else
traininst1.deleteAttributeAt(point1.classIndex());
m_clusterer1.trainOnInstanceImpl(traininst1);
}
if (processCounter >= m_processFrequency) {
processCounter = 0;
for(DataPoint p:pointBuffer0)
p.updateWeight(timestamp, m_stream0_decay_rate);
pointarray0 = new ArrayList<DataPoint>(pointBuffer0);
if(m_clusterer1!=null){
for(DataPoint p:pointBuffer1)
p.updateWeight(timestamp, m_stream0_decay_rate);
pointarray1 = new ArrayList<DataPoint>(pointBuffer1);
}
processClusterings(pointarray0, pointarray1);
int pauseInterval = m_visualPanel.getPauseInterval();
if(pauseInterval!=0 && lastPauseTimestamp+pauseInterval<=timestamp){
m_visualPanel.toggleVisualizer(true);
}
}
} else {
System.out.println("DONE");
return;
}
if(speedCounter > m_wait_frequency*30 && m_wait_frequency < 15){
try {
synchronized (this) {
if(m_wait_frequency == 0)
wait(50);
else
wait(1);
}
} catch (InterruptedException ex) {
}
speedCounter = 0;
}
}
if(!stop){
m_streampanel0.drawPointPanels(pointarray0, timestamp, m_stream0_decay_rate, m_stream0_decay_threshold);
if(m_clusterer1!=null)
m_streampanel1.drawPointPanels(pointarray1, timestamp, m_stream0_decay_rate, m_stream0_decay_threshold);
work_pause();
}
}
private void processClusterings(ArrayList<DataPoint> points0, ArrayList<DataPoint> points1){
gtClustering0 = new Clustering(points0);
gtClustering1 = new Clustering(points1);
Clustering evalClustering0 = null;
Clustering evalClustering1 = null;
//special case for ClusterGenerator
if(gtClustering0!= null){
if(m_clusterer0 instanceof ClusterGenerator)
((ClusterGenerator)m_clusterer0).setSourceClustering(gtClustering0);
if(m_clusterer1 instanceof ClusterGenerator)
((ClusterGenerator)m_clusterer1).setSourceClustering(gtClustering1);
}
macro0 = m_clusterer0.getClusteringResult();
evalClustering0 = macro0;
//TODO: should we check if micro/macro is being drawn or needed for evaluation and skip otherwise to speed things up?
if(m_clusterer0.implementsMicroClusterer()){
micro0 = m_clusterer0.getMicroClusteringResult();
if(macro0 == null && micro0 != null){
//TODO: we need a Macro Clusterer Interface and the option for kmeans to use the non optimal centers
macro0 = moa.clusterers.KMeans.gaussianMeans(gtClustering0, micro0);
}
if(m_clusterer0.evaluateMicroClusteringOption.isSet())
evalClustering0 = micro0;
else
evalClustering0 = macro0;
}
if(m_clusterer1!=null){
macro1 = m_clusterer1.getClusteringResult();
evalClustering1 = macro1;
if(m_clusterer1.implementsMicroClusterer()){
micro1 = m_clusterer1.getMicroClusteringResult();
if(macro1 == null && micro1 != null){
macro1 = moa.clusterers.KMeans.gaussianMeans(gtClustering1, micro1);
}
if(m_clusterer1.evaluateMicroClusteringOption.isSet())
evalClustering1 = micro1;
else
evalClustering1 = macro1;
}
}
evaluateClustering(evalClustering0, gtClustering0, points0, true);
evaluateClustering(evalClustering1, gtClustering1, points1, false);
drawClusterings(points0, points1);
}
private void evaluateClustering(Clustering found_clustering, Clustering trueClustering, ArrayList<DataPoint> points, boolean algorithm0){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < m_measures0.length; i++) {
if(algorithm0){
if(found_clustering!=null && found_clustering.size() > 0){
try {
double msec = m_measures0[i].evaluateClusteringPerformance(found_clustering, trueClustering, points);
sb.append(m_measures0[i].getClass().getSimpleName()+" took "+msec+"ms (Mean:"+m_measures0[i].getMeanRunningTime()+")");
sb.append("\n");
} catch (Exception ex) { ex.printStackTrace(); }
}
else{
for(int j = 0; j < m_measures0[i].getNumMeasures(); j++){
m_measures0[i].addEmptyValue(j);
}
}
}
else{
if(m_clusterer1!=null && found_clustering!=null && found_clustering.size() > 0){
try {
double msec = m_measures1[i].evaluateClusteringPerformance(found_clustering, trueClustering, points);
sb.append(m_measures1[i].getClass().getSimpleName()+" took "+msec+"ms (Mean:"+m_measures1[i].getMeanRunningTime()+")");
sb.append("\n");
}
catch (Exception ex) { ex.printStackTrace(); }
}
else{
for(int j = 0; j < m_measures1[i].getNumMeasures(); j++){
m_measures1[i].addEmptyValue(j);
}
}
}
}
m_logPanel.setText(sb.toString());
m_evalPanel.update();
m_graphcanvas.updateCanvas();
}
public void drawClusterings(List<DataPoint> points0, List<DataPoint> points1){
if(macro0!= null && macro0.size() > 0)
m_streampanel0.drawMacroClustering(macro0, points0, Color.RED);
if(micro0!= null && micro0.size() > 0)
m_streampanel0.drawMicroClustering(micro0, points0, Color.GREEN);
if(gtClustering0!= null && gtClustering0.size() > 0)
m_streampanel0.drawGTClustering(gtClustering0, points0, Color.BLACK);
if(m_clusterer1!=null){
if(macro1!= null && macro1.size() > 0)
m_streampanel1.drawMacroClustering(macro1, points1, Color.BLUE);
if(micro1!= null && micro1.size() > 0)
m_streampanel1.drawMicroClustering(micro1, points1, Color.GREEN);
if(gtClustering1!= null && gtClustering1.size() > 0)
m_streampanel1.drawGTClustering(gtClustering1, points1, Color.BLACK);
}
}
public void redraw(){
m_streampanel0.repaint();
m_streampanel1.repaint();
}
public static int getCurrentTimestamp(){
return timestamp;
}
private void work_pause(){
while(!work && !stop){
try {
synchronized (this) {
wait(1000);
}
} catch (InterruptedException ex) {
}
}
run();
}
public static void pause(){
work = false;
lastPauseTimestamp = timestamp;
}
public static void resume(){
work = true;
}
public void stop(){
work = false;
stop = true;
}
public void setSpeed(int speed) {
m_wait_frequency = speed;
}
public void actionPerformed(ActionEvent e) {
//reacte on graph selection and find out which measure was selected
int selected = Integer.parseInt(e.getActionCommand());
int counter = selected;
int m_select = 0;
int m_select_offset = 0;
boolean found = false;
for (int i = 0; i < m_measures0.length; i++) {
for (int j = 0; j < m_measures0[i].getNumMeasures(); j++) {
if(m_measures0[i].isEnabled(j)){
counter--;
if(counter<0){
m_select = i;
m_select_offset = j;
found = true;
break;
}
}
}
if(found) break;
}
m_graphcanvas.setGraph(m_measures0[m_select], m_measures1[m_select],m_select_offset,m_processFrequency);
}
public void setPointLayerVisibility(boolean selected) {
m_streampanel0.setPointVisibility(selected);
m_streampanel1.setPointVisibility(selected);
}
public void setMicroLayerVisibility(boolean selected) {
m_streampanel0.setMicroLayerVisibility(selected);
m_streampanel1.setMicroLayerVisibility(selected);
}
public void setMacroVisibility(boolean selected) {
m_streampanel0.setMacroLayerVisibility(selected);
m_streampanel1.setMacroLayerVisibility(selected);
}
public void setGroundTruthVisibility(boolean selected) {
m_streampanel0.setGroundTruthLayerVisibility(selected);
m_streampanel1.setGroundTruthLayerVisibility(selected);
}
public void changeCluster(ClusterEvent e) {
if(clusterEvents!=null) clusterEvents.add(e);
System.out.println(e.getType()+": "+e.getMessage());
}
public void exportCSV(String filepath) {
PrintWriter out = null;
try {
if(!filepath.endsWith(".csv"))
filepath+=".csv";
out = new PrintWriter(new BufferedWriter(new FileWriter(filepath)));
String del = ";";
Iterator<ClusterEvent> eventIt = null;
ClusterEvent event = null;
if(clusterEvents!=null && clusterEvents.size() > 0){
eventIt = clusterEvents.iterator();
event = eventIt.next();
}
//raw data
MeasureCollection measurecol[][] = new MeasureCollection[2][];
measurecol[0] = m_measures0;
measurecol[1] = m_measures1;
int numValues = 0;
//header
out.write("Nr"+del);
out.write("Event"+del);
for (int m = 0; m < 2; m++) {
for (int i = 0; i < measurecol[m].length; i++) {
for (int j = 0; j < measurecol[m][i].getNumMeasures(); j++) {
if(measurecol[m][i].isEnabled(j)){
out.write(m+"-"+measurecol[m][i].getName(j)+del);
numValues = measurecol[m][i].getNumberOfValues(j);
}
}
}
}
out.write("\n");
//rows
for (int v = 0; v < numValues; v++){
//Nr
out.write(v+del);
//events
if(event!=null && event.getTimestamp()<=m_stream0_decayHorizon*v){
out.write(event.getType()+del);
if(eventIt!= null && eventIt.hasNext()){
event=eventIt.next();
}
else
event = null;
}
else
out.write(del);
//values
for (int m = 0; m < 2; m++) {
for (int i = 0; i < measurecol[m].length; i++) {
for (int j = 0; j < measurecol[m][i].getNumMeasures(); j++) {
if(measurecol[m][i].isEnabled(j)){
double value = measurecol[m][i].getValue(j, v);
if(Double.isNaN(value))
out.write(del);
else
out.write(value+del);
}
}
}
}
out.write("\n");
}
out.close();
} catch (IOException ex) {
Logger.getLogger(RunVisualizer.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
public void weka() {
try{
Class.forName("weka.gui.Logger");
}
catch (Exception e){
m_logPanel.addText("Please add weka.jar to the classpath to use the Weka explorer.");
return;
}
Clustering wekaClustering;
if(m_clusterer0.implementsMicroClusterer() && m_clusterer0.evaluateMicroClusteringOption.isSet())
wekaClustering = micro0;
else
wekaClustering = macro0;
if(wekaClustering == null || wekaClustering.size()==0){
m_logPanel.addText("Empty Clustering");
return;
}
int dims = wekaClustering.get(0).getCenter().length;
FastVector attributes = new FastVector();
for(int i = 0; i < dims; i++)
attributes.addElement( new Attribute("att" + i) );
Instances instances = new Instances("trainset",attributes,0);
for(int c = 0; c < wekaClustering.size(); c++){
Cluster cluster = wekaClustering.get(c);
Instance inst = new DenseInstance(cluster.getWeight(), cluster.getCenter());
inst.setDataset(instances);
instances.add(inst);
}
WekaExplorer explorer = new WekaExplorer(instances);
}
}
| Java |
/*
* FileExtensionFilter.java
* Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package moa.gui;
import java.io.File;
import javax.swing.filechooser.FileFilter;
/**
* A filter that is used to restrict the files that are shown.
*
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision: 7 $
*/
public class FileExtensionFilter extends FileFilter {
protected String fileExtension;
public FileExtensionFilter(String extension) {
this.fileExtension = extension.toLowerCase();
}
@Override
public boolean accept(File f) {
if (f != null) {
if (f.isDirectory()) {
return true;
}
return (f.getName().toLowerCase().endsWith("." + this.fileExtension));
}
return false;
}
@Override
public String getDescription() {
return ("*." + this.fileExtension);
}
}
| Java |
/*
* OutlierVisualTab.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.outliertab;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.io.File;
import javax.swing.*;
import moa.gui.FileExtensionFilter;
import moa.gui.visualization.GraphCanvas;
import moa.gui.visualization.RunOutlierVisualizer;
import moa.gui.visualization.StreamOutlierPanel;
public class OutlierVisualTab extends javax.swing.JPanel implements ActionListener, ComponentListener{
private RunOutlierVisualizer visualizer = null;
private Thread visualizerThread = null;
private Boolean running = false;
private OutlierSetupTab outlierSetupTab = null;
private String exportFile;
private String screenshotFilebase;
/** Creates new form OutlierVisualTab */
public OutlierVisualTab() {
resetComponents();
}
private void resetComponents(){
initComponents();
comboY.setSelectedIndex(1);
graphCanvas.setViewport(graphScrollPanel.getViewport());
//TODO this needs to only affect the visual Panel
ToolTipManager.sharedInstance().setDismissDelay(20000);
ToolTipManager.sharedInstance().setInitialDelay(100);
}
public void setOutlierSetupTab(OutlierSetupTab outlierSetupTab){
this.outlierSetupTab = outlierSetupTab;
}
private void createVisualiterThread(){
visualizer = new RunOutlierVisualizer(this, outlierSetupTab);
visualizerThread = new Thread(visualizer);
}
public void setDimensionComobBoxes(int numDimensions){
String[] dimensions = new String[numDimensions];
for (int i = 0; i < dimensions.length; i++) {
dimensions[i] = "Dim "+(i+1);
}
comboX.setModel(new javax.swing.DefaultComboBoxModel(dimensions));
comboY.setModel(new javax.swing.DefaultComboBoxModel(dimensions));
comboY.setSelectedIndex(1);
}
public StreamOutlierPanel getLeftStreamPanel(){
return streamPanel0;
}
public StreamOutlierPanel getRightStreamPanel(){
return streamPanel1;
}
public GraphCanvas getGraphCanvas(){
return graphCanvas;
}
public OutlierVisualEvalPanel getEvalPanel(){
return null;
}
public boolean isEnabledDrawPoints(){
return checkboxDrawPoints.isSelected();
}
public boolean isEnabledDrawOutliers(){
return checkboxDrawOutliers.isSelected();
}
public void setProcessedPointsCounter(int value){
label_processed_points_value.setText(Integer.toString(value));
}
public int getPauseInterval(){
return Integer.parseInt(numPauseAfterPoints.getText());
}
public void setPauseInterval(int pause){
numPauseAfterPoints.setText(Integer.toString(pause));
}
private void UpdateSplitVisualDivider() {
if(splitVisual != null)
splitVisual.setDividerLocation(splitVisual.getWidth()/2);
}
@Override
public void repaint() {
super.repaint();
UpdateSplitVisualDivider();
}
@Override
public void componentResized(ComponentEvent ce) {
}
@Override
public void componentMoved(ComponentEvent ce) {
}
@Override
public void componentShown(ComponentEvent ce) {
}
@Override
public void componentHidden(ComponentEvent ce) {
}
public void toggleVisualizer(boolean internal){
if(visualizer == null)
createVisualiterThread();
if(!visualizerThread.isAlive()){
visualizerThread.start();
}
//pause
if(running){
running = false;
visualizer.pause();
buttonRun.setText("Resume");
}
else{
running = true;
visualizer.resume();
buttonRun.setText("Pause");
}
if(internal)
outlierSetupTab.toggleRunMode();
}
public void stopVisualizer(){
if (visualizer == null) return;
visualizer.stop();
running = false;
visualizer = null;
visualizerThread = null;
removeAll();
resetComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jSplitPane1 = new javax.swing.JSplitPane();
topWrapper = new javax.swing.JPanel();
panelVisualWrapper = new javax.swing.JPanel();
splitVisual = new javax.swing.JSplitPane();
scrollPane1 = new javax.swing.JScrollPane();
scrollPane0 = new javax.swing.JScrollPane();
streamPanel0 = new moa.gui.visualization.StreamOutlierPanel(Color.RED);
streamPanel1 = new moa.gui.visualization.StreamOutlierPanel(Color.BLUE);
panelControl = new javax.swing.JPanel();
buttonRun = new javax.swing.JButton();
buttonStop = new javax.swing.JButton();
buttonRedraw = new javax.swing.JButton();
buttonScreenshot = new javax.swing.JButton();
speedSlider = new javax.swing.JSlider();
jLabel1 = new javax.swing.JLabel();
comboX = new javax.swing.JComboBox();
labelX = new javax.swing.JLabel();
comboY = new javax.swing.JComboBox();
labelY = new javax.swing.JLabel();
checkboxDrawPoints = new javax.swing.JCheckBox();
checkboxDrawOutliers = new javax.swing.JCheckBox();
checkboxWaitWinFull = new javax.swing.JCheckBox();
label_processed_points = new javax.swing.JLabel();
label_processed_points_value = new javax.swing.JLabel();
labelNumPause = new javax.swing.JLabel();
numPauseAfterPoints = new javax.swing.JTextField();
panelEvalOutput = new javax.swing.JPanel();
// outlierVisualEvalPanel1 = new moa.gui.outliertab.OutlierVisualEvalPanel();
graphPanel = new javax.swing.JPanel();
graphPanelControlTop = new javax.swing.JPanel();
buttonZoomInY = new javax.swing.JButton();
buttonZoomOutY = new javax.swing.JButton();
labelEvents = new javax.swing.JLabel();
graphScrollPanel = new javax.swing.JScrollPane();
graphCanvas = new moa.gui.visualization.GraphCanvas();
graphPanelControlBottom = new javax.swing.JPanel();
buttonZoomInX = new javax.swing.JButton();
buttonZoomOutX = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
jSplitPane1.setDividerLocation(400);
jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
topWrapper.setPreferredSize(new java.awt.Dimension(688, 500));
topWrapper.setLayout(new java.awt.GridBagLayout());
//panelVisualWrapper.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
panelVisualWrapper.setLayout(new java.awt.BorderLayout());
splitVisual.setDividerLocation(400);
splitVisual.setResizeWeight(1.0);
scrollPane0.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
scrollPane0MouseWheelMoved(evt);
}
});
streamPanel1.setPreferredSize(new java.awt.Dimension(400, 250));
javax.swing.GroupLayout streamPanel1Layout = new javax.swing.GroupLayout(streamPanel1);
streamPanel1.setLayout(streamPanel1Layout);
streamPanel1Layout.setHorizontalGroup(
streamPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 428, Short.MAX_VALUE)
);
streamPanel1Layout.setVerticalGroup(
streamPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 339, Short.MAX_VALUE)
);
scrollPane1.setViewportView(streamPanel1);
splitVisual.setRightComponent(scrollPane1);
scrollPane0.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
scrollPane0MouseWheelMoved(evt);
}
});
streamPanel0.setPreferredSize(new java.awt.Dimension(400, 250));
javax.swing.GroupLayout streamPanel0Layout = new javax.swing.GroupLayout(streamPanel0);
streamPanel0.setLayout(streamPanel0Layout);
streamPanel0Layout.setHorizontalGroup(
streamPanel0Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
streamPanel0Layout.setVerticalGroup(
streamPanel0Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 339, Short.MAX_VALUE)
);
scrollPane0.setViewportView(streamPanel0);
splitVisual.setLeftComponent(scrollPane0);
splitVisual.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent ce) {
UpdateSplitVisualDivider();
}
@Override
public void componentMoved(ComponentEvent ce) {
}
@Override
public void componentShown(ComponentEvent ce) {
}
@Override
public void componentHidden(ComponentEvent ce) {
}
});
panelVisualWrapper.add(splitVisual, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = java.awt.GridBagConstraints.RELATIVE;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.ipadx = 400;
gridBagConstraints.ipady = 200;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
topWrapper.add(panelVisualWrapper, gridBagConstraints);
panelControl.setMinimumSize(new java.awt.Dimension(600, 76));
panelControl.setPreferredSize(new java.awt.Dimension(2000, 76));
panelControl.setLayout(new java.awt.GridBagLayout());
int iBtnHeight = 27;
int iInsetW = 2;
int iInsetH = 2;
buttonRun.setText("Start");
buttonRun.setMinimumSize(new java.awt.Dimension(90, iBtnHeight));
buttonRun.setPreferredSize(new java.awt.Dimension(90, iBtnHeight));
buttonRun.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
buttonRunMouseClicked(evt);
}
});
buttonRun.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRunActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(iInsetW, iInsetH, iInsetW, iInsetH);
panelControl.add(buttonRun, gridBagConstraints);
buttonStop.setText("Stop");
buttonStop.setMinimumSize(new java.awt.Dimension(90, iBtnHeight));
buttonStop.setPreferredSize(new java.awt.Dimension(90, iBtnHeight));
buttonStop.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonStopActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(iInsetW, iInsetH, iInsetW, iInsetH);
panelControl.add(buttonStop, gridBagConstraints);
buttonRedraw.setText("Redraw");
buttonRedraw.setMinimumSize(new java.awt.Dimension(100, iBtnHeight));
buttonRedraw.setPreferredSize(new java.awt.Dimension(100, iBtnHeight));
buttonRedraw.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
buttonRedrawMouseClicked(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(iInsetW, iInsetH, iInsetW, iInsetH);
panelControl.add(buttonRedraw, gridBagConstraints);
buttonScreenshot.setText("Screenshot");
buttonScreenshot.setMinimumSize(new java.awt.Dimension(100, iBtnHeight));
buttonScreenshot.setPreferredSize(new java.awt.Dimension(100, iBtnHeight));
buttonScreenshot.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
buttonScreenshotMouseClicked(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(iInsetW, iInsetH, iInsetW, iInsetH);
panelControl.add(buttonScreenshot, gridBagConstraints);
speedSlider.setValue(100);
speedSlider.setBorder(javax.swing.BorderFactory.createTitledBorder("Visualisation Speed"));
speedSlider.setMinimumSize(new java.awt.Dimension(160, 68));
speedSlider.setPreferredSize(new java.awt.Dimension(170, 68));
speedSlider.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseDragged(java.awt.event.MouseEvent evt) {
speedSliderMouseDragged(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 6;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.insets = new java.awt.Insets(0, 16, 1, 5);
panelControl.add(speedSlider, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 9;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
panelControl.add(jLabel1, gridBagConstraints);
comboX.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Dim 1", "Dim 2", "Dim 3", "Dim 4" }));
comboX.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboXActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
panelControl.add(comboX, gridBagConstraints);
labelX.setText("X");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 14, 0, 5);
panelControl.add(labelX, gridBagConstraints);
comboY.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Dim 1", "Dim 2", "Dim 3", "Dim 4" }));
comboY.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboYActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
panelControl.add(comboY, gridBagConstraints);
labelY.setText("Y");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(0, 14, 0, 5);
panelControl.add(labelY, gridBagConstraints);
checkboxDrawPoints.setSelected(true);
checkboxDrawPoints.setText("Points");
checkboxDrawPoints.setMargin(new java.awt.Insets(0, 0, 0, 0));
checkboxDrawPoints.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkboxDrawPointsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
panelControl.add(checkboxDrawPoints, gridBagConstraints);
checkboxDrawOutliers.setSelected(true);
checkboxDrawOutliers.setText("Outliers");
checkboxDrawOutliers.setMargin(new java.awt.Insets(0, 0, 0, 0));
checkboxDrawOutliers.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkboxDrawOutlierActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
panelControl.add(checkboxDrawOutliers, gridBagConstraints);
checkboxWaitWinFull.setSelected(true);
checkboxWaitWinFull.setText("WaitWinFull");
checkboxWaitWinFull.setMargin(new java.awt.Insets(0, 0, 0, 0));
checkboxWaitWinFull.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkboxWaitWinFullActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 1;
gridBagConstraints.gridheight = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.CENTER;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 0);
panelControl.add(checkboxWaitWinFull, gridBagConstraints);
label_processed_points.setText("Processed:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
panelControl.add(label_processed_points, gridBagConstraints);
label_processed_points_value.setText("0");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 8;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
panelControl.add(label_processed_points_value, gridBagConstraints);
labelNumPause.setText("Pause in:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
panelControl.add(labelNumPause, gridBagConstraints);
numPauseAfterPoints.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
numPauseAfterPoints.setText(Integer.toString(RunOutlierVisualizer.initialPauseInterval));
numPauseAfterPoints.setMinimumSize(new java.awt.Dimension(70, 25));
numPauseAfterPoints.setPreferredSize(new java.awt.Dimension(70, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 8;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
panelControl.add(numPauseAfterPoints, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
topWrapper.add(panelControl, gridBagConstraints);
jSplitPane1.setLeftComponent(topWrapper);
panelEvalOutput.setBorder(javax.swing.BorderFactory.createTitledBorder("Evaluation"));
panelEvalOutput.setLayout(new java.awt.GridBagLayout());
graphPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Process time per object"));
graphPanel.setPreferredSize(new java.awt.Dimension(530, 115));
graphPanel.setLayout(new java.awt.GridBagLayout());
graphPanelControlTop.setLayout(new java.awt.GridBagLayout());
buttonZoomInY.setText("Zoom in Y");
buttonZoomInY.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomInYActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
graphPanelControlTop.add(buttonZoomInY, gridBagConstraints);
buttonZoomOutY.setText("Zoom out Y");
buttonZoomOutY.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomOutYActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
graphPanelControlTop.add(buttonZoomOutY, gridBagConstraints);
labelEvents.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2);
graphPanelControlTop.add(labelEvents, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
graphPanel.add(graphPanelControlTop, gridBagConstraints);
graphCanvas.setPreferredSize(new java.awt.Dimension(500, 111));
javax.swing.GroupLayout graphCanvasLayout = new javax.swing.GroupLayout(graphCanvas);
graphCanvas.setLayout(graphCanvasLayout);
graphCanvasLayout.setHorizontalGroup(
graphCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 515, Short.MAX_VALUE)
);
graphCanvasLayout.setVerticalGroup(
graphCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 128, Short.MAX_VALUE)
);
graphScrollPanel.setViewportView(graphCanvas);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
graphPanel.add(graphScrollPanel, gridBagConstraints);
buttonZoomInX.setText("Zoom in X");
buttonZoomInX.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomInXActionPerformed(evt);
}
});
graphPanelControlBottom.add(buttonZoomInX);
buttonZoomOutX.setText("Zoom out X");
buttonZoomOutX.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonZoomOutXActionPerformed(evt);
}
});
graphPanelControlBottom.add(buttonZoomOutX);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
graphPanel.add(graphPanelControlBottom, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 2.0;
gridBagConstraints.weighty = 1.0;
panelEvalOutput.add(graphPanel, gridBagConstraints);
panelEvalOutput.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent ce) {
//System.out.println("panelEvalOutput componentResized");
graphCanvas.updateCanvas(true);
}
@Override
public void componentMoved(ComponentEvent ce) {
}
@Override
public void componentShown(ComponentEvent ce) {
}
@Override
public void componentHidden(ComponentEvent ce) {
}
});
jSplitPane1.setRightComponent(panelEvalOutput);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jSplitPane1, gridBagConstraints);
//add(topWrapper, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void buttonRedrawMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonRedrawMouseClicked
if (visualizer != null)
visualizer.redraw();
}//GEN-LAST:event_buttonScreenshotMouseClicked
private void buttonScreenshotMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonScreenshotMouseClicked
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
if(screenshotFilebase!=null)
fileChooser.setSelectedFile(new File(screenshotFilebase));
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
screenshotFilebase = fileChooser.getSelectedFile().getPath();
streamPanel0.screenshot(screenshotFilebase+"_"+label_processed_points_value.getText()+"_0", true, true);
}
}//GEN-LAST:event_buttonScreenshotMouseClicked
private void buttonRunMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonRunMouseClicked
toggleVisualizer(true);
}//GEN-LAST:event_buttonRunMouseClicked
private void speedSliderMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_speedSliderMouseDragged
if (speedSlider == null) return;
if (visualizer == null) return;
visualizer.setSpeed(speedSlider.getValue());
}//GEN-LAST:event_speedSliderMouseDragged
public int GetSpeed() {
return speedSlider.getValue();
}
private void scrollPane0MouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_scrollPane0MouseWheelMoved
streamPanel0.setZoom(evt.getX(),evt.getY(),(-1)*evt.getWheelRotation(),scrollPane0);
}//GEN-LAST:event_scrollPane0MouseWheelMoved
private void buttonZoomInXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomInXActionPerformed
graphCanvas.scaleXResolution(false);
graphCanvas.updateCanvas(true);
}//GEN-LAST:event_buttonZoomInXActionPerformed
private void buttonZoomOutYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomOutYActionPerformed
graphCanvas.setSize(new Dimension(graphCanvas.getWidth(), (int)(graphCanvas.getHeight()*0.8)));
graphCanvas.setPreferredSize(new Dimension(graphCanvas.getWidth(), (int)(graphCanvas.getHeight()*0.8)));
graphCanvas.updateCanvas(true);
}//GEN-LAST:event_buttonZoomOutYActionPerformed
private void buttonZoomOutXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomOutXActionPerformed
graphCanvas.scaleXResolution(true);
graphCanvas.updateCanvas(true);
}//GEN-LAST:event_buttonZoomOutXActionPerformed
private void buttonZoomInYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonZoomInYActionPerformed
graphCanvas.setSize(new Dimension(graphCanvas.getWidth(), (int)(graphCanvas.getHeight()*1.2)));
graphCanvas.setPreferredSize(new Dimension(graphCanvas.getWidth(), (int)(graphCanvas.getHeight()*1.2)));
graphCanvas.updateCanvas(true);
}//GEN-LAST:event_buttonZoomInYActionPerformed
public boolean getPointVisibility() {
return checkboxDrawPoints.isSelected();
}
public boolean getOutliersVisibility() {
return checkboxDrawOutliers.isSelected();
}
private void checkboxDrawPointsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkboxDrawPointsActionPerformed
if (visualizer == null) return;
visualizer.setPointsVisibility(checkboxDrawPoints.isSelected());
}//GEN-LAST:event_checkboxDrawPointsActionPerformed
private void checkboxDrawOutlierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkboxDrawOutlierActionPerformed
if (visualizer == null) return;
if (running) {
// outliers layer is hidden when running
return;
}
// visualizer.redrawOutliers();
visualizer.setOutliersVisibility(checkboxDrawOutliers.isSelected());
}//GEN-LAST:event_checkboxDrawOutlierActionPerformed
public boolean getWaitWinFull() {
return checkboxWaitWinFull.isSelected();
}
private void checkboxWaitWinFullActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkboxWaitWinFullActionPerformed
if (visualizer == null) return;
visualizer.setWaitWinFull(checkboxWaitWinFull.isSelected());
}//GEN-LAST:checkboxWaitWinFullActionPerformed
private void comboXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboXActionPerformed
if (visualizer == null) return;
JComboBox cb = (JComboBox)evt.getSource();
int dim = cb.getSelectedIndex();
streamPanel0.setActiveXDim(dim);
streamPanel1.setActiveXDim(dim);
if(visualizer!=null)
visualizer.redraw();
}//GEN-LAST:event_comboXActionPerformed
private void comboYActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboYActionPerformed
if (visualizer == null) return;
JComboBox cb = (JComboBox)evt.getSource();
int dim = cb.getSelectedIndex();
streamPanel0.setActiveYDim(dim);
streamPanel1.setActiveYDim(dim);
if(visualizer!=null)
visualizer.redraw();
}//GEN-LAST:event_comboYActionPerformed
private void buttonStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStopActionPerformed
stopVisualizer();
outlierSetupTab.stopRun();
}//GEN-LAST:event_buttonStopActionPerformed
private void buttonRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRunActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_buttonRunActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonRun;
private javax.swing.JButton buttonScreenshot;
private javax.swing.JButton buttonRedraw;
private javax.swing.JButton buttonStop;
private javax.swing.JButton buttonZoomInX;
private javax.swing.JButton buttonZoomInY;
private javax.swing.JButton buttonZoomOutX;
private javax.swing.JButton buttonZoomOutY;
private javax.swing.JCheckBox checkboxDrawOutliers;
private javax.swing.JCheckBox checkboxDrawPoints;
private javax.swing.JCheckBox checkboxWaitWinFull;
// ### private moa.gui.outliertab.OutlierVisualEvalPanel outlierVisualEvalPanel1;
private javax.swing.JComboBox comboX;
private javax.swing.JComboBox comboY;
private moa.gui.visualization.GraphCanvas graphCanvas;
private javax.swing.JPanel graphPanel;
private javax.swing.JPanel graphPanelControlBottom;
private javax.swing.JPanel graphPanelControlTop;
private javax.swing.JScrollPane graphScrollPanel;
private javax.swing.JLabel jLabel1;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JLabel labelEvents;
private javax.swing.JLabel labelNumPause;
private javax.swing.JLabel labelX;
private javax.swing.JLabel labelY;
private javax.swing.JLabel label_processed_points;
private javax.swing.JLabel label_processed_points_value;
private javax.swing.JTextField numPauseAfterPoints;
private javax.swing.JPanel panelControl;
private javax.swing.JPanel panelEvalOutput;
private javax.swing.JPanel panelVisualWrapper;
private javax.swing.JScrollPane scrollPane0;
private javax.swing.JScrollPane scrollPane1;
private javax.swing.JSlider speedSlider;
private javax.swing.JSplitPane splitVisual;
private moa.gui.visualization.StreamOutlierPanel streamPanel0;
private moa.gui.visualization.StreamOutlierPanel streamPanel1;
private javax.swing.JPanel topWrapper;
// End of variables declaration//GEN-END:variables
@Override
public void actionPerformed(ActionEvent e) {
if (visualizer == null) return;
if(e.getSource() instanceof JButton){
if(e.getActionCommand().equals("csv export")){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(new FileExtensionFilter("csv"));
if(exportFile!=null)
fileChooser.setSelectedFile(new File(exportFile));
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
exportFile = fileChooser.getSelectedFile().getPath();
visualizer.exportCSV(exportFile);
}
}
if(e.getActionCommand().equals("weka export")){
visualizer.weka();
}
}
}
}
| Java |
/*
* OutlierTabPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.outliertab;
import moa.gui.AbstractTabPanel;
public class OutlierTabPanel extends AbstractTabPanel{
/** Creates new form ClusterTab */
public OutlierTabPanel() {
initComponents();
outlierVisualTab.setOutlierSetupTab(outlierSetupTab);
outlierSetupTab.addButtonActionListener(outlierVisualTab);
outlierSetupTab.setOutlierTab(this);
}
void toggle() {
outlierVisualTab.toggleVisualizer(false);
}
void stop() {
outlierVisualTab.stopVisualizer();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
outlierSetupTab = new moa.gui.outliertab.OutlierSetupTab();
outlierVisualTab = new moa.gui.outliertab.OutlierVisualTab();
setLayout(new java.awt.BorderLayout());
jTabbedPane1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTabbedPane1MouseClicked(evt);
}
});
jTabbedPane1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTabbedPane1FocusGained(evt);
}
});
jTabbedPane1.addTab("Setup", outlierSetupTab);
jTabbedPane1.addTab("Visualization", outlierVisualTab);
add(jTabbedPane1, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void jTabbedPane1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTabbedPane1FocusGained
}//GEN-LAST:event_jTabbedPane1FocusGained
private void jTabbedPane1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTabbedPane1MouseClicked
}//GEN-LAST:event_jTabbedPane1MouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private moa.gui.outliertab.OutlierSetupTab outlierSetupTab;
private moa.gui.outliertab.OutlierVisualTab outlierVisualTab;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration//GEN-END:variables
//returns the string to display as title of the tab
public String getTabTitle() {
return "Outliers";
}
//a short description (can be used as tool tip) of the tab, or contributor, etc.
public String getDescription(){
return "MOA Outliers";
}
}
| Java |
/*
* OutlierAlgoPanel.java
* Copyright (C) 2013 Aristotle University of Thessaloniki, Greece
* @author D. Georgiadis, A. Gounaris, A. Papadopoulos, K. Tsichlas, Y. Manolopoulos
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.outliertab;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import moa.clusterers.outliers.MyBaseOutlierDetector;
import moa.gui.GUIUtils;
import moa.gui.OptionEditComponent;
import moa.options.ClassOption;
import moa.options.Option;
import moa.streams.clustering.ClusteringStream;
public class OutlierAlgoPanel extends javax.swing.JPanel implements ActionListener{
protected List<OptionEditComponent> editComponents = new LinkedList<OptionEditComponent>();
private ClassOption streamOption = new ClassOption("Stream", 's',
"", ClusteringStream.class,
"RandomRBFGeneratorEvents");
private ClassOption algorithmOption0 = new ClassOption("Algorithm0", 'a',
"Algorithm to use.", MyBaseOutlierDetector.class, "MCOD.MCOD");
private ClassOption algorithmOption1 = new ClassOption("Algorithm1", 'a',
"Algorithm to use.", MyBaseOutlierDetector.class, "Angiulli.ExactSTORM");
public OutlierAlgoPanel() {
initComponents();
}
public void renderAlgoPanel(){
setLayout(new BorderLayout());
ArrayList<Option> options = new ArrayList<Option>();
options.add(streamOption);
options.add(algorithmOption0);
options.add(algorithmOption1);
JPanel optionsPanel = new JPanel();
GridBagLayout gbLayout = new GridBagLayout();
optionsPanel.setLayout(gbLayout);
//Create generic label constraints
GridBagConstraints gbcLabel = new GridBagConstraints();
gbcLabel.gridx = 0;
gbcLabel.fill = GridBagConstraints.NONE;
gbcLabel.anchor = GridBagConstraints.EAST;
gbcLabel.weightx = 0;
gbcLabel.insets = new Insets(5, 5, 5, 5);
//Create generic editor constraints
GridBagConstraints gbcOption = new GridBagConstraints();
gbcOption.gridx = 1;
gbcOption.fill = GridBagConstraints.HORIZONTAL;
gbcOption.anchor = GridBagConstraints.CENTER;
gbcOption.weightx = 1;
gbcOption.insets = new Insets(5, 5, 5, 0);
//Stream Option
JLabel labelStream = new JLabel("Stream");
labelStream.setToolTipText("Stream to use.");
optionsPanel.add(labelStream, gbcLabel);
JComponent editorStream = streamOption.getEditComponent();
labelStream.setLabelFor(editorStream);
editComponents.add((OptionEditComponent) editorStream);
optionsPanel.add(editorStream, gbcOption);
//Algorithm0 Option
JLabel labelAlgo0 = new JLabel("Algorithm1");
labelAlgo0.setForeground(Color.RED);
labelAlgo0.setToolTipText("Algorithm to use.");
optionsPanel.add(labelAlgo0, gbcLabel);
JComponent editorAlgo0 = algorithmOption0.getEditComponent();
labelAlgo0.setLabelFor(editorAlgo0);
editComponents.add((OptionEditComponent) editorAlgo0);
optionsPanel.add(editorAlgo0, gbcOption);
//Algorithm1 Option
JLabel labelAlgo1 = new JLabel("Algorithm2");
labelAlgo1.setForeground(Color.BLUE);
labelAlgo1.setToolTipText("Algorithm to use.");
optionsPanel.add(labelAlgo1, gbcLabel);
JComponent editorAlgo1 = algorithmOption1.getEditComponent();
labelAlgo1.setLabelFor(editorAlgo1);
editComponents.add((OptionEditComponent) editorAlgo1);
optionsPanel.add(editorAlgo1, gbcOption);
//use comparison Algorithm Option
GridBagConstraints gbcClearButton = new GridBagConstraints();
gbcClearButton.gridx = 2;
gbcClearButton.gridy = 2;
gbcClearButton.fill = GridBagConstraints.NONE;
gbcClearButton.anchor = GridBagConstraints.CENTER;
gbcClearButton.insets = new Insets(5, 0, 5, 5);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setActionCommand("clear");
optionsPanel.add(clearButton, gbcClearButton);
add(optionsPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("clear")){
algorithmOption1.setValueViaCLIString("None");
editComponents.get(2).setEditState("None");
}
}
public MyBaseOutlierDetector getClusterer0(){
MyBaseOutlierDetector c = null;
applyChanges();
try {
c = (MyBaseOutlierDetector) ClassOption.cliStringToObject(algorithmOption0.getValueAsCLIString(), MyBaseOutlierDetector.class, null);
} catch (Exception ex) {
Logger.getLogger(OutlierAlgoPanel.class.getName()).log(Level.SEVERE, null, ex);
}
return c;
}
public MyBaseOutlierDetector getClusterer1(){
MyBaseOutlierDetector c = null;
if (algorithmOption1.getValueAsCLIString().equalsIgnoreCase("None") == false) {
applyChanges();
try {
c = (MyBaseOutlierDetector) ClassOption.cliStringToObject(algorithmOption1.getValueAsCLIString(), MyBaseOutlierDetector.class, null);
} catch (Exception ex) {
Logger.getLogger(OutlierAlgoPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
return c;
}
public ClusteringStream getStream(){
ClusteringStream s = null;
applyChanges();
try {
s = (ClusteringStream) ClassOption.cliStringToObject(streamOption.getValueAsCLIString(), ClusteringStream.class, null);
} catch (Exception ex) {
Logger.getLogger(OutlierAlgoPanel.class.getName()).log(Level.SEVERE, null, ex);
}
return s;
}
public String getStreamValueAsCLIString(){
applyChanges();
return streamOption.getValueAsCLIString();
}
public String getAlgorithm0ValueAsCLIString(){
applyChanges();
return algorithmOption0.getValueAsCLIString();
}
public String getAlgorithm1ValueAsCLIString(){
applyChanges();
return algorithmOption1.getValueAsCLIString();
}
/* We need to fetch the right item from editComponents list, index needs to match GUI order */
public void setStreamValueAsCLIString(String s){
streamOption.setValueViaCLIString(s);
editComponents.get(0).setEditState(streamOption.getValueAsCLIString());
}
public void setAlgorithm0ValueAsCLIString(String s){
algorithmOption0.setValueViaCLIString(s);
editComponents.get(1).setEditState(algorithmOption0.getValueAsCLIString());
}
public void setAlgorithm1ValueAsCLIString(String s){
algorithmOption1.setValueViaCLIString(s);
editComponents.get(2).setEditState(algorithmOption1.getValueAsCLIString());
}
public void applyChanges() {
for (OptionEditComponent editor : this.editComponents) {
try {
editor.applyState();
} catch (Exception ex) {
GUIUtils.showExceptionDialog(this, "Problem with option "
+ editor.getEditedOption().getName(), ex);
}
}
}
public void setPanelTitle(String title){
setBorder(javax.swing.BorderFactory.createTitledBorder(null,title, javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11)));
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Cluster Algorithm Setup", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
setLayout(new java.awt.GridBagLayout());
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* OutlierVisualEvalPanel.java
* Copyright (C) 2010 RWTH Aachen University, Germany
* @author Jansen (moa@cs.rwth-aachen.de)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.outliertab;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import moa.evaluation.MeasureCollection;
public class OutlierVisualEvalPanel extends javax.swing.JPanel{
private ArrayList<JLabel> names;
private ArrayList<JLabel> values;
private ArrayList<JRadioButton> radiobuttons;
private MeasureCollection[] measures0;
private ButtonGroup radioGroup;
private JLabel labelDummy;
private JLabel labelMeasure;
private JLabel labelCurrent0;
private JLabel labelMean0;
/** Creates new form OutlierEvalPanel */
public OutlierVisualEvalPanel() {
initComponents();
radioGroup = new ButtonGroup();
}
public void setMeasures(MeasureCollection[] measures0, ActionListener listener){
this.measures0 = measures0;
names = new ArrayList<JLabel>();
values = new ArrayList<JLabel>();
radiobuttons = new ArrayList<JRadioButton>();
for (int i = 0; i < measures0.length; i++) {
for (int j = 0; j < measures0[i].getNumMeasures(); j++) {
if(measures0[i].isEnabled(j)){
names.add(new JLabel(measures0[i].getName(j)));
}
}
}
setLayout(new java.awt.GridBagLayout());
GridBagConstraints gb;
//Radiobuttons
radioGroup = new ButtonGroup();
gb = new GridBagConstraints();
gb.gridx=0;
for (int i = 0; i < names.size(); i++) {
JRadioButton rb = new JRadioButton();
rb.setActionCommand(Integer.toString(i));
rb.addActionListener(listener);
radiobuttons.add(rb);
gb.gridy = i+1;
contentPanel.add(rb, gb);
radioGroup.add(rb);
}
radiobuttons.get(0).setSelected(true);
//name labels
gb = new GridBagConstraints();
gb.gridx=1;
for (int i = 0; i < names.size(); i++) {
names.get(i).setPreferredSize(new Dimension(40, 14));
gb.anchor = GridBagConstraints.WEST;
gb.insets = new java.awt.Insets(4, 7, 4, 7);
gb.gridy = i+1;
contentPanel.add(names.get(i), gb);
}
int counter = 0;
for (int i = 0; i < measures0.length; i++) {
for (int j = 0; j < measures0[i].getNumMeasures(); j++) {
if(!measures0[i].isEnabled(j)) continue;
for (int k = 0; k < 4; k++) {
String tooltip ="";
Color color = Color.black;
switch(k){
case 0:
tooltip = "current value";
color = Color.red;
break;
case 1:
tooltip = "current value";
color = Color.blue;
break;
case 2:
tooltip = "mean";
color = Color.black;
break;
case 3:
tooltip = "mean";
color = Color.black;
break;
}
JLabel l = new JLabel("-");
l.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
l.setPreferredSize(new java.awt.Dimension(50, 14));
l.setToolTipText(measures0[i].getName(j)+" "+tooltip);
l.setForeground(color);
values.add(l);
gb = new GridBagConstraints();
gb.gridy = 1 + counter;
gb.gridx = 2 + k;
gb.weightx = 1.0;
contentPanel.add(l, gb);
}
counter++;
}
}
//dummy label to align the labels at the top
gb = new GridBagConstraints();
gb.gridx = 0;
gb.gridy = names.size()+2;
gb.gridwidth = 6;
gb.weighty = 1.0;
JLabel fill = new JLabel();
contentPanel.add(fill, gb);
addLabels();
contentPanel.setPreferredSize(new Dimension(250, names.size()*(14+8)+20));
}
private void addLabels(){
labelMeasure = new javax.swing.JLabel("Measure");
labelCurrent0 = new JLabel("Current");
labelMean0 = new javax.swing.JLabel("Mean");
labelDummy = new javax.swing.JLabel();
GridBagConstraints gb = new GridBagConstraints();
gb.gridy = 0;
gb.gridx = 0;
contentPanel.add(labelDummy, gb);
gb.gridx = 1;
contentPanel.add(labelMeasure, gb);
gb = new GridBagConstraints();
gb.gridy = 0;
gb.gridx = 2;
gb.gridwidth = 2;
contentPanel.add(labelCurrent0, gb);
gb = new GridBagConstraints();
gb.gridy = 0;
gb.gridx=4;
gb.gridwidth = 2;
contentPanel.add(labelMean0, gb);
}
public void update(){
DecimalFormat d = new DecimalFormat("0.00");
if(measures0!=null){
int counter = 0;
for (MeasureCollection m : measures0) {
for (int i = 0; i < m.getNumMeasures(); i++) {
if(!m.isEnabled(i)) continue;
if(Double.isNaN(m.getLastValue(i)))
values.get(counter*4).setText("-");
else
values.get(counter*4).setText(d.format(m.getLastValue(i)));
if(Double.isNaN(m.getMean(i)))
values.get(counter*4+2).setText("-");
else
values.get(counter*4+2).setText(d.format(m.getMean(i)));
counter++;
}
}
}
}
@Override
//this is soooooo bad, but freaking gridbag somehow doesnt kick in...???
protected void paintComponent(Graphics g) {
scrollPane.setPreferredSize(new Dimension(getWidth()-20, getHeight()-30));
super.paintComponent(g);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
scrollPane = new javax.swing.JScrollPane();
contentPanel = new javax.swing.JPanel();
setBorder(javax.swing.BorderFactory.createTitledBorder("Values"));
setPreferredSize(new java.awt.Dimension(250, 115));
setLayout(new java.awt.GridBagLayout());
scrollPane.setBorder(null);
scrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setPreferredSize(new java.awt.Dimension(270, 180));
contentPanel.setPreferredSize(new java.awt.Dimension(100, 105));
contentPanel.setLayout(new java.awt.GridBagLayout());
scrollPane.setViewportView(contentPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(scrollPane, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel contentPanel;
private javax.swing.JScrollPane scrollPane;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* OutlierSetupTab.java
* Copyright (C) 2013 Aristotle University of Thessaloniki, Greece
* @author D. Georgiadis, A. Gounaris, A. Papadopoulos, K. Tsichlas, Y. Manolopoulos
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.outliertab;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JFileChooser;
import moa.clusterers.outliers.MyBaseOutlierDetector;
import moa.evaluation.MeasureCollection;
import moa.gui.FileExtensionFilter;
import moa.gui.TextViewerPanel;
import moa.streams.clustering.ClusteringStream;
public class OutlierSetupTab extends javax.swing.JPanel {
private OutlierTabPanel outlierTab;
private String lastfile;
/** Creates new form outlierSetupTab */
public OutlierSetupTab() {
initComponents();
outlierAlgoPanel0.renderAlgoPanel();
}
public MyBaseOutlierDetector getOutlierer0(){
return outlierAlgoPanel0.getClusterer0();
}
public MyBaseOutlierDetector getOutlierer1(){
return outlierAlgoPanel0.getClusterer1();
}
public ClusteringStream getStream0(){
return outlierAlgoPanel0.getStream();
}
public MeasureCollection[] getMeasures(){
return outlierEvalPanel1.getSelectedMeasures();
}
public TextViewerPanel getLogPanel(){
return logPanel;
}
public void addButtonActionListener(ActionListener l){
buttonWeka.addActionListener(l);
buttonWeka.setActionCommand("weka export");
buttonExport.addActionListener(l);
buttonExport.setActionCommand("csv export");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
outlierAlgoPanel0 = new moa.gui.outliertab.OutlierAlgoPanel();
outlierEvalPanel1 = new moa.gui.outliertab.OutlierEvalPanel();
buttonStart = new javax.swing.JButton();
buttonStop = new javax.swing.JButton();
buttonExport = new javax.swing.JButton();
buttonWeka = new javax.swing.JButton();
buttonImportSettings = new javax.swing.JButton();
buttonExportSettings = new javax.swing.JButton();
logPanel = new moa.gui.TextViewerPanel();
setLayout(new java.awt.GridBagLayout());
outlierAlgoPanel0.setMinimumSize(new java.awt.Dimension(335, 150));
outlierAlgoPanel0.setPanelTitle("Outlier Detection Algorithm Setup");
outlierAlgoPanel0.setPreferredSize(new java.awt.Dimension(500, 150));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(outlierAlgoPanel0, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
// ### add(outlierEvalPanel1, gridBagConstraints);
int iBtnHeight = 27;
buttonStart.setText("Start");
buttonStart.setMinimumSize(new java.awt.Dimension(80, iBtnHeight));
buttonStart.setPreferredSize(new java.awt.Dimension(80, iBtnHeight));
buttonStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonStartActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonStart, gridBagConstraints);
buttonStop.setText("Stop");
buttonStop.setMinimumSize(new java.awt.Dimension(80, iBtnHeight));
buttonStop.setPreferredSize(new java.awt.Dimension(80, iBtnHeight));
buttonStop.setEnabled(false);
buttonStop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonStopActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonStop, gridBagConstraints);
buttonExport.setText("Export CSV");
buttonExport.setMinimumSize(new java.awt.Dimension(120, iBtnHeight));
buttonExport.setPreferredSize(new java.awt.Dimension(120, iBtnHeight));
buttonExport.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 6;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonExport, gridBagConstraints);
buttonWeka.setText("Weka Explorer");
buttonWeka.setMinimumSize(new java.awt.Dimension(120, iBtnHeight));
buttonWeka.setPreferredSize(new java.awt.Dimension(120, iBtnHeight));
buttonWeka.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonWeka, gridBagConstraints);
buttonImportSettings.setText("Import");
buttonImportSettings.setMinimumSize(new java.awt.Dimension(80, iBtnHeight));
buttonImportSettings.setPreferredSize(new java.awt.Dimension(80, iBtnHeight));
buttonImportSettings.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonImportSettingsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 75, 4, 4);
add(buttonImportSettings, gridBagConstraints);
buttonExportSettings.setText("Export");
buttonExportSettings.setMinimumSize(new java.awt.Dimension(80, iBtnHeight));
buttonExportSettings.setPreferredSize(new java.awt.Dimension(80, iBtnHeight));
buttonExportSettings.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonExportSettingsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(buttonExportSettings, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 7;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(logPanel, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void buttonImportSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonImportSettingsActionPerformed
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.addChoosableFileFilter(new FileExtensionFilter("txt"));
if(lastfile!=null)
fileChooser.setSelectedFile(new File(lastfile));
if (fileChooser.showOpenDialog(this.buttonImportSettings) == JFileChooser.APPROVE_OPTION) {
lastfile = fileChooser.getSelectedFile().getPath();
loadOptionsFromFile(fileChooser.getSelectedFile().getPath());
}
}//GEN-LAST:event_buttonImportSettingsActionPerformed
private void buttonExportSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExportSettingsActionPerformed
StringBuffer sb = new StringBuffer();
sb.append(outlierAlgoPanel0.getStreamValueAsCLIString()+"\n");
sb.append(outlierAlgoPanel0.getAlgorithm0ValueAsCLIString()+"\n");
System.out.println(sb);
logPanel.addText(sb.toString());
}//GEN-LAST:event_buttonExportSettingsActionPerformed
private void buttonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStartActionPerformed
toggle(true);
}//GEN-LAST:event_buttonStartActionPerformed
private void buttonStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStopActionPerformed
stop(true);
}//GEN-LAST:event_buttonStopActionPerformed
private void loadOptionsFromFile(String filepath){
try {
BufferedReader in = new BufferedReader(new FileReader(filepath));
String stream0 = in.readLine();
outlierAlgoPanel0.setStreamValueAsCLIString(stream0);
String algo0 = in.readLine();
outlierAlgoPanel0.setAlgorithm0ValueAsCLIString(algo0);
System.out.println("Loading settings from "+filepath);
logPanel.addText("Loading settings from "+filepath);
} catch (Exception e) {
System.out.println("Bad option file:"+e.getMessage());
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonExport;
private javax.swing.JButton buttonExportSettings;
private javax.swing.JButton buttonImportSettings;
private javax.swing.JButton buttonStart;
private javax.swing.JButton buttonStop;
private javax.swing.JButton buttonWeka;
private moa.gui.outliertab.OutlierAlgoPanel outlierAlgoPanel0;
private moa.gui.outliertab.OutlierEvalPanel outlierEvalPanel1;
private moa.gui.TextViewerPanel logPanel;
// End of variables declaration//GEN-END:variables
void setOutlierTab(OutlierTabPanel outlierTab) {
this.outlierTab = outlierTab;
}
public void toggleRunMode(){
toggle(false);
}
public void stopRun(){
stop(false);
}
private void toggle(boolean internal) {
setStateConfigButtons(false);
if(buttonStart.getText().equals("Pause")){
buttonStart.setText("Resume");
buttonWeka.setEnabled(true);
buttonExport.setEnabled(true);
}
else{
buttonStart.setText("Pause");
buttonWeka.setEnabled(false);
buttonExport.setEnabled(false);
}
//push event forward to the cluster tab
if(internal)
outlierTab.toggle();
}
private void stop(boolean internal) {
buttonStart.setEnabled(true);
buttonStart.setText("Start");
buttonStop.setEnabled(false);
buttonWeka.setEnabled(false);
buttonExport.setEnabled(false);
setStateConfigButtons(true);
//push event forward to the cluster tab
if(internal)
outlierTab.stop();
}
private void setStateConfigButtons(boolean state){
buttonStop.setEnabled(!state);
buttonExportSettings.setEnabled(state);
buttonImportSettings.setEnabled(state);
}
}
| Java |
/*
* OutlierEvalPanel.java
* Copyright (C) 2013 Aristotle University of Thessaloniki, Greece
* @author D. Georgiadis, A. Gounaris, A. Papadopoulos, K. Tsichlas, Y. Manolopoulos
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.gui.outliertab;
import java.awt.GridBagConstraints;
import java.util.ArrayList;
import java.util.logging.Logger;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import moa.core.AutoClassDiscovery;
import moa.core.AutoExpandVector;
import moa.evaluation.ClassificationMeasureCollection;
import moa.evaluation.MeasureCollection;
import moa.evaluation.OutlierPerformance;
public class OutlierEvalPanel extends javax.swing.JPanel {
Class<?>[] measure_classes = null;
ArrayList<JLabel> labels = null;
ArrayList<JCheckBox> checkboxes = null;
/** Creates new form ClusteringEvalPanel */
public OutlierEvalPanel() {
initComponents();
measure_classes = findMeasureClasses();
labels = new ArrayList<JLabel>();
checkboxes = new ArrayList<JCheckBox>();
addComponents();
}
private void addComponents() {
GridBagConstraints gb = new GridBagConstraints();
gb.insets = new java.awt.Insets(4, 7, 4, 7);
int counter = 0;
for (int i = 0; i < measure_classes.length; i++) {
try {
MeasureCollection m = (MeasureCollection) measure_classes[i].newInstance();
for (int j = 0; j < m.getNumMeasures(); j++) {
String t = m.getName(j);
JLabel l = new JLabel(m.getName(j));
l.setPreferredSize(new java.awt.Dimension(100, 14));
//labels[i].setToolTipText("");
gb.gridx = 0;
gb.gridy = counter;
labels.add(l);
contentPanel.add(l, gb);
JCheckBox cb = new JCheckBox();
if (m.isEnabled(j)) {
cb.setSelected(true);
} else {
cb.setSelected(false);
}
gb.gridx = 1;
checkboxes.add(cb);
contentPanel.add(cb, gb);
counter++;
}
} catch (Exception ex) {
System.out.println("Couldn't create Instance for " + measure_classes[i].getName());
}
}
JLabel dummy = new JLabel();
gb.gridx = 0;
gb.gridy++;
gb.gridwidth = 3;
gb.weightx = 1;
gb.weighty = 1;
add(dummy, gb);
}
private Class<?>[] findMeasureClasses() {
AutoExpandVector<Class<?>> finalClasses = new AutoExpandVector<Class<?>>();
Class<?>[] classesFound = AutoClassDiscovery.findClassesOfType("moa.evaluation",
OutlierPerformance.class);
for (Class<?> foundClass : classesFound) {
finalClasses.add(foundClass);
}
return finalClasses.toArray(new Class<?>[finalClasses.size()]);
}
public MeasureCollection[] getSelectedMeasures() {
ArrayList<MeasureCollection> measuresSelect = new ArrayList<MeasureCollection>();
for (int i = 0; i < measure_classes.length; i++) {
try {
MeasureCollection m = (MeasureCollection) measure_classes[i].newInstance();
measuresSelect.add(m);
} catch (Exception ex) {
System.out.println("Couldn't create Instance for " + measure_classes[i].getName());
}
}
MeasureCollection[] measures = new MeasureCollection[measuresSelect.size()];
for (int i = 0; i < measures.length; i++) {
measures[i] = measuresSelect.get(i);
}
return measures;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
scrollPane = new javax.swing.JScrollPane();
contentPanel = new javax.swing.JPanel();
setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Evaluation Measures", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
setLayout(new java.awt.GridBagLayout());
scrollPane.setBorder(null);
scrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new java.awt.Dimension(100, 225));
contentPanel.setLayout(new java.awt.GridBagLayout());
scrollPane.setViewportView(contentPanel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(scrollPane, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel contentPanel;
private javax.swing.JScrollPane scrollPane;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* RatingPredictor.java
* Copyright (C) 2012 Universitat Politecnica de Catalunya
* @author Alex Catarineu (a.catarineu@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.recommender.predictor;
import java.io.Serializable;
import java.util.List;
import moa.recommender.rc.data.RecommenderData;
/**
* Rating predicting algorithm. The core of any recommender system is its
* rating prediction algorithm. Its purpose is to estimate the rating
* (a numeric score) that a certain user would give to a certain item,
* based on previous ratings given of the user and the item.
*
*/
public interface RatingPredictor extends Serializable {
public double predictRating(int userID, int itemID);
public List<Double> predictRatings(int userID, List<Integer> itemIDS);
public RecommenderData getData();
public void train();
}
| Java |
/*
* BaselinePredictor.java
* Copyright (C) 2012 Universitat Politecnica de Catalunya
* @author Alex Catarineu (a.catarineu@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.recommender.predictor;
import java.util.List;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.ClassOption;
import moa.tasks.TaskMonitor;
/**
* A naive algorithm which combines the global mean of all the existing
* ratings, the mean rating of the user and the mean rating of the item
* to make a prediction.
*
*/
public class BaselinePredictor extends AbstractOptionHandler implements moa.recommender.predictor.RatingPredictor {
protected moa.recommender.rc.predictor.impl.BaselinePredictor rp;
public ClassOption dataOption = new ClassOption("data", 'd',
"Data", moa.recommender.data.RecommenderData.class, "moa.recommender.data.MemRecommenderData");
@Override
protected void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) {
moa.recommender.data.RecommenderData data = (moa.recommender.data.RecommenderData) getPreparedClassOption(this.dataOption);
rp = new moa.recommender.rc.predictor.impl.BaselinePredictor(data.getData());
}
@Override
public void getDescription(StringBuilder sb, int indent) {
sb.append(rp.toString());
}
public double predictRating(Integer user, Integer item) {
return rp.predictRating(user,item);
}
public moa.recommender.rc.data.RecommenderData getData() {
return rp.getData();
}
@Override
public double predictRating(int userID, int itemID) {
return rp.predictRating(userID, itemID);
}
@Override
public List<Double> predictRatings(int userID, List<Integer> itemIDS) {
return rp.predictRatings(userID, itemIDS);
}
@Override
public void train() {
rp.train();
}
}
| Java |
/*
* BRISMFPredictor.java
* Copyright (C) 2012 Universitat Politecnica de Catalunya
* @author Alex Catarineu (a.catarineu@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package moa.recommender.predictor;
import java.util.List;
import moa.core.ObjectRepository;
import moa.options.AbstractOptionHandler;
import moa.options.ClassOption;
import moa.options.FloatOption;
import moa.options.IntOption;
import moa.recommender.data.RecommenderData;
import moa.tasks.TaskMonitor;
/**
* Implementation of the algorithm described in Scalable
* Collaborative Filtering Approaches for Large Recommender
* Systems (Gábor Takács, István Pilászy, Bottyán Németh,
* and Domonkos Tikk). A feature vector is learned for every
* user and item, so that the prediction of a rating is roughly
* the dot product of the corresponding user and item vector.
* Stochastic gradient descent is used to train the model,
* minimizing its prediction error. Both Tikhonov regularization
* and early stopping are used to reduce overfitting. The
* algorithm allows batch training (from scratch, using all
* ratings available at the moment) as well as incremental,
* by retraining only the affected user and item vectors when
* a new rating is inserted.
*
* <p>Parameters:</p>
* <ul>
* <li> f: features - the number of features to be trained for each user and
* item</li>
* <li> r: learning rate - the learning rate used in the regularization</li>
* <li> a: ratio - the regularization ratio to be used in the Tikhonov
* regularization</li>
* <li> i: iterations - the number of iterations to be used when retraining
* user and item features (online training). </li>
* </lu>
*
*/
public class BRISMFPredictor extends AbstractOptionHandler implements RatingPredictor {
protected moa.recommender.rc.predictor.impl.BRISMFPredictor rp;
public IntOption featuresOption = new IntOption("features",
'f',
"How many features to use.",
20, 0, Integer.MAX_VALUE);
public FloatOption lRateOption = new FloatOption("lRate",
'r', "lRate", 0.001);
public FloatOption rFactorOption = new FloatOption("rFactor",
'a', "rFactor", 0.01);
public IntOption iterationsOption = new IntOption("iterations",
'i',
"How many iterations to use.",
100, 0, Integer.MAX_VALUE);
public ClassOption dataOption = new ClassOption("data", 'd',
"Data", RecommenderData.class, "moa.recommender.data.MemRecommenderData");
@Override
protected void prepareForUseImpl(TaskMonitor monitor, ObjectRepository repository) {
RecommenderData data = (RecommenderData) getPreparedClassOption(this.dataOption);
rp = new moa.recommender.rc.predictor.impl.BRISMFPredictor(featuresOption.getValue(), data.getData(), lRateOption.getValue(), rFactorOption.getValue(), false);
rp.setNIterations(iterationsOption.getValue());
}
@Override
public void getDescription(StringBuilder sb, int indent) {
sb.append(rp.toString());
}
public double predictRating(Integer user, Integer item) {
return rp.predictRating(user,item);
}
public moa.recommender.rc.data.RecommenderData getData() {
return rp.getData();
}
@Override
public double predictRating(int userID, int itemID) {
return rp.predictRating(userID, itemID);
}
@Override
public List<Double> predictRatings(int userID, List<Integer> itemIDS) {
return rp.predictRatings(userID, itemIDS);
}
@Override
public void train() {
rp.train();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.