repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/cache/SymmetricBiCache.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.cache;
public class SymmetricBiCache<A, B> extends BiCache<A, A, B> {
// todo cache state read / write
@Override
public B get(final A firstKey, final A secondKey) {
B result = super.get(firstKey, secondKey);
if(result == null) {
result = super.get(secondKey, firstKey);
}
return result;
}
@Override
public void put(final A firstKey, final A secondKey, final B value) {
super.put(firstKey, secondKey, value);
}
@Override
public boolean remove(final A firstKey, final A secondKey) {
boolean removed = super.remove(firstKey, secondKey);
if(!removed) {
removed = super.remove(secondKey, firstKey);
}
return removed;
}
}
| 1,577 | 32.574468 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/checks/Checks.java | package tsml.classifiers.distance_based.utils.collections.checks;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
public class Checks {
public static double requireUnitInterval(double v) {
requireReal(v);
requireNonNegative(v);
if(v > 1) {
throw new IllegalStateException(v + " > 1");
}
return v;
}
public static double requirePercentage(double v) {
return requireUnitInterval(v / 100);
}
public static double requireNonNaN(double v) {
if(Double.isNaN(v)) {
throw new IllegalArgumentException("NaN not allowed");
}
return v;
}
public static double requireReal(double v) {
requireNonNaN(v);
if(v == Double.POSITIVE_INFINITY) {
throw new IllegalArgumentException("Positive infinity not allowed");
}
if(v == Double.NEGATIVE_INFINITY) {
throw new IllegalArgumentException("Negative infinity not allowed");
}
return v;
}
public static double requireNonNegative(double v) {
if(v < 0) throw new IllegalArgumentException(v + " < 0");
return v;
}
public static double requireNonPositive(double v) {
if(v > 0) throw new IllegalArgumentException(v + " > 0");
return v;
}
public static double requireNonZero(double v) {
if(v == 0) throw new IllegalArgumentException(v + " == 0");
return v;
}
public static double requireNegative(double v) {
if(v >= 0) throw new IllegalArgumentException(v + " >= 0");
return v;
}
public static double requirePositive(double v) {
if(v <= 0) throw new IllegalArgumentException(v + " <= 0");
return v;
}
public static int requireNonNegative(int v) {
if(v < 0) throw new IllegalArgumentException(v + " < 0");
return v;
}
public static int requireNonPositive(int v) {
if(v > 0) throw new IllegalArgumentException(v + " > 0");
return v;
}
public static int requireNonZero(int v) {
if(v == 0) throw new IllegalArgumentException(v + " == 0");
return v;
}
public static int requireNegative(int v) {
if(v >= 0) throw new IllegalArgumentException(v + " >= 0");
return v;
}
public static int requirePositive(int v) {
if(v <= 0) throw new IllegalArgumentException(v + " <= 0");
return v;
}
public static <A> A requireNonNull(A obj) {
Objects.requireNonNull(obj);
if(obj instanceof Iterable<?>) {
((Iterable<?>) obj).forEach(Objects::requireNonNull);
}
return obj;
}
public static <A> A requireSingle(List<A> list) {
if(list == null) {
return null;
}
if(list.size() != 1) {
throw new IllegalArgumentException("expected a single element in list");
}
return list.get(0);
}
}
| 3,030 | 27.59434 | 84 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/intervals/BaseInterval.java | package tsml.classifiers.distance_based.utils.collections.intervals;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import java.util.Objects;
public abstract class BaseInterval<A> implements Interval<A> {
public static String START_FLAG = "s";
public static String END_FLAG = "l";
public BaseInterval(A start, A end) {
setStart(start);
setEnd(end);
}
private A start;
private A end;
@Override public A getStart() {
return start;
}
@Override public void setStart(A start) {
this.start = Objects.requireNonNull(start);
}
@Override public A getEnd() {
return end;
}
@Override public void setEnd(final A end) {
this.end = Objects.requireNonNull(end);
}
@Override public ParamSet getParams() {
return Interval.super.getParams().add(START_FLAG, getStart()).add(END_FLAG, getEnd());
}
@Override public void setParams(final ParamSet paramSet) throws Exception {
Interval.super.setParams(paramSet);
setStart(paramSet.get(START_FLAG, getStart()));
setEnd(paramSet.get(END_FLAG, getEnd()));
}
@Override public String toString() {
return getStart() + " - " + getEnd();
}
@Override public boolean equals(final Object o) {
if(this == o) {
return true;
}
if(!(o instanceof BaseInterval)) {
return false;
}
final BaseInterval<?> that = (BaseInterval<?>) o;
return Objects.equals(start, that.start) && Objects.equals(end, that.end);
}
@Override public int hashCode() {
return Objects.hash(start, end);
}
}
| 1,711 | 25.338462 | 94 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/intervals/DoubleInterval.java | package tsml.classifiers.distance_based.utils.collections.intervals;
public class DoubleInterval extends BaseInterval<Double> {
public DoubleInterval() {
this(0, 1);
}
public DoubleInterval(double start, double end) {
super(start, end);
}
@Override public boolean contains(final Double item) {
return item <= getEnd() && item >= getStart();
}
@Override public Double size() {
return getEnd() - getStart();
}
}
| 487 | 22.238095 | 68 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/intervals/IntInterval.java | package tsml.classifiers.distance_based.utils.collections.intervals;
/**
* Purpose: represent an interval, i.e. some subsequence of indices. An interval therefore has a start and end point
* (inclusively!). The start point may be beyond the end point to reverse directionality.
*
* Contributors: goastler
*/
public class IntInterval extends BaseInterval<Integer> {
public IntInterval() {
this(0, 0);
}
public IntInterval(final int start, final int end) {
super(start, end);
}
public boolean contains(Integer index) {
return getStart() <= index && index <= getEnd();
}
public int translate(int index) {
return translate(index, true);
}
/**
* map interval index to instance index
* @param index
* @return
*/
public int translate(int index, boolean check) {
if(check) {
if(index > size() - 1) {
throw new ArrayIndexOutOfBoundsException(index);
}
if(index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
}
return index + getStart();
}
/**
* map instance index to interval index
* @param index
* @return
*/
public int inverseTranslate(int index) {
return inverseTranslate(index, true);
}
public int inverseTranslate(int index, boolean check) {
if(check) {
if(index > getEnd()) {
throw new ArrayIndexOutOfBoundsException(index);
}
if(index < getStart()) {
throw new ArrayIndexOutOfBoundsException(index);
}
}
return index - getStart();
}
@Override public Integer size() {
return getEnd() - getStart() + 1;
}
}
| 1,797 | 25.057971 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/intervals/IntIntervalTest.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.intervals;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class IntIntervalTest {
private IntInterval interval;
private int start;
private int length;
@Before
public void before() {
interval = new IntInterval();
this.start = 50;
this.length = 11;
interval.setStart(start);
interval.setEnd(length + start - 1);
}
@Test
public void testIntervalSize() {
Assert.assertEquals(length, (long) interval.size());
}
@Test
public void testTranslate() {
for(int i = 0; i < length; i++) {
final int index = interval.translate(i);
Assert.assertEquals(i + start, index);
}
}
@Test
public void testInverseTranslate() {
for(int i = 0; i < length; i++) {
final int index = interval.inverseTranslate(i + start);
Assert.assertEquals(i, index);
}
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testInverseTranslateOutOfBoundsAbove() {
interval.inverseTranslate(start + length);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testInverseTranslateOutOfBoundsBelow() {
interval.inverseTranslate(start - 1);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testTranslateOutOfBoundsAbove() {
interval.translate(length);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testTranslateOutOfBoundsBelow() {
interval.translate(-1);
}
}
| 2,422 | 28.91358 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/intervals/Interval.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.intervals;
import tsml.classifiers.distance_based.utils.collections.params.ParamHandler;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
public interface Interval<A> extends ParamHandler {
A getStart();
A getEnd();
void setStart(A start);
void setEnd(A end);
A size();
boolean contains(A item);
@Override String toString();
}
| 1,216 | 31.026316 | 77 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/intervals/IntervalInstance.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.intervals;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import java.util.Arrays;
import java.util.Enumeration;
public class IntervalInstance implements Instance {
public IntervalInstance(IntInterval interval, Instance instance) {
this(instance, interval);
}
public IntervalInstance(final Instance instance, IntInterval interval) {
setDataset(instance.dataset());
setInterval(interval);
setInstance(instance);
}
public IntervalInstance(IntervalInstance intervalInstance) {
this(intervalInstance.instance, intervalInstance.interval);
setDataset(intervalInstance.dataset);
}
private Instance instance;
private IntInterval interval;
private Instances dataset;
public IntInterval getInterval() {
return interval;
}
public void setInterval(final IntInterval interval) {
this.interval = interval;
}
@Override public double value(int attIndex) {
if(attIndex == interval.size() || attIndex == classIndex()) {
return instance.classValue();
}
attIndex = interval.translate(attIndex);
return instance.value(attIndex);
}
@Override public int numAttributes() {
return interval.size() + 1; // +1 for class label
}
@Override public int numClasses() {
return dataset.numClasses();
}
@Override public int numValues() {
throw new UnsupportedOperationException();
}
@Override public void replaceMissingValues(final double[] array) {
throw new UnsupportedOperationException();
}
@Override public void setClassMissing() {
instance.setClassMissing();
}
@Override public void setClassValue(final double value) {
instance.setClassValue(value);
}
@Override public void setClassValue(final String value) {
instance.setClassValue(value);
}
@Override public void setDataset(final Instances instances) {
dataset = instances;
}
@Override public void setMissing(int attIndex) {
attIndex = interval.translate(attIndex);
instance.setMissing(attIndex);
}
@Override public void setMissing(final Attribute att) {
instance.setMissing(att);
}
@Override public double[] toDoubleArray() {
final double[] array = new double[interval.size() + 1];
for(int i = 0; i < interval.size(); i++) {
array[i] = value(i);
}
array[array.length - 1] = value(array.length - 1);
return array;
}
@Override public String toStringNoWeight(final int afterDecimalPoint) {
return instance.toStringNoWeight(afterDecimalPoint);
}
@Override public String toStringNoWeight() {
return instance.toStringNoWeight();
}
@Override public String toStringMaxDecimalDigits(final int afterDecimalPoint) {
return instance.toStringMaxDecimalDigits(afterDecimalPoint);
}
@Override public String toString(final int attIndex, final int afterDecimalPoint) {
return instance.toString(attIndex, afterDecimalPoint);
}
@Override public String toString(final int attIndex) {
return instance.toString(attIndex);
}
@Override public String toString(final Attribute att, final int afterDecimalPoint) {
return instance.toString(att, afterDecimalPoint);
}
@Override public String toString(final Attribute att) {
return instance.toString(att);
}
@Override public String toString() {
return "IntervalInstance{" +
"interval=" + interval +
", label=" + classValue() +
", atts=" + Arrays.toString(toDoubleArray()) +
"}";
}
public Instance getInstance() {
return instance;
}
public void setInstance(final Instance instance) {
this.instance = instance;
}
@Override public Attribute classAttribute() {
return instance.classAttribute();
}
@Override public Attribute attribute(int index) {
index = interval.translate(index);
return instance.attribute(index);
}
@Override public Attribute attributeSparse(int indexOfIndex) {
indexOfIndex = interval.translate(indexOfIndex);
return instance.attributeSparse(indexOfIndex);
}
@Override public int classIndex() {
return interval.size();
}
@Override public boolean classIsMissing() {
return instance.classIsMissing();
}
@Override public double classValue() {
final int i = classIndex();
return value(i);
}
@Override public Instances dataset() {
return instance.dataset();
}
@Override public void deleteAttributeAt(int position) {
position = interval.translate(position);
instance.deleteAttributeAt(position);
}
@Override public Enumeration enumerateAttributes() {
return instance.enumerateAttributes();
}
@Override public boolean equalHeaders(final Instance inst) {
return instance.equalHeaders(inst);
}
@Override public String equalHeadersMsg(final Instance inst) {
return instance.equalHeadersMsg(inst);
}
@Override public boolean hasMissingValue() {
return instance.hasMissingValue();
}
@Override public int index(int position) {
position = interval.translate(position);
return instance.index(position);
}
@Override public void insertAttributeAt(int position) {
position = interval.translate(position);
instance.insertAttributeAt(position);
}
@Override public boolean isMissing(int attIndex) {
attIndex = interval.translate(attIndex);
return instance.isMissing(attIndex);
}
@Override public boolean isMissingSparse(int indexOfIndex) {
indexOfIndex = interval.translate(indexOfIndex);
return instance.isMissingSparse(indexOfIndex);
}
@Override public boolean isMissing(final Attribute att) {
return instance.isMissing(att);
}
@Override public Instance mergeInstance(final Instance inst) {
return instance.mergeInstance(inst);
}
@Override public void setValue(int attIndex, final double value) {
attIndex = interval.translate(attIndex);
instance.setValue(attIndex, value);
}
@Override public void setValueSparse(int indexOfIndex, final double value) {
indexOfIndex = interval.translate(indexOfIndex);
instance.setValueSparse(indexOfIndex, value);
}
@Override public void setValue(int attIndex, final String value) {
attIndex = interval.translate(attIndex);
instance.setValue(attIndex, value);
}
@Override public void setValue(final Attribute att, final double value) {
instance.setValue(att, value);
}
@Override public void setValue(final Attribute att, final String value) {
instance.setValue(att, value);
}
@Override public void setWeight(final double weight) {
instance.setWeight(weight);
}
@Override public Instances relationalValue(int attIndex) {
attIndex = interval.translate(attIndex);
return instance.relationalValue(attIndex);
}
@Override public Instances relationalValue(final Attribute att) {
return relationalValue(att);
}
@Override public String stringValue(int attIndex) {
attIndex = interval.translate(attIndex);
return instance.stringValue(attIndex);
}
@Override public String stringValue(final Attribute att) {
return instance.stringValue(att);
}
@Override public double valueSparse(int indexOfIndex) {
indexOfIndex = interval.translate(indexOfIndex);
return instance.valueSparse(indexOfIndex);
}
@Override public double value(final Attribute att) {
return instance.value(att);
}
@Override public double weight() {
return instance.weight();
}
@Override public IntervalInstance copy() {
return new IntervalInstance(this);
}
}
| 8,975 | 29.020067 | 88 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/intervals/IntervalInstanceTest.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.intervals;
import org.junit.Assert;
import org.junit.Test;
import weka.core.DenseInstance;
public class IntervalInstanceTest {
@Test
public void testIndices() {
final double[] attributes = new double[10];
for(int i = 0; i < attributes.length; i++) {
attributes[i] = i;
}
final DenseInstance instance = new DenseInstance(1, attributes);
int start = 5;
int length = 4;
final IntervalInstance intervalInstance = new IntervalInstance(new IntInterval(start, length), instance);
for(int i = 0; i < intervalInstance.numAttributes() - 1; i++) {
final double intervalValue = intervalInstance.value(i);
final double instanceValue = instance.value(i + start);
Assert.assertEquals(intervalValue, instanceValue, 0);
}
}
}
| 1,664 | 37.72093 | 113 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/AbstractIterator.java | package tsml.classifiers.distance_based.utils.collections.iteration;
import java.io.Serializable;
import java.util.Iterator;
public abstract class AbstractIterator<A> implements Iterator<A>, Serializable {
private boolean hasNextCalled = false;
private boolean hasNext = false;
protected abstract boolean findHasNext();
protected abstract A findNext();
@Override public boolean hasNext() {
if(hasNextCalled) {
return hasNext;
}
hasNext = findHasNext();
hasNextCalled = true;
return hasNext;
}
@Override public A next() {
if(!hasNext()) {
throw new IllegalStateException("hasNext false");
}
hasNextCalled = false;
return findNext();
}
}
| 782 | 24.258065 | 80 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/AbstractListIterator.java | package tsml.classifiers.distance_based.utils.collections.iteration;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public abstract class AbstractListIterator<A> implements DefaultListIterator<A>, Serializable {
private int index = -1;
private int nextIndex = -1;
private List<A> list;
private boolean findNextIndex = true;
public AbstractListIterator(List<A> list) {
buildIterator(list);
}
public AbstractListIterator() {
}
protected int getIndex() {
return index;
}
protected void setIndex(int index) {
this.index = index;
findNextIndex = true;
}
@Override public A next() {
setIndex(nextIndex());
return list.get(index);
}
@Override final public int nextIndex() {
if(!hasNext()) {
throw new IllegalStateException("hasNext false");
}
if(findNextIndex) {
nextIndex = findNextIndex();
findNextIndex = false;
}
return nextIndex;
}
@Override public final boolean hasNext() {
if(list == null) {
throw new IllegalStateException("iterator not built");
}
return !list.isEmpty() && findHasNext();
}
protected abstract boolean findHasNext();
abstract protected int findNextIndex();
@Override public void remove() {
list.remove(index);
}
@Override public void set(final A a) {
list.set(index, a);
}
@Override public void add(final A a) {
list.add(index, a);
}
public void buildIterator(final List<A> list) {
this.list = Objects.requireNonNull(list);
}
protected List<A> getList() {
return list;
}
}
| 1,824 | 21.8125 | 95 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/BaseRandomIterator.java | package tsml.classifiers.distance_based.utils.collections.iteration;
import tsml.classifiers.distance_based.utils.collections.CollectionUtils;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import static utilities.ArrayUtilities.sequence;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class BaseRandomIterator<A> extends AbstractListIterator<A> implements RandomIterator<A> {
private boolean withReplacement;
private List<Integer> indices;
private int indexOfIndex = -1;
private Random random = null;
private int seed;
@Override public Random getRandom() {
return random;
}
@Override public void setRandom(final Random random) {
this.random = random;
}
@Override public int getSeed() {
return seed;
}
@Override public void setSeed(final int seed) {
this.seed = seed;
setRandom(new Random(seed));
}
public BaseRandomIterator() {
setWithReplacement(false);
}
@Override public void add(final A a) {
indices.add(getList().size());
super.add(a);
}
@Override public boolean withReplacement() {
return withReplacement;
}
@Override public void setWithReplacement(final boolean withReplacement) {
this.withReplacement = withReplacement;
}
@Override public void buildIterator(final List<A> list) {
super.buildIterator(list);
indices = sequence(list.size());
if(random == null) throw new IllegalStateException("random / seed not set");
}
@Override protected int findNextIndex() {
final int size = indices.size();
indexOfIndex = random.nextInt(size);
return indices.get(indexOfIndex);
}
@Override public A next() {
final A element = super.next();
// if not choosing with replacement then remove the index from the pool of indices to be picked from next time
if(!withReplacement) {
removeIndex();
}
return element;
}
@Override protected boolean findHasNext() {
return !indices.isEmpty();
}
private void removeIndex() {
CollectionUtils.removeUnordered(indices, indexOfIndex);
}
@Override public void remove() {
super.remove();
// if choosing with replacement then the index has been kept during the next() call. The remove() call signals that it should be removed.
if(withReplacement) {
removeIndex();
}
}
}
| 2,582 | 25.90625 | 145 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/BaseRandomIteratorTest.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.iteration;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
public class BaseRandomIteratorTest {
private RandomIterator<String> iterator;
private List<String> elements;
@Before
public void before() {
elements = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e", "f", "g"));
iterator = new BaseRandomIterator<>();
iterator.setRandom(new Random(0));
iterator.buildIterator(elements);
}
@Test
public void testOrderWithoutReplacement() {
iterator.setWithReplacement(false);
StringBuilder builder = new StringBuilder();
Set<String> set = new HashSet<>();
while(iterator.hasNext()) {
final String next = iterator.next();
final boolean added = set.add(next);
Assert.assertTrue(added);
builder.append(next);
}
// System.out.println(builder.toString());
Assert.assertEquals("fegcdab", builder.toString());
}
@Test
public void testOrderWithReplacement() {
iterator.setWithReplacement(true);
int i = 0;
StringBuilder builder = new StringBuilder();
Set<String> set = new HashSet<>();
boolean dupe = false;
while(iterator.hasNext() && i++ < 10) {
final String next = iterator.next();
dupe = dupe || set.add(next);
builder.append(next);
}
Assert.assertTrue(dupe);
// System.out.println(builder.toString());
Assert.assertEquals("fceceacbgc", builder.toString());
}
}
| 2,430 | 33.239437 | 85 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/DefaultIterator.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.iteration;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
public interface DefaultIterator<A> extends Iterator<A>, Serializable {
@Override
default A next() {
throw new UnsupportedOperationException();
}
@Override
default boolean hasNext() {
throw new UnsupportedOperationException();
}
}
| 1,185 | 31.944444 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/DefaultListIterator.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.iteration;
import java.util.List;
import java.util.ListIterator;
/**
* Purpose: default implementation of a list iterator.
*
* Contributors: goastler
*
* @param <A>
*/
public interface DefaultListIterator<A> extends ListIterator<A> {
default void buildIterator(List<A> list) {
}
@Override
default boolean hasNext() {
throw new UnsupportedOperationException();
}
@Override
default A next() {
throw new UnsupportedOperationException();
}
@Override
default boolean hasPrevious() {
throw new UnsupportedOperationException();
}
@Override
default A previous() {
throw new UnsupportedOperationException();
}
@Override
default int nextIndex() {
throw new UnsupportedOperationException();
}
@Override
default int previousIndex() {
throw new UnsupportedOperationException();
}
@Override
default void remove() {
throw new UnsupportedOperationException();
}
@Override
default void set(final A a) {
throw new UnsupportedOperationException();
}
@Override
default void add(final A a) {
throw new UnsupportedOperationException();
}
}
| 2,056 | 24.7125 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/EmptyIterator.java | package tsml.classifiers.distance_based.utils.collections.iteration;
public class EmptyIterator<A> implements DefaultListIterator<A> {
@Override public boolean hasNext() {
return false;
}
@Override public boolean hasPrevious() {
return false;
}
}
| 281 | 22.5 | 68 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/FlatIterator.java | package tsml.classifiers.distance_based.utils.collections.iteration;
import java.util.Iterator;
import java.util.Objects;
public class FlatIterator<A> implements Iterator<A> {
public FlatIterator(Iterable<? extends Iterable<A>> iterables) {
mainIterator = new TransformIterator<>(iterables, Iterable::iterator);
}
private final Iterator<? extends Iterator<A>> mainIterator;
private Iterator<A> subIterator;
@Override public boolean hasNext() {
while((subIterator == null || !subIterator.hasNext()) && mainIterator.hasNext()) {
subIterator = mainIterator.next();
}
// no iterators in main therefore sub iterator null
if(subIterator == null) {
return false;
}
// otherwise sub iterator is a viable iterator
return subIterator.hasNext();
}
@Override public A next() {
return subIterator.next();
}
}
| 938 | 29.290323 | 90 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/LimitedIterator.java | package tsml.classifiers.distance_based.utils.collections.iteration;
import weka.core.OptionHandler;
import java.util.Enumeration;
import java.util.Iterator;
/**
* Purpose: traverse a list up to a point.
*
* Contributors: goastler
*
* @param <A>
*/
public class LimitedIterator<A>
implements DefaultIterator<A>,
OptionHandler {
public LimitedIterator() {}
public LimitedIterator(Iterator<A> iterator) {
setIterator(iterator);
}
public LimitedIterator(Iterator<A> iterator, int limit) {
setIterator(iterator);
setLimit(limit);
}
public LimitedIterator(int limit, Iterator<A> iterator) {
this(iterator, limit);
}
public LimitedIterator(int limit) {
setLimit(limit);
}
protected int limit = -1;
public int getLimit() {
return limit;
}
public void setLimit(final int limit) {
this.limit = limit;
}
protected int count = 0;
protected Iterator<A> iterator;
public Iterator<A> getIterator() {
return iterator;
}
public void setIterator(final Iterator<A> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return (count < limit || limit < 0) && iterator.hasNext();
}
@Override
public A next() {
count++;
return iterator.next();
}
public void resetCount() {
count = 0;
}
@Override
public void remove() {
iterator.remove();
}
@Override
public Enumeration listOptions() {
throw new UnsupportedOperationException();
}
@Override
public void setOptions(final String[] options) throws
Exception { // todo
}
@Override
public String[] getOptions() {
return new String[] {
"-l",
String.valueOf(limit)
}; // todo
}
// todo pass through other iterator funcs
}
| 1,997 | 18.98 | 70 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/LimitedListIterator.java | package tsml.classifiers.distance_based.utils.collections.iteration;
import weka.core.OptionHandler;
import java.util.Enumeration;
import java.util.Iterator;
/**
* Purpose: traverse a list up to a point.
*
* Contributors: goastler
*
* @param <A>
*/
public class LimitedListIterator<A> implements DefaultListIterator<A>, OptionHandler { // todo abst limit to abst
// class for iterator and listiterator version
public LimitedListIterator() {}
public LimitedListIterator(Iterator<A> iterator) {
setIterator(iterator);
}
public LimitedListIterator(Iterator<A> iterator, int limit) {
setIterator(iterator);
setLimit(limit);
}
public LimitedListIterator(int limit, Iterator<A> iterator) {
this(iterator, limit);
}
public LimitedListIterator(int limit) {
setLimit(limit);
}
protected int limit = -1;
public int getLimit() {
return limit;
}
public void setLimit(final int limit) {
this.limit = limit;
}
protected int count = 0;
protected Iterator<A> iterator;
public Iterator<A> getIterator() {
return iterator;
}
public void setIterator(final Iterator<A> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return (count < limit || limit < 0) && iterator.hasNext();
}
@Override
public A next() {
count++;
return iterator.next();
}
public void resetCount() {
count = 0;
}
@Override
public void remove() {
iterator.remove();
}
@Override
public Enumeration listOptions() {
throw new UnsupportedOperationException();
}
@Override
public void setOptions(final String[] options) throws
Exception { // todo
}
@Override
public String[] getOptions() {
return new String[] {
"-l",
String.valueOf(limit)
}; // todo
}
// todo pass through other iterator funcs
}
| 2,077 | 19.78 | 113 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/LinearIterator.java | package tsml.classifiers.distance_based.utils.collections.iteration;
import java.util.List;
/**
* Purpose: linearly traverse a list.
*
* Contributors: goastler
*
* @param <A>
*/
public class LinearIterator<A> extends AbstractListIterator<A> {
public LinearIterator(final List<A> list) {
super(list);
}
public LinearIterator() {
}
@Override protected int findNextIndex() {
return getIndex() + 1;
}
@Override protected boolean findHasNext() {
return findNextIndex() < getList().size();
}
}
| 557 | 17.6 | 68 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/RandomIterator.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.iteration;
import tsml.classifiers.distance_based.utils.system.random.Randomised;
import weka.core.Randomizable;
import java.io.Serializable;
import java.util.Random;
public interface RandomIterator<A> extends DefaultListIterator<A>, Serializable, Randomised {
boolean withReplacement();
void setWithReplacement(boolean withReplacement);
}
| 1,172 | 36.83871 | 93 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/Resetable.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.iteration;
/**
* Reset this class to uninitialised / default state.
* <p>
* Contributors: goastler
*/
public interface Resetable {
void reset();
static void reset(Object object) {
if(object instanceof tsml.classifiers.distance_based.utils.collections.iteration.Resetable) {
((tsml.classifiers.distance_based.utils.collections.iteration.Resetable) object).reset();
}
}
}
| 1,240 | 35.5 | 101 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/RoundRobinIterator.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.iteration;
import java.util.List;
/**
* Purpose: round robin traverse a list.
*
* Contributors: goastler
*
* @param <A>
*/
public class RoundRobinIterator<A> extends LinearIterator<A> {
public RoundRobinIterator(List<A> list) {
super(list);
}
public RoundRobinIterator() {}
@Override
public A next() {
A next = super.next();
if(getIndex() == getList().size()) {
setIndex(0);
}
return next;
}
@Override
public void remove() {
super.remove();
if(getIndex() < 0) {
setIndex(getList().size() - 1);
}
}
protected boolean findHasNext() {
return !getList().isEmpty();
}
@Override
protected int findNextIndex() {
return super.findNextIndex() % getList().size();
}
}
| 1,651 | 25.645161 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/iteration/TransformIterator.java | package tsml.classifiers.distance_based.utils.collections.iteration;
import java.io.Serializable;
import java.util.Iterator;
public class TransformIterator<A, B> implements Serializable, Iterator<B> {
public TransformIterator(final Iterable<A> iterable, final Transform<A, B> transform) {
this(iterable.iterator(), transform);
}
public TransformIterator(final Iterator<A> iterator,
final Transform<A, B> transform) {
this.iterator = iterator;
this.transform = transform;
}
public Iterator<A> getIterator() {
return iterator;
}
public void setIterator(final Iterator<A> iterator) {
this.iterator = iterator;
}
public Transform<A, B> getTransform() {
return transform;
}
public void setTransform(
final Transform<A, B> transform) {
this.transform = transform;
}
@Override public boolean hasNext() {
return iterator.hasNext();
}
@Override public B next() {
return transform.transform(iterator.next());
}
public interface Transform<A, B> extends Serializable {
B transform(A item);
}
private Iterator<A> iterator;
private Transform<A, B> transform;
}
| 1,252 | 24.06 | 91 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/lists/IndexList.java | package tsml.classifiers.distance_based.utils.collections.lists;
import java.io.Serializable;
import java.util.AbstractList;
public class IndexList extends AbstractList<Integer> implements Serializable {
public IndexList(final int size) {
if(size < 0) {
throw new IllegalArgumentException("size cannot be less than 0");
}
this.size = size;
}
private final int size;
@Override public Integer get(final int i) {
return i;
}
@Override public int size() {
return size;
}
}
| 559 | 21.4 | 78 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/lists/RepeatList.java | package tsml.classifiers.distance_based.utils.collections.lists;
import java.util.AbstractList;
public class RepeatList<A> extends AbstractList<A> {
public RepeatList(final A element, final int size) {
this.element = element;
this.size = size;
}
private final A element;
private final int size;
@Override public A get(final int i) {
return element;
}
@Override public int size() {
return size;
}
}
| 472 | 19.565217 | 64 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/lists/UniqueList.java | package tsml.classifiers.distance_based.utils.collections.lists;
import java.util.*;
public class UniqueList<A> extends AbstractList<A> {
private Set<A> set;
private List<A> list;
public UniqueList() {
clear();
}
@Override public int size() {
return list.size();
}
@Override public A get(final int i) {
return list.get(i);
}
@Override public A set(final int i, final A item) {
if(!set.add(item)) {
// already contains item so don't bother adding it, just return the current value in it's place
return list.get(i);
} else {
// does not contain item so set in the list
return list.set(i, item);
}
}
@Override public void add(final int i, final A item) {
if(set.add(item)) {
// item was not in the set so add to the list
list.add(i, item);
} else {
// cannot add the item as already in set
}
}
@Override public A remove(final int i) {
final A removed = list.remove(i);
set.remove(removed);
return removed;
}
@Override public boolean remove(final Object o) {
if(set.remove(o)) {
return list.remove(o);
} else {
return false;
}
}
@Override public void clear() {
set = new HashSet<>();
list = new ArrayList<>();
}
}
| 1,451 | 22.419355 | 107 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/lists/UnorderedArrayList.java | package tsml.classifiers.distance_based.utils.collections.lists;
import java.io.Serializable;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
/**
* An ArrayList except operations may reorder the list for efficiency purposes, e.g. the remove(int i) function swaps the element to the end and then removes to avoid shuffling all elements > i down 1 place.
* @param <A>
*/
public class UnorderedArrayList<A> extends AbstractList<A> implements Serializable {
private final ArrayList<A> list;
public UnorderedArrayList() {
this(new ArrayList<>());
}
public UnorderedArrayList(int size) {
this(new ArrayList<>(size));
}
public UnorderedArrayList(Collection<A> other) {
list = new ArrayList<>(other);
}
@Override public A remove(final int i) {
int endIndex = list.size() - 1;
// swap the element to be removed to the end
Collections.swap(list, i, endIndex);
// remove the end element
return list.remove(endIndex);
}
@Override public boolean remove(final Object o) {
return list.remove(o);
}
@Override public void clear() {
list.clear();
}
@Override public A get(final int i) {
return list.get(i);
}
@Override public void add(final int i, final A a) {
list.add(a);
Collections.swap(list, i, list.size() - 1);
}
@Override public A set(final int i, final A a) {
return list.set(i, a);
}
@Override public int size() {
return list.size();
}
}
| 1,685 | 25.761905 | 208 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/ParamHandler.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params;
import weka.core.OptionHandler;
import java.util.*;
/**
* Purpose: handle generic options for a class. These may be in the form of a String[] (weka style), List<String> or
* bespoke ParamSet / ParamSpace themselves.
*
* You must override the getParams() and setParams() functions. These will be automatically transformed into list /
* array format for compatibility with non-bespoke non-ParamSet / ParamSpace code.
*
* Contributors: goastler
*/
public interface ParamHandler
extends OptionHandler {
/**
* get the options array
* @return
*/
@Override
default String[] getOptions() {
return getOptionsList().toArray(new String[0]);
}
/**
* get the options list.
* @return
*/
default List<String> getOptionsList() {
return getParams().getOptionsList();
}
/**
* set options via list.
* @param options
* @throws Exception
*/
default void setOptions(List<String> options) throws
Exception {
ParamSet params = new ParamSet();
params.setOptions(options);
setParams(params);
}
/**
* set options via array.
* @param options the list of options as an array of strings
* @throws Exception
*/
@Override
default void setOptions(String[] options) throws
Exception {
setOptions(Arrays.asList(options));
}
@Override
default Enumeration listOptions() {
return Collections.enumeration(listParams());
}
default void setParams(ParamSet paramSet) throws Exception {
// OVERRIDE THIS
}
default ParamSet getParams() {
// OVERRIDE THIS
return new ParamSet();
}
default Set<String> listParams() {
// todo use getParams to populate this
throw new UnsupportedOperationException("param list not specified");
}
}
| 2,789 | 28.0625 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/ParamHandlerTest.java | package tsml.classifiers.distance_based.utils.collections.params;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import tsml.classifiers.distance_based.distances.dtw.DTWDistance;
import tsml.classifiers.distance_based.distances.ed.EDistance;
import tsml.classifiers.distance_based.distances.erp.ERPDistance;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.distances.msm.MSMDistance;
import tsml.classifiers.distance_based.distances.twed.TWEDistance;
import tsml.classifiers.distance_based.distances.wdtw.WDTWDistance;
import tsml.classifiers.distance_based.utils.system.copy.CopierUtils;
import java.util.Arrays;
import java.util.Collection;
import static tsml.classifiers.distance_based.distances.dtw.spaces.DDTWDistanceSpace.newDDTWDistance;
import static tsml.classifiers.distance_based.distances.wdtw.spaces.WDDTWDistanceSpace.newWDDTWDistance;
@RunWith(Parameterized.class)
public class ParamHandlerTest {
@Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ new DTWDistance() },
{ new ERPDistance() },
{ new LCSSDistance() },
{ new MSMDistance() },
{ new EDistance() },
{ new WDTWDistance() },
{ new TWEDistance() },
{ newWDDTWDistance() },
{ newDDTWDistance() },
});
}
@Parameterized.Parameter(0)
public Object handler;
public Object getHandler() {
return CopierUtils.deepCopy(handler);
}
// @Test()
// public void testSetMissingParams() {
// final Object handler = getHandler();
// try {
// ParamHandlerUtils.setParams(handler, new ParamSet().add("this is the missing flag", 0.6));
// Assert.fail("expected exception on invalid parameter");
// } catch(RuntimeException ignored) {}
// }
@Test
public void testGetParams() {
final Object handler = getHandler();
final ParamSet params = ParamHandlerUtils.getParams(handler);
}
@Test
public void testSetParams() throws Exception {
final Object handler = getHandler();
final ParamSet paramSet = ParamHandlerUtils.getParams(handler);
for(String name : paramSet.keySet()) {
final Object value = paramSet.get(name);
if(
value instanceof Double ||
value instanceof Float ||
value instanceof Integer ||
value instanceof Byte ||
value instanceof Short ||
value instanceof Character ||
value instanceof Long
) {
ParamHandlerUtils.setParams(handler, new ParamSet().add(name, "0"));
Assert.assertEquals(0d, (double) ParamHandlerUtils.getParams(handler).get(name), 0d);
ParamHandlerUtils.setParams(handler, new ParamSet().add(name, "1"));
Assert.assertEquals(1d, (double) ParamHandlerUtils.getParams(handler).get(name), 0d);
} else {
// non primitive type
// get the type, make fresh copy of it. This will then be != to the previous value
final Object copyA = CopierUtils.deepCopy(value);
final Object copyB = CopierUtils.deepCopy(value);
ParamHandlerUtils.setParams(handler, new ParamSet().add(name, copyA));
Assert.assertNotSame(value, ParamHandlerUtils.getParams(handler).get(name));
ParamHandlerUtils.setParams(handler, new ParamSet().add(name, copyB));
Assert.assertNotSame(copyA, ParamHandlerUtils.getParams(handler).get(name));
}
}
}
}
| 3,942 | 40.505263 | 104 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/ParamHandlerUtils.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params;
import tsml.classifiers.distance_based.utils.strings.StrUtils;
import weka.core.OptionHandler;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
public class ParamHandlerUtils {
/**
* set a parameter to a ParamSet. Parameters are propogated through that object to children, if any parameters
* are specified for the children.
* @param object
* @param paramSet
*/
public static void setParams(Object object, ParamSet paramSet) {
try {
if(object instanceof ParamHandler) {
((ParamHandler) object).setParams(paramSet);
} else if(object instanceof OptionHandler) {
((OptionHandler) object).setOptions(paramSet.getOptions());
} else {
throw new IllegalArgumentException("params not settable");
}
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public static ParamSet getParams(Object object) {
try {
if(object instanceof ParamHandler) {
return ((ParamHandler) object).getParams();
} else if(object instanceof OptionHandler) {
return new ParamSet(((OptionHandler) object).getOptions());
} else {
// not a paramhandler so return empty params
return new ParamSet();
}
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
}
| 2,381 | 34.552239 | 114 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/ParamMap.java | package tsml.classifiers.distance_based.utils.collections.params;
import tsml.classifiers.distance_based.utils.collections.DefaultMap;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.ParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.continuous.ContinuousParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.discrete.DiscreteParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.distribution.Distribution;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class ParamMap implements Serializable, DefaultMap<String, List<ParamDimension<?>>> {
// 1 to many mapping of param name to list of param dimensions
private final Map<String, List<ParamDimension<?>>> dimensionMap = new LinkedHashMap<>();
@Override
public String toString() {
return String.valueOf(dimensionMap);
}
@Override public List<ParamDimension<?>> get(final Object name) {
return dimensionMap.get(name);
}
@Override public int size() {
return dimensionMap.size();
}
@Override public Set<String> keySet() {
return Collections.unmodifiableMap(dimensionMap).keySet();
}
@Override public Collection<List<ParamDimension<?>>> values() {
return Collections.unmodifiableMap(dimensionMap).values();
}
@Override public Set<Entry<String, List<ParamDimension<?>>>> entrySet() {
return Collections.unmodifiableMap(dimensionMap).entrySet();
}
public ParamMap addDimension(String name, ParamDimension<?> dimension) {
dimensionMap.computeIfAbsent(name, s -> new ArrayList<>()).add(dimension);
return this;
}
public <A> ParamMap add(String name, double[] values) {
return add(name, Arrays.stream(values).boxed().collect(Collectors.toList()));
}
public <A> ParamMap add(String name, int[] values) {
return add(name, Arrays.stream(values).boxed().collect(Collectors.toList()));
}
public <A> ParamMap add(String name, long[] values) {
return add(name, Arrays.stream(values).boxed().collect(Collectors.toList()));
}
public <A> ParamMap add(String name, List<A> values) {
final DiscreteParamDimension<A> dimension;
if(values instanceof DiscreteParamDimension) {
dimension = (DiscreteParamDimension<A>) values;
} else {
dimension = new DiscreteParamDimension<>(values);
}
return addDimension(name, dimension);
}
public <A> ParamMap add(String name, List<A> values, ParamSpace subSpaces) {
return addDimension(name, new DiscreteParamDimension<>(values, subSpaces));
}
public <A> ParamMap add(String name, List<A> values, ParamMap subMap) {
return add(name, values, new ParamSpace(subMap));
}
public <A> ParamMap add(String name, Distribution<A> values) {
return addDimension(name, new ContinuousParamDimension<A>(values));
}
public <A> ParamMap add(String name, Distribution<A> values, ParamSpace subSpaces) {
return addDimension(name, new ContinuousParamDimension<>(values, subSpaces));
}
public <A> ParamMap add(String name, Distribution<A> values, ParamMap subMap) {
return add(name, values, new ParamSpace(subMap));
}
}
| 3,488 | 36.516129 | 111 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/ParamSet.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import tsml.classifiers.distance_based.utils.system.copy.CopierUtils;
import tsml.classifiers.distance_based.utils.strings.StrUtils;
import weka.core.OptionHandler;
import weka.core.Utils;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import static tsml.classifiers.distance_based.utils.strings.StrUtils.toOptionValue;
public class ParamSet implements Map<String, Object>, ParamHandler {
private final Map<String, Object> map = new LinkedHashMap<>();
public ParamSet(Map<String, Object> other) {
putAll(other);
}
public ParamSet() {}
public ParamSet(String[] options) throws Exception {
setOptions(options);
}
public ParamSet(List<String> options) throws Exception {
setOptions(options);
}
public ParamSet(String key, Object value, List<ParamSet> subParamSets) {
add(key, value, subParamSets);
}
public ParamSet(String key, Object value, ParamSet subParamSet) {
add(key, value, subParamSet);
}
public ParamSet(String key, Object value) {
add(key, value);
}
@Override public void setOptions(final List<String> options) throws Exception {
setOptions(options.toArray(new String[options.size()]));
}
@Override public void setOptions(final String[] options) throws Exception {
for(int i = 0; i < options.length; i++) {
String option = options[i];
if(option.isEmpty()) {
// skip this option as it's empty
continue;
}
String flag = StrUtils.unflagify(option);
// if the flag is an option (i.e. key value pair, not just a flag)
if(StrUtils.isOption(option, options)) {
// for example, "-d "DTW -w 5""
// get the next value as the option value and split it into sub options
// the example would be split into ["DTW", "-w", "5"]
String[] subOptions = Utils.splitOptions(options[++i]);
// the 0th element is the main option value
// in the example this is "DTW"
String optionValue = subOptions[0];
subOptions[0] = "";
// get the value from str form
Object value = StrUtils.fromOptionValue(optionValue);
// if the return value is not a string, there's further options to set and the value can handle options
if(subOptions.length > 1 && value instanceof OptionHandler) {
// handle sub parameters
ParamSet paramSet = new ParamSet();
// subOptions contains only the parameters for the option value
// in the example this is ["-w", "5"]
// set these suboptions for the parameter value
paramSet.setOptions(subOptions);
// add the parameter to this paramSet with correspond value (example "DTW") and corresponding
// sub options / parameters for that value (example "-w 5")
put(flag, value, paramSet);
} else {
// the parameter is raw, i.e. "-a 6" <-- 6 has no parameters, therefore is raw
put(flag, value);
}
} else {
// assume all flags are represented using boolean values
put(flag, true);
}
}
}
@Override public int size() {
return map.size();
}
@Override public boolean isEmpty() {
return map.isEmpty();
}
@Override public boolean containsKey(final Object o) {
return map.containsKey(o);
}
@Override public boolean containsValue(final Object o) {
return map.containsValue(o);
}
@Override public Object get(final Object o) {
// must copy value otherwise can be changed externally
return CopierUtils.deepCopy(map.get(o));
}
public <A> A get(String key) {
return (A) get((Object) key);
}
@Override public Object put(final String s, final Object o) {
// copy value so external changes to the value are not propagated in the paramset
return map.put(s, CopierUtils.deepCopy(o));
}
public Object put(final String key, final Object value, ParamSet paramSet) {
paramSet.applyTo(value);
return put(key, value);
}
public ParamSet add(final String key, final Object value) {
return add(key, value, new ParamSet());
}
public ParamSet add(final String key, final Object value, final ParamSet subParamSet) {
final Object before = put(key, value, subParamSet);
if(before != null) {
throw new IllegalArgumentException("already have parameter set under key: " + key);
}
return this;
}
public ParamSet add(final String key, final Object value, final Iterable<ParamSet> subParamSets) {
for(ParamSet paramSet : subParamSets) {
paramSet.applyTo(value);
}
return add(key, value);
}
public void applyTo(Object value) {
if(this.isEmpty()) {
return;
}
if(value instanceof ParamHandler) {
try {
((ParamHandler) value).setParams(this);
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
} else if(value instanceof OptionHandler) {
try {
((OptionHandler) value).setOptions(this.getOptions());
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
} else {
throw new IllegalArgumentException("{" + value.toString() + "} is not a ParamHandler or OptionHandler therefore "
+ "cannot set the parameters " + this.toString());
}
}
@Override public String toString() {
return Utils.joinOptions(getOptions());
}
@Override
public List<String> getOptionsList() {
List<String> list = new ArrayList<>();
for(Map.Entry<String, ?> entry : entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
list.add(StrUtils.flagify(name));
list.add(toOptionValue(value));
}
return list;
}
public String toJson() {
/*
supported formats:
{
"a": 1,
"b": [
2,
3
],
"c": [
[
4
],
[
5
]
],
"d": [
[
6,
{
"da": 6.1,
"db": [
6.2,
6.3
]
}
],
[
7,
{
"dc": 6.4,
"dd": [
6.5,
6.6
]
}
]
]
}
essentially, a param could:
- map to a single value (a)
- map to multiple values (b)
- map to multiple values each contained in a array (c)
- map to multiple values, each in their own array with a second obj in the array corresponding to their paramset in json form (d)
*/
return new GsonBuilder().create().toJson(toJsonValue());
}
protected Map<String, Object> toJsonValue() {
final HashMap<String, Object> output = new HashMap<>();
for(String name : keySet()) {
Object value = get(name);
final ParamSet params = ParamHandlerUtils.getParams(value);
if(!params.isEmpty()) {
value = Arrays.asList(value, params.toJsonValue());
}
output.put(name, value);
}
return output;
}
protected static ParamSet fromJsonValue(Map<String, Object> json) {
final ParamSet paramSet = new ParamSet();
for(String name : json.keySet()) {
Object value = json.get(name);
if(value instanceof List<?>) {
// list of 2 items: the value then the sub params
final List<?> parts = (List<?>) value;
value = parts.get(0);
final ParamSet params = (ParamSet) parts.get(1);
params.applyTo(value);
}
paramSet.put(name, value);
}
return paramSet;
}
public static ParamSet fromJson(String json) {
final HashMap<?, ?> hashMap = new Gson().fromJson(json, HashMap.class);
final ParamSet paramSet = new ParamSet();
for(Map.Entry<?, ?> entry : hashMap.entrySet()) {
final Object key = entry.getKey();
final String keyStr;
if(key instanceof String) {
keyStr = (String) key;
} else {
throw new IllegalStateException("expected string type for key: " + key);
}
Object value = entry.getValue();
ParamSet subParamSet = new ParamSet();
if(value instanceof List<?>) {
final List<?> parts = ((List<?>) value);
value = parts.get(0);
subParamSet = ParamSet.fromJsonValue((Map<String, Object>) parts.get(1));
}
paramSet.put(keyStr, value, subParamSet);
}
return paramSet;
}
@Override public Object remove(final Object o) {
return map.remove(o);
}
@Override public void putAll(final Map<? extends String, ?> map) {
this.map.putAll(map);
}
@Override public void clear() {
map.clear();
}
@Override public Set<String> keySet() {
return map.keySet();
}
@Override public Collection<Object> values() {
return map.values();
}
@Override public Set<Entry<String, Object>> entrySet() {
return map.entrySet();
}
@Override public boolean equals(final Object o) {
return map.equals(o);
}
@Override public int hashCode() {
return map.hashCode();
}
public <A> A get(String key, A defaultValue) {
return (A) getOrDefault(key, defaultValue);
}
@Override public Object getOrDefault(final Object o, final Object defaultValue) {
Object value = map.getOrDefault(o, defaultValue);
if(value instanceof String) {
value = StrUtils.parse((String) value, defaultValue.getClass());
}
return value;
}
@Override public void forEach(final BiConsumer<? super String, ? super Object> biConsumer) {
map.forEach(biConsumer);
}
@Override public void replaceAll(final BiFunction<? super String, ? super Object, ?> biFunction) {
map.replaceAll(biFunction);
}
@Override public Object putIfAbsent(final String s, final Object o) {
return map.putIfAbsent(s, o);
}
@Override public boolean remove(final Object o, final Object o1) {
return map.remove(o, o1);
}
@Override public boolean replace(final String s, final Object o, final Object v1) {
return map.replace(s, o, v1);
}
@Override public Object replace(final String s, final Object o) {
return map.replace(s, o);
}
@Override public Object computeIfAbsent(final String s, final Function<? super String, ?> function) {
return map.computeIfAbsent(s, function);
}
@Override public Object computeIfPresent(final String s,
final BiFunction<? super String, ? super Object, ?> biFunction) {
return map.computeIfPresent(s, biFunction);
}
@Override public Object compute(final String s,
final BiFunction<? super String, ? super Object, ?> biFunction) {
return map.compute(s, biFunction);
}
@Override public Object merge(final String s, final Object o,
final BiFunction<? super Object, ? super Object, ?> biFunction) {
return map.merge(s, o, biFunction);
}
}
| 13,165 | 32.586735 | 141 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/ParamSetTest.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params;
import com.beust.jcommander.internal.Lists;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.utils.strings.StrUtils;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class ParamSetTest {
@Test
public void testDuplicate() {
final ParamSet paramSet = new ParamSet();
paramSet.add("a", 5);
try {
paramSet.add("a", 6);
Assert.fail("added duplicate parameter");
} catch(Exception ignored) {}
}
@Test
public void testSetAndGetOptions() {
String aFlag = "a";
int aValue = 1;
ParamSet paramSet = new ParamSet(aFlag, aValue);
String[] options = paramSet.getOptions();
Assert.assertArrayEquals(options, new String[] {"-" + aFlag, String.valueOf(aValue)});
ParamSet other = new ParamSet();
try {
other.setOptions(options);
} catch(Exception e) {
Assert.fail(e.getMessage());
}
Assert.assertNotNull(other.get(aFlag));
final String o = other.get(aFlag);
Assert.assertEquals(String.valueOf(o), String.valueOf(aValue));
}
@Test
public void testEmptyToString() {
ParamSet paramSet;
paramSet = new ParamSet();
// System.out.println(paramSet);
Assert.assertEquals(paramSet.toString(), "");
}
@Test
public void testHashcodeAndEquals() {
String aFlag = "a";
int aValue = 1;
ParamSet paramSet = new ParamSet(aFlag, aValue);
String bFlag = "a";
int bValue = 1;
ParamSet otherParamSet = new ParamSet(bFlag, bValue);
String cFlag = "c";
int cValue = 111;
ParamSet unequalParamSet = new ParamSet(cFlag, cValue);
Assert.assertNotEquals(paramSet, unequalParamSet);
Assert.assertEquals(paramSet, otherParamSet);
Assert.assertEquals(paramSet.hashCode(), otherParamSet.hashCode());
Assert.assertNotEquals(otherParamSet, unequalParamSet);
}
@Test
public void testAddNameAndValue() {
String aFlag = "a";
int aValue = 1;
ParamSet paramSet = new ParamSet(aFlag, aValue);
// System.out.println(paramSet);
Assert.assertEquals(paramSet.toString(), "-a 1");
Assert.assertFalse(paramSet.isEmpty());
Assert.assertEquals(paramSet.size(), 1);
Object value = paramSet.get(aFlag);
Assert.assertEquals(value, aValue);
}
@Test
public void testAddNameAndValueAndParamSet() {
String aFlag = "a";
LCSSDistance aValue = new LCSSDistance();
String bFlag = WINDOW_FLAG;
double bValue = 0.5;
String cFlag = LCSSDistance.EPSILON_FLAG;
double cValue = 0.2;
ParamSet subParamSetB = new ParamSet(bFlag, bValue);
ParamSet subParamSetC = new ParamSet(cFlag, cValue);
ParamSet paramSet = new ParamSet(aFlag, aValue, Lists.newArrayList(subParamSetB, subParamSetC));
// System.out.println(paramSet);
aValue.setEpsilon(cValue);
aValue.setWindow(bValue);
Assert.assertEquals("-a \"tsml.classifiers.distance_based.distances.lcss.LCSSDistance "
+ "-w 0.5 -e 0.2\"", paramSet.toString());
Assert.assertFalse(paramSet.isEmpty());
Assert.assertEquals(paramSet.size(), 1);
Object aValueOut = paramSet.get(aFlag);
Assert.assertNotSame(aValueOut, aValue);
Object list = ((ParamHandler) aValueOut).getParams().get(bFlag);
Assert.assertEquals(list, bValue);
list = ((ParamHandler) aValueOut).getParams().get(cFlag);
Assert.assertEquals(list, cValue);
try {
Assert.assertNotSame(aValue, paramSet.get(aFlag));
} catch(Exception e) {
Assert.fail(e.toString());
}
try {
// value may be in string form
Assert.assertNotSame(aValue, new ParamSet(aFlag, StrUtils.toOptionValue(aValue)).get(aFlag, aValue));
} catch(Exception e) {
Assert.fail(e.toString());
}
try {
Assert.assertEquals(cValue, subParamSetC.get(cFlag, cValue), -1d);
} catch(Exception e) {
Assert.fail(e.toString());
}
try {
// value may be in string form
Assert.assertEquals(cValue, new ParamSet().add(cFlag, String.valueOf(cValue)).get(cFlag, -1d), 0d);
} catch(Exception e) {
Assert.fail(e.toString());
}
}
@Test
public void testStrings() {
String str = "string based parameter value";
String value = StrUtils.toOptionValue(str);
try {
Object obj = StrUtils.fromOptionValue(value);
Assert.assertEquals(str, obj);
} catch(Exception e) {
Assert.fail(e.toString());
}
}
}
| 5,915 | 34.42515 | 113 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/ParamSpace.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params;
import tsml.classifiers.distance_based.utils.collections.DefaultList;
import tsml.classifiers.distance_based.utils.collections.checks.Checks;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class ParamSpace implements DefaultList<ParamMap> {
public ParamSpace(final List<ParamMap> paramMaps) {
addAll(paramMaps);
}
public ParamSpace() {
}
public ParamSpace(ParamMap... paramMap) {
this(Arrays.asList(paramMap));
}
private final List<ParamMap> paramMaps = new ArrayList<>();
public boolean add(ParamMap paramMap) {
paramMaps.add(Objects.requireNonNull(paramMap));
return true;
}
@Override public ParamMap get(final int i) {
return paramMaps.get(i);
}
@Override public int size() {
return paramMaps.size();
}
@Override public String toString() {
return paramMaps.toString();
}
public ParamMap getSingle() {
return Checks.requireSingle(paramMaps);
}
}
| 1,904 | 27.863636 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/ParamSpaceBuilder.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params;
import tsml.data_containers.TimeSeriesInstances;
import tsml.data_containers.utilities.Converter;
import weka.core.Instances;
import java.io.Serializable;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public interface ParamSpaceBuilder extends Serializable {
default ParamSpace build(TimeSeriesInstances data) {
return build(Converter.toArff(data));
}
default ParamSpace build(Instances data) {
return build(Converter.fromArff(data));
}
}
| 1,367 | 31.571429 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/ParamSpaceTest.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import tsml.classifiers.distance_based.distances.DistanceMeasure;
import tsml.classifiers.distance_based.distances.dtw.DTWDistance;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.ParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.continuous.ContinuousParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.discrete.DiscreteParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.distribution.double_based.UniformDoubleDistribution;
import static tsml.classifiers.distance_based.distances.dtw.DTW.WINDOW_FLAG;
import static tsml.classifiers.distance_based.distances.dtw.spaces.DDTWDistanceSpace.newDDTWDistance;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class ParamSpaceTest {
public ParamSpaceTest() {
// for users outside of this class, make sure we're all setup for tests
before();
}
private int seed;
private ParamSpace wParams;
private List<Integer> wParamValues;
private ParamSpace lParams;
private UniformDoubleDistribution eDist;
private UniformDoubleDistribution dDist;
private DiscreteParamDimension<DistanceMeasure> wDmParams;
private DiscreteParamDimension<DistanceMeasure> lDmParams;
private ParamSpace params;
@Before
public void before() {
seed = 0;
wParamValues = buildWParamValues();
wParams = buildWParams();
lParams = buildLParams();
eDist = buildEDist();
dDist = buildDDist();
wDmParams = buildWDmParams();
lDmParams = buildLDmParams();
params = buildParams();
}
public Random buildRandom() {
return new Random(seed);
}
public List<Integer> buildWParamValues() {
return Arrays.asList(1, 2, 3, 4, 5);
}
public ParamSpace buildWParams() {
ParamMap wParams = new ParamMap();
List<Integer> wParamValues = buildWParamValues();
wParams.add(WINDOW_FLAG, wParamValues);
return new ParamSpace(wParams);
}
public List<Integer> buildDummyValuesA() {
return Arrays.asList(1,2,3,4,5);
}
public List<Integer> buildDummyValuesB() {
return Arrays.asList(6,7,8,9,10);
}
public ParamSpace build2DDiscreteSpace() {
ParamMap space = new ParamMap();
List<Integer> a = buildDummyValuesA();
List<Integer> b = buildDummyValuesB();
space.add("a", a);
space.add("b", b);
return new ParamSpace(space);
}
public UniformDoubleDistribution buildDummyDistributionA() {
UniformDoubleDistribution u = new UniformDoubleDistribution(0d, 0.5d);
return u;
}
public UniformDoubleDistribution buildDummyDistributionB() {
UniformDoubleDistribution u = new UniformDoubleDistribution(0.5d, 1d);
return u;
}
public ParamSpace build2DContinuousSpace() {
ParamMap space = new ParamMap();
UniformDoubleDistribution a = buildDummyDistributionA();
UniformDoubleDistribution b = buildDummyDistributionB();
space.add("a", a);
space.add("b", b);
return new ParamSpace(space);
}
public UniformDoubleDistribution buildEDist() {
UniformDoubleDistribution eDist = new UniformDoubleDistribution();
eDist.setStart(0d);
eDist.setEnd(0.25);
return eDist;
}
public UniformDoubleDistribution buildDDist() {
UniformDoubleDistribution eDist = new UniformDoubleDistribution();
eDist.setStart(0.5);
eDist.setEnd(1.0);
return eDist;
}
public ParamSpace buildLParams() {
ParamMap lParams = new ParamMap();
lParams.add(LCSSDistance.EPSILON_FLAG, buildEDist());
lParams.add(WINDOW_FLAG, buildDDist());
return new ParamSpace(lParams);
}
public DiscreteParamDimension<DistanceMeasure> buildWDmParams() {
DiscreteParamDimension<DistanceMeasure> wDmParams = new DiscreteParamDimension<>(
Arrays.asList(new DTWDistance(), newDDTWDistance()));
wDmParams.setSubSpace(buildWParams());
return wDmParams;
}
public DiscreteParamDimension<DistanceMeasure> buildLDmParams() {
DiscreteParamDimension<DistanceMeasure> lDmParams = new DiscreteParamDimension<>(
Arrays.asList(new LCSSDistance()));
lDmParams.setSubSpace(buildLParams());
return lDmParams;
}
public ParamSpace buildParams() {
ParamMap params = new ParamMap();
params.add(DistanceMeasure.DISTANCE_MEASURE_FLAG, lDmParams);
params.add(DistanceMeasure.DISTANCE_MEASURE_FLAG, wDmParams);
return new ParamSpace(params);
}
@Test
public void testAddAndGetForListOfValues() {
List<ParamDimension<?>> valuesOut = wParams.getSingle().get(WINDOW_FLAG);
List<?> values = ((DiscreteParamDimension<?>) valuesOut.get(0)).getValues();
Assert.assertEquals(values, wParamValues);
}
@Test
public void testAddAndGetForDistributionOfValues() {
List<ParamDimension<?>> dimensions = lParams.getSingle().get(LCSSDistance.EPSILON_FLAG);
for(ParamDimension<?> d : dimensions) {
ContinuousParamDimension<?> dimension = (ContinuousParamDimension<?>) d;
Object values = dimension.getDistribution();
Assert.assertEquals(eDist, values);
}
dimensions = lParams.getSingle().get(WINDOW_FLAG);
for(ParamDimension<?> d : dimensions) {
ContinuousParamDimension<?> dimension = (ContinuousParamDimension<?>) d;
Object values = dimension.getDistribution();
Assert.assertEquals(values, dDist);
}
}
@Test
public void testParamsToString() {
// System.out.println(params.toString());
Assert.assertEquals("[{d=[{values=[LCSSDistance -w 1.0 -e 0.01], "
+ "subSpace=[{e=[dist=UniformDouble(0.0, 0.25)], "
+ "w=[dist=UniformDouble(0.5, 1.0)]}]}, {values=[DTWDistance -w 1.0, DDTWDistance -w 1.0], "
+ "subSpace=[{w=[{values=[1, 2, 3, 4, 5]}]}]}]}]", params.toString());
}
@Test
public void testWParamsToString() {
// System.out.println(wParams.toString());
Assert.assertEquals("[{w=[{values=[1, 2, 3, 4, 5]}]}]", wParams.toString());
}
@Test
public void testLParamsToString() {
// System.out.println(lParams.toString());
Assert.assertEquals("[{e=[dist=UniformDouble(0.0, 0.25)], "
+ "w=[dist=UniformDouble(0.5, 1.0)]}]", lParams.toString());
}
@Test
public void testWDmParamsToString() {
// System.out.println(wDmParams.toString());
Assert.assertEquals("{values=[DTWDistance -w 1.0, DDTWDistance -w 1.0], subSpace=[{w=[{values=[1, "
+ "2, 3, 4, 5]}]}]}", wDmParams.toString());
}
@Test
public void testLDmParamsToString() {
// System.out.println(lDmParams.toString());
Assert.assertEquals("{values=[LCSSDistance -w 1.0 -e 0.01], "
+ "subSpace=[{e=[dist=UniformDouble(0.0, 0.25)], "
+ "w=[dist=UniformDouble(0.5, 1.0)]}]}", lDmParams.toString());
}
@Test
public void testEquals() {
ParamSpace a = wParams;
ParamSpace b = wParams;
ParamSpace c = lParams;
ParamSpace d = lParams;
Assert.assertEquals(a, b);
Assert.assertEquals(c, d);
Assert.assertNotEquals(a, c);
Assert.assertNotEquals(a.hashCode(), c.hashCode());
Assert.assertNotEquals(b, c);
Assert.assertNotEquals(b.hashCode(), c.hashCode());
Assert.assertNotEquals(a, d);
Assert.assertNotEquals(a.hashCode(), d.hashCode());
Assert.assertNotEquals(b, d);
Assert.assertNotEquals(b.hashCode(), d.hashCode());
}
}
| 8,948 | 35.82716 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/dimensions/ParamDimension.java | package tsml.classifiers.distance_based.utils.collections.params.dimensions;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* hold the parameter dimension. In here should be a method of retreiving values for the given parameter along
* with sub parameter spaces to explore
* @param <A>
*/
public abstract class ParamDimension<A> implements Serializable {
// list of subspaces to explore
private ParamSpace subSpace;
public ParamDimension() {
this(new ParamSpace());
}
public ParamDimension(ParamSpace subSpace) {
setSubSpace(subSpace);
}
@Override
public String toString() {
if(!getSubSpace().isEmpty()) {
return ", subSpace=" + subSpace;
}
return "";
}
public ParamSpace getSubSpace() {
return subSpace;
}
public void setSubSpace(final ParamSpace subSpace) {
this.subSpace = Objects.requireNonNull(subSpace);
}
}
| 1,089 | 23.222222 | 110 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/dimensions/continuous/ContinuousParamDimension.java | package tsml.classifiers.distance_based.utils.collections.params.dimensions.continuous;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.ParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.distribution.Distribution;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class ContinuousParamDimension<A> extends ParamDimension<Distribution<A>> {
public ContinuousParamDimension(final Distribution<A> values) {
this(values, new ParamSpace());
}
public ContinuousParamDimension(final Distribution<A> distribution,
final ParamSpace subSpace) {
super(subSpace);
this.distribution = Objects.requireNonNull(distribution);
}
private final Distribution<A> distribution;
public Distribution<A> getDistribution() {
return distribution;
}
@Override public String toString() {
return "dist=" + distribution + super.toString();
}
}
| 1,181 | 30.105263 | 90 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/dimensions/discrete/DiscreteParamDimension.java | package tsml.classifiers.distance_based.utils.collections.params.dimensions.discrete;
import tsml.classifiers.distance_based.utils.system.copy.CopierUtils;
import tsml.classifiers.distance_based.utils.collections.DefaultList;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.ParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.iteration.PermutationUtils;
import java.util.List;
import java.util.Objects;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class DiscreteParamDimension<A> extends ParamDimension<List<A>> implements DefaultList<Object> {
private List<A> values;
public DiscreteParamDimension(final List<A> values) {
this(values, new ParamSpace());
}
public DiscreteParamDimension(final List<A> values, ParamSpace subSpaces) {
super(subSpaces);
setValues(values);
}
public int getNumValues() {
return getValues().size();
}
@Override
public Object get(final int index) {
final List<Integer> binSizes = getBinSizes();
final List<Integer> indices = PermutationUtils.fromPermutation(index, binSizes);
final Integer valueIndex = indices.remove(0);
// must copy objects otherwise every paramset uses the same object reference!
final Object value = CopierUtils.deepCopy(values.get(valueIndex));
final ParamSpace subSpace = getSubSpace();
if(!subSpace.isEmpty()) {
// remove the first size as used
binSizes.remove(0);
int subIndex = PermutationUtils.toPermutation(indices, binSizes);
ParamSet subParamSet = new GridParamSpace(subSpace).get(subIndex);
subParamSet.applyTo(value);
}
return value;
}
@Override
public int size() {
return PermutationUtils.numPermutations(getBinSizes());
}
public List<Integer> getBinSizes() {
final List<Integer> sizes = getSubSpaceBinSizes();
// put values size on the front
sizes.add(0, getNumValues());
return sizes;
}
public List<Integer> getSubSpaceBinSizes() {
return new GridParamSpace(getSubSpace()).getParamMapSizes();
}
public List<A> getValues() {
return values;
}
public void setValues(final List<A> values) {
this.values = Objects.requireNonNull(values);
}
@Override public String toString() {
return "{" +
"values=" + values + super.toString() +
'}';
}
}
| 2,767 | 32.349398 | 103 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/dimensions/discrete/GridParamMap.java | package tsml.classifiers.distance_based.utils.collections.params.dimensions.discrete;
import tsml.classifiers.distance_based.utils.collections.DefaultMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.ParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.iteration.PermutationUtils;
import tsml.classifiers.distance_based.utils.collections.views.WrappedList;
import java.util.*;
public class GridParamMap implements DefaultMap<String, List<ParamDimension<?>>> {
public GridParamMap(final ParamMap paramMap) {
this.paramMap = Objects.requireNonNull(paramMap);
if(!isDiscrete(paramMap)) {
throw new IllegalArgumentException("param space not discrete");
}
}
private final ParamMap paramMap;
public int size() {
return PermutationUtils.numPermutations(getBinSizes());
}
@Override public List<ParamDimension<?>> get(final Object name) {
return paramMap.get(name);
}
public ParamSet get(List<Integer> indices) {
final ParamSet paramSet = new ParamSet();
int i = 0;
// loop through dimensions
for(Map.Entry<String, List<ParamDimension<?>>> entry : entrySet()) {
// get the dimension
final int subIndex = indices.get(i);
// find which dimension the index lands in
final List<ParamDimension<?>> paramDimensions = entry.getValue();
final int paramDimensionIndex =
PermutationUtils.spannedIndexOf(new WrappedList<>(paramDimensions, paramDimension -> ((DiscreteParamDimension<?>) paramDimension).size()), subIndex);
final ParamDimension<?> paramDimension = paramDimensions.get(paramDimensionIndex);
// get the value from that dimension at the given index
final Object value = ((DiscreteParamDimension<?>) paramDimension).get(subIndex);
// add to param set
paramSet.add(entry.getKey(), value);
i++;
}
return paramSet;
}
public List<Integer> getBinSizes() {
final List<Integer> sizes = new ArrayList<>();
for(final Map.Entry<String, List<ParamDimension<?>>> entry : paramMap.entrySet()) {
final List<ParamDimension<?>> dimensions = entry.getValue();
int size = 0;
for(ParamDimension<?> dimension : dimensions) {
if(dimension instanceof DiscreteParamDimension<?>) {
size += ((DiscreteParamDimension<?>) dimension).size();
} else {
throw new IllegalArgumentException("dimension not discrete: " + dimension);
}
}
sizes.add(size);
}
return sizes;
}
@Override public boolean containsKey(final Object o) {
return paramMap.containsKey(o);
}
@Override public boolean containsValue(final Object o) {
return paramMap.containsValue(o);
}
@Override public Set<String> keySet() {
return paramMap.keySet();
}
@Override public Collection<List<ParamDimension<?>>> values() {
return paramMap.values();
}
@Override public Set<Entry<String, List<ParamDimension<?>>>> entrySet() {
return paramMap.entrySet();
}
public static boolean isDiscrete(ParamMap paramMap) {
for(final Map.Entry<String, List<ParamDimension<?>>> entry : paramMap.entrySet()) {
for(ParamDimension<?> dimension : entry.getValue()) {
if(!(dimension instanceof DiscreteParamDimension<?>)) {
return false;
}
if(!GridParamSpace.isDiscrete(dimension.getSubSpace())) {
return false;
}
}
}
return true;
}
}
| 4,063 | 37.704762 | 169 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/dimensions/discrete/GridParamSpace.java | package tsml.classifiers.distance_based.utils.collections.params.dimensions.discrete;
import tsml.classifiers.distance_based.utils.collections.DefaultList;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.iteration.PermutationUtils;
import utilities.ArrayUtilities;
import java.util.*;
/**
* Purpose: given a paramspace which contains only discrete dimensions, index each permutation of the parameters to appear as a list of paramsets.
* <p>
* Contributors: goastler
*/
public class GridParamSpace implements DefaultList<ParamSet> {
private final ParamSpace paramSpace;
public GridParamSpace(final ParamSpace paramSpace) {
this.paramSpace = Objects.requireNonNull(paramSpace);
}
public ParamSpace getParamSpace() {
return paramSpace;
}
@Override
public boolean equals(final Object o) {
if(this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
return false;
}
final GridParamSpace space = (GridParamSpace) o;
return getParamSpace().equals(space.getParamSpace());
}
@Override
public int hashCode() {
return Objects.hash(getParamSpace());
}
/**
* get the paramset given the permutation index
* @param index
* @return
*/
@Override
public ParamSet get(final int index) {
final List<Integer> a = new ArrayList<>();
for(ParamMap map : paramSpace) {
Integer size = new GridParamMap(map).size();
a.add(size);
}
final int paramMapIndex = PermutationUtils.spannedIndexOf(a, index);
final ParamMap paramMap = paramSpace.get(paramMapIndex);
// now we have the parammap, we need to get the paramset from that using the index
// discretise the param map
final GridParamMap gridParamMap = new GridParamMap(paramMap);
// find the bin sizes for each dimension inside the param map
final List<Integer> sizes = gridParamMap.getBinSizes();
// get the indices for each dimension given the index and bin sizes of each dimension
final List<Integer> indices = ArrayUtilities.fromPermutation(index, sizes);
return gridParamMap.get(indices);
}
@Override
public int size() {
return getParamMapSizes().stream().mapToInt(i -> i).sum();
}
public List<Integer> getParamMapSizes() {
List<Integer> list = new ArrayList<>();
for(ParamMap paramMap : paramSpace) {
Integer size = new GridParamMap(paramMap).size();
list.add(size);
}
return list;
}
public static boolean isDiscrete(ParamSpace paramSpace) {
for(ParamMap paramMap : paramSpace) {
if(!GridParamMap.isDiscrete(paramMap)) {
return false;
}
}
return true;
}
//
// /**
// * get the value of the parameter dimension at the given index
// * @param dimension
// * @param index
// * @return
// */
// private Object getValue(ParamDimension<?> dimension, int index) {
// if(dimension instanceof DiscreteParamDimension<?>) {
//
// } else {
// throw new IllegalArgumentException("expected finite list of options");
// }
// }
//
// /**
// * get the paramset corresponding to the given indices
// * @param spaces
// * @param indices
// * @return
// */
// public ParamSet get(final List<ParamSpace> spaces, final List<Integer> indices) {
// Assert.assertEquals(spaces.size(), indices.size());
// final ParamSet overallParamSet = new ParamSet();
// for(int i = 0; i < spaces.size(); i++) {
// final ParamSet paramSet = get(spaces.get(i), indices.get(i));
// overallParamSet.addAll(paramSet);
// }
// return overallParamSet;
// }
//
// /**
// * get the object at the given index across several dimensions
// * @param dimensions
// * @param index
// * @return
// */
// private Object get(List<ParamDimension<?>> dimensions, int index) {
// for(ParamDimension<?> dimension : dimensions) {
// int size = size(dimension);
// index -= size;
// if(index < 0) {
// index += size;
// return get(dimension, index);
// }
// }
// throw new IndexOutOfBoundsException();
// }
//
// public static int size(ParamDimension<?> dimension) {
// return PermutationUtils.numPermutations(getBinSizes(dimension));
// }
//
// public static List<Integer> sizesParameterSpace(List<ParamSpace> spaces) {
// return spaces.stream().map(IndexedParamSpace::size).collect(Collectors.toList());
// }
//
// public static int size(List<ParamDimension<?>> dimensions) {
// return PermutationUtils.numPermutations(sizesParameterDimension(dimensions));
// }
//
// public static List<Integer> sizesParameterDimension(List<ParamDimension<?>> dimensions) {
// return dimensions.stream().map(IndexedParamSpace::size).collect(Collectors.toList());
// }
//
// public static List<Integer> getBinSizes(ParamDimension<?> dimension) {
// List<Integer> sizes = sizesParameterSpace(dimension.getSubSpace());
// Object values = dimension.getValues();
// if(values instanceof List<?>) {
// int size = ((List<?>) values).size();
// sizes.add(0, size);
// } else {
// throw new IllegalArgumentException("cannot handle dimension type");
// }
// return sizes;
// }
}
| 5,908 | 32.95977 | 146 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/dimensions/discrete/GridParamSpaceTest.java | package tsml.classifiers.distance_based.utils.collections.params.dimensions.discrete;
import org.junit.Assert;
import org.junit.Test;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceTest;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class GridParamSpaceTest {
@Test(expected = IllegalArgumentException.class)
public void testNonDiscreteParameterDimensionException() {
GridParamSpace space = new GridParamSpace(new ParamSpaceTest().buildLParams());
for(int i = 0; i < space.size(); i++) {
space.get(i);
}
}
@Test
public void testUniquePermutations() {
GridParamSpace space = new GridParamSpace(new ParamSpaceTest().buildWParams());
int size = space.size();
Set<ParamSet> set = new HashSet<>();
for(int i = 0; i < size; i++) {
ParamSet paramSet = space.get(i);
boolean added = set.add(paramSet);
if(!added) Assert.fail("duplicate parameter set: " + paramSet);
}
Assert.assertEquals(space.size(), set.size());
}
@Test
public void testEquals() {
ParamSpace wParams = new ParamSpaceTest().buildWParams();
GridParamSpace a = new GridParamSpace(wParams);
GridParamSpace b = new GridParamSpace(wParams);
ParamSpace alt = new ParamSpace();
alt.add(new ParamMap().add("letters", new DiscreteParamDimension<>(Arrays.asList("a", "b", "c"))));
GridParamSpace c = new GridParamSpace(alt);
GridParamSpace d = new GridParamSpace(alt);
Assert.assertEquals(a, b);
Assert.assertEquals(a.hashCode(), b.hashCode());
Assert.assertEquals(c, d);
Assert.assertEquals(c.hashCode(), c.hashCode());
Assert.assertNotEquals(a, c);
Assert.assertNotEquals(a.hashCode(), c.hashCode());
Assert.assertNotEquals(b, c);
Assert.assertNotEquals(b.hashCode(), c.hashCode());
Assert.assertNotEquals(a, d);
Assert.assertNotEquals(a.hashCode(), d.hashCode());
Assert.assertNotEquals(b, d);
Assert.assertNotEquals(b.hashCode(), d.hashCode());
}
}
| 2,506 | 37.569231 | 107 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/distribution/BaseDistribution.java | package tsml.classifiers.distance_based.utils.collections.params.distribution;
import java.util.Random;
/**
* Purpose: model a distribution which can be sampled from, e.g. a normal distribution bell curve.
* <p>
* Contributors: goastler
*/
public abstract class BaseDistribution<A> implements Distribution<A> {
public BaseDistribution() {
}
@Override public String toString() {
return getClass().getSimpleName().replaceAll(Distribution.class.getSimpleName(), "");
}
}
| 510 | 23.333333 | 98 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/distribution/ClampedDistribution.java | package tsml.classifiers.distance_based.utils.collections.params.distribution;
import org.junit.Assert;
import tsml.classifiers.distance_based.utils.collections.intervals.Interval;
import java.util.Objects;
public abstract class ClampedDistribution<A> extends BaseDistribution<A> implements Interval<A> {
private Interval<A> interval;
public ClampedDistribution(Interval<A> interval) {
setInterval(interval);
}
public void setInterval(final Interval<A> interval) {
this.interval = Objects.requireNonNull(interval);
}
public Interval<A> getInterval() {
return interval;
}
@Override public A getStart() {
return interval.getStart();
}
@Override public A getEnd() {
return interval.getEnd();
}
@Override public void setStart(final A start) {
interval.setStart(start);
}
@Override public void setEnd(final A end) {
interval.setEnd(end);
}
@Override public A size() {
return interval.size();
}
@Override public boolean contains(final A item) {
return interval.contains(item);
}
@Override public String toString() {
return super.toString() + "(" + interval.getStart() + ", " + interval.getEnd() + ")";
}
@Override public boolean equals(final Object o) {
if(!(o instanceof ClampedDistribution)) {
return false;
}
ClampedDistribution<?> other = (ClampedDistribution<?>) o;
return other.getClass().equals(getClass()) && other.interval.equals(interval);
}
}
| 1,587 | 25.466667 | 97 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/distribution/CompositeDistribution.java | package tsml.classifiers.distance_based.utils.collections.params.distribution;
import tsml.classifiers.distance_based.utils.collections.params.distribution.double_based.UniformDoubleDistribution;
import tsml.classifiers.distance_based.utils.collections.params.distribution.int_based.UniformIntDistribution;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.function.BiFunction;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class CompositeDistribution<A> extends BaseDistribution<A> {
public static <A> CompositeDistribution<A> newCompositeFromRange(List<A> list, BiFunction<A, A, Distribution<A>> func) {
final CompositeDistribution<A> distribution = new CompositeDistribution<>();
for(int i = 0; i < list.size() - 1; i++) {
final A start = list.get(i);
final A end = list.get(i + 1);
distribution.getDistributions().add(func.apply(start, end));
}
return distribution;
}
public static CompositeDistribution<Double> newUniformDoubleCompositeFromRange(List<Double> list) {
return newCompositeFromRange(list, UniformDoubleDistribution::new);
}
public static CompositeDistribution<Integer> newUniformIntCompositeFromRange(List<Integer> list) {
return newCompositeFromRange(list, UniformIntDistribution::new);
}
public CompositeDistribution() {}
public CompositeDistribution(Distribution<A>... distributions) {
this(newArrayList(distributions));
}
public CompositeDistribution(List<Distribution<A>> distributions) {
setDistributions(distributions);
}
private List<Distribution<A>> distributions = new ArrayList<>();
@Override public A sample(Random random) {
final int index = random.nextInt(distributions.size());
final Distribution<A> distribution = distributions.get(index);
return distribution.sample(random);
}
public List<Distribution<A>> getDistributions() {
return distributions;
}
public void setDistributions(final List<Distribution<A>> distributions) {
this.distributions = Objects.requireNonNull(distributions);
if(distributions.isEmpty()) {
throw new IllegalArgumentException("empty");
}
}
}
| 2,407 | 37.222222 | 124 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/distribution/Distribution.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params.distribution;
import java.io.Serializable;
import java.util.Random;
public interface Distribution<A> extends Serializable {
A sample(Random random);
}
| 986 | 34.25 | 78 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/distribution/double_based/ExponentialDoubleDistribution.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params.distribution.double_based;
import tsml.classifiers.distance_based.utils.collections.params.distribution.BaseDistribution;
import tsml.classifiers.distance_based.utils.collections.params.distribution.Distribution;
import java.util.Random;
public class ExponentialDoubleDistribution extends BaseDistribution<Double> implements Distribution<Double> {
private Distribution<? extends Number> exponentDistribution;
private double base;
public ExponentialDoubleDistribution(double base, Distribution<? extends Number> exponentDistribution) {
setBase(base);
setExponentDistribution(exponentDistribution);
}
public ExponentialDoubleDistribution(double base) {
this(base, new UniformDoubleDistribution());
}
public ExponentialDoubleDistribution(Distribution<? extends Number> exponentDistribution) {
this(2, exponentDistribution);
}
public ExponentialDoubleDistribution() {
this(2);
}
public Double sample(Random random) {
final Number exponent = exponentDistribution.sample(random);
return Math.pow(base, exponent.doubleValue());
}
public Distribution<? extends Number> getExponentDistribution() {
return exponentDistribution;
}
public void setExponentDistribution(
final Distribution<? extends Number> exponentDistribution) {
this.exponentDistribution = exponentDistribution;
}
public double getBase() {
return base;
}
public void setBase(final double base) {
this.base = base;
}
}
// OLD VERSION BELOW
//package tsml.classifiers.distance_based.utils.collections.params.distribution.double_based;
//
//import java.io.IOException;
//import java.util.Random;
//
//public class ExponentialDoubleDistribution extends DoubleDistribution {
// public ExponentialDoubleDistribution(final Double min, final Double max) {
// super(min, max);
// }
//
//// @Override public Double sample() {
//// double lambda = 1;
//// double max = getMax();
//// double min = getMin();
//// double a = Math.exp(-lambda);
//// final Random random = getRandom();
////
//// double u = a * random.nextDouble();
//// double v;
//// if(u == 0) {
//// v = 0 / -lambda;
//// } else {
//// v = Math.log(u) / -lambda;
//// }
//
//// v = Math.min(max, v);
//// v = Math.max(v, min); // for imprecision overflow outside the bounds
////
//// return v;
//
//// double max = getMax();
//// double min = getMin();
//// max = Math.exp(-max * lambda);
//// min = Math.exp(-min * lambda);
//// final Random random = getRandom();
////
//// double u = min + (max - min) * random.nextDouble();
//// double v;
//// if(u == 0) {
//// v = 0 / -lambda;
//// } else {
//// v = Math.log(u) / -lambda;
//// }
////
//// v = Math.min(max, v);
//// v = Math.max(v, min); // for imprecision overflow outside the bounds
////
//// return v;
//// }
//
// public static void main(String[] args) throws IOException {
//// System.out.println(Math.exp(1));
//// System.out.println(Math.exp(0));
//// System.out.println(Math.log(Math.exp(0)));
//// System.out.println(Math.log(Math.exp(1)));
//// System.out.println(Math.log(1));
//// System.out.println();
//// System.setOut(new PrintStream("hello.txt"));
// final ExponentialDoubleDistribution distribution = new ExponentialDoubleDistribution(500d, 505d);
// distribution.setRandom(new Random(0));
// double min = Double.POSITIVE_INFINITY;
// double max = Double.NEGATIVE_INFINITY;
// for(int i = 0; i < 1000; i++) {
// double v = distribution.sample();
// if(v < min) {
// min = v;
//// System.out.println("min: " + min);
// }
// if(v > max) {
// max = v;
//// System.out.println("max: " + max);
// }
// System.out.println(v);
// }
// }
//
// @Override public Double sample() {
// final Random random = getRandom();
// final double u = random.nextDouble();
// final double v = Math.exp(9.21 * u) * 0.0001;
// return v;
// }
//}
| 5,252 | 32.458599 | 109 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/distribution/double_based/UniformDoubleDistribution.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params.distribution.double_based;
import tsml.classifiers.distance_based.utils.collections.intervals.DoubleInterval;
import tsml.classifiers.distance_based.utils.collections.params.distribution.ClampedDistribution;
import java.util.Random;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class UniformDoubleDistribution extends ClampedDistribution<Double> {
public UniformDoubleDistribution() {
this(0d, 1d);
}
public UniformDoubleDistribution(final Double start, final Double end) {
super(new DoubleInterval(start, end));
}
@Override
public Double sample(Random random) {
double start = getStart();
double end = getEnd();
return random.nextDouble() * Math.abs(end - start) + Math.min(start, end);
}
}
| 1,663 | 34.404255 | 97 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/distribution/int_based/UniformIntDistribution.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params.distribution.int_based;
import tsml.classifiers.distance_based.utils.collections.intervals.IntInterval;
import tsml.classifiers.distance_based.utils.collections.params.distribution.ClampedDistribution;
import java.util.Random;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class UniformIntDistribution extends ClampedDistribution<Integer> {
public UniformIntDistribution() {
this(0, 1);
}
public UniformIntDistribution(final Integer start, final Integer end) {
super(new IntInterval(start, end));
}
public Integer sample(Random random) {
int end = getEnd();
int start = getStart();
return random.nextInt(Math.abs(end - start) + 1) + Math.min(start, end);
}
}
| 1,625 | 34.347826 | 97 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/iteration/AbstractSearch.java | package tsml.classifiers.distance_based.utils.collections.params.iteration;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Objects;
public abstract class AbstractSearch implements Iterator<ParamSet>, Serializable {
private ParamSpace paramSpace;
private int iterationCount;
@Override
public String toString() {
return getClass().getSimpleName();
}
public void buildSearch(ParamSpace paramSpace) {
this.paramSpace = Objects.requireNonNull(paramSpace);
iterationCount = 0;
}
public ParamSpace getParamSpace() {
return paramSpace;
}
protected abstract boolean hasNextParamSet();
protected abstract ParamSet nextParamSet();
@Override public final boolean hasNext() {
if(paramSpace == null) throw new IllegalStateException("param space search has not been built");
return hasNextParamSet();
}
@Override public final ParamSet next() {
if(!hasNext()) {
throw new IllegalStateException("hasNext false");
}
final ParamSet paramSet = nextParamSet();
iterationCount++;
return paramSet;
}
public int getIterationCount() {
return iterationCount;
}
public abstract int size();
}
| 1,458 | 26.528302 | 104 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/iteration/GridSearch.java | package tsml.classifiers.distance_based.utils.collections.params.iteration;
import tsml.classifiers.distance_based.utils.collections.iteration.LinearIterator;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.discrete.GridParamSpace;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class GridSearch extends AbstractSearch {
private GridParamSpace gridParamSpace;
private final LinearIterator<ParamSet> iterator = new LinearIterator<>();
public GridSearch() {}
public GridParamSpace getIndexedParamSpace() {
return gridParamSpace;
}
private void setParamSpace(final ParamSpace paramSpace) {
gridParamSpace = new GridParamSpace(paramSpace);
iterator.buildIterator(gridParamSpace);
}
@Override public void buildSearch(final ParamSpace paramSpace) {
super.buildSearch(paramSpace);
setParamSpace(paramSpace);
}
@Override
public String toString() {
return getClass().getSimpleName() + "paramSpace=" + gridParamSpace.getParamSpace().toString() + "}";
}
@Override
public boolean hasNextParamSet() {
return iterator.hasNext();
}
@Override
public ParamSet nextParamSet() {
return iterator.next();
}
public int size() {
return gridParamSpace.size();
}
}
| 1,545 | 27.62963 | 108 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/iteration/GridSearchTest.java | package tsml.classifiers.distance_based.utils.collections.params.iteration;
import org.junit.Assert;
import org.junit.Test;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceTest;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class GridSearchTest {
@Test
public void testIteration() {
ParamSpace space = new ParamSpaceTest().build2DDiscreteSpace();
GridSearch iterator = new GridSearch();
iterator.buildSearch(space);
StringBuilder stringBuilder = new StringBuilder();
while(iterator.hasNext()) {
ParamSet paramSet = iterator.next();
stringBuilder.append(paramSet);
stringBuilder.append("\n");
}
// System.out.println(stringBuilder.toString());
Assert.assertEquals(stringBuilder.toString(),
"-a 1 -b 6\n"
+ "-a 2 -b 6\n"
+ "-a 3 -b 6\n"
+ "-a 4 -b 6\n"
+ "-a 5 -b 6\n"
+ "-a 1 -b 7\n"
+ "-a 2 -b 7\n"
+ "-a 3 -b 7\n"
+ "-a 4 -b 7\n"
+ "-a 5 -b 7\n"
+ "-a 1 -b 8\n"
+ "-a 2 -b 8\n"
+ "-a 3 -b 8\n"
+ "-a 4 -b 8\n"
+ "-a 5 -b 8\n"
+ "-a 1 -b 9\n"
+ "-a 2 -b 9\n"
+ "-a 3 -b 9\n"
+ "-a 4 -b 9\n"
+ "-a 5 -b 9\n"
+ "-a 1 -b 10\n"
+ "-a 2 -b 10\n"
+ "-a 3 -b 10\n"
+ "-a 4 -b 10\n"
+ "-a 5 -b 10\n"
);
}
}
| 1,858 | 31.614035 | 79 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/iteration/PermutationUtils.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params.iteration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class PermutationUtils {
/**
* Find the index of the collection which contains the given index. I.e. given several lists,
* [ [0,1,2,3], [4], [5,6], [7,8,9] ]
* these give the sizes
* sizes: [ 4, 1, 2, 3 ]
* view those lists as one contiguous list and find the index of the list which the specified index falls into.
* cumulative sizes: [ 4, 5, 7, 10 ]
* For this example, say the specified index is 6. This would fall into the 3rd list, so we'd return 2.
* If the specified index were 2, we'd return 0 for the first list.
* If the specified index were 8, we'd return 3 for the last list.
* Etc...
*
* @param collections
* @param index
* @return
*/
public static int spannedIndexOf(Collection<Integer> collections, int index) {
if(index < 0) {
throw new IllegalArgumentException("index negative");
}
Objects.requireNonNull(collections);
if(collections.isEmpty()) {
throw new IllegalArgumentException("empty set of sizes");
}
int collectionIndex = 0;
for(Integer size : collections) {
index -= size;
if(index < 0) {
return collectionIndex;
}
collectionIndex++;
}
throw new IndexOutOfBoundsException();
}
public static List<Integer> fromPermutation(int permutation, List<Integer> binSizes) {
int maxCombination = numPermutations(binSizes) - 1;
if(permutation > maxCombination || binSizes.size() == 0 || permutation < 0) {
throw new IndexOutOfBoundsException();
}
List<Integer> result = new ArrayList<>();
for(int binSize : binSizes) {
if(binSize > 1) {
result.add(permutation % binSize);
permutation /= binSize;
} else if(binSize == 1) {
result.add(0);
} else {
// binSize is 0 or less (i.e. no index as that bin cannot be indexed as size <=0)
result.add(-1);
}
}
return result;
}
public static int toPermutation(List<Integer> values, List<Integer> binSizes) {
if(values.size() != binSizes.size()) {
throw new IllegalArgumentException("incorrect number of args");
}
int permutation = 0;
for(int i = binSizes.size() - 1; i >= 0; i--) {
int binSize = binSizes.get(i);
if(binSize > 1) {
int value = values.get(i);
permutation *= binSize;
permutation += value;
}
}
return permutation;
}
public static int numPermutations(List<Integer> binSizes) {
List<Integer> maxValues = new ArrayList<>();
boolean positive = false;
for(Integer binSize : binSizes) {
int size = binSize - 1;
if(size < 0) {
size = 0;
} else {
positive = true;
}
maxValues.add(size);
}
int result = toPermutation(maxValues, binSizes);
if(positive && !maxValues.isEmpty()) {
result++;
}
return result;
}
}
| 4,358 | 34.439024 | 120 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/iteration/PermutationUtilsTest.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params.iteration;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static tsml.classifiers.distance_based.utils.collections.params.iteration.PermutationUtils.*;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
@RunWith(Parameterized.class)
public class PermutationUtilsTest {
private List<Integer> bins;
private int index;
public PermutationUtilsTest(List<Integer> bins, int index) {
this.bins = bins;
this.index = index;
}
@Parameterized.Parameters
public static Collection permutations() {
return Arrays.asList(new Object[][]{
{Arrays.asList(2, 3, 4), 24},
{Arrays.asList(0, 0, 0), 0},
{Arrays.asList(0, 1, 0), 1},
{Arrays.asList(0, -1, 0), 0},
{Arrays.asList(2, -1, 5), 10},
{Arrays.asList(-3392, -348642, -4), 0},
});
}
@Test
public void testToAndFromUniquePermutations() {
List<List<Integer>> seenPermutations = new ArrayList<>();
for(int i = 0; i < index; i++) {
List<Integer> permutation = fromPermutation(i, bins);
int index = toPermutation(permutation, bins);
// System.out.println("permutation for " + i + " is " + permutation + " and reverse is " + index);
Assert.assertEquals(index, i);
for(List<Integer> seenPermutation : seenPermutations) {
assertThat(permutation, is(not(seenPermutation)));
}
// System.out.println("permutation " + permutation + " with index " + i + " is unique");
seenPermutations.add(permutation);
}
}
@Test
public void testNumPermutations() {
int index = numPermutations(bins);
// System.out.println("num perms for " + bins + " is " + index);
Assert.assertEquals(index, this.index);
}
}
| 3,034 | 34.705882 | 109 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/iteration/RandomSearch.java | package tsml.classifiers.distance_based.utils.collections.params.iteration;
import tsml.classifiers.distance_based.utils.collections.iteration.BaseRandomIterator;
import tsml.classifiers.distance_based.utils.collections.iteration.RandomIterator;
import tsml.classifiers.distance_based.utils.collections.params.ParamMap;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.ParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.continuous.ContinuousParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.discrete.DiscreteParamDimension;
import tsml.classifiers.distance_based.utils.collections.params.dimensions.discrete.GridParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.distribution.Distribution;
import tsml.classifiers.distance_based.utils.system.random.RandomUtils;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* Purpose: randomly iterate over a parameter space. The random iteration occurs with replacement therefore the same
* parameter set may be hit more than once.
* <p>
* Contributors: goastler
*/
public class RandomSearch extends AbstractSearch implements RandomIterator<ParamSet> {
public static final int DEFAULT_ITERATION_LIMIT = 100;
private int iterationLimit = DEFAULT_ITERATION_LIMIT;
private final RandomIterator<ParamSet> randomIterator = new BaseRandomIterator<>();
private boolean discrete;
private GridParamSpace gridParamSpace; // only used if paramspace is discrete
public RandomSearch() {
setWithReplacement(false);
}
@Override public void setRandom(final Random random) {
randomIterator.setRandom(random);
}
@Override public Random getRandom() {
return randomIterator.getRandom();
}
@Override public void setSeed(final int seed) {
randomIterator.setSeed(seed);
}
@Override public int getSeed() {
return randomIterator.getSeed();
}
@Override public void buildSearch(final ParamSpace paramSpace) {
super.buildSearch(paramSpace);
checkRandom();
// is the param space discrete?
gridParamSpace = null;
discrete = GridParamSpace.isDiscrete(paramSpace);
if(discrete) {
// if so then build the random iterator
gridParamSpace = new GridParamSpace(paramSpace);
randomIterator.buildIterator(gridParamSpace);
} // else param space is not discrete. Do not use the random iterator
}
public boolean hasIterationLimit() {
return getIterationLimit() >= 0;
}
public boolean insideIterationCountLimit() {
return !hasIterationLimit() || getIterationCount() < getIterationLimit();
}
@Override protected boolean hasNextParamSet() {
return insideIterationCountLimit() && (!discrete || getParamSpace().isEmpty() || randomIterator.hasNext());
}
@Override protected ParamSet nextParamSet() {
// if dealing with a discrete space
if(getParamSpace().isEmpty()) {
return new ParamSet();
} else if(discrete) {
// then use the random iterator to iterate over it
return randomIterator.next();
} else {
// otherwise extract a random param set whilst managing discrete and continuous dimensions
return extractRandomParamSet(getParamSpace(), getRandom());
}
}
/**
*
* @param random
* @return
*/
private static Object extractRandomValue(ParamDimension<?> dimension, Random random) {
final Object value;
if(dimension instanceof ContinuousParamDimension<?>) {
Distribution<?> distribution = ((ContinuousParamDimension<?>) dimension).getDistribution();
// same as below, but a distribution should make a new instance of the value already. Take a copy just in case.
value = distribution.sample(random);
} else if(dimension instanceof DiscreteParamDimension<?>) {
List<?> list = ((DiscreteParamDimension<?>) dimension).getValues();
value = RandomUtils.choice(list, random);
} else {
throw new IllegalArgumentException("cannot handle dimension of type " + dimension.getClass().getSimpleName());
}
return value;
}
public static ParamSet extractRandomParamSet(ParamSpace paramSpace, Random random) {
final ParamSet paramSet = new ParamSet();
if(paramSpace.isEmpty()) {
return paramSet;
}
final ParamMap paramMap = RandomUtils.choice(paramSpace, random);
for(Map.Entry<String, List<ParamDimension<?>>> entry : paramMap.entrySet()) {
final String name = entry.getKey();
List<ParamDimension<?>> dimensions = entry.getValue();
ParamDimension<?> dimension = RandomUtils.choice(dimensions, random);
final Object value = extractRandomValue(dimension, random);
final ParamSpace subSpace = dimension.getSubSpace();
final ParamSet subParamSet = extractRandomParamSet(subSpace, random);
paramSet.add(name, value, subParamSet);
}
return paramSet;
}
public int getIterationLimit() {
return iterationLimit;
}
public RandomSearch setIterationLimit(final int iterationLimit) {
this.iterationLimit = iterationLimit;
return this;
}
public static ParamSet choice(ParamSpace paramSpace, Random random) {
return choice(paramSpace, random, 1).get(0);
}
public static List<ParamSet> choice(ParamSpace paramSpace, Random random, int numChoices) {
final RandomSearch iterator = new RandomSearch();
iterator.setRandom(random);
iterator.setIterationLimit(numChoices);
iterator.buildSearch(paramSpace);
return RandomUtils.choice(iterator, numChoices);
}
@Override public boolean withReplacement() {
return randomIterator.withReplacement();
}
@Override public void setWithReplacement(final boolean withReplacement) {
randomIterator.setWithReplacement(withReplacement);
}
@Override public int size() {
int size = iterationLimit;
if(getParamSpace().isEmpty()) {
size = Math.min(size, 1);
} else if(discrete) {
size = Math.min(size, gridParamSpace.size());
}
return size;
}
}
| 6,644 | 38.319527 | 123 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/params/iteration/RandomSearchTest.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.params.iteration;
import org.junit.Assert;
import org.junit.Test;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpace;
import tsml.classifiers.distance_based.utils.collections.params.ParamSpaceTest;
import java.util.Random;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class RandomSearchTest {
@Test
public void testIteration() {
ParamSpace space = new ParamSpaceTest().build2DContinuousSpace();
final int limit = 10;
RandomSearch iterator = new RandomSearch();
iterator.setSeed(0);
iterator.setIterationLimit(limit);
iterator.buildSearch(space);
StringBuilder stringBuilder = new StringBuilder();
int count = 0;
while(iterator.hasNext()) {
count++;
ParamSet paramSet = iterator.next();
stringBuilder.append(paramSet);
stringBuilder.append("\n");
}
// System.out.println(stringBuilder.toString());
Assert.assertEquals(count, limit);
Assert.assertEquals(
"-a 0.3654838936883285 -b 0.6202682078357429\n"
+ "-a 0.31870871267505413 -b 0.775218502558817\n"
+ "-a 0.2987726388986009 -b 0.6666091997383249\n"
+ "-a 0.19259459237035925 -b 0.9924207700999045\n"
+ "-a 0.43959125893624007 -b 0.9706245897410573\n"
+ "-a 0.13747698301774242 -b 0.5644485754368884\n"
+ "-a 0.07330082882325911 -b 0.5116190612419447\n"
+ "-a 0.2733698785992328 -b 0.9822434303384251\n"
+ "-a 0.052245343125485844 -b 0.8125731817327797\n"
+ "-a 0.20539809774553086 -b 0.8881561456374663\n"
, stringBuilder.toString()
);
}
}
| 2,800 | 39.594203 | 79 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/patience/Patience.java | package tsml.classifiers.distance_based.utils.collections.patience;
import tsml.classifiers.distance_based.utils.collections.checks.Checks;
public class Patience {
public Patience() {
setMaximise();
setWindowSize(5);
setTolerance(0);
reset();
expired = false;
}
public Patience(int windowSize) {
this();
setWindowSize(windowSize);
}
private int index;
private int windowSize;
private double best;
private int bestIndex;
private double tolerance;
private boolean minimise;
private int windowStart;
private boolean expired;
// /**
// * Has the score improved within the window?
// * @return
// */
// public boolean hasImproved() {
// return index - windowIndex < windowSize;
// }
private boolean isBetter(double value) {
if(minimise) {
return value < best - tolerance;
} else {
return value > best + tolerance;
}
}
public boolean add(double value) {
index++;
boolean better = isBetter(value);
if(better) {
best = value;
bestIndex = index;
windowStart = bestIndex;
}
expired = (index - windowStart) >= windowSize;
return better;
}
public void reset() {
index = -1;
best = -1;
bestIndex = -1;
windowStart = 0;
expired = false;
}
public int getWindowStart() {
return windowStart;
}
public void resetPatience() {
windowStart = index;
}
public boolean isExpired() {
return expired;
}
public int getIndex() {
return index;
}
public int getBestIndex() {
return bestIndex;
}
public double getBest() {
return best;
}
public double getTolerance() {
return tolerance;
}
public void setTolerance(final double tolerance) {
this.tolerance = Checks.requireNonNegative(tolerance);
}
public int getWindowSize() {
return windowSize;
}
public void setWindowSize(final int windowSize) {
this.windowSize = Checks.requirePositive(windowSize);
}
public boolean isMinimise() {
return minimise;
}
public void setMinimise() {
this.minimise = true;
}
public boolean isMaximise() {
return !isMinimise();
}
public void setMaximise() {
minimise = false;
}
public int size() {
return index + 1;
}
public boolean isEmpty() {
return size() == 0;
}
}
| 2,673 | 19.728682 | 71 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/patience/PatienceTest.java | package tsml.classifiers.distance_based.utils.collections.patience;
import org.junit.Assert;
import org.junit.Test;
public class PatienceTest {
@Test
public void testPatience() {
final Patience patience = new Patience(4);
Assert.assertEquals(4, patience.getWindowSize());
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(0, patience.size());
Assert.assertTrue(patience.add(4));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(1, patience.size());
Assert.assertTrue(patience.add(5));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(2, patience.size());
Assert.assertFalse(patience.add(3));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(3, patience.size());
Assert.assertFalse(patience.add(1));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(4, patience.size());
Assert.assertFalse(patience.add(2));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(5, patience.size());
Assert.assertFalse(patience.add(2));
Assert.assertTrue(patience.isExpired());
Assert.assertEquals(6, patience.size());
Assert.assertEquals(5, patience.getBest(), 0d);
Assert.assertEquals(1, patience.getBestIndex());
patience.resetPatience();
Assert.assertEquals(6, patience.size());
Assert.assertFalse(patience.add(2));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(7, patience.size());
Assert.assertFalse(patience.add(4));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(8, patience.size());
Assert.assertTrue(patience.add(6));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(9, patience.size());
Assert.assertFalse(patience.add(1));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(10, patience.size());
Assert.assertFalse(patience.add(2));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(11, patience.size());
Assert.assertFalse(patience.add(4));
Assert.assertFalse(patience.isExpired());
Assert.assertEquals(12, patience.size());
Assert.assertFalse(patience.add(2));
Assert.assertTrue(patience.isExpired());
Assert.assertEquals(13, patience.size());
Assert.assertEquals(8, patience.getBestIndex());
Assert.assertEquals(6, patience.getBest(), 0d);
Assert.assertEquals(8, patience.getWindowStart());
Assert.assertEquals(12, patience.getIndex());
patience.setTolerance(2.5);
Assert.assertFalse(patience.add(8.4));
Assert.assertEquals(14, patience.size());
Assert.assertTrue(patience.add(8.6));
Assert.assertEquals(15, patience.size());
Assert.assertFalse(patience.isEmpty());
patience.reset();
Assert.assertEquals(-1, patience.getIndex());
Assert.assertEquals(0, patience.getWindowStart());
Assert.assertEquals(4, patience.getWindowSize());
Assert.assertEquals(-1, patience.getBestIndex());
Assert.assertEquals(-1, patience.getBest(), 0);
Assert.assertEquals(2.5, patience.getTolerance(), 0d);
Assert.assertTrue(patience.isEmpty());
Assert.assertFalse(patience.isExpired());
}
}
| 3,498 | 40.164706 | 67 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/pruned/PrunedMap.java | package tsml.classifiers.distance_based.utils.collections.pruned;
import tsml.classifiers.distance_based.utils.collections.CollectionUtils;
import java.io.Serializable;
import java.util.*;
public class PrunedMap<A, B> implements Map<A, List<B>>,
NavigableMap<A, List<B>>,
SortedMap<A, List<B>>,
Serializable {
public static void main(String[] args) {
class A {}
final TreeMap<A, Integer> map = new TreeMap<>();
}
private int limit;
private int size;
private final TreeMap<A, List<B>> map;
public static <A extends Comparable<? super A>, B> PrunedMap<A, B> asc() {
return new PrunedMap<>(Comparator.naturalOrder());
}
public static <A extends Comparable<? super A>, B> PrunedMap<A, B> desc() {
return new PrunedMap<>(Comparator.reverseOrder());
}
public static <A extends Comparable<? super A>, B> PrunedMap<A, B> asc(int limit) {
final PrunedMap<A, B> map = asc();
map.setLimit(limit);
return map;
}
public static <A extends Comparable<? super A>, B> PrunedMap<A, B> desc(int limit) {
final PrunedMap<A, B> map = desc();
map.setLimit(limit);
return map;
}
public static <A extends Comparable<? super A>, B> PrunedMap<A, B> newPrunedMap(int limit, boolean asc) {
if(asc) {
return asc(limit);
} else {
return desc(limit);
}
}
public static <A extends Comparable<? super A>, B> PrunedMap<A, B> newPrunedMap(boolean asc) {
if(asc) {
return asc();
} else {
return desc();
}
}
public PrunedMap(Comparator<? super A> comparator) {
this(1, comparator);
}
public PrunedMap(int limit, Comparator<? super A> comparator) {
map = new TreeMap<>(comparator);
setLimit(limit);
clear();
}
public int getLimit() {
return limit;
}
public boolean setLimit(final int limit) {
this.limit = limit;
return prune();
}
@Override public void clear() {
map.clear();
size = 0;
}
@Override public Entry<A, List<B>> firstEntry() {
return map.firstEntry();
}
@Override public Entry<A, List<B>> lastEntry() {
return map.lastEntry();
}
@Override public Entry<A, List<B>> pollFirstEntry() {
final Entry<A, List<B>> entry = map.pollFirstEntry();
size -= entry.getValue().size();
return entry;
}
@Override public Entry<A, List<B>> pollLastEntry() {
final Entry<A, List<B>> entry = map.pollLastEntry();
size -= entry.getValue().size();
return entry;
}
@Override public Entry<A, List<B>> lowerEntry(final A a) {
return map.lowerEntry(a);
}
@Override public A lowerKey(final A a) {
return map.lowerKey(a);
}
@Override public Entry<A, List<B>> floorEntry(final A a) {
return map.floorEntry(a);
}
@Override public A floorKey(final A a) {
return map.floorKey(a);
}
@Override public Entry<A, List<B>> ceilingEntry(final A a) {
return map.ceilingEntry(a);
}
@Override public A ceilingKey(final A a) {
return map.ceilingKey(a);
}
@Override public Entry<A, List<B>> higherEntry(final A a) {
return map.higherEntry(a);
}
@Override public A higherKey(final A a) {
return map.higherKey(a);
}
@Override public Set<A> keySet() {
return map.keySet();
}
@Override public NavigableSet<A> navigableKeySet() {
return map.navigableKeySet();
}
@Override public NavigableSet<A> descendingKeySet() {
return map.descendingKeySet();
}
@Override public Collection<List<B>> values() {
return map.values();
}
@Override public Set<Entry<A, List<B>>> entrySet() {
return map.entrySet();
}
@Override public NavigableMap<A, List<B>> descendingMap() {
return map.descendingMap();
}
@Override public NavigableMap<A, List<B>> subMap(final A a, final boolean b, final A k1, final boolean b1) {
return map.subMap(a, b, k1, b1);
}
@Override public NavigableMap<A, List<B>> headMap(final A a, final boolean b) {
return map.headMap(a, b);
}
@Override public NavigableMap<A, List<B>> tailMap(final A a, final boolean b) {
return map.tailMap(a, b);
}
@Override public SortedMap<A, List<B>> subMap(final A a, final A k1) {
return map.subMap(a, k1);
}
@Override public SortedMap<A, List<B>> headMap(final A a) {
return map.headMap(a);
}
@Override public SortedMap<A, List<B>> tailMap(final A a) {
return map.tailMap(a);
}
@Override public List<B> remove(final Object o) {
final List<B> removed = map.remove(o);
if(removed != null) {
size -= removed.size();
}
return removed;
}
@Override public boolean remove(final Object o, final Object o1) {
final List<B> bs = map.get(o);
boolean removed = false;
if(bs != null) {
if(bs.remove(o1)) {
size--;
removed = true;
}
if(bs.isEmpty()) {
map.remove(o);
}
}
return removed;
}
public boolean putAll(A key, List<B> value) {
return addAll(key, value);
}
public boolean add(A key, B value) {
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
size++;
prune();
return map.comparator().compare(key, lastKey()) <= 0;
}
public boolean addAll(A key, List<B> values) {
for(B value : values) {
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
size++;
}
prune();
return map.comparator().compare(key, lastKey()) <= 0;
}
private boolean prune() {
boolean pruned = false;
if(size > limit) {
Map.Entry<A, List<B>> lastEntry = lastEntry();
while(size() - lastEntry.getValue().size() >= limit) {
pollLastEntry();
lastEntry = lastEntry();
pruned = true;
}
}
return pruned;
}
@Override public int size() {
return size;
}
@Override public boolean isEmpty() {
return map.isEmpty();
}
@Override public boolean equals(final Object o) {
if(o instanceof PrunedMap) {
return map.equals(o) && ((PrunedMap<?, ?>) o).limit == limit;
}
return false;
}
@Override public int hashCode() {
return map.hashCode();
}
@Override public String toString() {
return map.toString();
}
@Override public boolean containsKey(final Object o) {
return map.containsKey(o);
}
@Override public boolean containsValue(final Object o) {
for(Map.Entry<A, List<B>> entry : entrySet()) {
if(entry.getValue().equals(o)) {
return true;
}
for(B value : entry.getValue()) {
if(value.equals(o)) {
return true;
}
}
}
return false;
}
@Override public List<B> get(final Object o) {
final List<B> list = map.get(o);
if(list == null) {
return null;
}
return Collections.unmodifiableList(list);
}
@Override public List<B> put(final A a, final List<B> bs) {
addAll(a, bs);
return get(a);
}
@Override public Comparator<? super A> comparator() {
return map.comparator();
}
@Override public A firstKey() {
return map.firstKey();
}
@Override public A lastKey() {
return map.lastKey();
}
@Override public void putAll(final Map<? extends A, ? extends List<B>> map) {
for(Map.Entry<? extends A, ? extends List<B>> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public List<B> valuesList() {
return CollectionUtils.concat(values());
}
}
| 8,392 | 25.729299 | 112 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/pruned/PrunedMapTest.java | package tsml.classifiers.distance_based.utils.collections.pruned;
import org.junit.Assert;
import org.junit.Test;
import tsml.classifiers.distance_based.utils.system.copy.CopierUtils;
import java.util.Arrays;
public class PrunedMapTest {
@Test
public void testPrune() {
final PrunedMap<Integer, Integer> map = PrunedMap.desc(3);
// test overflow when equal
for(int i = 0; i < 5; i++) {
map.add(3, i);
}
Assert.assertEquals("{3=[0, 1, 2, 3, 4]}", map.toString());
Assert.assertEquals(5, map.size());
// test underflow
for(int i = 0; i < 2; i++) {
map.add(4, i);
}
Assert.assertEquals("{4=[0, 1], 3=[0, 1, 2, 3, 4]}", map.toString());
Assert.assertEquals(7, map.size());
// test prune
map.add(5, 0);
Assert.assertEquals("{5=[0], 4=[0, 1]}", map.toString());
Assert.assertEquals(3, map.size());
// test prune on set limit
map.setLimit(1);
Assert.assertEquals("{5=[0]}", map.toString());
Assert.assertEquals(1, map.size());
// test can't beat best
for(int i = 0; i < 10; i++) {
map.add(1, i);
}
Assert.assertEquals("{5=[0]}", map.toString());
Assert.assertEquals(1, map.size());
map.clear();
Assert.assertEquals("{}", map.toString());
Assert.assertEquals(0, map.size());
map.setLimit(20);
for(int i = 0; map.size() < map.getLimit(); i++) {
for(int j = 0; j < 3; j++) {
map.add(i, j);
}
}
Assert.assertEquals("{6=[0, 1, 2], 5=[0, 1, 2], 4=[0, 1, 2], 3=[0, 1, 2], 2=[0, 1, 2], 1=[0, 1, 2], 0=[0, 1, 2]}", map.toString());
Assert.assertEquals(21, map.size());
map.setLimit(10);
Assert.assertEquals("{6=[0, 1, 2], 5=[0, 1, 2], 4=[0, 1, 2], 3=[0, 1, 2]}", map.toString());
Assert.assertEquals(12, map.size());
map.setLimit(1);
Assert.assertEquals("{6=[0, 1, 2]}", map.toString());
Assert.assertEquals(3, map.size());
map.clear();
Assert.assertEquals(0, map.size());
map.setLimit(5);
map.put(1, Arrays.asList(1,2,3,4,5));
map.put(2, Arrays.asList(1,2,3,4,5));
map.put(3, Arrays.asList(1,2,3,4,5));
Assert.assertEquals("{3=[1, 2, 3, 4, 5]}", map.toString());
Assert.assertEquals(5, map.size());
map.put(4, Arrays.asList(1,2));
map.put(5, Arrays.asList(3,4));
Assert.assertEquals("{5=[3, 4], 4=[1, 2], 3=[1, 2, 3, 4, 5]}", map.toString());
Assert.assertEquals(9, map.size());
map.pollLastEntry();
Assert.assertEquals("{5=[3, 4], 4=[1, 2]}", map.toString());
Assert.assertEquals(4, map.size());
map.pollFirstEntry();
Assert.assertEquals("{4=[1, 2]}", map.toString());
Assert.assertEquals(2, map.size());
map.putAll(CopierUtils.deepCopy(map));
Assert.assertEquals("{4=[1, 2, 1, 2]}", map.toString());
Assert.assertEquals(4, map.size());
map.remove(4, 1);
map.remove(4, 1);
Assert.assertEquals("{4=[2, 2]}", map.toString());
Assert.assertEquals(2, map.size());
map.remove(4);
Assert.assertEquals("{}", map.toString());
Assert.assertEquals(0, map.size());
map.addAll(4, Arrays.asList(4,4,4,4));
Assert.assertEquals("{4=[4, 4, 4, 4]}", map.toString());
Assert.assertEquals(4, map.size());
map.remove(5);
Assert.assertEquals("{4=[4, 4, 4, 4]}", map.toString());
Assert.assertEquals(4, map.size());
map.remove(5,5);
Assert.assertEquals("{4=[4, 4, 4, 4]}", map.toString());
Assert.assertEquals(4, map.size());
map.remove(4);
Assert.assertEquals("{}", map.toString());
Assert.assertEquals(0, map.size());
map.setLimit(3);
map.clear();
Assert.assertTrue(map.add(3, 3));
Assert.assertTrue(map.add(4, 4));
Assert.assertTrue(map.add(5, 5));
Assert.assertTrue(map.add(5, 5));
Assert.assertFalse(map.add(2, 2));
Assert.assertFalse(map.add(1, 1));
map.setLimit(1);
Assert.assertTrue(map.add(6, 6));
Assert.assertTrue(map.add(6, 6));
Assert.assertFalse(map.add(5, 5));
}
}
| 4,396 | 37.234783 | 139 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/tree/BaseTree.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.tree;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Iterator;
/**
* A general tree data structure. No context of nodes at all, just a simple hierarchy.
*
* Contributors: goastler
*/
public class BaseTree<A> extends AbstractList<A> implements Tree<A> {
public BaseTree() {
clear();
}
private TreeNode<A> root;
@Override
public TreeNode<A> getRoot() {
return root;
}
@Override
public void setRoot(TreeNode<A> root) {
this.root = root;
}
@Override
public String toString() {
return getClass().getSimpleName() + "{root=" + root + "}";
}
public A get(int i) {
throw new UnsupportedOperationException("get not implemented for tree");
}
@Override public int size() {
return Tree.super.size();
}
@Override public boolean equals(final Object o) {
return this == o;
}
}
| 1,754 | 26 | 86 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/tree/BaseTreeNode.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.tree;
import java.util.*;
/**
* Purpose: node of a tree data structure.
*
* Contributors: goastler
*/
public class BaseTreeNode<A> extends AbstractList<TreeNode<A>> implements TreeNode<A> {
private final List<TreeNode<A>> children = new ArrayList<>();
private A element;
private TreeNode<A> parent;
// skip is a utility to skip calling recursive calls when handling the parent/child relationship of nodes
private boolean skip;
public BaseTreeNode() {}
public BaseTreeNode(A element) {
this(element, null);
}
public BaseTreeNode(A element, TreeNode<A> parent) {
setValue(element);
setParent(parent);
}
@Override public boolean equals(final Object o) {
return this == o;
}
@Override
public TreeNode<A> getParent() {
return parent;
}
@Override
public void setParent(TreeNode<A> nextParent) {
if(parent == nextParent) {
// do nothing
return;
}
if(parent != null && !skip) {
// remove this child from the parent
parent.remove(this);
}
if(nextParent != null) {
// add this child to the new parent
nextParent.add(this);
}
this.parent = nextParent;
}
@Override
public A getValue() {
return element;
}
@Override
public void setValue(A element) {
this.element = element;
}
/**
* total number of nodes in the tree, including this one
* @return
*/
@Override
public int size() {
return children.size();
}
@Override public void add(final int i, final TreeNode<A> node) {
if(skip) return;
if(node.getParent() == this) {
throw new IllegalArgumentException("already a child");
}
// node is not a child yet
// add the node to the children
children.add(i, node);
// set this node as the parent
skip = true;
node.setParent(this);
skip = false;
}
@Override public boolean add(final TreeNode<A> node) {
int size = children.size();
add(children.size(), node);
return size != children.size();
}
@Override public TreeNode<A> get(final int i) {
return children.get(i);
}
@Override public TreeNode<A> set(final int i, final TreeNode<A> child) {
if(skip) return null;
if(child.getParent() == this) {
// already a child - cannot house multiple children
throw new IllegalArgumentException("already a child: " + child);
}
// get the previous
TreeNode<A> previous = children.get(i);
// overwrite the previous
children.set(i, child);
skip = true;
// remove this as the parent of the overwritten
previous.removeParent();
// setup the new node as a child
child.setParent(this);
skip = false;
return previous;
}
@Override public TreeNode<A> remove(final int i) {
if(skip) return null;
// remove the child
TreeNode<A> child = children.remove(i);
// discard the parent
skip = true;
child.removeParent();
skip = false;
return child;
}
@Override public String toString() {
if(children.isEmpty()) {
return "BaseTreeNode{" +
"location=" + getLocation() +
", element=" + element + "}";
}
return "BaseTreeNode{" +
"location=" + getLocation() +
", element=" + element +
", children=" + children +
'}';
}
@Override public void clear() {
// remove all the children
for(int i = children.size() - 1; i >= 0; i--) {
final TreeNode<A> child = children.get(i);
child.removeParent();
}
}
}
| 4,813 | 28 | 109 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/tree/BaseTreeNodeTest.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.tree;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class BaseTreeNodeTest {
private TreeNode<String> empty;
private TreeNode<String> root;
private TreeNode<String> left;
private TreeNode<String> leftLeft;
private TreeNode<String> leftMiddle;
private TreeNode<String> leftRight;
private TreeNode<String> middle;
private TreeNode<String> middleLeft;
private TreeNode<String> middleMiddle;
private TreeNode<String> middleRight;
private TreeNode<String> right;
private TreeNode<String> rightLeft;
private TreeNode<String> rightMiddle;
private TreeNode<String> rightRight;
@Before
public void before() {
root = new BaseTreeNode<>("root");
left = new BaseTreeNode<>("left", root);
leftLeft = new BaseTreeNode<>("left", left);
leftMiddle = new BaseTreeNode<>("middle", left);
leftRight = new BaseTreeNode<>("right", left);
middle = new BaseTreeNode<>("middle", root);
middleLeft = new BaseTreeNode<>("middleLeft", middle);
middleMiddle = new BaseTreeNode<>("middleMiddle", middle);
middleRight = new BaseTreeNode<>("middleRight", middle);
right = new BaseTreeNode<>("right", root);
rightLeft = new BaseTreeNode<>("rightLeft", right);
rightMiddle = new BaseTreeNode<>("rightMiddle", right);
rightRight = new BaseTreeNode<>("rightRight", right);
empty = new BaseTreeNode<>("empty");
}
@Test
public void testHeight() {
Assert.assertEquals(3, root.height());
Assert.assertEquals(2, left.height());
Assert.assertEquals(1, leftLeft.height());
Assert.assertEquals(1, empty.height());
}
@Test
public void testNodeCount() {
Assert.assertEquals(13, root.numNodes());
Assert.assertEquals(4, left.numNodes());
Assert.assertEquals(1, leftLeft.numNodes());
Assert.assertEquals(1, empty.numNodes());
}
@Test
public void testSize() {
Assert.assertEquals(3, root.size());
Assert.assertEquals(3, left.size());
Assert.assertEquals(0, leftLeft.size());
Assert.assertEquals(0, empty.size());
}
@Test
public void testGetAndSetValue() {
String value = root.getValue();
Assert.assertEquals("root", value);
String newValue = "something";
root.setValue(newValue);
Assert.assertEquals(newValue, root.getValue());
}
@Test
public void testSetParent() {
Assert.assertNull(empty.getParent());
empty.setParent(root);
Assert.assertEquals(root, empty.getParent());
Assert.assertEquals(empty, root.get(3));
Assert.assertEquals(14, root.numNodes());
}
@Test
public void testAddChild() {
Assert.assertNull(empty.getParent());
root.add(empty);
Assert.assertEquals(root, empty.getParent());
Assert.assertEquals(empty, root.get(3));
Assert.assertEquals(14, root.numNodes());
}
@Test
public void testRemoveChild() {
Assert.assertEquals(newArrayList(left, middle, right), root);
root.remove(1);
Assert.assertEquals(newArrayList(left, right), root);
Assert.assertNull(middle.getParent());
Assert.assertEquals(9, root.numNodes());
}
@Test
public void testEmpty() {
Assert.assertTrue(empty.isLeaf());
Assert.assertEquals(1, empty.numNodes());
Assert.assertEquals(1, empty.height());
Assert.assertEquals(0, empty.size());
}
@Test
public void testClear() {
Assert.assertEquals(newArrayList(left, middle, right), root);
root.clear();
Assert.assertEquals(0, root.size());
Assert.assertNull(middle.getParent());
Assert.assertNull(left.getParent());
Assert.assertNull(right.getParent());
Assert.assertEquals(1, root.numNodes());
Assert.assertEquals(0, root.size());
Assert.assertEquals(1, root.height());
}
@Test
public void testSet() {
Assert.assertEquals(newArrayList(left, middle, right), root);
root.set(0, empty);
Assert.assertEquals(newArrayList(empty, middle, right), root);
Assert.assertEquals(10, root.numNodes());
Assert.assertEquals(3, root.size());
Assert.assertEquals(3, root.height());
}
}
| 5,479 | 33.037267 | 93 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/tree/Tree.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.tree;
import java.io.Serializable;
import java.util.List;
/**
*
* Purpose: a tree data structure. Imposes no ideology regarding context of nodes, e.g. sorted / balanced, etc.
* This solely provide structural implementation and leave the responsibility of maintaining a coherent context to
* an implementing class.
* <p>
* Contributors: goastler
*/
public interface Tree<A> extends Serializable, List<A> {
TreeNode<A> getRoot();
void setRoot(TreeNode<A> root);
/**
* Return the number of nodes in the tree
* @return
*/
default int size() {
TreeNode<A> root = getRoot();
if(root == null) {
return 0;
}
return root.size();
}
/**
* Return the max depth. This is measured with root node == height 0.
* @return
*/
default int height() {
TreeNode<A> root = getRoot();
if(root == null) {
return 0;
}
return root.height();
}
default void clear() {
setRoot(null);
}
default int nodeCount() {
TreeNode<A> root = getRoot();
if(root == null) {
return 0;
}
return root.numNodes();
}
}
| 2,039 | 26.2 | 116 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/tree/TreeNode.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.tree;
import utilities.Utilities;
import java.io.Serializable;
import java.util.*;
/**
* Purpose: a node of a tree. Tree nodes are a list of their child nodes.
* <p>
* Contributors: goastler
*/
public interface TreeNode<A> extends Serializable, List<TreeNode<A>> {
TreeNode<A> getParent();
void setParent(TreeNode<A> parent);
A getValue();
void setValue(A element);
default boolean isLeaf() {
return isEmpty();
}
default int numChildren() {
return size();
}
default int numNodes() {
// +1 for current node
return 1 + Utilities.apply(this, TreeNode::numNodes).stream().mapToInt(i -> i).sum();
}
default int height() {
int height = 1; // start at 1 because this node is 1 level itself
int maxHeight = 1;
LinkedList<TreeNode<?>> nodeStack = new LinkedList<>();
LinkedList<Iterator<? extends TreeNode<?>>> childrenIteratorStack = new LinkedList<>();
nodeStack.add(this);
childrenIteratorStack.add(this.iterator());
while (!nodeStack.isEmpty()) {
TreeNode<?> node = nodeStack.peekLast();
Iterator<? extends TreeNode<?>> iterator = childrenIteratorStack.peekLast();
if(iterator.hasNext()) {
// descend down to next child
height++;
node = iterator.next();
iterator = node.iterator();
nodeStack.add(node);
childrenIteratorStack.add(iterator);
} else {
// ascend up to parent
maxHeight = Math.max(height, maxHeight);
height--;
nodeStack.pollLast();
childrenIteratorStack.pollLast();
}
}
return maxHeight;
}
default int level() {
TreeNode<A> parent = getParent();
int level = 0;
while(parent != null) {
parent = parent.getParent();
level++;
}
return level;
}
default boolean isRoot() {
return getParent() == null;
}
@Override TreeNode<A> get(int i);
@Override TreeNode<A> set(int i, TreeNode<A> child);
@Override TreeNode<A> remove(int i);
@Override void clear();
default void removeParent() {
setParent(null);
}
/**
* Get the location of the node within the tree. This is separated by dots on each level
* @return
*/
default List<Integer> getLocation() {
TreeNode<A> parent = getParent();
final List<Integer> location;
if(parent == null) {
location = new ArrayList<>();
} else {
location = parent.getLocation();
location.add(getParent().indexOf(this));
}
return location;
}
}
| 3,654 | 28.475806 | 95 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/views/IntListView.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.collections.views;
import tsml.classifiers.distance_based.utils.collections.DefaultList;
public class IntListView implements DefaultList<Integer> {
final int[] array;
public IntListView(final int[] array) {this.array = array;}
@Override public Integer get(final int i) {
return array[i];
}
@Override public Integer set(final int i, final Integer integer) {
int prev = array[i];
array[i] = integer;
return prev;
}
@Override public int size() {
return array.length;
}
}
| 1,355 | 31.285714 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/collections/views/WrappedList.java | package tsml.classifiers.distance_based.utils.collections.views;
import tsml.classifiers.distance_based.utils.collections.DefaultList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
public class WrappedList<A, B> implements DefaultList<B> {
public WrappedList(final List<A> list, final Function<A, B> function) {
this.list = Objects.requireNonNull(list);
this.function = Objects.requireNonNull(function);
}
private final List<A> list;
private final Function<A, B> function;
@Override public B get(final int i) {
return function.apply(list.get(i));
}
@Override public int size() {
return list.size();
}
}
| 713 | 25.444444 | 75 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/experiment/DatasetSplit.java | package tsml.classifiers.distance_based.utils.experiment;
import tsml.data_containers.TimeSeriesInstance;
import tsml.data_containers.TimeSeriesInstances;
import tsml.data_containers.utilities.Converter;
import weka.core.Instances;
public class DatasetSplit {
private Instances trainDataArff;
private Instances testDataArff;
private TimeSeriesInstances trainDataTs;
private TimeSeriesInstances testDataTs;
public DatasetSplit(TimeSeriesInstances trainData, TimeSeriesInstances testData) {
setTrainData(trainData);
setTestData(testData);
}
public DatasetSplit(Instances trainData, Instances testData) {
setTrainData(trainData);
setTestData(testData);
}
public DatasetSplit(Instances[] data) {
this(data[0], data[1]);
}
public Instances getTestDataArff() {
if(testDataArff == null) {
setTestData(Converter.toArff(testDataTs));
}
return testDataArff;
}
public TimeSeriesInstances getTestDataTS() {
if(testDataTs == null) {
setTestData(Converter.fromArff(testDataArff));
}
return testDataTs;
}
public void setTestData(final Instances testData) {
this.testDataArff = testData;
testDataTs = null;
}
public void setTestData(final TimeSeriesInstances testData) {
this.testDataTs = testData;
testDataArff = null;
}
public Instances getTrainDataArff() {
if(trainDataArff == null) {
setTrainData(Converter.toArff(trainDataTs));
}
return trainDataArff;
}
public TimeSeriesInstances getTrainDataTS() {
if(trainDataTs == null) {
setTrainData(Converter.fromArff(trainDataArff));
}
return trainDataTs;
}
public void setTrainData(final Instances trainData) {
this.trainDataArff = trainData;
trainDataTs = null;
}
public void setTrainData(final TimeSeriesInstances trainData) {
this.trainDataTs = trainData;
trainDataArff = null;
}
}
| 2,105 | 26.710526 | 86 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/experiment/Experiment.java | package tsml.classifiers.distance_based.utils.experiment;
import evaluation.storage.ClassifierResults;
import experiments.ExperimentalArguments;
import experiments.ClassifierExperiments;
import experiments.data.DatasetLoading;
import tsml.classifiers.*;
import tsml.classifiers.distance_based.proximity.ProximityForest;
import tsml.classifiers.distance_based.proximity.ProximityForestWrapper;
import tsml.classifiers.distance_based.utils.classifiers.*;
import tsml.classifiers.distance_based.utils.classifiers.checkpointing.Checkpointed;
import tsml.classifiers.distance_based.utils.classifiers.configs.Builder;
import tsml.classifiers.distance_based.utils.classifiers.configs.Config;
import tsml.classifiers.distance_based.utils.classifiers.configs.Configs;
import tsml.classifiers.distance_based.utils.classifiers.contracting.ContractedTrain;
import tsml.classifiers.distance_based.utils.classifiers.results.ResultUtils;
import tsml.classifiers.distance_based.utils.system.copy.Copier;
import tsml.classifiers.distance_based.utils.system.logging.LogUtils;
import tsml.classifiers.distance_based.utils.system.logging.Loggable;
import tsml.classifiers.distance_based.utils.system.memory.MemoryWatcher;
import tsml.classifiers.distance_based.utils.system.timing.StopWatch;
import tsml.data_containers.TimeSeriesInstances;
import tsml.data_containers.utilities.Converter;
import utilities.ClassifierTools;
import weka.classifiers.Classifier;
import weka.core.Instances;
import weka.core.Randomizable;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import static tsml.classifiers.distance_based.utils.system.SysUtils.hostName;
import static utilities.FileUtils.*;
import static weka.core.Debug.OFF;
public class Experiment implements Copier {
public Experiment(String[] args) {
this(new ExperimentConfig(args));
}
public Experiment(ExperimentConfig config) {
this.config = Objects.requireNonNull(config);
setExperimentLogLevel(Level.ALL);
addClassifierConfigs(ProximityForest.CONFIGS);
addClassifierConfigs(ProximityForestWrapper.CONFIGS);
}
private void addClassifierConfig(Config<? extends Classifier> config) {
if(classifierLookup.containsKey(config.name())) {
throw new IllegalStateException("already contains classifier config for " + config.name());
}
classifierLookup.put(config.name(), config);
}
private void addClassifierConfigs(Configs<? extends Classifier> configs) {
configs.forEach((Consumer<Config<? extends Classifier>>) this::addClassifierConfig);
}
private void benchmarkHardware() {
log.info("benchmarking hardware");
// delegate to the benchmarking system from main experiments code. This maintains consistency across benchmarks, but it substantially quicker and therefore less reliable of a benchmark. todo talks to james about merging these
ExperimentalArguments args = new ExperimentalArguments();
args.performTimingBenchmark = true;
benchmarkScore = ClassifierExperiments.findBenchmarkTime(args);
// long sum = 0;
// int repeats = 30;
// long startTime = System.nanoTime();
// for(int i = 0; i < repeats; i++) {
// Random random = new Random(i);
// final double[] array = new double[1000000];
// for(int j = 0; j < array.length; j++) {
// array[j] = random.nextDouble();
// }
// Arrays.sort(array);
// }
// benchmarkScore = (System.nanoTime() - startTime) / repeats;
}
public static void main(String... args) throws Exception {
new Experiment(args).run();
}
private void buildClassifier() {
log.info("creating new instance of " + config.getClassifierName());
final Builder<? extends Classifier> builder = classifierLookup.get(config.getClassifierName());
if(builder == null) {
throw new NoSuchElementException(config.getClassifierName() + " not found");
}
classifier = builder.build();
if(classifier instanceof TSClassifier) {
tsClassifier = (TSClassifier) classifier;
} else {
tsClassifier = TSClassifier.wrapClassifier(classifier);
}
}
private final Map<String, Builder<? extends Classifier>> classifierLookup = new TreeMap<>();
private TimeSeriesInstances trainData;
private TimeSeriesInstances testData;
private Classifier classifier;
private TSClassifier tsClassifier;
private final StopWatch timer = new StopWatch();
private final StopWatch experimentTimer = new StopWatch();
private final MemoryWatcher memoryWatcher = new MemoryWatcher();
private final MemoryWatcher experimentMemoryWatcher = new MemoryWatcher();
private long benchmarkScore;
private final Logger log = LogUtils.getLogger(this);
private ExperimentConfig config;
private ExperimentConfig previousConfig;
private Map<String, FileLock> locks;
private void loadData() throws Exception {
final Instances[] instances =
DatasetLoading.sampleDataset(config.getDataDirPath(), config.getProblemName(), config.getSeed());
trainData = Converter.fromArff(instances[0]);
testData = Converter.fromArff(instances[1]);
// load the data
log.info("loading " + config.getProblemName() + " dataset ");
}
private FileLock getLock(String path) throws FileLock.LockException {
FileLock lock = locks.get(path);
if(lock == null) {
lock = new FileLock(path, false);
locks.put(path, lock);
}
return lock;
}
/**
* Runs the experiment. Make sure all fields have been set prior to this call otherwise Exceptions will be thrown accordingly.
*/
public void run() throws Exception {
locks = new HashMap<>();
// build the classifier
buildClassifier();
// configure the classifier with experiment settings as necessary
configureClassifier();
loadData();
benchmarkHardware();
// reset the memory watchers
experimentTimer.resetAndStart();
experimentMemoryWatcher.resetAndStart();
// iterate over every train time limit
final List<TimeSpan> trainTimeLimits = config.getTrainTimeLimits();
for(int trainTimeLimitIndex = 0; trainTimeLimitIndex < trainTimeLimits.size(); trainTimeLimitIndex++) {
final TimeSpan trainTimeLimit = trainTimeLimits.get(trainTimeLimitIndex);
config.setTrainTimeLimit(trainTimeLimit);
// attempt to lock the current config and maintain lock on previous
final FileLock lock = getLock(config);
lock.lock();
// run checks to see if files are in order (e.g. results don't exist / can be overwritten)
checkTestResultsExistence();
checkTrainResultsExistence();
// setup the contract
setupTrainTimeContract();
// setup checkpointing config
setupCheckpointing();
// copy over any previous checkpoints from previous contracts (and optionally remove previous checkpoint post copy)
copyMostRecentCheckpoint(trainTimeLimitIndex);
// train the classifier
train();
// test the classifier
test();
// stop the classifier from rebuilding on next buildClassifier call
if(classifier instanceof Rebuildable) {
((Rebuildable) classifier).setRebuild(false);
} else if(config.getTrainTimeLimits().size() > 1) {
log.warning("cannot disable rebuild on " + config.getClassifierNameInResults() +
", therefore it will be rebuilt entirely for every train time contract");
}
if(trainTimeLimitIndex >= trainTimeLimits.size() - 1) {
// optionally remove the checkpoint as it's the last one
optionallyRemoveCheckpoint(config);
}
if(config.getTrainTimeLimit() == null) {
log.info(config.getClassifierNameInResults() + " experiment complete");
} else {
log.info(config.getClassifierNameInResults() + " experiment complete under train time contract " + config.getTrainTimeLimit().label());
}
// release lock
lock.unlock();
previousConfig = config;
}
// clear any previously held locks / check they've been released
locks.forEach((k, v) -> {
if(v.isLocked()) {
throw new IllegalStateException("all locks should have been released: " + k);
}
});
locks = null;
// experiment complete
experimentTimer.stop();
experimentMemoryWatcher.stop();
log.info("experiment time: " + experimentTimer.toTimeSpan());
log.info("experiment mem: " + experimentMemoryWatcher.getMaxMemoryUsage());
}
/**
* I.e. if we're currently preparing to run a 3h contract and previously a 1h and 2h have been run, we should check the 1h and 2h workspace for checkpoint files. If there are no checkpoint files for 2h but there are for 1h, copy them into the checkpoint dir folder to resume from the 1h contract end point.
* @throws IOException
*/
private void copyMostRecentCheckpoint(int trainTimeLimitIndex) throws IOException {
if(isModelFullyBuiltFromPreviousRun()) {
log.info("skipping setup recent checkpoints for " + config.getClassifierNameInResults() + " as model fully built");
return;
}
// check the state of all train time contracts so far to copy over old checkpoints
if(config.isCheckpoint()) {
// if there's no train contract then bail
if(config.getTrainTimeLimit() == null) {
return;
}
// check whether the checkpoint dir is empty. If not, then we already have a checkpoint to work from, i.e. no need to copy a checkpoint from a lesser contract.
if(!isEmptyDir(config.getCheckpointDirPath())) {
log.info("checkpoint already exists in " + config.getCheckpointDirPath() + " , not copying from previous train time limit runs");
return;
}
// if the checkpoint dir is empty then there's no usable checkpoints
final FileLock lock = getLock(previousConfig);
lock.lock();
if(!isEmptyDir(previousConfig.getCheckpointDirPath())) {
// if a previous checkpoint has been located, copy the contents into the checkpoint dir for this contract time run
log.info("checkpoint found in " + previousConfig.getClassifierNameInResults() + " workspace");
final String src = previousConfig.getCheckpointDirPath();
final String dest = config.getCheckpointDirPath();
log.info("copying checkpoint contents from " + src + " to " + dest);
makeDir(config.getCheckpointDirPath());
copy(src, dest);
// optionally remove the checkpoint now it's copied to a new location
optionallyRemoveCheckpoint(previousConfig);
} else {
log.info("no checkpoints found from previous contracts");
}
lock.unlock();
}
}
private void setResultInfo(ClassifierResults results) throws IOException {
results.setFoldID(config.getSeed());
String paras = results.getParas();
if(!paras.isEmpty()) {
paras += ",";
}
paras += "hostName," + hostName();
results.setParas(paras);
results.setBenchmarkTime(benchmarkScore);
}
private void setTrainTime(ClassifierResults results, StopWatch timer) {
// if the build time has not been set
if(results.getBuildTime() < 0) {
// then set it to the build time witnessed during this experiment
results.setBuildTime(timer.elapsedTime());
results.setBuildPlusEstimateTime(timer.elapsedTime());
results.setTimeUnit(TimeUnit.NANOSECONDS);
}
}
private void setMemory(ClassifierResults results, MemoryWatcher memoryWatcher) {
// if the memory usage has not been set
if(results.getMemory() < 0) {
// then set it to the max mem witnessed during this experiment
results.setMemory(memoryWatcher.getMaxMemoryUsage());
}
}
private void checkTrainResultsExistence() {
if(config.isEvaluateClassifier()) {
checkResultsExistence("train", config.getTrainFilePath());
}
}
private void checkTestResultsExistence() {
if(!config.isTrainOnly()) {
checkResultsExistence("test", config.getTestFilePath());
}
}
private void writeResults(String label, ClassifierResults results, String path) throws Exception {
// write the train results to file, overwriting if necessary
final boolean exists = checkResultsExistence(label, path);
results.setSplit(label);
log.info((exists ? "overwriting" : "writing") + " " + label + " results");
results.writeFullResultsToFile(path);
}
private boolean checkResultsExistence(String label, String path) {
final boolean exists = new File(path).exists();
if(exists && !config.isOverwriteResults()) {
throw new IllegalStateException(label + " results exist at " + path);
}
return exists;
}
private void setupTrainTimeContract() {
if(isModelFullyBuiltFromPreviousRun()) {
log.info("skipping setup contract for " + config.getClassifierNameInResults() + " as model fully built");
return;
}
if(config.getTrainTimeLimit() != null) {
// there is a contract
if(classifier instanceof TrainTimeContractable) {
log.info("setting " + config.getClassifierName() + " train contract to " + config.getTrainTimeLimit() + " : " + config.getClassifierNameInResults());
((TrainTimeContractable) classifier).setTrainTimeLimit(config.getTrainTimeLimit().inNanos());
} else {
throw new IllegalStateException("classifier cannot handle train time contract");
}
} // else there is no contract, proceed as is
}
private void configureClassifier() {
// set estimate train error
if(config.isEvaluateClassifier()) {
if(classifier instanceof TrainEstimateable) {
log.info("setting " + config.getClassifierNameInResults() + " to estimate train error");
((TrainEstimateable) classifier).setEstimateOwnPerformance(true);
if(classifier instanceof EnhancedAbstractClassifier) {
EnhancedAbstractClassifier eac = (EnhancedAbstractClassifier) classifier;
// default to a cv if not set when building the classifier
if(eac.getEstimatorMethod().equalsIgnoreCase("none")) {
eac.setTrainEstimateMethod("cv");
}
}
} else {
throw new IllegalStateException("classifier cannot evaluate the train error");
}
}
// set log level
if(classifier instanceof Loggable) {
log.info("setting " + config.getClassifierNameInResults() + " log level to " + config.getLogLevel());
((Loggable) classifier).setLogLevel(config.getLogLevel());
} else if(classifier instanceof EnhancedAbstractClassifier) {
boolean debug = !config.getLogLevel().equals(OFF);
log.info("setting " + config.getClassifierNameInResults() + " debug to " + debug);
((EnhancedAbstractClassifier) classifier).setDebug(debug);
} else {
if(!config.getLogLevel().equals(Level.OFF)) {
log.info("classifier does not support logging");
}
}
// set seed
if(classifier instanceof Randomizable) {
log.info("setting " + config.getClassifierNameInResults() + " seed to " + config.getSeed());
((Randomizable) classifier).setSeed(config.getSeed());
} else {
log.info("classifier does not accept a seed");
}
// set threads
if(classifier instanceof MultiThreadable) {
log.info("setting " + config.getClassifierNameInResults() + " to use " + config.getNumThreads() + " threads");
((MultiThreadable) classifier).enableMultiThreading(config.getNumThreads());
} else if(config.getNumThreads() != 1) {
log.info("classifier cannot use multiple threads");
}
// todo mem
// // set memory
// if(classifier instanceof MemoryContractable) {
// ((MemoryContractable) classifier).setMemoryLimit();
// }
}
private boolean isModelFullyBuiltFromPreviousRun() {
// skip if the model is fully built from a previous contract
return previousConfig != null && classifier instanceof ContractedTrain && ((ContractedTrain) classifier).isFullyBuilt();
}
private void train() throws Exception {
if(isModelFullyBuiltFromPreviousRun()) {
log.info("skipping training " + config.getClassifierNameInResults() + " as model fully built");
String src = previousConfig.getTrainFilePath();
String dest = config.getTrainFilePath();
if(Files.exists(Paths.get(src))) {
log.info("copying " + src + " to " + dest);
copy(src, dest);
}
return;
}
// build the classifier
log.info("training " + config.getClassifierNameInResults());
timer.start();
memoryWatcher.start();
tsClassifier.buildClassifier(trainData);
memoryWatcher.stop();
timer.stop();
log.info("train time: " + timer.toTimeSpan());
log.info("train mem: " + memoryWatcher.getMaxMemoryUsage());
// if estimating the train error then write out train results
if(config.isEvaluateClassifier()) {
final ClassifierResults trainResults = ((TrainEstimateable) classifier).getTrainResults();
ResultUtils.setInfo(trainResults, tsClassifier, trainData);
setResultInfo(trainResults);
setTrainTime(trainResults, timer);
setMemory(trainResults, memoryWatcher);
trainResults.findAllStatsOnce();
log.info("train results: ");
log.info(trainResults.writeSummaryResultsToString());
writeResults("train", trainResults, config.getTrainFilePath());
}
log.info(config.getClassifierNameInResults() + " training complete");
}
private void test() throws Exception {
// if only training then skip the test phase
if(config.isTrainOnly()) {
log.info("skipping testing classifier");
return;
}
if(isModelFullyBuiltFromPreviousRun()) {
log.info("skipping testing " + config.getClassifierNameInResults() + " as model fully built");
String src = previousConfig.getTestFilePath();
String dest = config.getTestFilePath();
log.info("copying " + src + " to " + dest);
copy(src, dest);
return;
}
// test the classifier
log.info("testing " + config.getClassifierNameInResults());
timer.resetAndStart();
memoryWatcher.resetAndStart();
final ClassifierResults testResults = new ClassifierResults();
ClassifierTools.addPredictions(tsClassifier, testData, testResults, new Random(config.getSeed()));
timer.stop();
memoryWatcher.stop();
log.info("test time: " + timer.toTimeSpan());
log.info("test mem: " + memoryWatcher.getMaxMemoryUsage());
ResultUtils.setInfo(testResults, tsClassifier, trainData);
setResultInfo(testResults);
setTrainTime(testResults, timer);
setMemory(testResults, memoryWatcher);
log.info("test results: ");
log.info(testResults.writeSummaryResultsToString());
writeResults("test", testResults, config.getTestFilePath());
log.info(config.getClassifierNameInResults() + " testing complete");
}
private void setupCheckpointing() throws IOException {
if(config.isCheckpoint()) {
if(classifier instanceof Checkpointable) {
// the copy over the most suitable checkpoint from another run if exists
log.info("setting checkpoint path for " + config.getClassifierNameInResults() + " to " + config.getCheckpointDirPath());
((Checkpointable) classifier).setCheckpointPath(config.getCheckpointDirPath());
} else {
log.info(config.getClassifierNameInResults() + " cannot produce checkpoints");
}
if(classifier instanceof Checkpointed) {
if(config.getCheckpointInterval() != null) {
log.info("setting checkpoint interval for " + config.getClassifierNameInResults() + " to " + config.getCheckpointInterval());
((Checkpointed) classifier).setCheckpointInterval(config.getCheckpointInterval());
}
if(config.isKeepCheckpoints()) {
log.info("setting keep all checkpoints for " + config.getClassifierNameInResults());
}
((Checkpointed) classifier).setKeepCheckpoints(config.isKeepCheckpoints());
}
}
}
public Level getExperimentLogLevel() {
return log.getLevel();
}
public void setExperimentLogLevel(final Level level) {
log.setLevel(level);
}
public ExperimentConfig getConfig() {
return config;
}
private void optionallyRemoveCheckpoint(ExperimentConfig config) throws IOException {
if(config == null) {
return;
}
if(config.isCheckpoint()) {
// optionally remove the checkpoint
if(config.isRemoveCheckpoint()) {
log.info("deleting checkpoint at " + config.getCheckpointDirPath());
final FileLock lock = getLock(config);
lock.lock();
delete(config.getCheckpointDirPath());
lock.unlock();
}
}
}
private FileLock getLock(ExperimentConfig config) {
return getLock(config.getLockFilePath());
}
}
| 23,069 | 45.14 | 310 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/experiment/ExperimentConfig.java | package tsml.classifiers.distance_based.utils.experiment;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import org.junit.Assert;
import tsml.classifiers.distance_based.utils.system.copy.Copier;
import tsml.classifiers.distance_based.utils.strings.StrUtils;
import tsml.classifiers.distance_based.utils.system.memory.MemoryAmount;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.stream.Collectors;
public class ExperimentConfig implements Copier {
public ExperimentConfig() {}
@Parameter(names = {"-c", "--classifier"}, description = "The classifier to use.")
private String classifierName;
@Parameter(names = {"-s", "--seed"}, description = "The seed used in resampling the data and producing random numbers in the classifier.")
private Integer seed;
@Parameter(names = {"-r", "--results"}, description = "The results directory.")
private String resultsDirPath;
@Parameter(names = {"-d", "--data"}, description = "The data directory.")
private String dataDirPath;
@Parameter(names = {"-p", "--problem"}, description = "The problem name. E.g. GunPoint.")
private String problemName;
@Parameter(names = {"--cp", "--checkpoint"}, description = "Periodically save the classifier to disk. Default: off")
private boolean checkpoint = false;
@Parameter(names = {"--rcp", "--removeCheckpoint"}, description = "Remove any checkpoints upon completion of a train time contract. The assumption here is that once the classifier has built in the given time limit, no further work will be done and the checkpoint can be safely removed. In other words, the assumption is that the checkpoint is only useful if the classifier gets stoppped mid-build and must be restarted. When the classifier finishes building, the checkpoint files are redundant, therefore. Note this does not affect multiple contracts as the checkpoint files are copied before removal. I.e. a contract of 1h completes and leaves behind some checkpoint files. These are copied over to the subsequent 2h contract before removal from the 1h contract working area. Default: off")
private boolean removeCheckpoint = false;
@Parameter(names = {"--cpi", "--checkpointInterval"}, description = "The minimum interval between checkpoints. Classifiers may not produce checkpoints within the checkpoint interval time from the last checkpoint. Therefore, classifiers may produce checkpoints with (much) larger intervals inbetween, depending on their checkpoint frequency.", converter = TimeSpanConverter.class)
private TimeSpan checkpointInterval = new TimeSpan("4h");
@Parameter(names = {"--kcp", "--keepCheckpoints"}, description = "Keep every checkpoint as a snapshot of the classifier model at that point in time. When disabled, classifiers overwrite their last checkpoint. When enabled, classifiers will write checkpoints with a time stamp rather than overwriting previous checkpoints. Default: off")
private boolean keepCheckpoints = false;
public MemoryAmount getMemory() {
return memory;
}
private static class TimeSpanConverter implements IStringConverter<TimeSpan> {
@Override public TimeSpan convert(final String s) {
return new TimeSpan(s);
}
}
private static class MemoryAmountConverter implements IStringConverter<MemoryAmount> {
@Override public MemoryAmount convert(final String s) {
return new MemoryAmount(s);
}
}
@Parameter(names = {"--ttl", "--trainTimeLimit"}, description = "Contract the classifier to build in a set time period. Give this option two arguments in the form of '--contractTrain <amount> <units>', e.g. '--contractTrain 5 minutes'", converter = TimeSpanConverter.class)
private List<TimeSpan> trainTimeLimits = new ArrayList<>();
@Parameter(names = {"-e", "--evaluate"}, description = "Estimate the train error. Default: false")
private boolean evaluateClassifier = false;
@Parameter(names = {"-t", "--threads"}, description = "The number of threads to use. Set to 0 or less for all available processors at runtime. Default: 1")
private int numThreads = 1;
@Parameter(names = {"-m", "--memory"}, description = "The amount of memory allocated at maximum during the runtime of this program. Default: no limit", converter = MemoryAmountConverter.class)
private MemoryAmount memory = null;
@Parameter(names = {"--trainOnly"}, description = "Only train the classifier, do not test.")
private boolean trainOnly = false;
@Parameter(names = {"-o", "--overwrite"}, description = "Overwrite previous results.")
private boolean overwriteResults = false;
public TimeSpan getTrainTimeLimit() {
return trainTimeLimit;
}
public void setTrainTimeLimit(final TimeSpan trainTimeLimit) {
this.trainTimeLimit = trainTimeLimit;
}
private static class LogLevelConverter implements IStringConverter<Level> {
@Override public Level convert(final String s) {
return Level.parse(s.toUpperCase());
}
}
@Parameter(names = {"-l", "--logLevel"}, description = "The amount of logging. This should be set to a Java log level. Default: OFF", converter = LogLevelConverter.class)
private Level logLevel = Level.OFF;
private TimeSpan trainTimeLimit; // the current train time limit
public ExperimentConfig(String[] args) {
JCommander.newBuilder()
.addObject(this)
.build()
.parse(Arrays.stream(args).filter(((Predicate<String>) String::isEmpty).negate()).toArray(String[]::new));
// check the state of this experiment is set up
if(seed == null) throw new IllegalStateException("seed not set");
if(classifierName == null) throw new IllegalStateException("classifier name not set");
if(problemName == null) throw new IllegalStateException("problem name not set");
if(dataDirPath == null) throw new IllegalStateException("data dir path not set");
if(resultsDirPath == null) throw new IllegalStateException("results dir path not set");
if(trainTimeLimits.isEmpty()) {
// add a null limit to indicate there is no limit
trainTimeLimits.add(null);
} else {
// sort the train contracts in asc order
trainTimeLimits = trainTimeLimits.stream().distinct().sorted().collect(Collectors.toList());
}
// default to all cpus
if(numThreads < 1) {
numThreads = Runtime.getRuntime().availableProcessors();
}
Assert.assertFalse(trainTimeLimits.isEmpty());
}
public String getClassifierName() {
return classifierName;
}
public Integer getSeed() {
return seed;
}
public String getResultsDirPath() {
return resultsDirPath;
}
public String getDataDirPath() {
return dataDirPath;
}
public String getProblemName() {
return problemName;
}
public boolean isCheckpoint() {
return checkpoint;
}
public boolean isRemoveCheckpoint() {
return removeCheckpoint;
}
public TimeSpan getCheckpointInterval() {
return checkpointInterval;
}
public boolean isKeepCheckpoints() {
return keepCheckpoints;
}
public List<TimeSpan> getTrainTimeLimits() {
return trainTimeLimits;
}
public boolean isEvaluateClassifier() {
return evaluateClassifier;
}
public int getNumThreads() {
return numThreads;
}
public boolean isTrainOnly() {
return trainOnly;
}
public boolean isOverwriteResults() {
return overwriteResults;
}
public Level getLogLevel() {
return logLevel;
}
public void setClassifierName(final String classifierName) {
this.classifierName = classifierName;
}
public void setSeed(final Integer seed) {
this.seed = seed;
}
public void setResultsDirPath(final String resultsDirPath) {
this.resultsDirPath = resultsDirPath;
}
public void setDataDirPath(final String dataDirPath) {
this.dataDirPath = dataDirPath;
}
public void setProblemName(final String problemName) {
this.problemName = problemName;
}
public void setCheckpoint(final boolean checkpoint) {
this.checkpoint = checkpoint;
}
public void setRemoveCheckpoint(final boolean removeCheckpoint) {
this.removeCheckpoint = removeCheckpoint;
}
public void setCheckpointInterval(final TimeSpan checkpointInterval) {
this.checkpointInterval = checkpointInterval;
}
public void setKeepCheckpoints(final boolean keepCheckpoints) {
this.keepCheckpoints = keepCheckpoints;
}
public void setTrainTimeLimits(final List<TimeSpan> trainTimeLimits) {
this.trainTimeLimits = trainTimeLimits;
}
public void setEvaluateClassifier(final boolean evaluateClassifier) {
this.evaluateClassifier = evaluateClassifier;
}
public void setNumThreads(final int numThreads) {
this.numThreads = numThreads;
}
public void setTrainOnly(final boolean trainOnly) {
this.trainOnly = trainOnly;
}
public void setOverwriteResults(final boolean overwriteResults) {
this.overwriteResults = overwriteResults;
}
public void setLogLevel(final Level logLevel) {
this.logLevel = Objects.requireNonNull(logLevel);
}
public String getTestFilePath() {
return StrUtils.joinPath(getExperimentResultsDirPath(), "testFold" + seed + ".csv");
}
public String getTrainFilePath() {
return StrUtils.joinPath(getExperimentResultsDirPath(), "trainFold" + seed + ".csv");
}
public String getClassifierNameInResults() {
String classifierNameInResults = classifierName;
if(trainTimeLimit != null) {
classifierNameInResults += "_" + trainTimeLimit.label();
}
return classifierNameInResults;
}
public String getExperimentResultsDirPath() {
return StrUtils.joinPath( getResultsDirPath(), getClassifierNameInResults(), "Predictions", getProblemName());
}
public String getLockFilePath() {
return StrUtils.joinPath(getExperimentResultsDirPath(), "fold" + getSeed());
}
public String getCheckpointDirPath() {
return StrUtils.joinPath( getResultsDirPath(), getClassifierNameInResults(), "Workspace", getProblemName(), "fold" + getSeed());
}
public void setMemory(final MemoryAmount memory) {
this.memory = memory;
}
}
| 10,864 | 37.257042 | 795 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/experiment/ExperimentRunner.java | package tsml.classifiers.distance_based.utils.experiment;
public class ExperimentRunner {
public static void main(String[] args) throws Exception {
// Experiment.main(
// "-r", "results"
// , "-d", "/bench/phd/data/all_2019"
// , "-p", "GunPoint"
// , "-c", "PF_R5"
// , "-s", "0"
// , "-l", "all"
// , "-o"
// );
String cmd =
" -o -d /bench/phd/data/all_2019 -p GunPoint -r results -c PF_R5_OOB -s 0 -m 8000 -t 1 -l ALL -e"; // --cp --cpi 5s --kcp
cmd = cmd.trim();
args = cmd.split(" ");
Experiment.main(args);
// Experiment.main(
// "-r", "results"
// , "-d", "/bench/phd/data/all"
// , "-p", "GunPoint"
// , "-c", "PF_R5_OOB"
//// , "-c", "PF_R5"
// , "-s", "0"
// , "-l", "all"
// , "-o"
// , "--cp"
// , "--cpi", "30s"
// , "--rcp"
// , "-e"
//// , "--ttl", "10s"
//// , "--ttl", "20s"
//// , "--ttl", "30s"
// , "--ttl", "1m"
// , "--ttl", "2m"
// , "--ttl", "3m"
// , "--ttl", "4m"
// );
}
}
| 1,395 | 30.022222 | 138 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/experiment/TimeSpan.java | package tsml.classifiers.distance_based.utils.experiment;
import tsml.classifiers.distance_based.utils.strings.StrUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.*;
public class TimeSpan implements Comparable<TimeSpan>, Serializable {
public TimeSpan(TimeSpan other) {
this(other.inNanos());
}
public TimeSpan(long nanos) {
this.nanos = nanos;
if(nanos < 0) {
nanos = Math.abs(nanos);
}
long remainingAmount = nanos;
final TimeUnit[] values = TimeUnit.values();
amounts = new long[TimeUnit.values().length];
for(int i = values.length - 1; i >= 0; i--) {
final TimeUnit unit = values[i];
final long amount = unit.convert(remainingAmount, TimeUnit.NANOSECONDS);
amounts[i] = amount;
if(amount > 0) {
// subtract the amount of time this accounts for in the remaining time. I.e. if the remaining time
// was 1.5 days (in nanos) then the amount would be only 1 day. We need to subtract the 1 day from
// the 1.5 days to give .5 days which can be represented in smaller units, i.e. hours.
remainingAmount -= TimeUnit.NANOSECONDS.convert(amount, unit);
// quit if remaining amount is 0
if(remainingAmount == 0) {
break;
}
}
}
}
public TimeSpan(final String label) {
this(labelToNanos(label));
}
private static long labelToNanos(String label) {
if(label.isEmpty()) {
throw new IllegalArgumentException("empty input");
}
boolean negative = false;
int i = 0;
if(label.charAt(0) == '-') {
negative = true;
i++;
}
StringBuilder sb = new StringBuilder();
long totalNanos = 0;
List<String> parts = new ArrayList<>();
boolean previousIsDigit = true; // whether the last char was a digit or not
for(; i < label.length(); i++) {
final char c = label.charAt(i);
final boolean isDigit = StrUtils.isDigit(c);
final boolean isAlpha = StrUtils.isAlpha(c);
if(!isAlpha && !isDigit) {
throw new IllegalArgumentException(c + " is not a digit or alpha character");
}
if(isAlpha && isDigit) {
throw new IllegalStateException("the character cannot be a letter and a digit!! This should never happen!");
}
if(i != 0 && ((isDigit && !previousIsDigit) || (!isDigit && previousIsDigit))) {
// was looking at value, now parsing unit
// or vice versa
// so store the contents of sb and reinitialise
parts.add(sb.toString());
sb = new StringBuilder();
}
sb.append(c);
previousIsDigit = isDigit;
}
parts.add(sb.toString());
if(parts.size() % 2 != 0) {
throw new IllegalArgumentException("odd number of parts to string: " + label);
}
for(int j = 0; j < parts.size(); j += 2) {
final long value = Long.parseLong(parts.get(j));
final String unit = parts.get(j + 1);
totalNanos += TimeUnit.NANOSECONDS.convert(value, strToUnit(unit));
}
if(negative) {
totalNanos = -totalNanos;
}
return totalNanos;
}
public static TimeUnit strToUnit(String str) {
switch(str.toLowerCase()) {
case "d": return DAYS;
case "h": return HOURS;
case "m": return MINUTES;
case "s": return TimeUnit.SECONDS;
case "ms": return TimeUnit.MILLISECONDS;
case "us": return TimeUnit.MICROSECONDS;
case "ns": return TimeUnit.NANOSECONDS;
default: throw new IllegalArgumentException("unknown unit conversion from: " + str);
}
}
public static String unitToStr(TimeUnit unit) {
switch(unit) {
case DAYS: return "d";
case HOURS: return "h";
case MINUTES: return "m";
case SECONDS: return "s";
case MILLISECONDS: return "ms";
case MICROSECONDS: return "us";
case NANOSECONDS: return "ns";
default: throw new IllegalArgumentException("unknown string label for unit: " + unit);
}
}
private String label;
private final long nanos;
private final long[] amounts;
/**
* Get the specific amount of a given unit. I.e. take 1h33m50s. days() would give 0, hours() would give 1, minutes() would give 33 and seconds() would give 50.
* @param unit
* @return
*/
public long get(TimeUnit unit) {
return amounts[unit.ordinal()];
}
public long days() {
return get(DAYS);
}
public long hours() {
return get(HOURS);
}
public long minutes() {
return get(MINUTES);
}
public long seconds() {
return get(TimeUnit.SECONDS);
}
public long milliseconds() {
return get(TimeUnit.MILLISECONDS);
}
public long microseconds() {
return get(TimeUnit.MICROSECONDS);
}
public long nanoseconds() {
return get(TimeUnit.NANOSECONDS);
}
/**
* The time span expressed in nanoseconds.
* @return
*/
public long inNanos() {
return nanos;
}
public String label() {
if(label == null) {
// the input label may be in an odd format, i.e. 90m. Therefore, convert the nanos back to a label which will output in maximised units, i.e. 1h30m. Use the nanos representation to do this.
StringBuilder sb = new StringBuilder();
if(nanos < 0) {
sb.append("-");
}
for(int i = TimeUnit.values().length - 1; i >= 0; i--) {
TimeUnit unit = TimeUnit.values()[i];
long amount = get(unit);
if(amount > 0) {
sb.append(amount).append(unitToStr(unit));
}
}
label = sb.toString();
}
return label;
}
public String asTimeStamp() {
StringBuilder sb = new StringBuilder();
if(nanos < 0) {
sb.append("-");
}
boolean first = true;
for(int i = values().length - 1; i >= MINUTES.ordinal(); i--) {
TimeUnit unit = values()[i];
long amount = get(unit);
if(!first) {
sb.append(String.format("%02d", amount));
} else if(amount > 0 || unit.equals(MINUTES)) {
sb.append(amount).append(":");
first = false;
}
}
sb.append(String.format("%02d", seconds())).append(".").append(String.format("%03d", milliseconds()));
return sb.toString();
}
@Override public String toString() {
return asTimeStamp();
}
@Override public int compareTo(final TimeSpan other) {
return Long.compare(inNanos(), other.inNanos());
}
@Override public boolean equals(final Object o) {
if(this == o) {
return true;
}
if(!(o instanceof TimeSpan)) {
return false;
}
final TimeSpan timeSpan = (TimeSpan) o;
return nanos == timeSpan.nanos;
}
@Override public int hashCode() {
return Objects.hash(nanos);
}
}
| 7,739 | 31.93617 | 201 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/experiment/TimeSpanTest.java | package tsml.classifiers.distance_based.utils.experiment;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static tsml.classifiers.distance_based.utils.collections.CollectionUtils.newArrayList;
public class TimeSpanTest {
@Test
public void testTimeSpanConversion() {
Assert.assertEquals(130000000000L, new TimeSpan(130000000000L).inNanos());
Assert.assertEquals(-130000000000L, new TimeSpan(-130000000000L).inNanos());
Assert.assertEquals(130000000000L, new TimeSpan("130s").inNanos());
Assert.assertEquals(130000000000L, new TimeSpan("1m70s").inNanos());
Assert.assertEquals(130000000000L, new TimeSpan("2m10s").inNanos());
Assert.assertEquals(-130000000000L, new TimeSpan("-130s").inNanos());
Assert.assertEquals(-130000000000L, new TimeSpan("-1m70s").inNanos());
Assert.assertEquals(-130000000000L, new TimeSpan("-2m10s").inNanos());
Assert.assertEquals("2:10.000", new TimeSpan("130s").asTimeStamp());
Assert.assertEquals("-2:10.000", new TimeSpan("-130s").asTimeStamp());
}
@Test
public void testSort() {
final List<String> output =
newArrayList("130s", "2m10s", "71s", "1m000001s").stream().map(TimeSpan::new).sorted()
.map(TimeSpan::label).collect(Collectors.toList());
final ArrayList<String> expected = newArrayList("1m1s", "1m11s", "2m10s", "2m10s");
Assert.assertEquals(expected, output);
}
@Test
public void testStrToNanos1m70s() {
Assert.assertEquals(130000000000L, new TimeSpan("1m70s").inNanos());
}
@Test
public void testNanosToStr1m70s() {
Assert.assertEquals("2m10s", new TimeSpan(130000000000L).label());
}
@Test
public void testStrToNanos130s() {
Assert.assertEquals(130000000000L, new TimeSpan("130s").inNanos());
}
@Test
public void testNanosToStr130s() {
Assert.assertEquals("2m10s", new TimeSpan(130000000000L).label());
}
@Test
public void testEquals() {
Assert.assertEquals(new TimeSpan(130000000000L), new TimeSpan(130000000000L));
Assert.assertNotEquals(new TimeSpan(130000000000L), new TimeSpan(130000000001L));
Assert.assertEquals(new TimeSpan("1h30m"), new TimeSpan("90m"));
Assert.assertEquals(new TimeSpan("2m10s"), new TimeSpan("130s"));
Assert.assertEquals(new TimeSpan("2m10s"), new TimeSpan("1m70s"));
Assert.assertEquals(new TimeSpan("130s"), new TimeSpan("1m70s"));
Assert.assertNotEquals(new TimeSpan("131s"), new TimeSpan("1m70s"));
Assert.assertEquals(new TimeSpan("130s"), new TimeSpan(new TimeSpan(new TimeSpan("1m70s"))));
}
@Test
public void testNanosToStr1h() {
Assert.assertEquals("1h", new TimeSpan(3600000000000L).label());
}
@Test
public void testNanosToStr90m() {
Assert.assertEquals("1h30m", new TimeSpan(5400000000000L).label());
}
@Test
public void testNanosToStr26h87m102s() {
Assert.assertEquals("1d3h28m42s", new TimeSpan(98922000000000L).label());
}
@Test
public void testStrToNanos1h() {
Assert.assertEquals(3600000000000L, new TimeSpan("1h").inNanos());
}
@Test
public void testStrToNanos90m() {
Assert.assertEquals(5400000000000L, new TimeSpan("90m").inNanos());
}
@Test
public void testStrToNanos26h87m102s() {
Assert.assertEquals(98922000000000L, new TimeSpan("26h87m102s").inNanos());
}
@Test(expected = IllegalArgumentException.class)
public void testStrToNanosInvalidUnit() {
new TimeSpan("26z");
}
@Test(expected = IllegalArgumentException.class)
public void testStrToNanosEmpty() {
new TimeSpan("");
}
}
| 3,901 | 34.798165 | 102 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/SummaryStat.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.stats;
import java.math.BigDecimal;
public class SummaryStat {
private double firstValue = 0;
private long count = 0;
private BigDecimal sum = new BigDecimal(0);
private BigDecimal sqSum = new BigDecimal(0);
public void add(double v) {
if(count == 0) {
firstValue = v;
}
final double diff = v - firstValue;
final double sqDiff = Math.pow(diff, 2);
sum = sum.add(new BigDecimal(diff));
sqSum = sqSum.add(new BigDecimal(sqDiff));
count++;
}
public void remove(double v) {
if(count <= 0) {
throw new IllegalArgumentException();
}
count--;
final double diff = v - firstValue;
final double sqDiff = Math.pow(diff, 2);
sum = sum.subtract(new BigDecimal(diff));
sqSum = sqSum.subtract(new BigDecimal(sqDiff));
}
public double getMean() {
return firstValue + sum.divide(new BigDecimal(count), BigDecimal.ROUND_HALF_UP).doubleValue();
}
public double getPopulationVariance() {
if(count <= 0) {
return 0;
}
return sqSum.subtract(sum.multiply(sum).divide(new BigDecimal(count), BigDecimal.ROUND_HALF_UP)).divide(new BigDecimal(
count),
BigDecimal.ROUND_HALF_UP).doubleValue();
}
public double getSampleVariance() {
if(count <= 0) {
return 0;
}
return sqSum.subtract(sum.multiply(sum).divide(new BigDecimal(count), BigDecimal.ROUND_HALF_UP)).divide(new BigDecimal(
count - 1),
BigDecimal.ROUND_HALF_UP).doubleValue();
}
public double getSampleStandardDeviation() {
if(count <= 0) {
return 0;
}
return Math.sqrt(getSampleVariance());
}
public double getPopulationStandardDeviation() {
if(count <= 0) {
return 0;
}
return Math.sqrt(getPopulationVariance());
}
public long getCount() {
return count;
}
}
| 2,839 | 30.555556 | 127 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/ChiSquared.java | package tsml.classifiers.distance_based.utils.stats.scoring;
import java.util.List;
public class ChiSquared implements SplitScorer {
@Override public <A> double score(final Labels<A> parent, final List<Labels<A>> children) {
final List<Double> parentDistribution = parent.getDistribution();
double sum = 0;
for(final Labels<A> labels : children) {
labels.setLabelSet(parent.getLabelSet());
final double childSum = labels.getWeights().stream().mapToDouble(d -> d).sum();
final List<Double> childCounts = labels.getCountsList();
for(int i = 0; i < parentDistribution.size(); i++) {
final double observed = childCounts.get(i);
final double expected = parentDistribution.get(i) * childSum;
double v = Math.pow(observed - expected, 2);
v /= expected;
sum += v;
}
}
return sum;
}
}
| 984 | 36.884615 | 95 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/ChiSquaredTest.java | package tsml.classifiers.distance_based.utils.stats.scoring;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
public class ChiSquaredTest {
@Test
public void testImpure() {
Assert.assertEquals(0, new ChiSquared().score(new Labels<>(
Arrays.asList(0,0,0,0,1,1,1,1,1,1,1,1)), Arrays.asList(new Labels<>(Arrays.asList(0,0,1,1,1,1)), new Labels<>(Arrays.asList(0,0,1,1,1,1)))), 0d);
}
@Test
public void testPure() {
Assert.assertEquals(12.000000000000002, new ChiSquared().score(new Labels<>(Arrays.asList(0,0,0,0,1,1,1,1,1,1,1,1)), Arrays.asList(new Labels<>(Arrays.asList(0,0,0,0)), new Labels<>(Arrays.asList(1,1,1,1,1,1,1,1)))), 0d);
}
@Test
public void testA() {
Assert.assertEquals(4.6875, new ChiSquared().score(new Labels<>(Arrays.asList(0,0,0,0,0,0,0,0,1,1,1,1)), Arrays.asList(new Labels<>(Arrays.asList(0,0,0,0,0,0,0,1)), new Labels<>(Arrays.asList(0,1,1,1)))), 0d);
}
@Test
public void testB() {
Assert.assertEquals(0.30000000000000004, new ChiSquared().score(new Labels<>(Arrays.asList(0,0,0,0,1,1,1,1,1,1,1,1)), Arrays.asList(new Labels<>(Arrays.asList(0,0,0,1,1,1,1,1,1,1)), new Labels<>(Arrays.asList(0,1)))), 0d);
}
}
| 1,258 | 39.612903 | 230 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/GiniEntropy.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.stats.scoring;
public class GiniEntropy implements PartitionEntropy {
public <A> double entropy(Labels<A> labels) {
return 1d - labels.getDistribution().stream().mapToDouble(d -> Math.pow(d, 2)).sum();
}
}
| 1,036 | 38.884615 | 93 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/GiniEntropyTest.java | package tsml.classifiers.distance_based.utils.stats.scoring;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import static tsml.classifiers.distance_based.utils.stats.scoring.Labels.fromCounts;
public class GiniEntropyTest {
@Test
public void testImpure() {
Assert.assertEquals(0.5, new GiniEntropy().entropy(new Labels<>().setDistribution(Arrays.asList(0.5, 0.5))), 0d);
}
@Test
public void testPure() {
Assert.assertEquals(0.0, new GiniEntropy().entropy(new Labels<>().setDistribution(Arrays.asList(1d, 0d))), 0d);
}
@Test
public void testA() {
Assert.assertEquals(0.48, new GiniEntropy().entropy(new Labels<>().setDistribution(Arrays.asList(0.4, 0.6))), 0d);
}
@Test
public void testB() {
Assert.assertEquals(0.17999999999999994, new GiniEntropy().entropy(new Labels<>().setDistribution(Arrays.asList(0.1, 0.9))), 0d);
}
@Test
public void testImpureScore() {
Assert.assertEquals(0d, new GiniEntropy().score(fromCounts(Arrays.asList(6d, 6d)), Arrays.asList(fromCounts(Arrays.asList(3d, 3d)), fromCounts(Arrays.asList(3d, 3d)))), 0d);
}
@Test
public void testPureScore() {
Assert.assertEquals(0.5, new GiniEntropy().score(fromCounts(Arrays.asList(6d, 6d)), Arrays.asList(fromCounts(Arrays.asList(6d, 0d)), fromCounts(Arrays.asList(0d, 6d)))), 0d);
}
@Test
public void testAScore() {
Assert.assertEquals(0.05555555555555558, new GiniEntropy().score(fromCounts(Arrays.asList(8d, 4d)), Arrays.asList(fromCounts(Arrays.asList(4d, 2d)), fromCounts(Arrays.asList(4d, 2d)))), 0d);
}
@Test
public void testBScore() {
Assert.assertEquals(0.06666666666666664, new GiniEntropy().score(fromCounts(Arrays.asList(8d, 4d)), Arrays.asList(fromCounts(Arrays.asList(7d, 3d)), fromCounts(Arrays.asList(1d, 1d)))), 0d);
}
@Test
public void testCScore() {
Assert.assertEquals(0.22916666666666666, new GiniEntropy().score(fromCounts(Arrays.asList(8d, 4d)), Arrays.asList(fromCounts(Arrays.asList(7d, 1d)), fromCounts(Arrays.asList(1d, 3d)))), 0d);
}
}
| 2,149 | 36.719298 | 198 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/GiniGain.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.stats.scoring;
import java.util.List;
public class GiniGain implements SplitScorer {
public <A> double score(Labels<A> parent, List<Labels<A>> children) {
return gain(parent, children, new GiniEntropy());
}
protected static <A> double weightedInverseEntropy(Labels<A> parent, List<Labels<A>> children, PartitionEntropy entropy) {
final double parentSum = parent.getWeightSum();
double childEntropySum = 0;
for(Labels<A> child : children) {
child.setLabelSet(parent.getLabelSet());
double childEntropy = entropy.inverseEntropy(child);
final double childSum = child.getWeightSum();
final double proportion = childSum / parentSum;
childEntropy *= proportion;
childEntropySum += childEntropy;
}
return childEntropySum;
}
protected static <A> double weightedEntropy(Labels<A> parent, List<Labels<A>> children, PartitionEntropy entropy) {
final double parentSum = parent.getWeightSum();
double childEntropySum = 0;
for(Labels<A> child : children) {
child.setLabelSet(parent.getLabelSet());
double childEntropy = entropy.entropy(child);
final double childSum = child.getWeightSum();
final double proportion = childSum / parentSum;
childEntropy *= proportion;
childEntropySum += childEntropy;
}
return childEntropySum;
}
protected static <A> double gain(Labels<A> parent, List<Labels<A>> children, PartitionEntropy entropy) {
final double parentEntropy = entropy.entropy(parent);
double childEntropySum = weightedEntropy(parent, children, entropy);
return parentEntropy - childEntropySum;
}
}
| 2,603 | 41 | 126 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/GiniGainTest.java | package tsml.classifiers.distance_based.utils.stats.scoring;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import static tsml.classifiers.distance_based.utils.stats.scoring.Labels.fromCounts;
public class GiniGainTest {
@Test
public void testImpure() {
Assert.assertEquals(0d, new GiniGain().score(fromCounts(Arrays.asList(6d, 6d)), Arrays.asList(fromCounts(Arrays.asList(3d, 3d)), fromCounts(Arrays.asList(3d, 3d)))), 0d);
}
@Test
public void testPure() {
Assert.assertEquals(0.5, new GiniGain().score(fromCounts(Arrays.asList(6d, 6d)), Arrays.asList(fromCounts(Arrays.asList(6d, 0d)), fromCounts(Arrays.asList(0d, 6d)))), 0d);
}
@Test
public void testA() {
Assert.assertEquals(0d, new GiniGain().score(fromCounts(Arrays.asList(8d, 4d)), Arrays.asList(fromCounts(Arrays.asList(4d, 2d)), fromCounts(Arrays.asList(4d, 2d)))), 0d);
}
@Test
public void testB() {
Assert.assertEquals(0.011111111111111072, new GiniGain().score(fromCounts(Arrays.asList(8d, 4d)), Arrays.asList(fromCounts(Arrays.asList(7d, 3d)), fromCounts(Arrays.asList(1d, 1d)))), 0d);
}
@Test
public void testC() {
Assert.assertEquals(0.1736111111111111, new GiniGain().score(fromCounts(Arrays.asList(8d, 4d)), Arrays.asList(fromCounts(Arrays.asList(7d, 1d)), fromCounts(Arrays.asList(1d, 3d)))), 0d);
}
}
| 1,418 | 37.351351 | 196 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/InfoEntropy.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.stats.scoring;
import utilities.Utilities;
public class InfoEntropy implements PartitionEntropy {
public <A> double entropy(Labels<A> labels) {
return labels.getDistribution().stream().mapToDouble(d -> d * Utilities.log(d, 2)).sum() * -1;
}
}
| 1,069 | 38.62963 | 102 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/InfoEntropyTest.java | package tsml.classifiers.distance_based.utils.stats.scoring;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import static tsml.classifiers.distance_based.utils.stats.scoring.Labels.fromCounts;
public class InfoEntropyTest {
@Test
public void testImpure() {
Assert.assertEquals(1d, new InfoEntropy().entropy(new Labels<>().setDistribution(Arrays.asList(0.5, 0.5))), 0d);
}
@Test
public void testPure() {
Assert.assertEquals(0.0, new InfoEntropy().entropy(new Labels<>().setDistribution(Arrays.asList(1d, 0d))), 0d);
}
@Test
public void testA() {
Assert.assertEquals(0.8904916402194913, new InfoEntropy().entropy(new Labels<>().setDistribution(Arrays.asList(9d/13, 4d/13))), 0d);
}
@Test
public void testB() {
Assert.assertEquals(0.8812908992306928, new InfoEntropy().entropy(new Labels<>().setDistribution(Arrays.asList(7d/10, 3d/10))), 0d);
}
@Test
public void testImpureScore() {
Assert.assertEquals(0d, new InfoEntropy().score(fromCounts(Arrays.asList(6d, 6d)), Arrays.asList(fromCounts(Arrays.asList(3d, 3d)), fromCounts(Arrays.asList(3d, 3d)))), 0d);
}
@Test
public void testPureScore() {
Assert.assertEquals(1d, new InfoEntropy().score(fromCounts(Arrays.asList(6d, 6d)), Arrays.asList(fromCounts(Arrays.asList(6d, 0d)), fromCounts(Arrays.asList(0d, 6d)))), 0d);
}
@Test
public void testAScore() {
Assert.assertEquals(0.08170416594551044, new InfoEntropy().score(fromCounts(Arrays.asList(8d, 4d)), Arrays.asList(fromCounts(Arrays.asList(4d, 2d)), fromCounts(Arrays.asList(4d, 2d)))), 0d);
}
@Test
public void testBScore() {
Assert.assertEquals(0.09892425064108933, new InfoEntropy().score(fromCounts(Arrays.asList(8d, 4d)), Arrays.asList(fromCounts(Arrays.asList(7d, 3d)), fromCounts(Arrays.asList(1d, 1d)))), 0d);
}
@Test
public void testCScore() {
Assert.assertEquals(0.36719766304722473, new InfoEntropy().score(fromCounts(Arrays.asList(8d, 4d)), Arrays.asList(fromCounts(Arrays.asList(7d, 1d)), fromCounts(Arrays.asList(1d, 3d)))), 0d);
}
}
| 2,168 | 37.052632 | 198 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/InfoGain.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.stats.scoring;
import java.util.List;
public class InfoGain implements SplitScorer {
@Override public <A> double score(final Labels<A> parent, final List<Labels<A>> children) {
return GiniGain.gain(parent, children, new InfoEntropy());
}
}
| 1,067 | 37.142857 | 95 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/Label.java | package tsml.classifiers.distance_based.utils.stats.scoring;
import java.io.Serializable;
import java.util.Objects;
import static tsml.classifiers.distance_based.utils.collections.checks.Checks.requireReal;
public class Label<A> implements Serializable {
private final A id;
private final double weight;
public Label(A id, double weight) {
this.weight = weight;
this.id = Objects.requireNonNull(id);
requireReal(weight);
}
public Label(A id) {
this(id, 1d);
}
public double getWeight() {
return weight;
}
public A getId() {
return id;
}
@Override public String toString() {
return id + ": " + weight;
}
}
| 725 | 20.352941 | 90 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/Labels.java | package tsml.classifiers.distance_based.utils.stats.scoring;
import tsml.classifiers.distance_based.utils.collections.lists.RepeatList;
import utilities.ArrayUtilities;
import java.io.Serializable;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static utilities.ArrayUtilities.normalise;
public class Labels<A> extends AbstractList<Label<A>> implements Serializable {
public Labels(final List<A> labels, final List<Double> weights) {
this();
assertEquals(labels.size(), weights.size());
for(int i = 0; i < labels.size(); i++) {
add(new Label<>(labels.get(i), weights.get(i)));
}
}
public Labels(final List<A> labels) {
this(labels, new RepeatList<>(1d, labels.size()));
}
public Labels() {
clear();
}
public Labels(Labels<A> labels) {
this();
addAll(labels);
}
private List<Label<A>> labels = new ArrayList<>();
// label set is a list of unique labels. This is required specifically for labels which are not represented, i.e. given the labels 0,0,1,1,2,2,5,5. The labels are 1,2,3 and 5. Note there is no label 4. However, there is a label 3 which is not represented at all, and appears to not be an option like label 4. This leads to incorrect entropy / scoring calculations as the number of possible partitions is incorrectly reduced. I.e. given labels 0,2 a gini score would give 0.5 for two classes: 0 and 2. If however, there is in fact 3 classes, 0, 1 and 2, the gini score will be different. Therefore this label set is designed to specify the available labels, some of which may not be present in the main labels list whatsoever.
private List<A> labelSet;
private TreeMap<A, Double> countsMap;
private List<Double> distribution;
private List<Double> countsList;
private Double weightSum;
@Override public String toString() {
return labels.toString();
}
@Override public Label<A> set(final int i, final Label<A> label) {
final Label<A> prev = labels.set(i, label);
countsMap.compute(label.getId(), (a, count) -> {
if(count == null) {
throw new IllegalStateException("expected a count for previous");
} else {
return count - prev.getWeight() + label.getWeight();
}
});
resetMetaData();
return prev;
}
@Override public void add(final int i, final Label<A> label) {
labels.add(i, label);
countsMap.compute(label.getId(), (a, count) -> {
if(count == null) {
labelSet.add(label.getId());
return label.getWeight();
} else {
return count + label.getWeight();
}
});
resetMetaData();
}
@Override public Label<A> remove(final int i) {
final Label<A> label = labels.remove(i);
countsMap.compute(label.getId(), (a, count) -> {
if(count == null) {
throw new IllegalStateException("expected a count for previous");
} else {
return count - label.getWeight();
}
});
resetMetaData();
return label;
}
@Override public int size() {
return labels.size();
}
@Override public void clear() {
labels = new ArrayList<>();
countsMap = new TreeMap<>();
labelSet = new ArrayList<>();
resetMetaData();
}
@Override public Label<A> get(final int i) {
return labels.get(i);
}
private void resetMetaData() {
setDistribution(null);
setWeightSum(null);
}
public Labels<A> setLabels(final List<A> labels) {
for(int i = 0; i < labels.size(); i++) {
final double weight;
if(i == size()) {
weight = 1d;
} else {
weight = get(i).getWeight();
}
set(i, new Label<>(get(i).getId(), weight));
}
return this;
}
public Labels<A> setWeights(final List<Double> weights) {
for(int i = 0; i < weights.size(); i++) {
set(i, new Label<>(get(i).getId(), weights.get(i)));
}
return this;
}
public Labels<A> setDistribution(final List<Double> distribution) {
this.distribution = distribution;
return this;
}
public List<A> getLabelSet() {
return Collections.unmodifiableList(labelSet);
}
public TreeMap<A, Double> getCountsMap() {
return countsMap;
}
public List<Double> getDistribution() {
if(distribution == null) {
distribution = normalise(getCountsMap().values());
}
return distribution;
}
public Map<A, Double> getDistributionMap() {
return new AbstractMap<A, Double>() {
@Override public Set<Entry<A, Double>> entrySet() {
return getCountsMap().entrySet();
}
@Override public Double get(final Object o) {
Double value = getCountsMap().get(o);
if(value != null) {
value /= getWeightSum();
}
return value;
}
};
}
public Labels<A> setLabelSet(final List<A> labelSet) {
this.labelSet = labelSet;
if(labelSet != null) {
for(A label : labelSet) {
countsMap.computeIfAbsent(label, x -> 0d);
}
final HashSet<A> set = new HashSet<>(labelSet);
for(A label : countsMap.keySet()) {
if(!set.contains(label)) {
throw new IllegalArgumentException("label set " + labelSet + " does not contain the label " + label);
}
}
}
return this;
}
public List<A> getLabels() {
return new AbstractList<A>() {
@Override public A get(final int i) {
return Labels.this.get(i).getId();
}
@Override public int size() {
return Labels.this.size();
}
};
}
public List<Double> getWeights() {
return new AbstractList<Double>() {
@Override public Double get(final int i) {
return Labels.this.get(i).getWeight();
}
@Override public int size() {
return Labels.this.size();
}
};
}
public List<Double> getCountsList() {
if(countsList == null) {
final Map<A, Double> countsMap = getCountsMap();
countsList = Collections.unmodifiableList(new ArrayList<>(countsMap.values()));
}
return countsList;
}
protected static Labels<Integer> fromCounts(List<Double> countsList) {
final Labels<Integer> labels = new Labels<>();
labels.setLabelSet(ArrayUtilities.sequence(countsList.size()));
TreeMap<Integer, Double> map = new TreeMap<>();
double sum = 0;
for(int i = 0; i < countsList.size(); i++) {
final Double count = countsList.get(i);
map.put(i, count);
sum += count;
}
labels.setCountsMap(map);
labels.setWeightSum(sum);
return labels;
}
public Labels<A> setCountsMap(final TreeMap<A, Double> countsMap) {
this.countsMap = Objects.requireNonNull(countsMap);
return this;
}
public double getWeightSum() {
if(weightSum == null) {
weightSum = stream().mapToDouble(Label::getWeight).sum();
}
return weightSum;
}
public Labels<A> setWeightSum(final Double weightSum) {
this.weightSum = weightSum;
return this;
}
}
| 7,763 | 30.950617 | 730 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/PartitionEntropy.java | package tsml.classifiers.distance_based.utils.stats.scoring;
import java.util.List;
import static tsml.classifiers.distance_based.utils.stats.scoring.GiniGain.weightedInverseEntropy;
public interface PartitionEntropy extends SplitScorer {
<A> double entropy(Labels<A> labels);
@Override default <A> double score(Labels<A> parent, List<Labels<A>> children) {
// invert the weighted entropy as entropy is inverse, i.e. larger values mean worse. Score is the other way around, larger values are better. Therefore multiply by -1 to invert the entropy into a score (though will be less than 0!)
return weightedInverseEntropy(parent, children, this);
// OR
// just negate the weighted sum of entropies. I.e. larger entropies would become small and small values greater, inverting the range as required
// return -1d * weightedEntropy(parent, children, this);
}
default <A> double inverseEntropy(Labels<A> labels) {
// the label set contains a single entry for each unique label. This is the worst distribution possible, i.e. uniform dist, over all available classes
// entropy is defined as lower values == better and vice versa
// inverse entropy inverts this to higher values == better, similar to a score
// to invert, we use the worst possible distribution of labels (the label set) to produce the worst entropy. Then subtract from that the actual entropy of all labels
return entropy(new Labels<>(labels.getLabelSet())) - entropy(labels);
}
}
| 1,573 | 53.275862 | 239 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/stats/scoring/SplitScorer.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.stats.scoring;
import java.io.Serializable;
import java.util.List;
public interface SplitScorer extends Serializable {
<A> double score(Labels<A> parent, List<Labels<A>> children);
}
| 1,007 | 35 | 76 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/strings/StrUtils.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.strings;
import tsml.classifiers.distance_based.utils.system.copy.CopierUtils;
import weka.core.OptionHandler;
import weka.core.Utils;
import java.io.File;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
public class StrUtils {
public static String joinPath(String... parts) {
return join("/", parts);
}
public static String toString(double[][] matrix) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for(double[] row : matrix) {
if(first) {
first = false;
} else {
builder.append(System.lineSeparator());
}
builder.append(Arrays.toString(row));
}
return builder.toString();
}
public static boolean isAlpha(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
public static boolean isDigit(char c) {
return (c >= '0' && c <= '9');
}
public static String[] extractAmountAndUnit(String str) {
str = str.trim();
StringBuilder amount = new StringBuilder();
StringBuilder unit = new StringBuilder();
char[] chars = str.toCharArray();
int i = 0;
boolean digitsEnded = false;
for(;i < chars.length; i++) {
char c = chars[i];
if(!Character.isDigit(c)) {
digitsEnded = true;
}
if(digitsEnded) {
unit.append(c);
} else {
amount.append(c);
}
}
return new String[] {amount.toString(), unit.toString()};
}
public static String depluralise(String str) {
if(str.endsWith("s")) {
str = str.substring(0, str.length() - 1);
}
return str;
}
public static String joinOptions(List<String> options) {
return Utils.joinOptions(options.toArray(new String[0]));
}
public static String join(String separator, String... parts) {
return join(separator, Arrays.asList(parts));
}
public static void forEachPair(String[] options, BiConsumer<String, String> function) {
if(options.length % 2 != 0) {
throw new IllegalArgumentException("options is not correct length, must be key-value pairs");
}
for(int i = 0; i < options.length; i += 2) {
String key = options[i];
String value = options[i + 1];
function.accept(key, value);
}
}
public static String join(String separator, double... values) {
String[] strings = new String[values.length];
for (int i = 0; i < values.length; i++) {
strings[i] = String.valueOf(values[i]);
}
return join(separator, strings);
}
public static HashMap<String, String> pairValuesToMap(String... pairValues) {
HashMap<String, String> map = new HashMap<>();
forEachPair(pairValues, map::put);
return map;
}
public static boolean equalPairs(String[] a, String[] b) {
HashMap<String, String> mapA = pairValuesToMap(a);
HashMap<String, String> mapB = pairValuesToMap(b);
for(Map.Entry<String, String> entry : mapA.entrySet()) {
String valueA = entry.getValue();
String keyA = entry.getKey();
String valueB = mapB.get(keyA);
if(!valueA.equals(valueB)) {
return false;
}
}
return true;
}
public static boolean isOption(String flag, String[] options) {
try {
flag = unflagify(flag);
int i = Utils.getOptionPos(flag, options);
if(i < 0 || i + 1 >= options.length) {
return false;
}
String option = options[i + 1];
return !isFlag(option);
} catch (Exception e) {
return false;
}
}
public static void updateOptions(OptionHandler optionHandler, String[] options) throws
Exception {
String[] current = optionHandler.getOptions();
String[] next = uniteOptions(options, current);
optionHandler.setOptions(next);
}
public static String[] uniteOptions(String[] next, String[] current) throws
Exception {
return uniteOptions(next, current, true);
}
public static String[] uniteOptions(String[] next, String[] current, boolean flagsFromCurrent) throws
Exception {
ArrayList<String> list = new ArrayList<>();
for(int i = 0; i < current.length; i++) {
String flag = current[i];
flag = unflagify(flag);
if(isOption(flag, current)) {
String nextOption = Utils.getOption(flag, next);
if(nextOption.length() > 0) {
addOption(flag, list, nextOption);
} else {
String currentOption = Utils.getOption(flag, current);
addOption(flag, list, currentOption);
}
i++;
} else {
if(Utils.getFlag(flag, next) || flagsFromCurrent) {
addFlag(flag, list);
} else {
// don't add the flag
}
}
}
return list.toArray(new String[0]);
}
public static <A> void setOption(String[] options, String flag, Consumer<A> setter) throws
Exception {
flag = unflagify(flag);
String option = Utils.getOption(flag, options);
while(option.length() != 0) {
A result = fromOptionValue(option);
setter.accept(result);
option = Utils.getOption(flag, options);
}
}
public static <A> A fromOptionValue(String optionsStr) throws Exception {
return (A) fromOptionValue(optionsStr, str -> str);
}
/**
* Given a string containing "{class name} {-flag} {value} ..." construct a new instance of the class given by "class name" and set the remaining options.
* NOTE: to represent strings, they must be enclosed in quotes.
* @param optionsStr
* @return
* @throws Exception
*/
public static <A> A fromOptionValue(String optionsStr, Function<String, A> parser) throws Exception {
if(optionsStr.equals("null")) {
return null;
}
// split into class and options
String[] parts = Utils.splitOptions(optionsStr);
if(parts.length == 0) {
throw new Exception("Invalid option: " + optionsStr);
}
if(parts.length == 1) {
// then this may be a primitive type or string
String str = parts[0];
// if string then the str will contain whitespace at the front
if(str.startsWith("\"") && str.endsWith("\"")) {
str = str.substring(1, str.length() - 1); // get rid of the char added during encoding
return parser.apply(str);
}
// if the first digit is a digit then dealing with a primitive number. Using the opposing case here, i.e. for it to be a non-primitive the first option is the canonical class name. These cannot begin with numbers or hyphens (for neg numbers) therefore we can assume it's a primitive number by this point
if(!Character.isAlphabetic(str.charAt(0)) || str.equals("true") || str.equals("false")) {
return parser.apply(str);
}
// otherwise proceed, the parts[0] string must be a class name and needs instantiation
}
// the class is always the first entry, options after that
String className = parts[0];
final Object result = CopierUtils.newInstanceFromClassName(className);
// if there are options then set them
if(parts.length > 1) {
// get rid of the class name from the options so it won't affect any sub options later on
parts[0] = "";
if(result instanceof OptionHandler) {
((OptionHandler) result).setOptions(parts);
} else {
throw new IllegalArgumentException("cannot set options on " + className);
}
}
return (A) result;
}
public static String toOptionValue(Object value, boolean withSubOptions) {
String str;
if(value == null) {
str = "null";
}
else if(value instanceof Integer ||
value instanceof Double ||
value instanceof Float ||
value instanceof Byte ||
value instanceof Short ||
value instanceof Long ||
value instanceof Boolean) {
str = String.valueOf(value);
} else if(value instanceof Character || value instanceof String) {
// add quotes to maintain whitespace (the delimited inside-most ones), delimiters to avoid parsing the inner quotes in first pass, and outer quotes to indicate dealing with a string type
str = "\"\\\"" + value + "\\\"\"";
} else {
Class<?> classValue;
if(value instanceof Class<?>) {
classValue = (Class<?>) value;
} else {
classValue = value.getClass();
}
str = classValue.getName();
if(value instanceof OptionHandler && withSubOptions) {
String options = Utils.joinOptions(((OptionHandler) value).getOptions());
if(!options.isEmpty()) {
str = str + " " + options;
}
}
}
return str;
}
public static String toOptionValue(Object value) {
return toOptionValue(value, true);
}
public static void addOption(final String flag, final Collection<String> options, final Object value) {
addFlag(flag, options);
String str = toOptionValue(value);
options.add(str);
}
public static <A> void addOption(final String flag, final Collection<String> options, final Collection<A> values) {
for(A value : values) {
addOption(flag, options, value);
}
}
public static String flagify(String flag) {
if(flag.charAt(0) != '-') {
flag = "-" + flag;
}
return flag;
}
public static String unflagify(String flag) {
if(flag.charAt(0) == '-') {
flag = flag.substring(1);
}
return flag;
}
public static void addFlag(String flag, final Collection<String> options) {
flag = flagify(flag);
options.add(flag);
}
public static void addFlag(String flag, final Collection<String> options, boolean flagEnabled) {
if(flagEnabled) {
addFlag(flag, options);
}
}
public static String asDirPath(String path) {
int len = File.separator.length();
String subStr = path.substring(path.length() - len);
if(!subStr.equals(File.separator)) {
return path + File.separator;
}
return path;
}
public static String join(final String separator, final List<String> parts) {
if(parts.isEmpty()) {
return "";
}
StringBuilder list = new StringBuilder();
for(int i = 0; i < parts.size() - 1; i++){
list.append(parts.get(i));
list.append(separator);
}
list.append(parts.get(parts.size() - 1));
return list.toString();
}
public static boolean isFlag(String str) {
return str.length() >= 2 && str.charAt(0) == '-' && Character.isLetter(str.charAt(1));
}
public static void setOptions(OptionHandler optionHandler, final String options) throws
Exception {
optionHandler.setOptions(Utils.splitOptions(options));
}
public static void setOptions(OptionHandler optionHandler, String options, String delimiter) throws
Exception {
String[] optionsArray = options.split(delimiter);
optionHandler.setOptions(optionsArray);
}
public static <A> A parse(String str, Class<A> clazz) {
final Object output;
if(clazz.equals(Integer.class)) {
output = Integer.parseInt(str);
} else if(clazz.equals(Double.class)) {
output = Double.parseDouble(str);
} else if(clazz.equals(Long.class)) {
output = Long.parseLong(str);
} else if(clazz.equals(Float.class)) {
output = Float.parseFloat(str);
} else if(clazz.equals(String.class)) {
output = str;
} else if(clazz.equals(Byte.class)) {
output = Byte.parseByte(str);
} else if(clazz.equals(Boolean.class)) {
output = Boolean.parseBoolean(str);
} else if(clazz.equals(Short.class)) {
output = Short.parseShort(str);
} else {
try {
output = fromOptionValue(str);
} catch(Exception e) {
throw new IllegalStateException(e);
}
}
if(clazz.isInstance(output)) {
return (A) output;
} else {
throw new ClassCastException("cannot cast " + output.getClass() + " to " + clazz);
}
}
}
| 14,241 | 35.424552 | 315 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/strings/StrUtilsTest.java | package tsml.classifiers.distance_based.utils.strings;
import org.junit.Assert;
import org.junit.Test;
import tsml.classifiers.distance_based.distances.lcss.LCSSDistance;
import tsml.classifiers.distance_based.distances.transformed.BaseTransformDistanceMeasure;
import tsml.classifiers.distance_based.distances.transformed.TransformDistanceMeasure;
import tsml.classifiers.distance_based.utils.collections.params.ParamSet;
import tsml.transformers.Derivative;
import weka.classifiers.functions.SMO;
import weka.classifiers.functions.supportVector.RBFKernel;
import weka.core.Utils;
public class StrUtilsTest {
@Test
public void testSMOSetOptions() throws Exception {
SMO smo = new SMO();
ParamSet paramSet = new ParamSet();
paramSet.add("-C", 5.5);
ParamSet kernelParams = new ParamSet();
kernelParams.add("-G", 0.5);
paramSet.add("-K", new RBFKernel(), kernelParams);
String[] options = paramSet.getOptions();
smo.setOptions(options);
Assert.assertEquals(5.5, smo.getC(), 0.0);
Assert.assertTrue(smo.getKernel() instanceof RBFKernel);
Assert.assertEquals(0.5, ((RBFKernel) smo.getKernel()).getGamma(), 0.0);
}
@Test
public void testOptionsFormat() throws Exception {
String[] strs = Utils.splitOptions("a \"b -c 5 -d 6\"");
Assert.assertEquals("a", strs[0]);
Assert.assertEquals("b -c 5 -d 6", strs[1]);
Assert.assertEquals(2, strs.length);
strs = Utils.splitOptions(strs[1]);
Assert.assertEquals("b", strs[0]);
Assert.assertEquals("-c", strs[1]);
Assert.assertEquals("5", strs[2]);
Assert.assertEquals("-d", strs[3]);
Assert.assertEquals("6", strs[4]);
Assert.assertEquals(5, strs.length);
}
@Test
public void testToAndFromOptions() throws Exception {
LCSSDistance lcss = new LCSSDistance();
final TransformDistanceMeasure tdm = new BaseTransformDistanceMeasure("", new Derivative(), lcss);
lcss.setEpsilon(6);
lcss.setWindow(0.7);
String[] strs = tdm.getOptions();
Assert.assertEquals("-d", strs[2]);
Assert.assertEquals("tsml.classifiers.distance_based.distances.lcss.LCSSDistance -w 0.7 -e 6.0", strs[3]);
Assert.assertEquals("-t", strs[0]);
Assert.assertEquals("tsml.transformers.Derivative", strs[1]);
Assert.assertEquals(4, strs.length);
String[] substrs = Utils.splitOptions(strs[3]);
Assert.assertEquals("tsml.classifiers.distance_based.distances.lcss.LCSSDistance", substrs[0]);
Assert.assertEquals("-e", substrs[3]);
Assert.assertEquals("6.0", substrs[4]);
Assert.assertEquals("-w", substrs[1]);
Assert.assertEquals("0.7", substrs[2]);
Assert.assertEquals(5, substrs.length);
lcss.setEpsilon(-1);
lcss.setWindow(-1);
tdm.setOptions(strs);
lcss = (LCSSDistance) tdm.getDistanceMeasure();
Assert.assertEquals(6, lcss.getEpsilon(), 0.0d);
Assert.assertEquals(0.7, lcss.getWindow(), 0d);
final ParamSet paramSet = new ParamSet();
paramSet.setOptions(strs);
lcss.setEpsilon(-1);
lcss.setWindow(1);
tdm.setParams(paramSet);
lcss = (LCSSDistance) tdm.getDistanceMeasure();
Assert.assertEquals(6, lcss.getEpsilon(), 0.0d);
Assert.assertEquals(0.7, lcss.getWindow(), 0d);
}
@Test
public void testToOptionsValueNull() {
Assert.assertEquals("null", StrUtils.toOptionValue(null));
}
@Test
public void testToOptionsValueDouble() {
Assert.assertEquals("5.786", StrUtils.toOptionValue(5.786));
}
@Test
public void testToOptionsValueInt() {
Assert.assertEquals("5", StrUtils.toOptionValue(5));
}
@Test
public void testToOptionsValueString() {
Assert.assertEquals("\"\\\"hello\\\"\"", StrUtils.toOptionValue("hello"));
}
@Test
public void testToOptionsValueObject() {
Assert.assertEquals("tsml.classifiers.distance_based.distances.lcss.LCSSDistance -w 1.0 -e 0.01", StrUtils.toOptionValue(new LCSSDistance()));
}
@Test
public void testToOptionsValueStringWithWhiteSpace() throws Exception {
Assert.assertEquals("\"\\\"hello goodbye\\\"\"", StrUtils.toOptionValue("hello goodbye"));
}
@Test
public void testFromOptionsValueNull() throws Exception {
Assert.assertNull(StrUtils.fromOptionValue("null", null));
}
@Test
public void testFromOptionsValueDouble() throws Exception {
Assert.assertEquals(new Double(5.786), StrUtils.fromOptionValue("5.786", Double::parseDouble));
}
@Test
public void testFromOptionsValueDoubleNegative() throws Exception {
Assert.assertEquals(new Double(-5.786), StrUtils.fromOptionValue("-5.786", Double::parseDouble));
}
@Test
public void testFromOptionsValueDoubleNegativeMissingLeadingZero() throws Exception {
Assert.assertEquals(new Double(-.786), StrUtils.fromOptionValue("-.786", Double::parseDouble));
}
@Test
public void testFromOptionsValueDoubleMissingLeadingZero() throws Exception {
Assert.assertEquals(new Double(.786), StrUtils.fromOptionValue(".786", Double::parseDouble));
}
@Test
public void testFromOptionsValueInt() throws Exception {
Assert.assertEquals(new Integer(5), StrUtils.fromOptionValue("5", Integer::parseInt));
}
@Test
public void testFromOptionsValueBooleanTrue() throws Exception {
Assert.assertEquals(Boolean.TRUE, StrUtils.fromOptionValue("true", Boolean::parseBoolean));
}
@Test
public void testFromOptionsValueBooleanFalse() throws Exception {
Assert.assertEquals(Boolean.FALSE, StrUtils.fromOptionValue("false", Boolean::parseBoolean));
}
@Test
public void testFromOptionsValueString() throws Exception {
Assert.assertEquals(StrUtils.fromOptionValue("\"\\\"hello\\\"\""), "hello");
}
@Test
public void testFromOptionsValueStringWithWhiteSpace() throws Exception {
Assert.assertEquals(StrUtils.fromOptionValue("\"\\\"hello goodbye\\\"\""), "hello goodbye");
}
@Test
public void testFromOptionsValueObject() throws Exception {
Object obj = StrUtils.fromOptionValue("tsml.classifiers.distance_based.distances.lcss.LCSSDistance -e 0.01 -ws -1");
final LCSSDistance lcss = new LCSSDistance();
// should be entirely different instances
Assert.assertNotEquals(lcss, obj);
// but be the same parameter-wise
Assert.assertEquals(lcss.toString(), obj.toString());
}
@Test(expected = Exception.class)
public void testFromOptionsValueEmptyString() throws Exception {
Assert.assertEquals("", StrUtils.fromOptionValue(""));
}
@Test
public void testIsFlagEmpty() throws Exception {
Assert.assertFalse(StrUtils.isFlag(""));
}
@Test
public void testIsFlagSingleLetter() throws Exception {
Assert.assertTrue(StrUtils.isFlag("-b"));
}
@Test
public void testIsFlagMultiLetter() throws Exception {
Assert.assertTrue(StrUtils.isFlag("-bbbbbbb"));
}
@Test
public void testIsFlagNoMinusSingleLetter() throws Exception {
Assert.assertFalse(StrUtils.isFlag("b"));
}
@Test
public void testIsFlagNoMinusMultiLetter() throws Exception {
Assert.assertFalse(StrUtils.isFlag("bbbbbbb"));
}
@Test
public void testIsOptionNoMinus() throws Exception {
Assert.assertFalse(StrUtils.isOption("b", new String[] {"b", "c"}));
}
@Test
public void testIsOptionFalse() throws Exception {
Assert.assertFalse(StrUtils.isOption("-b", new String[] {"-b", "-c"}));
}
@Test
public void testIsOptionTrue() throws Exception {
Assert.assertTrue(StrUtils.isOption("-b", new String[] {"-b", "c"}));
}
@Test
public void testIsOptionEmpty() throws Exception {
Assert.assertFalse(StrUtils.isOption("", new String[] {"", "-c", "5"}));
}
}
| 8,110 | 35.701357 | 150 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/SysUtils.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.system;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import tsml.classifiers.distance_based.utils.strings.StrUtils;
/**
* Purpose: find details about the system we're running on.
*
* Contributors: goastler
*/
public class SysUtils {
public static String hostName() {
if(!getOS().equals(OS.WINDOWS)) {
try {
return StrUtils.join("\n", exec("hostname"));
} catch(IOException | InterruptedException ignored) {
}
}
return "unknown"; // todo windows version
}
public static List<String> exec(String command) throws
IOException,
InterruptedException {
Process process = Runtime.getRuntime().exec(command);
List<String> result;
process.waitFor();
if(process.exitValue() == 0) {
result = IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new IllegalStateException(StrUtils.join("\n", IOUtils.readLines(process.getErrorStream(),
StandardCharsets.UTF_8)));
}
process.destroyForcibly();
return result;
}
public static String findCpuInfo() {
try {
OS os = getOS();
String cpuInfo;
switch(os) {
case MAC:
case LINUX:
case SOLARIS:
List<String> output = exec("cat /proc/cpuinfo");
cpuInfo = "linux";
for(String line : output) {
if(line.contains("model name")) {
cpuInfo = line.split(":")[1].trim();
break;
}
}
break;
case WINDOWS:
default:
cpuInfo = "windows"; // todo windows version
break;
}
return cpuInfo;
} catch(IOException | InterruptedException e) {
return "unknown";
}
}
public static String getOsName() {
return getOS().name().toLowerCase();
}
public enum OS {
WINDOWS, LINUX, MAC, SOLARIS
}
private static OS os;
public static OS getOS() {
if (os == null) {
String operSys = System.getProperty("os.name").toLowerCase();
if (operSys.contains("win")) {
os = OS.WINDOWS;
} else if (operSys.contains("nix") || operSys.contains("nux")
|| operSys.contains("aix")) {
os = OS.LINUX;
} else if (operSys.contains("mac")) {
os = OS.MAC;
} else if (operSys.contains("sunos")) {
os = OS.SOLARIS;
}
}
return os;
}
public static void main(String[] args) {
System.out.println(findCpuInfo());
}
}
| 3,962 | 32.025 | 108 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/copy/Copier.java | package tsml.classifiers.distance_based.utils.system.copy;
import java.io.Serializable;
/**
* Purpose: shallow and deep copy various fields from object to object using reflection. You can filter the fields to
* ignore final fields / transient fields, etc, it's all flexible. Classes can implement this interface to provide
* copy functionality but these functions can also be called statically and work in the same way. The benefit of the
* former is being able to override the copy functions using inheritance, although that might not be in high demand.
* Either way it works.
*
* Contributors: goastler
*/
public interface Copier extends Serializable {
/**
* shallow copy an object, creating a new instance
* @return
* @throws Exception
*/
default <A> A shallowCopy() {
return (A) CopierUtils.shallowCopy(this);
}
default void shallowCopyTo(Object dest) {
CopierUtils.shallowCopy(this, dest);
}
default void shallowCopyTo(Object dest, Iterable<String> fields) {
CopierUtils.shallowCopy(this, dest, fields);
}
default void shallowCopyTo(Object dest, String... fields) {
CopierUtils.shallowCopy(this, dest, fields);
}
default void shallowCopyFrom(Object src) {
CopierUtils.shallowCopy(src, this);
}
default void shallowCopyFrom(Object src, Iterable<String> fields) {
CopierUtils.shallowCopy(src, this, fields);
}
default void shallowCopyFrom(Object src, String... fields) {
CopierUtils.shallowCopy(src, this, fields);
}
default <A> A deepCopy() {
return (A) CopierUtils.deepCopy(this);
}
default void deepCopyFrom(Object src) {
CopierUtils.deepCopy(src, this);
}
default void deepCopyFrom(Object src, Iterable<String> fields) {
CopierUtils.deepCopy(src, this, fields);
}
default void deepCopyFrom(Object src, String... fields) {
CopierUtils.deepCopy(src, this, fields);
}
default void deepCopyTo(Object dest) {
CopierUtils.deepCopy(this, dest);
}
default void deepCopyTo(Object dest, Iterable<String> fields) {
CopierUtils.deepCopy(this, dest, fields);
}
default void deepCopyTo(Object dest, String... fields) {
CopierUtils.deepCopy(this, dest, fields);
}
}
| 2,335 | 28.948718 | 117 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/copy/CopierTest.java | package tsml.classifiers.distance_based.utils.system.copy;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import static org.junit.Assert.*;
public class CopierTest {
private static class Dummy implements Serializable, Copier {
public int[] a = {3};
public String[] b = {"hello"};
public double p = 1.6;
}
private static class BigDummy extends Dummy {
public Long[] c = {-1L};
}
private static class NoDeepCopyDummy {
public int[] a = {4};
public String[] b = {"goodbye"};
}
private static class AdvDummy {
public int[] a = {99};
public String[] b = {":)"};
public double p = 4.4;
}
private static class TransientDummy implements Serializable {
public transient int[] c;
public TransientDummy() {
c = new int[]{11}; // this should be invoked when deep copying
}
}
private Dummy dummy;
@Before
public void before() {
dummy = new Dummy();
}
@Test
public void testDeepCopyTransient() {
final TransientDummy dummy = new TransientDummy();
dummy.c[0] = 15;
final TransientDummy copy = CopierUtils.deepCopy(dummy);
assertNotSame(copy, dummy);
assertNotSame(copy.c, dummy.c);
assertEquals(11, copy.c[0]);
}
@Test
public void testShallowCopyString() {
String a = "hello";
String b = CopierUtils.shallowCopy(a);
assertEquals(a, b);
assertNotSame(a, b);
}
@Test
public void testShallowCopy() {
final Dummy copy = (Dummy) dummy.shallowCopy();
assertSame(dummy.a, copy.a);
assertSame(dummy.b, copy.b);
assertNotSame(copy, dummy);
}
@Test
public void testDeepCopy() {
final Dummy copy = (Dummy) dummy.deepCopy();
assertNotSame(dummy.a, copy.a);
assertArrayEquals(dummy.a, copy.a);
assertNotSame(dummy.b, copy.b);
assertArrayEquals(dummy.b, copy.b);
assertNotSame(copy, dummy);
}
@Test
public void testInheritanceDeepCopy() {
final BigDummy copy = new BigDummy();
CopierUtils.deepCopy(dummy, copy);
assertNotSame(dummy.a, copy.a);
assertArrayEquals(dummy.a, copy.a);
assertNotSame(dummy.b, copy.b);
assertArrayEquals(dummy.b, copy.b);
assertNotSame(copy, dummy);
assertEquals(copy.c[0], new Long(-1L));
}
@Test
public void testInheritanceShallowCopy() {
final BigDummy copy = new BigDummy();
CopierUtils.shallowCopy(dummy, copy);
assertSame(dummy.a, copy.a);
assertArrayEquals(dummy.a, copy.a);
assertSame(dummy.b, copy.b);
assertArrayEquals(dummy.b, copy.b);
assertNotSame(copy, dummy);
assertEquals(copy.c[0], new Long(-1L));
}
@Test
public void testPartialDeepCopy() throws IOException {
final Dummy copy = new BigDummy();
copy.a[0] = 5;
CopierUtils.deepCopy(dummy, copy, "b");
assertNotSame(dummy.a, copy.a);
assertNotSame(dummy.b, copy.b);
assertArrayEquals(dummy.b, copy.b);
assertNotSame(copy, dummy);
}
@Test
public void testCopyByFieldNames() {
final AdvDummy copy = new AdvDummy();
CopierUtils.deepCopy(dummy, copy);
assertNotSame(dummy.a, copy.a);
assertArrayEquals(dummy.a, copy.a);
assertNotSame(dummy.b, copy.b);
assertArrayEquals(dummy.b, copy.b);
assertNotSame(copy, dummy);
}
@Test
public void testPartialShallowCopy()
throws InstantiationException, ClassNotFoundException, InvocationTargetException, IOException {
final Dummy copy = new BigDummy();
copy.a[0] = 5;
CopierUtils.shallowCopy(dummy, copy, "b");
assertNotSame(dummy.a, copy.a);
assertSame(dummy.b, copy.b);
assertArrayEquals(dummy.b, copy.b);
assertNotSame(copy, dummy);
}
@Test(expected = IllegalStateException.class)
public void testDeepCopyNoSerialisable() {
final NoDeepCopyDummy test = new NoDeepCopyDummy();
test.a[0] = 5;
CopierUtils.deepCopy(test);
}
}
| 4,340 | 27.748344 | 107 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/copy/CopierUtils.java | package tsml.classifiers.distance_based.utils.system.copy;
import java.io.*;
import java.lang.annotation.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.Collections.addAll;
public class CopierUtils {
/**
* disable copy annotation. Put this above any field you *DO NOT* want to be copied. That field will be ignored
* by default during copying, however this can be overriden.
*/
@Retention(RetentionPolicy.RUNTIME) // accessible at runtime
@Documented
@Target(ElementType.FIELD) // only apply to fields
@interface DisableCopy {
String value() default "";
}
// some default predicates for field types, these are used by default to avoid copying final / static fields and
// avoid transient fields. Transient fields are usually instance specific ties to tmp resources, hence why they cannot be saved to disk. As they're instance specific they are left out of the copying procedure.
public static final Predicate<Field> TRANSIENT = field -> Modifier.isTransient(field.getModifiers());
// avoid static fields (as these are init'd / managed outside of the instance and therefore should not be included in copying
public static Predicate<Field> STATIC = field -> Modifier.isStatic(field.getModifiers());
public static Predicate<Field> FINAL = field -> Modifier.isFinal(field.getModifiers());
// custom annotation to disable copy (I.e. mark a field with @DisableCopy) to remove it from the default field list when copying
// avoid fields annotated with @DisableCopy
public static Predicate<Field> DISABLE_COPY = field -> field.getAnnotation(DisableCopy.class) != null;
public static void shallowCopy(Object src, Object dest) {
CopierUtils.shallowCopy(src, dest, findDefaultShallowCopyFieldNames(src));
}
public static void deepCopy(Object src, Object dest) {
deepCopy(src, dest, findDefaultDeepCopyFieldNames(src));
}
public static List<Field> findDefaultShallowCopyFields(Object src) {
final List<Field> fields = findFields(src);
// do not deep copy static, transient or disable_copy fields
fields.removeIf(STATIC.or(TRANSIENT).or(DISABLE_COPY));
return fields;
}
public static List<String> findDefaultShallowCopyFieldNames(Object src) {
return findDefaultShallowCopyFields(src).stream().map(Field::getName).collect(Collectors.toList());
}
public static List<Field> findDefaultDeepCopyFields(Object src) {
final List<Field> fields = findFields(src);
// do not deep copy static, transient or disable_copy fields
fields.removeIf(STATIC.or(TRANSIENT).or(DISABLE_COPY));
return fields;
}
public static List<String> findDefaultDeepCopyFieldNames(Object src) {
return findDefaultDeepCopyFields(src).stream().map(Field::getName).collect(Collectors.toList());
}
public static void shallowCopy(Object src, Object dest, Iterable<String> fields) {
if(src == null || dest == null) return;
copyFieldValues(src, dest, false, fields);
}
public static void deepCopy(Object src, Object dest, Iterable<String> fields) {
if(src == null || dest == null) return;
copyFieldValues(src, dest, true, fields);
}
public static void deepCopy(Object src, Object dest, String... fields) {
if(src == null || dest == null) return;
deepCopy(src, dest, Arrays.asList(fields));
}
public static void shallowCopy(Object src, Object dest, String... fields) {
if(src == null || dest == null) return;
shallowCopy(src, dest, Arrays.asList(fields));
}
/**
* copy several fields across to another object
*/
private static void copyFieldValues(Object src, Object dest, boolean deep, Iterable<String> fields) {
for(String field : fields) {
copyFieldValue(src, dest, deep, field);
}
}
public static void deepCopyFieldValues(Object src, Object dest, Iterable<String> fields) {
copyFieldValues(src, dest, true, fields);
}
public static void shallowCopyFieldValues(Object src, Object dest, Iterable<String> fields) {
copyFieldValues(src, dest, false, fields);
}
public static void shallowCopyFieldValues(Object src, Object dest, String... fields) {
shallowCopyFieldValues(src, dest, Arrays.asList(fields));
}
public static void deepCopyFieldValues(Object src, Object dest, String... fields) {
deepCopyFieldValues(src, dest, Arrays.asList(fields));
}
/**
* copy a field value from source to destination, ignoring accessibility protocol
* @param src
* @param fields
* @param dest
* @param deep
* @return
* @throws Exception
*/
private static void copyFieldValue(Object src, Object dest, boolean deep, String... fields) {
for(String field : fields) {
Object value = getFieldValue(src, field);
value = copy(value, deep);
setFieldValue(dest, field, value);
}
}
/**
* set field value ignoring accessibility protocol
* @param dest
* @param field
* @param value
* @return
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public static void setFieldValue(Object dest, Field field, Object value) {
boolean accessible = field.isAccessible();
field.setAccessible(true);
try {
field.set(dest, value);
} catch(IllegalAccessException e) {
throw new IllegalStateException(e);
}
field.setAccessible(accessible);
}
public static void setFieldValue(Object dest, String name, Object value) {
setFieldValue(dest, getField(dest, name), value);
}
public static Object getFieldValue(Object src, Field field) {
boolean accessible = field.isAccessible();
field.setAccessible(true);
try {
final Object value = field.get(src);
field.setAccessible(accessible);
return value;
} catch(IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
public static Object getFieldValue(Object src, String name) {
return getFieldValue(src, getField(src, name));
}
public static byte[] serialise(Object obj) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
return baos.toByteArray();
} catch(IOException e) {
throw new IllegalStateException(e);
}
}
public static <A> A deserialise(byte[] bytes) {
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return (A) ois.readObject();
} catch(IOException | ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
private static <A> A copy(A object, boolean deep) {
if(deep) {
return deepCopy(object);
} else {
return object;
}
}
public static <A> A shallowCopy(A src) {
if(src == null) return null;
return shallowCopyViaDefaultConstructor(src);
}
public static <A> A newInstanceFromClassName(String className) {
try {
return newInstance(Class.forName(className));
} catch(ClassCastException | ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
public static <A> A newInstance(A object) {
if(object == null) {
return null;
}
return newInstance(object.getClass());
}
public static <A> A newInstance(Class<?> clazz) {
try {
// get the default constructor
final Constructor<?> noArgsConstructor = clazz.getDeclaredConstructor();
// find out whether it's accessible from here (no matter if it's not)
final boolean origAccessible = noArgsConstructor.isAccessible();
// force it to be accessible if not already
noArgsConstructor.setAccessible(true);
// use the constructor to build a default instance
final Object inst = noArgsConstructor.newInstance();
// set the constructor's accessibility back to what it was
noArgsConstructor.setAccessible(origAccessible);
return (A) inst;
} catch(ClassCastException | InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
private static <A> A shallowCopyViaDefaultConstructor(A src) {
if(src == null) return null;
A dest = newInstance(src);
// copy over the fields from the current object to the new instance
shallowCopy(src, dest);
return dest;
}
public static <A> A deepCopy(A src) {
if(src == null) return null;
// quick check for boxed primitives / immutable objects, as these don't need copying
if(src instanceof String
|| src instanceof Double
|| src instanceof Integer
|| src instanceof Long
|| src instanceof Float
|| src instanceof Byte
|| src instanceof Boolean
|| src instanceof Character
|| src instanceof Short
) {
return src;
}
// deep copy the source
src = deserialise(serialise(src));
try {
// then attempt to invoke the default constructor to make a new instance and copy the deeply copied src into the new instance
// this is necessary so a new instance is created and the default constructor is run, initialising any transient variables not copied during the serialisation copy
return shallowCopyViaDefaultConstructor(src);
} catch(IllegalStateException e) {
// if there's no default constructor then use the deep copy already made. This means the default constructor will not be called and transient field may be left null. Users will have to account for this when using transient fields
return src;
}
}
public static List<Field> findFields(Object src) {
return findFields(src.getClass());
}
public static List<Field> findFields(Class<?> clazz) {
final Set<Field> fields = new HashSet<>();
do {
addAll(fields, clazz.getDeclaredFields());
clazz = clazz.getSuperclass();
} while(clazz != null);
return new ArrayList<>(fields);
}
public static Field getField(Object obj, String name) {
return getField(obj.getClass(), name);
}
public static Field getField(Class<?> clazz, String name) {
Field field = null;
IllegalStateException ex = null;
while(clazz != null && field == null) {
try {
field = clazz.getDeclaredField(name);
} catch(NoSuchFieldException e) {
ex = new IllegalStateException(e);
}
clazz = clazz.getSuperclass();
}
if(field == null) {
throw ex;
}
return field;
}
}
| 11,682 | 37.055375 | 241 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/logging/LogUtils.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.system.logging;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.logging.*;
import tsml.classifiers.distance_based.utils.experiment.TimeSpan;
/**
* Purpose: build loggers / handy logging functions
* <p>
* Contributors: goastler
*/
public class LogUtils {
private LogUtils() {
}
public static final Logger DEFAULT_LOG = getLogger("global");
public static Logger updateLogLevel(Object src, Logger log, Level level) {
// if setting a log level then this object needs its own logger instance to differentiate the logging levels.
// i.e. everything by default is pointed at DEFAULT_LOG. If the level of the DEFAULT_LOG were to be changed it would affect every object's logging. Instead, a specific logger is required to house the log level for this specific object.
if(DEFAULT_LOG.equals(log)) {
// build the logger for this object. Only do this once if still using the DEFAULT_LOGGER. Once a bespoke logger has been created the log level can be mutated freely on that with no problems.
log = LogUtils.getLogger(src);
}
log.setLevel(level);
return log;
}
public static Logger getLogger(Object src) {
final String name;
if(src instanceof Class) {
name = ((Class<?>) src).getCanonicalName();
} else if(src instanceof String) {
name = (String) src;
} else {
name = src.getClass().getCanonicalName();
}
Logger logger = Logger.getLogger(name);
if(logger.getLevel() == null) {
logger.setLevel(Level.SEVERE);
}
Handler[] handlers = logger.getHandlers();
for(Handler handler : handlers) {
logger.removeHandler(handler);
}
logger.addHandler(buildStdOutStreamHandler(new CustomLogFormat()));
logger.addHandler(buildStdErrStreamHandler(new CustomLogFormat()));
logger.setUseParentHandlers(false);
return logger;
}
public static class CustomLogFormat extends Formatter {
@Override
public String format(final LogRecord logRecord) {
String separator = " | ";
// return logRecord.getSequenceNumber() + separator +
// logRecord.getLevel() + separator +
// logRecord.getLoggerName() + separator +
// logRecord.getSourceClassName() + separator +
// logRecord.getSourceMethodName() + System.lineSeparator() +
// logRecord.getMessage() + System.lineSeparator();
return LocalDateTime.now().toString().replace("T", " ") + separator + logRecord.getMessage() + System.lineSeparator();
}
}
public static class CustomStreamHandler extends StreamHandler {
public CustomStreamHandler(final OutputStream out, final Formatter formatter) {
super(out, formatter);
}
@Override
public synchronized void publish(LogRecord record) {
super.publish(record);
flush();
}
@Override
public synchronized void close() throws SecurityException {
flush();
}
}
public static StreamHandler buildStdErrStreamHandler(Formatter formatter) {
StreamHandler soh = new CustomStreamHandler(System.err, formatter);
soh.setLevel(Level.SEVERE); //Default StdErr Setting
return soh;
}
public static StreamHandler buildStdOutStreamHandler(Formatter formatter) {
StreamHandler soh = new CustomStreamHandler(System.out, formatter);
soh.setLevel(Level.ALL); //Default StdOut Setting
return soh;
}
public static long logTimeContract(long timeNanos, long limitNanos, Logger logger, String name, long lastCallTimeStamp) {
if(System.nanoTime() - lastCallTimeStamp > TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS)) {
logTimeContract(timeNanos, limitNanos, logger, name);
return System.nanoTime();
} else {
return lastCallTimeStamp;
}
}
public static void logTimeContract(long timeNanos, long limitNanos, Logger logger, String name) {
if(limitNanos > 0) {
logger.info(() -> {
TimeSpan limit = new TimeSpan(limitNanos);
TimeSpan time = new TimeSpan(timeNanos);
TimeSpan diff = new TimeSpan(limitNanos - timeNanos);
return time.asTimeStamp() + " elapsed of " + limit.asTimeStamp() +
" " + name + " "
+ "time "
+ "limit, " + diff.asTimeStamp() + " remaining";
});
}
}
}
| 5,674 | 38.409722 | 243 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/logging/Loggable.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.system.logging;
import akka.event.Logging;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Handle different log levels for providing anywhere from none to verbose output via logging.
*
* Contributors: goastler
*/
public interface Loggable {
default Level getLogLevel() {
return getLogger().getLevel();
}
default void setLogLevel(Level level) {
getLogger().setLevel(level);
}
default void setLogLevel(String level) {
setLogLevel(Level.parse(level.toUpperCase()));
}
Logger getLogger();
/**
* Manually specify the logger to log to. This is helpful to share loggers between classes / insts.
* @param logger
*/
void setLogger(Logger logger);
}
| 1,595 | 29.692308 | 103 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/memory/MemoryAmount.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.system.memory;
import tsml.classifiers.distance_based.utils.strings.StrUtils;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class MemoryAmount implements Comparable<MemoryAmount> {
private long amount;
private MemoryUnit unit;
public MemoryAmount() {
this(0, MemoryUnit.BYTES);
}
public MemoryAmount(long amount, MemoryUnit unit) {
setAmount(amount);
setUnit(unit);
}
public MemoryAmount(String str) {
this(StrUtils.extractAmountAndUnit(str));
}
private MemoryAmount(String[] parts) {
this(Long.parseLong(parts[0].trim()), MemoryUnit.valueOf(parts[1].trim()));
}
@Override
public String toString() {
return getAmount() + " " + getUnit();
}
public long getAmount() {
return amount;
}
public MemoryAmount setAmount(final long amount) {
this.amount = amount;
return this;
}
public MemoryUnit getUnit() {
return unit;
}
public MemoryAmount setUnit(final MemoryUnit unit) {
this.unit = unit;
return this;
}
public MemoryAmount convert(MemoryUnit unit) {
return new MemoryAmount(unit.convert(getAmount(), getUnit()), unit);
}
@Override
public int compareTo(final MemoryAmount other) {
MemoryAmount otherNanos = other.convert(MemoryUnit.BYTES);
MemoryAmount nanos = convert(MemoryUnit.BYTES);
return (int) (otherNanos.getAmount() - nanos.getAmount());
}
}
| 2,376 | 27.638554 | 83 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/memory/MemoryUnit.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.system.memory;
import org.junit.Assert;
import org.junit.Test;
import java.util.Locale;
import java.util.Objects;
public class MemoryUnit implements Comparable<MemoryUnit> {
public static final MemoryUnit BYTES = new MemoryUnit(1);
public static final MemoryUnit KIBIBYTES = new MemoryUnit(1024);
public static final MemoryUnit KILOBYTES = new MemoryUnit(1000);
public static final MemoryUnit MEBIBYTES = new MemoryUnit(1024, KIBIBYTES);
public static final MemoryUnit MEGABYTES = new MemoryUnit(1000, KILOBYTES);
public static final MemoryUnit GIGABYTES = new MemoryUnit(1000, MEGABYTES);
public static final MemoryUnit GIBIBYTES = new MemoryUnit(1024, MEBIBYTES);
private final long oneUnitInBytes;
private MemoryUnit(final long oneUnitInBytes) {
Assert.assertTrue(oneUnitInBytes > 0);
this.oneUnitInBytes = oneUnitInBytes;
}
private MemoryUnit(MemoryUnit alias) {
this(1, alias);
}
private MemoryUnit(long amount, MemoryUnit unit) {
this(amount * unit.oneUnitInBytes);
}
public long convert(long amount, MemoryUnit unit) {
if(oneUnitInBytes > unit.oneUnitInBytes) {
long ratio = oneUnitInBytes / unit.oneUnitInBytes;
return amount / ratio;
} else {
long ratio = unit.oneUnitInBytes / oneUnitInBytes;
return amount * ratio;
}
}
public static MemoryUnit valueOf(String str) {
str = str.toLowerCase();
switch(str) {
case "": // default to MBs
case "mb":
case "mebibyte":
case "mebibytes": return MEBIBYTES;
case "b":
case "bytes":
case "byte": return BYTES;
case "kb":
case "kibibyte":
case "kibibytes": return KIBIBYTES;
case "gb":
case "gibibyte":
case "gibibytes": return GIBIBYTES;
case "gigabyte":
case "gigabytes": return GIGABYTES;
case "kilobyte":
case "kilobytes": return KILOBYTES;
case "megabyte":
case "megabytes": return MEGABYTES;
default: throw new IllegalArgumentException("unknown memory unit type: " + str);
}
}
@Override public int compareTo(final MemoryUnit other) {
return Long.compare(oneUnitInBytes, other.oneUnitInBytes);
}
@Override public boolean equals(final Object o) {
if(this == o) {
return true;
}
if(!(o instanceof MemoryUnit)) {
return false;
}
final MemoryUnit that = (MemoryUnit) o;
return oneUnitInBytes == that.oneUnitInBytes;
}
@Override public int hashCode() {
return Objects.hash(oneUnitInBytes);
}
}
| 3,622 | 33.179245 | 92 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/memory/MemoryUnitTest.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.system.memory;
import static tsml.classifiers.distance_based.utils.system.memory.MemoryUnit.GIBIBYTES;
import static tsml.classifiers.distance_based.utils.system.memory.MemoryUnit.MEBIBYTES;
import org.junit.Assert;
import org.junit.Test;
/**
* Purpose: // todo - docs - type the purpose of the code here
* <p>
* Contributors: goastler
*/
public class MemoryUnitTest {
@Test
public void gibibyteToMebibyte() {
long amount = MEBIBYTES.convert(8, GIBIBYTES);
Assert.assertEquals(amount, 8192);
}
@Test
public void mebibyteToGibibyte() {
long amount = GIBIBYTES.convert(8192, MEBIBYTES);
Assert.assertEquals(amount, 8);
}
}
| 1,494 | 32.222222 | 87 | java |
tsml-java | tsml-java-master/src/main/java/tsml/classifiers/distance_based/utils/system/memory/MemoryWatchable.java | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
package tsml.classifiers.distance_based.utils.system.memory;
/**
* Purpose: get stats related to memory.
*
* Contributors: goastler
*/
public interface MemoryWatchable {
long getMaxMemoryUsage();
static void gc() {
// do it twice and this automagically cleans up memory somehow...
System.gc();
System.gc();
// above may have put some objs in a queue for finalization, so let's clear them out
System.runFinalization();
System.runFinalization();
}
}
| 1,286 | 32.868421 | 92 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.