index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/TooManyConnectionRetriesException.java
|
package ai.libs.jaicore.basic;
/**
* Exception may be thrown if too many retries happened when trying to connect to the database via the SQLAdapter.
*
* @author mwever
*
*/
public class TooManyConnectionRetriesException extends RuntimeException {
public TooManyConnectionRetriesException(final String msg) {
super(msg);
}
public TooManyConnectionRetriesException(final String msg, final Throwable cause) {
super(msg, cause);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/ValueUtil.java
|
package ai.libs.jaicore.basic;
public class ValueUtil {
/**
* Forbid to create an object of ListHelper as there are only static methods allowed here.
*/
private ValueUtil() {
// intentionally do nothing
}
public static String valueToString(final double value, final int decimals) {
StringBuilder sb = new StringBuilder();
sb.append(round(value, decimals));
while (sb.toString().length() < decimals + 2) {
sb.append("0");
}
return sb.toString();
}
public static double round(final double valueToRound, final int decimals) {
int multiplier = (int) Math.pow(10, decimals);
double raisedValue = Math.round(valueToRound * multiplier);
return raisedValue / multiplier;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate/package-info.java
|
/**
* This package contains aggregation functions for various domains.
*/
package ai.libs.jaicore.basic.aggregate;
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate/reals/Max.java
|
package ai.libs.jaicore.basic.aggregate.reals;
import java.util.List;
import org.api4.java.common.aggregate.IRealsAggregateFunction;
/**
* The aggregation function "Max" aggregates the given values with the maximum operator, thus, returning the maximum of a list of values.
*
* @author mwever
*/
public class Max implements IRealsAggregateFunction {
@Override
public Double aggregate(final List<Double> values) {
return values.stream().mapToDouble(x -> x).max().getAsDouble();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate/reals/Mean.java
|
package ai.libs.jaicore.basic.aggregate.reals;
import java.util.List;
import org.api4.java.common.aggregate.IRealsAggregateFunction;
/**
* The aggregation function "Mean" aggregates the given values with the mean operator, thus, returning the average of a list of values.
*
* @author mwever
*/
public class Mean implements IRealsAggregateFunction {
@Override
public Double aggregate(final List<Double> values) {
return values.stream().mapToDouble(x -> x).average().getAsDouble();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate/reals/Median.java
|
package ai.libs.jaicore.basic.aggregate.reals;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.api4.java.common.aggregate.IRealsAggregateFunction;
/**
* The aggregation function "Median" aggregates the given values with the median operator, thus, returning the median of a list of values.
*
* @author mwever
*/
public class Median implements IRealsAggregateFunction {
@Override
public Double aggregate(final List<Double> values) {
if (values.isEmpty()) {
return Double.NaN;
}
List<Double> copyOfValues = new LinkedList<>(values);
Collections.sort(copyOfValues);
if (copyOfValues.size() % 2 == 0) {
int indexL = (values.size() / 2) - 1;
int indexU = (values.size() / 2);
return (copyOfValues.get(indexL) + copyOfValues.get(indexU)) / 2;
} else {
int index = (values.size() + 1 / 2) - 1;
return copyOfValues.get(index);
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate/reals/Min.java
|
package ai.libs.jaicore.basic.aggregate.reals;
import java.util.List;
import org.api4.java.common.aggregate.IRealsAggregateFunction;
/**
* The aggregation function "Min" aggregates the given values with the minimum operator, thus, returning the minimum of a list of values.
*
* @author mwever
*/
public class Min implements IRealsAggregateFunction {
@Override
public Double aggregate(final List<Double> values) {
return values.stream().mapToDouble(x -> x).min().getAsDouble();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate/reals/package-info.java
|
/**
* This package provides a set of aggregation functions dealing with collections of doubles.
* Examples are taking the min, max, mean, or median.
*
* @author mwever
*/
package ai.libs.jaicore.basic.aggregate.reals;
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate/string/Concat.java
|
package ai.libs.jaicore.basic.aggregate.string;
import java.util.List;
import org.api4.java.common.aggregate.IStringAggregateFunction;
import ai.libs.jaicore.basic.sets.SetUtil;
/**
* Concat is an aggregation function for Strings simply concatenating all the String values provided.
*
* @author mwever
*/
public class Concat implements IStringAggregateFunction {
@Override
public String aggregate(final List<String> values) {
return SetUtil.implode(values, "");
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/aggregate/string/pacakge-info.java
|
/**
* This package provides basic aggregation functions for strings.
* Example: Concatenating a collection of strings to a single string.
*
* @author mwever
*/
package ai.libs.jaicore.basic.aggregate.string;
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/AAlgorithm.java
|
package ai.libs.jaicore.basic.algorithm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.aeonbits.owner.ConfigFactory;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.algorithm.exceptions.ExceptionInAlgorithmIterationException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.common.event.IRelaxedEventEmitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.EventBus;
import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig;
import ai.libs.jaicore.interrupt.Interrupter;
import ai.libs.jaicore.timing.TimedComputation;
public abstract class AAlgorithm<I, O> implements IAlgorithm<I, O>, ILoggingCustomizable, IRelaxedEventEmitter {
/* Logger variables */
private Logger logger = LoggerFactory.getLogger(AAlgorithm.class);
private String loggerName;
/* Parameters of the algorithm. */
private IOwnerBasedAlgorithmConfig config;
/* Semantic input to the algorithm. */
private final I input;
/* State and event bus for sending algorithm events. */
private long shutdownInitialized = -1; // timestamp for when the shutdown has been initialized
private long activationTime = -1; // timestamp of algorithm activation
private String id;
private long deadline = -1; // timestamp when algorithm must terminate due to timeout
private long timeOfTimeoutDetection = -1; // timestamp for when timeout has been triggered
private long canceled = -1; // timestamp for when the algorithm has been canceled
private final Set<Thread> activeThreads = new HashSet<>();
private EAlgorithmState state = EAlgorithmState.CREATED;
private final EventBus eventBus = new EventBus();
private final List<Object> listeners = new ArrayList<>();
private int timeoutPrecautionOffset = 100; // this offset is substracted from the true remaining time whenever a timer is scheduled to ensure that the timeout is respected
private static final int MIN_RUNTIME_FOR_OBSERVED_TASK = 50;
private static final String INTERRUPT_NAME_SUFFIX = "-shutdown";
/**
* C'tor providing the input for the algorithm already.
*
* @param input
* The input for the algorithm.
*/
protected AAlgorithm(final I input) {
this(null, input);
}
/**
* Internal c'tore overwriting the internal configuration and setting the input.
*
* @param input
* The input for the algorithm.
* @param config
* The configuration to take as the internal configuration object.
*/
protected AAlgorithm(final IOwnerBasedAlgorithmConfig config, final I input) {
this.input = input;
this.config = (config != null) ? config : ConfigFactory.create(IOwnerBasedAlgorithmConfig.class);
}
@Override
public Iterator<IAlgorithmEvent> iterator() {
return this;
}
@Override
public boolean hasNext() {
return this.state != EAlgorithmState.INACTIVE;
}
@Override
public IAlgorithmEvent next() {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
try {
return this.nextWithException();
} catch (Exception e) {
this.unregisterThreadAndShutdown();
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw new ExceptionInAlgorithmIterationException(e);
}
}
@Override
public I getInput() {
return this.input;
}
@Override
public void registerListener(final Object listener) {
this.eventBus.register(listener);
this.listeners.add(listener);
}
public List<Object> getListeners() {
return Collections.unmodifiableList(this.listeners);
}
@Override
public int getNumCPUs() {
return this.getConfig().cpus();
}
@Override
public void setNumCPUs(final int numberOfCPUs) {
this.getConfig().setProperty(IOwnerBasedAlgorithmConfig.K_CPUS, numberOfCPUs + "");
}
@Override
public void setMaxNumThreads(final int maxNumberOfThreads) {
this.getConfig().setProperty(IOwnerBasedAlgorithmConfig.K_THREADS, maxNumberOfThreads + "");
}
@Override
public final void setTimeout(final long timeout, final TimeUnit timeUnit) {
this.setTimeout(new Timeout(timeout, timeUnit));
this.logger.info("Timeout set to {}s", this.getTimeout().seconds());
}
@Override
public void setTimeout(final Timeout timeout) {
this.logger.info("Setting timeout to {}ms", timeout.milliseconds());
this.getConfig().setProperty(IOwnerBasedAlgorithmConfig.K_TIMEOUT, timeout.milliseconds() + "");
}
public boolean isTimeoutDefined() {
return this.getTimeout().milliseconds() > 0;
}
public int getTimeoutPrecautionOffset() {
return this.timeoutPrecautionOffset;
}
public void setTimeoutPrecautionOffset(final int timeoutPrecautionOffset) {
this.timeoutPrecautionOffset = timeoutPrecautionOffset;
}
@Override
public Timeout getTimeout() {
return new Timeout(this.getConfig().timeout(), TimeUnit.MILLISECONDS);
}
public boolean isTimeouted() {
if (this.timeOfTimeoutDetection > 0) {
return true;
}
if (this.deadline > 0 && System.currentTimeMillis() >= this.deadline) {
this.timeOfTimeoutDetection = System.currentTimeMillis();
return true;
}
return false;
}
protected long getDeadline() {
return this.deadline;
}
protected Timeout getRemainingTimeToDeadline() {
if (this.deadline < 0) {
return new Timeout(Integer.MAX_VALUE, TimeUnit.SECONDS);
}
return new Timeout(this.deadline - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
public boolean isStopCriterionSatisfied() {
return this.isCanceled() || this.isTimeouted() || Thread.currentThread().isInterrupted();
}
/**
* @return Flag denoting whether this algorithm has been canceled.
*/
public boolean isCanceled() {
return this.canceled > 0;
}
@Override
public String getId() {
if (this.id == null) {
this.id = this.getClass().getName() + "-" + System.currentTimeMillis();
}
return this.id;
}
protected void checkTermination(final boolean shutdownOnStoppingCriterion) throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
this.logger.debug("Checking Termination");
Thread t = Thread.currentThread();
/* if the thread is interrupted, handle it appropriately.
* - Interrupts caused by a shutdown will be resolved and ignored. They will be handled in the timeout or cancel block
* - Interrupts not caused by a shutdown will be merged into an InterruptedException
**/
Interrupter interrupter = Interrupter.get();
if (t.isInterrupted()) {
/* synchronously check whether we have been interrupted on purpose */
boolean isIntentionalInterrupt;
synchronized (interrupter) {
this.logger.info("Interruption detected for {}. Resetting interrupted-flag. Now checking whether this was due to a shutdown.", this.getId());
Thread.interrupted(); // clear the interrupt-field. This is necessary, because otherwise some shutdown-activities (like waiting for pool shutdown) might fail
isIntentionalInterrupt = this.hasThreadBeenInterruptedDuringShutdown(t);
if (!isIntentionalInterrupt) {
this.avoidReinterruptionOnShutdownOnCurrentThread();
}
}
/* if the interrupt has been intentional, resolve it and proceed */
if (isIntentionalInterrupt) {
this.logger.debug("Thread has been interrupted during shutdown (so we will not throw an InterruptedException). Resolving this interruption cause now.");
this.resolveShutdownInterruptOnCurrentThread();
this.logger.debug("Interrupt reason resolved. Now proceeding with termination check, which should end with a timeout or cancellation.");
assert this.isTimeouted() || this.isCanceled() : "If a thread is interrupted during the shutdown, this should be caused by a timeout or a cancel!";
}
/* for an external interrupt, shutdown the algorithm */
else {
this.logger.debug("The interrupt has not been caused by a shutdown. Will throw an InterruptedException (and maybe previously shutdown if configured so).");
if (shutdownOnStoppingCriterion) {
this.logger.debug("Invoking shutdown");
this.unregisterThreadAndShutdown();
} else {
this.logger.debug("Not shutting down, because shutdown-on-stop-criterion has been set to false");
}
this.logger.debug("Throwing InterruptedException to communicate the interrupt to the invoker.");
throw new InterruptedException(); // if the thread itself was actively interrupted by somebody
}
}
if (this.isTimeouted()) {
this.logger.info("Timeout detected for {}", this.getId());
if (shutdownOnStoppingCriterion) {
this.logger.debug("Invoking shutdown");
this.unregisterThreadAndShutdown();
} else {
this.logger.debug("Not shutting down, because shutdown-on-stop-criterion has been set to false");
}
this.logger.debug("Throwing TimeoutException");
throw new AlgorithmTimeoutedException(this.timeOfTimeoutDetection - this.deadline);
}
if (this.isCanceled()) { // for a cancel, we assume that the shutdown has already been triggered by the canceler
this.logger.info("Cancel detected for {}. Cancel was issued {}ms ago.", this.getId(), (System.currentTimeMillis() - this.canceled));
if (Thread.interrupted()) { // reset the flag
this.logger.debug("Thread has been interrupted during shutdown. Resetting the flag and not invoking shutdown again.");
}
this.logger.debug("Throwing AlgorithmExecutionCanceledException.");
throw new AlgorithmExecutionCanceledException(System.currentTimeMillis() - this.canceled);
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("No termination condition observed. Remaining time to timeout is {}", this.getRemainingTimeToDeadline());
}
}
protected void checkAndConductTermination() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
this.checkTermination(true);
}
/**
* This method does two things:
* 1. it interrupts all threads that are registered to be active inside this algorithm
* 2. it cancels the (possibly created) timeout thread
*
* This method should be called ALWAYS when the algorithm activity ceases.
*
* This method takes effect only once. Further invocations will be ignored.
*/
protected void shutdown() {
synchronized (this) {
if (this.shutdownInitialized > 0) {
this.logger.info("Tried to enter shutdown for {}, but the shutdown has already been initialized in the past, so exiting the shutdown block.", this);
return;
}
this.shutdownInitialized = System.currentTimeMillis();
this.logger.info("Entering shutdown procedure for {}. Interrupting {} active threads: {}", this.getId(), this.activeThreads.size(), this.activeThreads);
}
for (Thread t : this.activeThreads) {
this.logger.debug("Triggering interrupt on {} as part of shutdown of {}", t, this.getId());
this.interruptThreadAsPartOfShutdown(t);
}
this.logger.info("Shutdown of {} completed.", this.getId());
}
protected void interruptThreadAsPartOfShutdown(final Thread t) {
Interrupter.get().interruptThread(t, this.getId() + INTERRUPT_NAME_SUFFIX);
}
public boolean hasThreadBeenInterruptedDuringShutdown(final Thread t) {
return Interrupter.get().hasThreadBeenInterruptedWithReason(t, this.getId() + INTERRUPT_NAME_SUFFIX);
}
protected void resolveShutdownInterruptOnCurrentThread() throws InterruptedException {
Interrupter.get().markInterruptOnCurrentThreadAsResolved(this.getId() + INTERRUPT_NAME_SUFFIX);
}
protected void avoidReinterruptionOnShutdownOnCurrentThread() {
Interrupter.get().avoidInterrupt(Thread.currentThread(), this.getId() + INTERRUPT_NAME_SUFFIX);
}
public boolean isShutdownInitialized() {
return this.shutdownInitialized > 0;
}
protected void unregisterThreadAndShutdown() {
this.unregisterActiveThread();
this.shutdown();
}
protected void registerActiveThread() {
/* check this already prior to synchronizing to not run into a dead-lock if the shutdown is currently in progress. */
if (this.shutdownInitialized > 0) {
this.logger.warn("Ignoring registration of thread, because the algorithm has been shutdown already");
return;
}
/* now conduct the synchronized check */
synchronized (this) {
if (this.shutdownInitialized > 0) {
this.logger.warn("Ignoring registration of thread, because the algorithm has been shutdown already");
return;
}
this.activeThreads.add(Thread.currentThread());
}
}
protected void unregisterActiveThread() {
this.logger.trace("Unregistering current thread {}", Thread.currentThread());
this.activeThreads.remove(Thread.currentThread());
}
public long getActivationTime() {
return this.activationTime;
}
/**
* @return The current state of the algorithm.
*/
public EAlgorithmState getState() {
return this.state;
}
/**
* @param state
* The new state of the algorithm.
*/
protected void setState(final EAlgorithmState state) {
if (state == EAlgorithmState.ACTIVE) {
throw new IllegalArgumentException("Cannot switch state to active. Use \"activate\" instead, which will set the state to active and provide the AlgorithmInitializedEvent.");
} else if (state == EAlgorithmState.INACTIVE) {
throw new IllegalArgumentException("Cannot switch state to inactive. Use \"terminate\" instead, which will set the state to inactive and provide the AlgorithmFinishedEvent.");
}
this.state = state;
}
@Override
public void cancel() {
this.logger.info("Received cancel for algorithm {}.", this.getId());
if (this.isCanceled()) {
this.logger.debug("Ignoring cancel command since the algorithm has been canceled before.");
return;
}
this.canceled = System.currentTimeMillis();
this.logger.info("Cancel flag for {} is set to {}. Now invoke shutdown procedure.", this.getId(), this.canceled);
this.shutdown();
}
/**
* This method
* - defines the definite deadline for when the algorithm must have finished
* - sets the algorithm state to ACTIVE
* - sends the mandatory AlgorithmInitializedEvent over the event bus.
* Should only be called once and as before the state is set to something else.
*/
protected AlgorithmInitializedEvent activate() {
assert this.state == EAlgorithmState.CREATED : "Can only activate an algorithm as long as its state has not been changed from CREATED to something else. It is currently " + this.state;
this.activationTime = System.currentTimeMillis();
if (this.getTimeout().milliseconds() > 0 && this.deadline < 0) {
this.setDeadline();
}
this.state = EAlgorithmState.ACTIVE;
AlgorithmInitializedEvent event = new AlgorithmInitializedEvent(this);
this.eventBus.post(event);
this.logger.debug("Starting algorithm {} with problem of type {} and config {}.", this.getId(), this.input.getClass().getName(), this.config);
return event;
}
protected void setDeadline() {
if (this.deadline >= 0) {
throw new IllegalStateException();
}
if (this.getTimeout().milliseconds() > 0) {
this.deadline = System.currentTimeMillis() + this.getTimeout().milliseconds() - this.timeoutPrecautionOffset;
if (this.logger.isInfoEnabled()) {
this.logger.info("Timeout is {}, and precaution offset is {}. Setting deadline to timestamp {}. Remaining time: {}", this.getTimeout(), this.timeoutPrecautionOffset, this.deadline, this.getRemainingTimeToDeadline());
}
} else {
this.deadline = System.currentTimeMillis() + 86400 * 1000 * 365;
this.logger.info("No timeout defined. Setting deadline to timestamp {}. Remaining time: {}", this.deadline, this.getRemainingTimeToDeadline());
}
}
/**
* This methods terminates the algorithm, setting the internal state to inactive and emitting the mandatory AlgorithmFinishedEvent over the event bus.
*
* @return The algorithm finished event.
*/
protected AlgorithmFinishedEvent terminate() {
this.logger.info("Terminating algorithm {}.", this.getId());
this.state = EAlgorithmState.INACTIVE;
AlgorithmFinishedEvent finishedEvent = new AlgorithmFinishedEvent(this);
this.unregisterThreadAndShutdown();
this.eventBus.post(finishedEvent);
return finishedEvent;
}
/**
* This methods allows for posting an event on the algorithm's event bus.
*
* @param e
* The event to post on the event bus.
*/
protected void post(final Object e) {
this.eventBus.post(e);
}
@Override
public IOwnerBasedAlgorithmConfig getConfig() {
return this.config;
}
/**
* Sets the config object to the new config object.
*
* @param config
* The new config object.
*/
public void setConfig(final IOwnerBasedAlgorithmConfig config) {
this.config = config;
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switching logger to {}", name);
this.loggerName = name;
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Switched to logger {}", name);
}
@Override
public String getLoggerName() {
return this.loggerName;
}
protected void announceTimeoutDetected() {
this.timeOfTimeoutDetection = System.currentTimeMillis(); // artificially set the timeout detected variable
}
protected <T> T computeTimeoutAware(final Callable<T> r, final String reasonToLogOnTimeout, final boolean shutdownOnStoppingCriterionSatisfied)
throws InterruptedException, AlgorithmException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
this.logger.debug("Received request to execute {} with awareness of timeout {}. Currently active threads: {}.", r, this.getTimeout(), this.activeThreads);
/* if no timeout is sharp, just execute the task */
if (this.getTimeout().milliseconds() < 0) {
try {
return r.call();
} catch (InterruptedException e) { // the fact that we are interrupted here can have several reasons. Could be an interrupt from the outside, a cancel, or a timeout by the above timer
boolean interruptedDueToShutdown = this.hasThreadBeenInterruptedDuringShutdown(Thread.currentThread());
this.logger.info("Received interrupt. Cancel flag is {}. Thread contained in interrupted by shutdown: {}", this.isCanceled(), interruptedDueToShutdown);
if (!interruptedDueToShutdown) {
throw e;
}
this.checkTermination(shutdownOnStoppingCriterionSatisfied);
throw new IllegalStateException("Received an interrupt and checked termination, thus, termination routine should have thrown an exception which it apparently did not!");
} catch (AlgorithmExecutionCanceledException e) { // these exceptions should just be forwarded
throw e;
} catch (Exception e) {
throw new AlgorithmException("The algorithm has failed due to an exception of a Callable.", e);
}
}
/* if the remaining time is not sufficient to conduct further calculation, cancel at this point */
long remainingTime = this.getRemainingTimeToDeadline().milliseconds();
if (remainingTime < this.timeoutPrecautionOffset + MIN_RUNTIME_FOR_OBSERVED_TASK) {
this.logger.debug("Only {}ms left, which is not enough to reliably continue computation. Terminating algorithm at this point, throwing an AlgorithmTimeoutedException.", remainingTime);
this.announceTimeoutDetected();
this.checkTermination(shutdownOnStoppingCriterionSatisfied);
}
/* conduct timed computation */
try {
return TimedComputation.compute(r, new Timeout(remainingTime - this.timeoutPrecautionOffset, TimeUnit.MILLISECONDS), reasonToLogOnTimeout);
} catch (AlgorithmTimeoutedException e) {
this.logger.debug("TimedComputation has been timeouted. Setting the TimeoutDetection flag to now. Remaining time is {}ms.", this.getRemainingTimeToDeadline().milliseconds());
this.timeOfTimeoutDetection = System.currentTimeMillis();
this.checkTermination(shutdownOnStoppingCriterionSatisfied);
throw new IllegalStateException("The flag for timeout detection has been set, but checkTermination did not throw an exception!"); // this line should never be reached
} catch (InterruptedException e) {
this.logger.info("Received interrupt for {} during timed computation. Cancel flag is {}", this.getId(), this.isCanceled());
assert !Thread.currentThread().isInterrupted() : "By java convention, the thread should not be interrupted when an InterruptedException is thrown.";
boolean interruptedDueToShutdown = this.hasThreadBeenInterruptedDuringShutdown(Thread.currentThread());
if (!interruptedDueToShutdown) {
throw e;
}
this.resolveShutdownInterruptOnCurrentThread();
this.checkTermination(shutdownOnStoppingCriterionSatisfied);
throw new IllegalStateException("A stopping criterion must have been true (probably cancel), but checkTermination did not throw an exception!"); // this line should never be reached
} catch (ExecutionException e) {
throw new AlgorithmException("The algorithm has failed due to an exception of Callable " + r + " with timeout log message " + reasonToLogOnTimeout, e);
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/AAlgorithmEvent.java
|
package ai.libs.jaicore.basic.algorithm;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.events.IAlgorithmEvent;
/**
* Simple implementation of an algorithm event that takes the current time as the time stamp.
*
* @author Felix Mohr
*
*/
public class AAlgorithmEvent implements IAlgorithmEvent {
private final long timestamp = System.currentTimeMillis();
private final String algorithmId;
/**
* @param algorithm The algorithm to which this event is related.
*/
public AAlgorithmEvent(final IAlgorithm<?, ?> algorithm) {
super();
this.algorithmId = algorithm != null ? algorithm.getId() : "<unknown algorithm>";
}
@Override
public String getAlgorithmId() {
return this.algorithmId;
}
@Override
public long getTimestamp() {
return this.timestamp;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/AAlgorithmFactory.java
|
package ai.libs.jaicore.basic.algorithm;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.IAlgorithmFactory;
public abstract class AAlgorithmFactory<I,O, A extends IAlgorithm<I,O>> implements IAlgorithmFactory<I, O, A> {
private I input;
public void setProblemInput(final I problemInput) {
this.input = problemInput;
}
public I getInput() {
return this.input;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/ADelayedTerminationCheckException.java
|
package ai.libs.jaicore.basic.algorithm;
/**
* The purpose of this exception is to indicate that the checkTermination method
* of AAlgorithm was invoked too late. Too late means that the algorithm has
* been interrupted, timeouted or canceled at least 100ms prior to the
* invocation of the check.
*
* The motivation is that it is difficult to track time leaks, i.e. which code
* is responsible that the control is not returned in time after an interruption
* or timeout. This exception is thrown by checkTermination in order to enforce
* developers to handle this particular case and to ease debugging.
*
* @author fmohr
*
*/
@SuppressWarnings("serial")
public abstract class ADelayedTerminationCheckException extends Exception {
private final long delay;
protected ADelayedTerminationCheckException(final String message, final long delay) {
super(message);
this.delay = delay;
}
public long getDelay() {
return this.delay;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/AOptimizer.java
|
package ai.libs.jaicore.basic.algorithm;
import java.util.NoSuchElementException;
import org.api4.java.algorithm.IOptimizationAlgorithm;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.events.result.ISolutionCandidateFoundEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.attributedobjects.ScoredItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig;
/**
* The AOptimizer represents an algorithm that is meant to optimize for a single best solution.
* While it may observe multiple candidates for the best solution and report them via events
* when running, eventually it will return only the single best observed one.
*
* @author fmohr, wever
*
* @param <I> The type of input instances (problems) to be solved by the algorithm.
* @param <O> The type of output that is obtained by running the algorithm on the input.
* @param <V> The type performance values will have to compare different solutions.
*/
public abstract class AOptimizer<I, O extends ScoredItem<V>, V extends Comparable<V>> extends ASolutionCandidateIterator<I, O> implements IOptimizationAlgorithm<I, O, V> {
/* Logger variables */
private Logger logger = LoggerFactory.getLogger(AOptimizer.class);
private String loggerName;
/* currently best solution candidate observed so far */
private O bestSeenSolution;
private V bestScoreKnownToExist = null;
/**
* C'tor taking only an input as a parameter.
*
* @param input The input of the algorithm.
*/
protected AOptimizer(final I input) {
super(input);
}
/**
* C'tor taking a configuration of the algorithm and an input for the algorithm as arguments.
*
* @param config The parameterization of the algorithm.
* @param input The input to the algorithm (the problem to solve).
*/
protected AOptimizer(final IOwnerBasedAlgorithmConfig config, final I input) {
super(config, input);
}
/**
* Updates the best seen solution if the new solution is better. Returns true iff the best seen solution has been updated.
*
* @param candidate A candidate for a new best seen solution. It is only updated iff the candidate performs better than the bestSeenSolution observed so far.
* @return Returns true iff the candidate is the best seen solution.
*/
protected synchronized boolean updateBestSeenSolution(final O candidate) {
assert (candidate != null) : "Cannot update best solution with null.";
this.tellAboutBestScoreKnownToExist(candidate.getScore());
if (this.bestSeenSolution == null || (candidate.getScore() != null && candidate.getScore().compareTo(this.bestSeenSolution.getScore()) < 0)) {
if (this.bestSeenSolution != null) {
this.logger.info("New best solution found with score={} (old={})", candidate.getScore(), this.bestSeenSolution.getScore());
} else {
this.logger.info("First best solution found with score={} ", candidate.getScore());
}
this.bestSeenSolution = candidate;
return true;
}
return false;
}
/**
* Sets the best seen solution regardless the currently best solution.
*
* @param candidate
* @return true iff the new solution has a higher score than the existing one
*/
protected boolean setBestSeenSolution(final O candidate) {
boolean isBetterThanCurrent = (this.bestSeenSolution == null || (candidate.getScore() != null && candidate.getScore().compareTo(this.bestSeenSolution.getScore()) < 0));
this.tellAboutBestScoreKnownToExist(candidate.getScore());
this.bestSeenSolution = candidate;
return isBetterThanCurrent;
}
@Override
public O nextSolutionCandidate() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
O candidate = super.nextSolutionCandidate();
this.updateBestSeenSolution(candidate);
return candidate;
}
@Override
public ISolutionCandidateFoundEvent<O> nextSolutionCandidateEvent() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
while (this.hasNext()) {
IAlgorithmEvent event = this.nextWithException();
if (event instanceof ISolutionCandidateFoundEvent) {
@SuppressWarnings("unchecked")
ISolutionCandidateFoundEvent<O> castedEvent = (ISolutionCandidateFoundEvent<O>) event;
return castedEvent;
}
}
throw new NoSuchElementException();
}
public V getBestScoreKnownToExist() {
return this.bestScoreKnownToExist;
}
public void tellAboutBestScoreKnownToExist(final V bestScoreKnownToExist) {
if (this.bestScoreKnownToExist == null || bestScoreKnownToExist.compareTo(this.bestScoreKnownToExist) < 0) {
this.logger.info("Updating best known achievable score to {}.", bestScoreKnownToExist);
this.bestScoreKnownToExist = bestScoreKnownToExist;
}
}
/**
* @return The best seen solution, yet.
*/
public O getBestSeenSolution() {
return this.bestSeenSolution;
}
@Override
public O call() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
while (this.hasNext()) {
this.nextWithException();
}
return this.bestSeenSolution;
}
@Override
public String getLoggerName() {
return this.loggerName;
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switching logger from {} to {}", this.logger.getName(), name);
this.loggerName = name;
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Activated logger {} with name {}", name, this.logger.getName());
super.setLoggerName(this.loggerName + "._algorithm");
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/ASolutionCandidateFoundEvent.java
|
package ai.libs.jaicore.basic.algorithm;
import java.util.concurrent.atomic.AtomicInteger;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.events.result.ISolutionCandidateFoundEvent;
/**
* This is to notify listeners that an algorithm has found a solution candidate.
* Note that this is generally not the answer returned by the algorithm but only one possible candidate.
*
* @author Felix Mohr
*
* @param <O>
* class from which solution elements stem from
*/
public class ASolutionCandidateFoundEvent<O> extends AAlgorithmEvent implements ISolutionCandidateFoundEvent<O> {
private static final AtomicInteger ID_COUNTER = new AtomicInteger(0);
private final O solutionCandidate;
private final int gid;
public ASolutionCandidateFoundEvent(final IAlgorithm<?, ?> algorithm, final O solutionCandidate) {
super(algorithm);
this.solutionCandidate = solutionCandidate;
this.gid = ID_COUNTER.getAndIncrement();
}
@Override
public O getSolutionCandidate() {
return this.solutionCandidate;
}
public int getGID() {
return this.gid;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/ASolutionCandidateIterator.java
|
package ai.libs.jaicore.basic.algorithm;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeoutException;
import org.api4.java.algorithm.ISolutionCandidateIterator;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.events.result.ISolutionCandidateFoundEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig;
/**
* A template for algorithms that iterate over solution candidates. By default,
* if this algorithm is called, it returns the first solution it finds.
*
* @author fmohr
*
* @param <I>
* @param <O>
*/
public abstract class ASolutionCandidateIterator<I, O> extends AAlgorithm<I, O> implements ISolutionCandidateIterator<I, O> {
protected ASolutionCandidateIterator(final I input) {
super(input);
}
protected ASolutionCandidateIterator(final IOwnerBasedAlgorithmConfig config, final I input) {
super(config, input);
}
@Override
public O nextSolutionCandidate() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
ISolutionCandidateFoundEvent<O> event = this.nextSolutionCandidateEvent();
return event.getSolutionCandidate();
}
@Override
public ISolutionCandidateFoundEvent<O> nextSolutionCandidateEvent() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
while (this.hasNext()) {
IAlgorithmEvent event = this.nextWithException();
if (event instanceof ISolutionCandidateFoundEvent) {
@SuppressWarnings("unchecked")
ISolutionCandidateFoundEvent<O> castedEvent = (ISolutionCandidateFoundEvent<O>) event;
return castedEvent;
}
}
throw new NoSuchElementException();
}
@Override
public O call() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
O candidate = this.nextSolutionCandidate();
this.terminate(); // make sure that a termination event is sent
return candidate;
}
/**
* Gathers all solutions that exist
*
* @return
* @throws InterruptedException
* @throws AlgorithmExecutionCanceledException
* @throws TimeoutException
* @throws AlgorithmException
*/
public List<O> collectAllSolutions() throws InterruptedException, AlgorithmExecutionCanceledException, TimeoutException, AlgorithmException {
List<O> solutions = new ArrayList<>();
while (this.hasNext()) {
solutions.add(this.nextSolutionCandidate());
}
return solutions;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/AlgorithmCanceledEvent.java
|
package ai.libs.jaicore.basic.algorithm;
import org.api4.java.algorithm.IAlgorithm;
/**
* Event that an algorithm has been canceled.
*
* @author Felix Mohr
*
*/
public class AlgorithmCanceledEvent extends AAlgorithmEvent {
public AlgorithmCanceledEvent(final IAlgorithm<?, ?> algorithm) {
super(algorithm);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/AlgorithmFinishedEvent.java
|
package ai.libs.jaicore.basic.algorithm;
import org.api4.java.algorithm.IAlgorithm;
/**
* Event that an algorithm has finished
*
* @author Felix Mohr
*
*/
public class AlgorithmFinishedEvent extends AAlgorithmEvent {
public AlgorithmFinishedEvent(final IAlgorithm<?, ?> algorithm) {
super(algorithm);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/AlgorithmInitializedEvent.java
|
package ai.libs.jaicore.basic.algorithm;
import org.api4.java.algorithm.IAlgorithm;
/**
* Event that an algorithm has been initialized.
*
* @author Felix Mohr
*/
public class AlgorithmInitializedEvent extends AAlgorithmEvent {
public AlgorithmInitializedEvent(final IAlgorithm<?, ?> algorithm) {
super(algorithm);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/AlgorithmInterruptedEvent.java
|
package ai.libs.jaicore.basic.algorithm;
import org.api4.java.algorithm.IAlgorithm;
/**
* Event that an algorithm has been interrupted.
*
* @author Felix Mohr
*
*/
public class AlgorithmInterruptedEvent extends AAlgorithmEvent {
public AlgorithmInterruptedEvent(final IAlgorithm<?, ?> algorithm) {
super(algorithm);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/EAlgorithmState.java
|
package ai.libs.jaicore.basic.algorithm;
/**
* This enum encapsulates the states an algorithm may take.
*
* @author fmohr, mwever
*/
public enum EAlgorithmState {
// the algorithm just got created and needs to be initialized first.
CREATED,
// the algorithm has already been initialized and is running
ACTIVE,
// the algorithm already terminated for whatever reason
INACTIVE;
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/reduction/AReducingSolutionIterator.java
|
package ai.libs.jaicore.basic.algorithm.reduction;
import java.util.NoSuchElementException;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.IAlgorithmFactory;
import org.api4.java.algorithm.ISolutionCandidateIterator;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.events.result.ISolutionCandidateFoundEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.algorithm.ASolutionCandidateFoundEvent;
import ai.libs.jaicore.basic.algorithm.ASolutionCandidateIterator;
public class AReducingSolutionIterator<I1, O1, I2, O2> extends ASolutionCandidateIterator<I1, O1> {
private Logger logger = LoggerFactory.getLogger(AReducingSolutionIterator.class);
private String loggerName;
/* algorithm inputs */
private final AlgorithmicProblemReduction<I1, O1, I2, O2> problemTransformer;
private final ISolutionCandidateIterator<I2, O2> baseAlgorithm;
public AReducingSolutionIterator(final I1 problem, final AlgorithmicProblemReduction<I1, O1, I2, O2> problemTransformer, final IAlgorithmFactory<I2, O2, ?> baseFactory) {
super(problem);
this.problemTransformer = problemTransformer;
this.baseAlgorithm = (ISolutionCandidateIterator<I2, O2>)baseFactory.getAlgorithm(problemTransformer.encodeProblem(problem));
}
@Override
public final void cancel() {
super.cancel();
this.baseAlgorithm.cancel();
}
public void runPreCreationHook() {
/* by default, this is an empty hook */
}
protected ISolutionCandidateFoundEvent<O1> getSolutionEvent(final O1 solution) {
return new ASolutionCandidateFoundEvent<>(this, solution);
}
@Override
public final IAlgorithmEvent nextWithException() throws AlgorithmExecutionCanceledException, InterruptedException, AlgorithmTimeoutedException, AlgorithmException {
if (this.isCanceled()) {
throw new IllegalStateException("The algorithm has already been canceled. Cannot conduct futŕther steps.");
}
switch (this.getState()) {
case CREATED:
this.runPreCreationHook();
/* set timeout on base algorithm */
Timeout to = this.getTimeout();
this.logger.debug("Setting timeout of search to {}", to);
this.baseAlgorithm.setTimeout(to);
return this.activate();
case ACTIVE:
this.logger.info("Starting/continuing search for next plan.");
try {
O2 solution = this.baseAlgorithm.nextSolutionCandidate();
if (solution == null) {
this.logger.info("No more solutions will be found. Terminating algorithm.");
return this.terminate();
}
this.logger.info("Next solution found.");
O1 solutionToOriginalProlem = this.problemTransformer.decodeSolution(solution);
ISolutionCandidateFoundEvent<O1> event = this.getSolutionEvent(solutionToOriginalProlem);
this.post(event);
return event;
} catch (NoSuchElementException e) { // if no more solution exists, terminate
return this.terminate();
}
default:
throw new IllegalStateException("Don't know what to do in state " + this.getState());
}
}
@Override
public String getLoggerName() {
return this.loggerName;
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switching logger from {} to {}", this.logger.getName(), name);
this.loggerName = name;
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Activated logger {} with name {}", name, this.logger.getName());
if (this.problemTransformer instanceof ILoggingCustomizable) {
this.logger.info("Setting logger of problem transformer to {}.problemtransformer", name);
((ILoggingCustomizable) this.problemTransformer).setLoggerName(name + ".problemtransformer");
}
if (this.baseAlgorithm instanceof ILoggingCustomizable) {
this.logger.info("Setting logger of search to {}.base", name);
((ILoggingCustomizable) this.baseAlgorithm).setLoggerName(name + ".base");
}
super.setLoggerName(this.loggerName + "._algorithm");
}
protected Logger getLogger() {
return this.logger;
}
public AlgorithmicProblemReduction<I1, O1, I2, O2> getProblemTransformer() {
return this.problemTransformer;
}
public IAlgorithm<I2, O2> getBaseAlgorithm() {
return this.baseAlgorithm;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/reduction/AlgorithmicProblemReduction.java
|
package ai.libs.jaicore.basic.algorithm.reduction;
public interface AlgorithmicProblemReduction<I1, O1, I2, O2> {
public I2 encodeProblem(I1 problem);
public O1 decodeSolution(O2 solution);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/reduction/IdentityReduction.java
|
package ai.libs.jaicore.basic.algorithm.reduction;
public class IdentityReduction<I, O> implements AlgorithmicProblemReduction<I, O, I, O> {
@Override
public I encodeProblem(final I problem) {
return problem;
}
@Override
public O decodeSolution(final O solution) {
return solution;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/algorithm/reduction/ReducingOptimizer.java
|
package ai.libs.jaicore.basic.algorithm.reduction;
import org.api4.java.algorithm.IOptimizationAlgorithm;
import org.api4.java.algorithm.IOptimizationAlgorithmFactory;
import org.api4.java.common.attributedobjects.ScoredItem;
public class ReducingOptimizer<I1, O1 extends ScoredItem<V>, I2, O2 extends ScoredItem<V>, V extends Comparable<V>> extends AReducingSolutionIterator<I1, O1, I2, O2> implements IOptimizationAlgorithm<I1,O1, V> {
/* algorithm inputs */
public ReducingOptimizer(final I1 problem, final AlgorithmicProblemReduction<I1, O1, I2, O2> problemTransformer, final IOptimizationAlgorithmFactory<I2, O2, V, ?> baseFactory) {
super(problem, problemTransformer, baseFactory);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/complexity/SquaredBackwardDifferenceComplexity.java
|
package ai.libs.jaicore.basic.complexity;
import org.api4.java.common.timeseries.ITimeSeriesComplexity;
/**
* Complexity metric as described in "A Complexity-Invariant Distance Measure
* for Time Series".
*
* $$ c = sum_{i=1}^n-1 \sqrt{ (T_i - T_{i+1})^2 }$$
*
* where $T_i$ are the values of the time series.
*
* @author fischor
*/
public class SquaredBackwardDifferenceComplexity implements ITimeSeriesComplexity {
@Override
public double complexity(final double[] t) {
int n = t.length;
double sum = .0;
for (int i = 0; i < n - 1; i++) {
sum += (t[i] - t[i + 1]) * (t[i] - t[i + 1]);
}
return Math.sqrt(sum);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/complexity/StretchingComplexity.java
|
package ai.libs.jaicore.basic.complexity;
import org.api4.java.common.timeseries.ITimeSeriesComplexity;
/**
* Stretching Complexity that calulates the length of a time series when
* stretched to a straight line.
*
* $$ c = sum_{i=1}^n-1 \sqrt{ (t_2 - t_1)^2 + (T_{i+1} - T_i)^2 }$$
*
* where $t_i$ are the timestamps (here $t_i = i$) an $T_i$ are the values of
* the time series.
*
* @author fischor
*/
public class StretchingComplexity implements ITimeSeriesComplexity {
@Override
public double complexity(final double[] t) {
int n = t.length;
double sum = .0;
for (int i = 0; i < n - 1; i++) {
sum += Math.sqrt(1 + Math.pow(t[i + 1] - t[i], 2));
}
return sum;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/complexity/package-info.java
|
/**
* This package contains implementations for time series complexity measures.
*
* @author fischor
*/
package ai.libs.jaicore.basic.complexity;
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/ESignificanceTestResult.java
|
package ai.libs.jaicore.basic.kvstore;
/**
* Enum for the outcomes for a significance test.
* If superior: the considered sample is significantly better.
* If inferior: the considered sample is significantly worse.
* If tie: there is no significant difference between the two samples.
*
* @author mwever
*/
public enum ESignificanceTestResult {
SUPERIOR, TIE, INFERIOR;
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/KVStore.java
|
package ai.libs.jaicore.basic.kvstore;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.api4.java.datastructure.kvstore.IKVFilter;
import org.api4.java.datastructure.kvstore.IKVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.SetUtil;
/**
* A KVStore can be used to store arbitrary objects for some string key.
* The KVStore allows for more convenient data access and some basic operations.
* Within KVStoreCollections it can be subject to significance tests and it may
* be transformed into a table representation.
*
* @author mwever
*/
public class KVStore extends HashMap<String, Object> implements IKVStore, Serializable {
/**
* Auto-generated standard serial version UID.
*/
private static final long serialVersionUID = 6635572555061279948L;
/**
* Logger for controlled command line outputs.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(KVStore.class);
/**
* Default separator to separate elements of a list.
*/
private static final String DEFAULT_LIST_SEP = ",";
private KVStoreCollection collection;
/**
* Standard c'tor creating an empty KV store.
*/
public KVStore() {
}
/**
* C'tor creating a KV store loading the data from the provided string representation.
*
* @param stringRepresentation
* A string formatted key value store to be restored.
*/
public KVStore(final String stringRepresentation) {
this.readKVStoreFromDescription(stringRepresentation);
}
/**
* C'tor for creating a shallow copy of another KeyValueStore or to initialize with the provided keyValueMap.
*
* @param keyValueMap
* Map of keys and values to initialize this KeyValueStore with.
*/
public KVStore(final Map<String, Object> keyValueMap) {
this.putAll(keyValueMap);
}
/**
* C'tor for making a deep copy of another KVStore.
*
* @param keyValueStoreToCopy
* The KVStore to make a deep copy from.
*/
public KVStore(final IKVStore keyValueStoreToCopy) {
this(keyValueStoreToCopy.toString());
}
@Override
public String getAsString(final String key) {
Object value = this.get(key);
if (value == null) {
return null;
} else if (value instanceof String) {
return (String) value;
} else {
return value + "";
}
}
@Override
public Boolean getAsBoolean(final String key) {
Object value = this.get(key);
if (value == null) {
return false;
} else if (value instanceof Boolean) {
return (Boolean) value;
} else if (value instanceof String) {
return Boolean.valueOf((String) value);
} else {
throw new IllegalStateException("Tried to get non-boolean value as boolean from KVStore.");
}
}
@Override
public Integer getAsInt(final String key) {
Object value = this.get(key);
if (value == null) {
return null;
} else if (value instanceof Integer) {
return (Integer) value;
} else if (value instanceof Long) {
return Integer.valueOf(value.toString());
} else if (value instanceof Double) {
return ((Double) value).intValue();
} else if (value instanceof String) {
try {
return Integer.valueOf((String) value);
} catch (NumberFormatException e) {
try {
return (int) (double) Double.valueOf((String) value);
} catch (NumberFormatException e1) {
throw new IllegalStateException("Tired of casting this value " + value + " to a number and I give up.");
}
}
} else {
throw new IllegalStateException("Tried to get non-integer value as integer from KVStore. Type of value " + value + " is " + value.getClass().getName());
}
}
@Override
public Double getAsDouble(final String key) {
Object value = this.get(key);
if (value == null) {
return null;
} else if (value instanceof Double) {
return (Double) value;
} else if (value instanceof String) {
return Double.valueOf((String) value);
} else if (value instanceof Integer) {
return Double.parseDouble(value + "");
} else if (value instanceof Long) {
return Double.parseDouble(value + "");
} else {
throw new IllegalStateException("Tried to get non-double value as double from KVStore.");
}
}
@Override
public Long getAsLong(final String key) {
Object value = this.get(key);
if (value == null) {
return null;
} else if (value instanceof Long) {
return (Long) value;
} else if (value instanceof String) {
return Long.valueOf((String) value);
} else {
throw new IllegalStateException("Tried to get non-long value as long from KVStore.");
}
}
@Override
public Short getAsShort(final String key) {
Object value = this.get(key);
if (value == null) {
return null;
} else if (value instanceof Short) {
return (Short) value;
} else if (value instanceof String) {
return Short.valueOf((String) value);
} else {
throw new IllegalStateException("Tried to get non-short value as short from KVStore.");
}
}
@Override
public Byte getAsByte(final String key) {
Object value = this.get(key);
if (value == null) {
return null;
} else if (value instanceof Byte) {
return (Byte) value;
} else if (value instanceof String) {
return Byte.valueOf((String) value);
} else {
throw new IllegalStateException("Tried to get non-byte value as byte from KVStore.");
}
}
@Override
public <T> T getAsObject(final String key, final Class<T> objectClass) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return objectClass.getConstructor().newInstance(this.get(key));
}
@Override
public byte[] getAsBytes(final String columnClassifierObject) {
return (byte[]) this.get(columnClassifierObject);
}
@Override
public List<Double> getAsDoubleList(final String key) {
return this.getAsDoubleList(key, DEFAULT_LIST_SEP);
}
@Override
public List<Double> getAsDoubleList(final String key, final String separator) {
if (this.get(key) == null) {
return new LinkedList<>();
}
return Stream.of(this.getAsString(key).split(separator)).map(Double::valueOf).collect(Collectors.toList());
}
@Override
public List<Integer> getAsIntList(final String key) {
return this.getAsIntList(key, DEFAULT_LIST_SEP);
}
@Override
public List<Integer> getAsIntList(final String key, final String separator) {
return Stream.of(this.getAsString(key).split(separator)).map(Integer::valueOf).collect(Collectors.toList());
}
@Override
public List<String> getAsStringList(final String key) {
return this.getAsStringList(key, DEFAULT_LIST_SEP);
}
@Override
public List<String> getAsStringList(final String key, final String separator) {
return Stream.of(this.getAsString(key).split(separator)).map(this::trimString).collect(Collectors.toList());
}
@Override
public List<Boolean> getAsBooleanList(final String key) {
return this.getAsBooleanList(key, DEFAULT_LIST_SEP);
}
@Override
public List<Boolean> getAsBooleanList(final String key, final String separator) {
return Stream.of(this.getAsString(key).split(separator)).map(Boolean::valueOf).collect(Collectors.toList());
}
@Override
public File getAsFile(final String key) {
Object value = this.get(key);
if (value instanceof File) {
return (File) value;
} else if (value instanceof String) {
return new File((String) value);
} else {
throw new IllegalStateException("Cannot return value as a file if it is not of that type.");
}
}
/**
* Takes a String, trims and returns it.
* @param x The string to be trimmed.
* @return The trimmed string.
*/
private String trimString(final String x) {
return x.trim();
}
/**
* Reads a KVStore from a string description.
*
* @param kvDescription
* The string description of the kv store.
*/
public void readKVStoreFromDescription(final String kvDescription) {
String[] pairSplit = kvDescription.trim().split(";");
for (String kvPair : pairSplit) {
String[] kvSplit = kvPair.trim().split("=");
try {
if (kvSplit.length == 2) {
this.put(kvSplit[0], kvSplit[1]);
} else {
this.put(kvSplit[0], "");
}
} catch (Exception e) {
LOGGER.error("Could not read kv store from string description", e);
}
}
}
@Override
public boolean matches(final Map<String, String> selection) {
boolean doesNotMatchAllSelectionCriteria = selection.entrySet().stream().anyMatch(x -> {
boolean isEqual = this.getAsString(x.getKey()).equals(x.getValue());
if (!x.getValue().contains("*")) {
return !x.getValue().equals(this.getAsString(x.getKey()));
}
String[] exprSplit = x.getValue().split("\\*");
String currentValue = x.getValue();
boolean matchesPattern = true;
for (int i = 0; i < exprSplit.length; i++) {
if (i == 0 && !x.getValue().startsWith("*") && !currentValue.startsWith(exprSplit[i])) {
matchesPattern = false;
}
if (currentValue.contains(exprSplit[i])) {
currentValue = currentValue.replaceFirst("(" + exprSplit[i] + ")", "#$#");
currentValue = currentValue.split("#$#")[1];
} else {
matchesPattern = false;
}
if (i == (exprSplit.length - 1) && !x.getValue().endsWith("*") && !currentValue.endsWith(exprSplit[i])) {
matchesPattern = false;
}
if (!matchesPattern) {
break;
}
}
return !isEqual && !matchesPattern;
});
return !doesNotMatchAllSelectionCriteria;
}
@Override
public void project(final String[] filterKeys) {
Set<String> keysToKeep = Arrays.stream(filterKeys).collect(Collectors.toSet());
Collection<String> keysToRemove = SetUtil.difference(this.keySet(), keysToKeep);
this.removeAll(keysToRemove.toArray(new String[] {}));
}
@Override
public void removeAll(final String[] removeKeys) {
Set<String> keysToRemove = Arrays.stream(removeKeys).collect(Collectors.toSet());
for (String key : keysToRemove) {
this.remove(key);
}
}
@Override
public void filter(final Map<String, IKVFilter> filterMap) {
filterMap.entrySet().stream().forEach(x -> this.filter(x.getKey(), x.getValue()));
}
@Override
public void filter(final String key, final IKVFilter filter) {
if (!this.containsKey(key)) {
return;
}
this.put(key, filter.filter(this.get(key)));
}
/**
* Serializes the key value store to a file with the given {@code fileName}.
*
* @param fileName
* The name of the file, the key value store shall be serialized to.
* @throws IOException
*/
public void serializeTo(final String fileName) throws IOException {
this.serializeTo(new File(fileName));
}
/**
* Serializes the key value store to the {@code file} with the given {@code fileName}.
*
* @param fileName
* The name of the file, the key value store shall be serialized to.
* @throws IOException
*/
public void serializeTo(final File file) throws IOException {
if (file.getParent() != null) {
file.getParentFile().mkdirs();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(this.toString());
}
}
@Override
public void merge(final String[] fieldKeys, final String separator, final String newKey) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String fieldKey : fieldKeys) {
if (first) {
first = false;
} else {
sb.append(separator);
}
sb.append(this.getAsString(fieldKey));
this.remove(fieldKey);
}
this.put(newKey, sb.toString());
}
@Override
public void prefixAllKeys(final String prefix) {
Set<String> keySet = new HashSet<>(this.keySet());
for (String key : keySet) {
Object value = this.get(key);
this.remove(key);
this.put(prefix + key, value);
}
}
@Override
public void renameKey(final String key, final String newKeyName) {
if (this.containsKey(key)) {
this.put(newKeyName, this.get(key));
this.remove(key);
}
}
/**
* @return Get the collection this KVStore belongs to.
*/
public KVStoreCollection getCollection() {
return this.collection;
}
/**
* Assigns the KVStore to a KVStoreCollection.
*
* @param collection
* The collection this KVStore belongs to.
*/
public void setCollection(final KVStoreCollection collection) {
this.collection = collection;
}
/**
* Allows to get a string representation of this KVStore incorporating only key value pairs for the named
*
* @param projectionFilter
* @return
*/
public String getStringRepresentation(final String[] projectionFilter) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String filter : projectionFilter) {
if (first) {
first = false;
} else {
sb.append(";");
}
sb.append(filter + "=" + this.getAsString(filter));
}
return sb.toString();
}
@Override
public String toString() {
return this.getStringRepresentation(this.keySet().toArray(new String[] {}));
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(final Object obj) {
return super.equals(obj);
}
@Override
public boolean isNull(final String key) {
return (this.get(key) == null || this.getAsString(key).equals("null"));
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/KVStoreCollection.java
|
package ai.libs.jaicore.basic.kvstore;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.api4.java.datastructure.kvstore.IKVFilter;
import org.api4.java.datastructure.kvstore.IKVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.FileUtil;
import ai.libs.jaicore.basic.Maps;
import ai.libs.jaicore.basic.StatisticsUtil;
import ai.libs.jaicore.basic.sets.SetUtil;
public class KVStoreCollection extends LinkedList<IKVStore> {
/** Logger for controlled output. */
private static final Logger logger = LoggerFactory.getLogger(KVStoreCollection.class);
/** Automatically generated serial version UID. */
private static final long serialVersionUID = -4198481782449606136L;
private static final String LABEL_GROUP_SIZE = "GROUP_SIZE";
public enum EGroupMethod {
AVG, AVG_TRIMMED, MIN, MAX, MAJORITY, MINORITY, LIST, ADD;
public static EGroupMethod getStandardGroupingHandler() {
return EGroupMethod.LIST;
}
}
private static final EGroupMethod STANDARD_GROUPING_HANDLER = EGroupMethod.LIST;
/* META data */
private static final String FIELD_COLLECTIONID = "collectionID";
private final KVStore metaData = new KVStore();
public KVStoreCollection() {
}
public KVStoreCollection(final String taskChunkDescription) {
this.readFrom(taskChunkDescription);
}
public KVStoreCollection(final List<IKVStore> other) {
this.addAll(other);
}
public KVStoreCollection(final File file) {
if (file.isDirectory()) {
this.setCollectionID(file.getName());
for (File subFile : file.listFiles()) {
if (subFile.isFile()) {
try (BufferedReader br = new BufferedReader(new FileReader(subFile))) {
String line;
while ((line = br.readLine()) != null) {
KVStore kvStore = new KVStore(line);
kvStore.setCollection(this);
this.add(kvStore);
}
} catch (Exception e) {
logger.error("An exception occurred while parsing the directory collecting the chunk: {}", subFile, e);
}
} else {
try {
this.readFrom(FileUtil.readFileAsString(file));
} catch (Exception e) {
logger.error("An exception occurred while reading the chunk from the given file: {}", subFile, e);
}
}
}
}
}
public KVStoreCollection select(final Map<String, String> selection) {
KVStoreCollection selectedCollection = new KVStoreCollection();
for (IKVStore store : this) {
if (store.matches(selection)) {
selectedCollection.add(store);
}
}
return selectedCollection;
}
public KVStoreCollection selectContained(final Map<String, Collection<String>> containsSelect, final boolean or) {
KVStoreCollection selectedCollection = new KVStoreCollection();
for (IKVStore store : this) {
long count = containsSelect.entrySet().stream().filter(x -> x.getValue().contains(store.getAsString(x.getKey()))).count();
if ((or && count > 0) || (!or && count == containsSelect.size())) {
selectedCollection.add(store);
}
}
return selectedCollection;
}
public KVStoreCollection filter(final String[] filterKeys) {
KVStoreCollection filteredCollection = new KVStoreCollection();
for (IKVStore store : this) {
store.project(filterKeys);
filteredCollection.add(store);
}
return filteredCollection;
}
/** (De-)Serialization handles */
public void readFrom(final String chunkDescription) {
String[] lines = chunkDescription.split("\n");
if (lines.length < 1) {
throw new IllegalArgumentException("Invalid format of chunk description");
}
boolean first = true;
for (String line : lines) {
if (line.trim().equals("") || line.trim().startsWith("#")) {
continue;
}
if (first) {
// first line in chunk description being no white line nor comment
// such a line must carry all the meta information of the chunk!
first = false;
this.metaData.readKVStoreFromDescription(line);
} else {
KVStore task = new KVStore(line);
task.setCollection(this);
this.add(task);
}
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.metaData.toString() + "\n");
for (IKVStore t : this) {
sb.append(t.toString() + "\n");
}
return sb.toString();
}
public void removeAny(final String value) {
this.removeAny(new String[] { value }, true);
}
public void removeAny(final String[] value, final boolean or) {
List<IKVStore> tasksToRemove = new LinkedList<>();
for (IKVStore t : this) {
if (or) {
for (String v : value) {
if (t.toString().contains(v)) {
tasksToRemove.add(t);
break;
}
}
} else {
throw new UnsupportedOperationException("Not yet implemented");
}
}
this.removeAll(tasksToRemove);
}
public void removeAny(final Map<String, String> condition, final boolean or) {
if (or) {
this.removeIf(t -> {
for (Entry<String, String> entry : condition.entrySet()) {
String val = t.getAsString(entry.getKey());
if (val == null && entry.getValue() == null || val != null && val.equals(entry.getValue())) {
return true;
}
}
return false;
});
} else {
this.removeIf(t -> {
for (Entry<String, String> entry : condition.entrySet()) {
if (!t.getAsString(entry.getKey()).equals(entry.getValue())) {
return false;
}
}
return true;
});
}
}
public void removeAnyContained(final Map<String, Collection<String>> condition, final boolean or) {
if (or) {
this.removeIf(t -> {
for (Entry<String, Collection<String>> entry : condition.entrySet()) {
String val = t.getAsString(entry.getKey());
if (val == null && (entry.getValue() == null || entry.getValue().isEmpty()) || val != null && entry.getValue().contains(val)) {
return true;
}
}
return false;
});
} else {
this.removeIf(t -> {
for (Entry<String, Collection<String>> entry : condition.entrySet()) {
if (!entry.getValue().contains(t.getAsString(entry.getKey()))) {
return false;
}
}
return true;
});
}
}
public void removeGroupsIfNotAtLeastWithSize(final int size) {
Map<String, String> groupSizeCondition = new HashMap<>();
for (int i = 1; i < size; i++) {
groupSizeCondition.put(LABEL_GROUP_SIZE, "" + i);
this.removeAny(groupSizeCondition, true);
}
}
public void removeGroupsIfNotAtLeastWithSizeButOne(final int size, final String[] groupingKeys) {
Map<String, String> groupSizeCondition = new HashMap<>();
for (int i = 1; i < size; i++) {
logger.debug("Remove any groups that dont have at least {} entries.", (i + 1));
int currentMinLength = i;
KVStoreCollection group = new KVStoreCollection(this.toString());
group.renameKey(LABEL_GROUP_SIZE, "size");
group = group.group(groupingKeys, new HashMap<>());
for (IKVStore t : group) {
List<Integer> sizeList = t.getAsIntList("size", ",").stream().filter(x -> x > currentMinLength).collect(Collectors.toList());
logger.debug("{} {} {}", currentMinLength, sizeList, t.getAsIntList("size", ","));
if (sizeList.size() > 0) {
for (String groupingKey : groupingKeys) {
groupSizeCondition.put(groupingKey, t.getAsString(groupingKey));
}
groupSizeCondition.put(LABEL_GROUP_SIZE, "" + i);
logger.debug("{}", groupSizeCondition);
this.removeAny(groupSizeCondition, false);
}
}
}
}
public void renameKey(final String keyName, final String newKeyName) {
for (IKVStore t : this) {
t.renameKey(keyName, newKeyName);
}
}
public KVStoreCollection group(final String[] groupingKeys, final Map<String, EGroupMethod> groupingHandler) {
KVStoreCollection tempCollection = new KVStoreCollection();
tempCollection.setCollectionID(this.getCollectionID());
Map<String, List<IKVStore>> groupedTasks = new HashMap<>();
for (IKVStore t : this) {
StringBuilder sb = new StringBuilder();
for (String key : groupingKeys) {
sb.append(t.getAsString(key) + "#");
}
List<IKVStore> groupedTaskList = groupedTasks.get(sb.toString());
if (groupedTaskList == null) {
groupedTaskList = new LinkedList<>();
groupedTasks.put(sb.toString(), groupedTaskList);
}
groupedTaskList.add(t);
}
for (Entry<String, List<IKVStore>> groupedTaskEntry : groupedTasks.entrySet()) {
List<IKVStore> groupedTaskList = groupedTaskEntry.getValue();
IKVStore groupedTask = new KVStore(groupedTaskList.get(0));
groupedTask.put(LABEL_GROUP_SIZE, groupedTaskList.size());
Map<String, List<Object>> values = new HashMap<>();
for (IKVStore t : groupedTaskList) {
for (Entry<String, Object> e : t.entrySet()) {
boolean containedInGrouping = false;
for (String groupingKey : groupingKeys) {
if (groupingKey.equals(e.getKey())) {
containedInGrouping = true;
break;
}
}
if (containedInGrouping) {
continue;
}
List<Object> objectList = values.get(e.getKey());
if (objectList == null) {
objectList = new LinkedList<>();
values.put(e.getKey(), objectList);
}
objectList.add(e.getValue());
}
}
for (Entry<String, List<Object>> valueEntry : values.entrySet()) {
EGroupMethod groupingMethod = groupingHandler.get(valueEntry.getKey());
if (groupingMethod == null) {
groupingMethod = STANDARD_GROUPING_HANDLER;
}
Object value = null;
switch (groupingMethod) {
case AVG_TRIMMED:
case AVG:
List<Double> valueList = valueEntry.getValue().stream().map(x -> Double.valueOf(x.toString())).collect(Collectors.toList());
if (groupingMethod == EGroupMethod.AVG_TRIMMED && valueList.size() > 5) {
for (int i = 0; i < 2; i++) {
double min = valueList.stream().min(Double::compare).get();
double max = valueList.stream().max(Double::compare).get();
valueList.remove(min);
valueList.remove(max);
}
}
groupedTask.put(valueEntry.getKey() + "_stdDev", StatisticsUtil.standardDeviation(valueList));
groupedTask.put(valueEntry.getKey() + "_max", StatisticsUtil.max(valueList));
groupedTask.put(valueEntry.getKey() + "_min", StatisticsUtil.min(valueList));
groupedTask.put(valueEntry.getKey() + "_var", StatisticsUtil.variance(valueList));
groupedTask.put(valueEntry.getKey() + "_sum", StatisticsUtil.sum(valueList));
groupedTask.put(valueEntry.getKey() + "_list", SetUtil.implode(valueList, ","));
value = StatisticsUtil.mean(valueList);
break;
case MIN:
value = StatisticsUtil.min(valueEntry.getValue().stream().map(x -> Double.valueOf(x.toString())).collect(Collectors.toList()));
break;
case MAX:
value = StatisticsUtil.max(valueEntry.getValue().stream().map(x -> Double.valueOf(x.toString())).collect(Collectors.toList()));
break;
case MINORITY:
value = this.frequentObject(valueEntry.getValue(), false);
break;
case MAJORITY:
value = this.frequentObject(valueEntry.getValue(), true);
break;
case ADD:
value = StatisticsUtil.sum(valueEntry.getValue().stream().map(x -> Double.valueOf(x.toString())).collect(Collectors.toList()));
break;
default:
case LIST:
value = SetUtil.implode(valueEntry.getValue(), ",");
break;
}
groupedTask.put(valueEntry.getKey(), value);
}
tempCollection.add(groupedTask);
}
return new KVStoreCollection(tempCollection.toString());
}
/**
* Searches for the most or least frequent object within a list.
*
* @param top If set to true most frequent object is returned otherwise the least frequent.
* @return The most frequent or least frequent object.
*/
private Object frequentObject(final List<Object> listOfObjects, final boolean top) {
Map<Object, Integer> counterMap = new HashMap<>();
for (Object v : listOfObjects) {
Maps.increaseCounterInMap(counterMap, v);
}
Object frequentObject = null;
for (Entry<Object, Integer> counterMapEntry : counterMap.entrySet()) {
if (frequentObject == null || (top && counterMap.get(counterMapEntry.getKey()) > counterMap.get(frequentObject)) || (!top && counterMap.get(counterMapEntry.getKey()) < counterMap.get(frequentObject))) {
frequentObject = counterMapEntry.getKey();
}
}
return frequentObject;
}
public void merge(final String[] fieldKeys, final String separator, final String newFieldName) {
for (IKVStore t : this) {
t.merge(fieldKeys, separator, newFieldName);
}
}
public void project(final String[] keepKeys) {
this.metaData.project(keepKeys);
for (IKVStore t : this) {
t.project(keepKeys);
}
}
public void projectRemove(final String... removeKeys) {
this.metaData.removeAll(removeKeys);
for (IKVStore t : this) {
t.removeAll(removeKeys);
}
}
public void applyFilter(final Map<String, IKVFilter> filterMap) {
this.metaData.filter(filterMap);
for (IKVStore t : this) {
t.filter(filterMap);
}
}
public void applyFilter(final String keyName, final IKVFilter filter) {
Map<String, IKVFilter> filterMap = new HashMap<>();
filterMap.put(keyName, filter);
this.applyFilter(filterMap);
}
public void mergeTasks(final KVStore other, final Map<String, String> combineMap) {
for (IKVStore t : this) {
boolean equals = true;
for (Entry<String, String> combineEntry : combineMap.entrySet()) {
if (!t.containsKey(combineEntry.getKey()) || !other.containsKey(combineEntry.getValue()) || !t.getAsString(combineEntry.getKey()).equals(other.getAsString(combineEntry.getValue()))) {
equals = false;
break;
}
}
if (!equals) {
continue;
}
t.putAll(other);
}
}
public String getCollectionID() {
return this.metaData.getAsString(FIELD_COLLECTIONID);
}
public void setCollectionID(final String collectionID) {
this.metaData.put(FIELD_COLLECTIONID, collectionID);
}
public void serializeTo(final File file) throws IOException {
this.serializeTo(file, false);
}
public void serializeTo(final File file, final boolean append) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, append))) {
bw.write(this.toString());
}
}
public KVStoreCollection group(final String... groupingKeys) {
return this.group(groupingKeys, new HashMap<>());
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof KVStoreCollection)) {
return false;
}
KVStoreCollection other = (KVStoreCollection) obj;
if (new EqualsBuilder().append(this.metaData, other.metaData).isEquals()) {
return super.equals(other);
} else {
return false;
}
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.metaData).append(super.hashCode()).toHashCode();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/KVStoreCollectionOneLayerPartition.java
|
package ai.libs.jaicore.basic.kvstore;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.api4.java.datastructure.kvstore.IKVStore;
import ai.libs.jaicore.logging.ToJSONStringUtil;
/**
* Automatically partitions a KVStoreCollection according to the values of the partitioning key when KVStores or KVStoreCollections are added.
*
* @author mwever
*/
public class KVStoreCollectionOneLayerPartition implements Iterable<Entry<String, KVStoreCollection>> {
/* Key for partitioning. */
private final String partitionKey;
/* data store */
private Map<String, KVStoreCollection> data;
/**
* Creates an empty two layer {@link KVStoreCollection} partition.
*
* @param partitionKey The field name for the partitioning key.
* @param collection The {@link KVStoreCollection} to initialize this partition.
*/
public KVStoreCollectionOneLayerPartition(final String partitionKey, final KVStoreCollection collection) {
this(partitionKey);
this.addAll(collection);
}
/**
* Creates an empty two layer KVStorCollection partition.
*
* @param partitionKey The field name for the first level partition.
*/
public KVStoreCollectionOneLayerPartition(final String firstLevelKey) {
this.partitionKey = firstLevelKey;
this.data = new HashMap<>();
}
public Map<String, KVStoreCollection> getData() {
return this.data;
}
/**
* Adds a signle {@link KVStore} to this {@link KVStoreCollectionOneLayerPartition}.
* @param store
*/
public void add(final IKVStore store) {
this.data.computeIfAbsent(store.getAsString(this.partitionKey), t -> new KVStoreCollection()).add(store);
}
/**
* Adds an entire {@link KVStoreCollection to this {@link KVStoreCollectionOneLayerPartition}.
* @param collection The collection to be added to this partition.
*/
public void addAll(final KVStoreCollection collection) {
collection.forEach(this::add);
}
/**
* @return The set of entries of this partition.
*/
public Set<Entry<String, KVStoreCollection>> entrySet() {
return this.data.entrySet();
}
@Override
public Iterator<Entry<String, KVStoreCollection>> iterator() {
return this.data.entrySet().iterator();
}
@Override
public String toString() {
Map<String, Object> fields = new HashMap<>();
fields.put("partitionKey", this.partitionKey);
fields.put("data", this.data);
return ToJSONStringUtil.toJSONString(fields);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/KVStoreCollectionTwoLayerPartition.java
|
package ai.libs.jaicore.basic.kvstore;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.api4.java.datastructure.kvstore.IKVStore;
/**
* Automatically partitions a KVStoreCollection in a two-layered fashion according to a first and second level key when KVStores or KVStoreCollections are added.
*
* @author mwever
*/
public class KVStoreCollectionTwoLayerPartition implements Iterable<Entry<String, Map<String, KVStoreCollection>>> {
/* Keys for partitioning. */
private final String firstLayerKey;
private final String secondLayerKey;
/* Data store. */
private Map<String, Map<String, KVStoreCollection>> data;
/**
* Creates an empty two layer {@link KVStoreCollection} partition.
*
* @param firstLayerKey The field name for the first level partition.
* @param secondLayerKey The field name for the second level partition.
* @param collection The {@link KVStoreCollection} to initialize this two-layer partition.
*/
public KVStoreCollectionTwoLayerPartition(final String firstLayerKey, final String secondLayerKey, final KVStoreCollection collection) {
this(firstLayerKey, secondLayerKey);
this.addAll(collection);
}
/**
* Creates an empty two layer KVStorCollection partition.
*
* @param firstLevelKey The field name for the first level partition.
* @param secondLevelKey The field name for the second level partition.
*/
public KVStoreCollectionTwoLayerPartition(final String firstLevelKey, final String secondLevelKey) {
this.firstLayerKey = firstLevelKey;
this.secondLayerKey = secondLevelKey;
this.data = new HashMap<>();
}
public Map<String, Map<String, KVStoreCollection>> getData() {
return this.data;
}
/**
* Adds a signle {@link KVStore} to this {@link KVStoreCollectionTwoLayerPartition}.
* @param store
*/
public void add(final IKVStore store) {
/* First ensure that nested maps contain the required keys and KVStoreCollection respectively. */
String firstLevelValue = store.getAsString(this.firstLayerKey);
String secondLevelValue = store.getAsString(this.secondLayerKey);
if (!this.data.containsKey(firstLevelValue)) {
Map<String, KVStoreCollection> secondLevelMap = new HashMap<>();
secondLevelMap.put(secondLevelValue, new KVStoreCollection());
this.data.put(firstLevelValue, secondLevelMap);
} else if (!this.data.get(firstLevelValue).containsKey(secondLevelValue)) {
this.data.get(firstLevelValue).put(secondLevelValue, new KVStoreCollection());
}
this.data.get(firstLevelValue).get(secondLevelValue).add(store);
}
/**
* Adds an entire {@link KVStoreCollection to this {@link KVStoreCollectionTwoLayerPartition}.
* @param collection The collection to be added to this partition.
*/
public void addAll(final KVStoreCollection collection) {
collection.forEach(this::add);
}
/**
* @return The set of entries of this partition.
*/
public Set<Entry<String, Map<String, KVStoreCollection>>> entrySet() {
return this.data.entrySet();
}
@Override
public Iterator<Entry<String, Map<String, KVStoreCollection>>> iterator() {
return this.data.entrySet().iterator();
}
/**
* @return The key name that is used to do the partition for the first layer.
*/
public String getFirstLayerKey() {
return this.firstLayerKey;
}
/**
* @return The key name that is used to do the partition for the second layer.
*/
public String getSecondLayerKey() {
return this.secondLayerKey;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/KVStoreSequentialComparator.java
|
package ai.libs.jaicore.basic.kvstore;
import java.util.Comparator;
import org.api4.java.datastructure.kvstore.IKVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This comparator may be used to sort KVStore objects in a KVStoreCollection according to the values for the specified keys.
* The KVStores are then compared successively for the provided keys and ordered in ascending order.
*
* @author mwever
*/
public class KVStoreSequentialComparator implements Comparator<IKVStore> {
private static final Logger LOGGER = LoggerFactory.getLogger(KVStoreSequentialComparator.class);
private final String[] sortKeys;
/**
* Default c'tor initializing the comparator for a set of keys for which the kvstores are to be sorted.
*
* @param sortKeys The array of keys for which to sort the KVStoreCollection.
*/
public KVStoreSequentialComparator(final String... sortKeys) {
this.sortKeys = sortKeys;
}
@Override
public int compare(final IKVStore arg0, final IKVStore arg1) {
for (String sortKey : this.sortKeys) {
Integer compare = null;
try {
compare = arg0.getAsInt(sortKey).compareTo(arg1.getAsInt(sortKey));
} catch (Exception e) {
try {
compare = arg0.getAsLong(sortKey).compareTo(arg1.getAsLong(sortKey));
} catch (Exception e1) {
try {
compare = arg0.getAsString(sortKey).compareTo(arg1.getAsString(sortKey));
} catch (Exception e2) {
LOGGER.warn("The values of the key {} are neither int nor long nor string. This type of value is thus not supported for sorting and the key is skipped.", sortKey);
}
}
}
if (compare == null || compare == 0) {
continue;
}
return compare;
}
return 0;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/KVStoreStatisticsUtil.java
|
package ai.libs.jaicore.basic.kvstore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.api4.java.datastructure.kvstore.IKVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.StatisticsUtil;
/**
* This util may be used to compute some statistics and carrying out significance tests.
* In particular implementations for three different significance tests are provided:
*
* t-test - requirements: data distribution must follow a normal distribution and it must be sampled independently from the two populations.
* Wilcoxon signed-rank test - requirements: sample variables d_i = x_i,1 - x_i,2 have to be iid and symmetric.
* MannWhitneyU - requirements: all observations from both groups are independent of each other, responses are (at least) ordinal, i.e. one can say which one is better.
*
* @author mwever
*/
public class KVStoreStatisticsUtil {
/* logging */
private static final Logger logger = LoggerFactory.getLogger(KVStoreStatisticsUtil.class);
/* default key name of the best annotation */
private static final String DEFAULT_OUTPUT_BEST = "best";
private static final String DEFAULT_OUTPUT_RANK = "rank";
private KVStoreStatisticsUtil() {
/* Private c'tor to prevent instanstantiation of this class. */
}
/**
* For each setting this method finds the best mean value for setting <code>setting</code> among all the <code>sampleIDs</code> averaging the <code>sampledValues</code> (minimization).
*
* @param collection The collection of KVStores.
* @param setting The field name of the setting description, e.g. dataset.
* @param sampleID The field name of the ids for the different populations, e.g. algorithm.
* @param sampledValues The field name of the values sampled from the populations, e.g. error rates.
*/
public static void best(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues) {
best(collection, setting, sampleID, sampledValues, DEFAULT_OUTPUT_BEST);
}
public static void rank(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues) {
rank(collection, setting, sampleID, sampledValues, DEFAULT_OUTPUT_RANK);
}
public static void rank(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues, final String output) {
rank(collection, setting, sampleID, sampledValues, output, true);
}
public static void rank(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues, final String output, final boolean minimize) {
KVStoreCollection grouped = new KVStoreCollection(collection);
grouped.group(setting, sampleID);
KVStoreCollectionTwoLayerPartition partition = new KVStoreCollectionTwoLayerPartition(setting, sampleID, grouped);
for (Entry<String, Map<String, KVStoreCollection>> partitionEntry : partition) {
List<IKVStore> competitorList = new LinkedList<>();
partitionEntry.getValue().values().stream().map(x -> x.get(0)).forEach(competitorList::add);
Collections.sort(competitorList, (o1, o2) -> (minimize) ? Double.compare(StatisticsUtil.mean(o1.getAsDoubleList(sampledValues)), StatisticsUtil.mean(o2.getAsDoubleList(sampledValues)))
: Double.compare(StatisticsUtil.mean(o2.getAsDoubleList(sampledValues)), StatisticsUtil.mean(o1.getAsDoubleList(sampledValues))));
for (int i = 0; i < competitorList.size(); i++) {
competitorList.get(i).put(output, (i + 1));
}
}
}
/**
* For each setting this method finds the best mean value for setting <code>setting</code> among all the <code>sampleIDs</code> averaging the <code>sampledValues</code> (minimization).
*
* @param collection The collection of KVStores.
* @param setting The field name of the setting description, e.g. dataset.
* @param sampleID The field name of the ids for the different populations, e.g. algorithm.
* @param sampledValues The field name of the values sampled from the populations, e.g. error rates.
* @param output The name of the field where to store the result to.
* @param minimize Whether minimum is better or not.
*/
public static void best(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues, final String output, final boolean minimize) {
Set<String> availableSampleIDs = collection.stream().map(x -> x.getAsString(sampleID)).collect(Collectors.toSet());
best(collection, setting, sampleID, sampledValues, availableSampleIDs, output, minimize);
}
/**
* For each setting this method finds the best mean value for setting <code>setting</code> among all the <code>sampleIDs</code> averaging the <code>sampledValues</code> (minimization).
*
* @param collection The collection of KVStores.
* @param setting The field name of the setting description, e.g. dataset.
* @param sampleID The field name of the ids for the different populations, e.g. algorithm.
* @param sampledValues The field name of the values sampled from the populations, e.g. error rates.
* @param output The name of the field where to store the result to.
*/
public static void best(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues, final String output) {
best(collection, setting, sampleID, sampledValues, output, true);
}
/**
* For each setting this method finds the best mean value for setting <code>setting</code> among all the <code>sampleIDs</code> averaging the <code>sampledValues</code> (minimization).
*
* @param collection The collection of KVStores.
* @param setting The field name of the setting description, e.g. dataset.
* @param sampleID The field name of the ids for the different populations, e.g. algorithm.
* @param sampledValues The field name of the values sampled from the populations, e.g. error rates.
* @param sampleIDsToConsider The set of sample IDs which are to be considered in the comparison.
* @param output The name of the field where to store the result to.
* @param minimize Whether minimum is better or not.
*/
public static void best(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues, final Set<String> sampleIDsToConsider, final String output, final boolean minimize) {
KVStoreCollection grouped = new KVStoreCollection(collection);
grouped.group(setting, sampleID);
KVStoreCollectionOneLayerPartition partition = new KVStoreCollectionOneLayerPartition(setting, collection);
for (Entry<String, KVStoreCollection> entry : partition) {
OptionalDouble bestValue;
if (minimize) {
bestValue = entry.getValue().stream().filter(x -> sampleIDsToConsider.contains(x.getAsString(sampleID)))
.mapToDouble(x -> (x.get(sampledValues) != null) ? StatisticsUtil.mean(x.getAsDoubleList(sampledValues)) : Double.MAX_VALUE).min();
} else {
bestValue = entry.getValue().stream().filter(x -> sampleIDsToConsider.contains(x.getAsString(sampleID)))
.mapToDouble(x -> (x.get(sampledValues) != null) ? StatisticsUtil.mean(x.getAsDoubleList(sampledValues)) : Double.MIN_VALUE).max();
}
if (bestValue.isPresent()) {
double best = bestValue.getAsDouble();
for (IKVStore store : entry.getValue()) {
if (store.get(sampledValues) != null) {
store.put(output, StatisticsUtil.mean(store.getAsDoubleList(sampledValues)) == best);
} else {
Double surrogateValue = Double.MIN_VALUE;
if (minimize) {
surrogateValue = Double.MAX_VALUE;
}
store.put(output, surrogateValue == best);
}
}
}
}
}
/**
* Computes a 1-to-n Wilcoxon signed rank test to compare a single sample to each other sample of the collection.
* For the significance test a pair-wise signed rank test is used to test the hypothesis whether the two considered
* related samples stem from the same distribution (H_0).
*
* @param collection The collection of KVStores to carry out the wilcoxon signed rank test for.
* @param setting The field name of the setting description for each of which the wilcoxon has to be computed, e.g. dataset.
* @param sampleIDs The field name of the identifier of what is to be compared, e.g. the different approaches.
* @param pairingIndex The field name of the index according to which samples are internally paired, e.g. seed for the random object.
* @param nam)eOfTestPopulation The value of the targetOfComparison field that is to be used as the 1 sample which is compared to the n other samples.
* @param output The field name where to put the results of the significance tests.
*/
public static KVStoreCollection wilcoxonSignedRankTest(final KVStoreCollection collection, final String setting, final String sampleIDs, final String pairingIndex, final String sampledValues, final String nameOfTestPopulation,
final String output) {
KVStoreCollection groupedCollection = new KVStoreCollection(collection);
groupedCollection.group(setting, sampleIDs);
KVStoreCollectionTwoLayerPartition settingAndSampleWisePartition = new KVStoreCollectionTwoLayerPartition(setting, sampleIDs, groupedCollection);
for (Entry<String, Map<String, KVStoreCollection>> settingToSampleWisePartition : settingAndSampleWisePartition) {
/* Description of the ground truth. */
IKVStore onesStore = settingToSampleWisePartition.getValue().get(nameOfTestPopulation).get(0);
if (onesStore == null) {
continue;
}
onesStore.put(output, ESignificanceTestResult.TIE);
Map<String, Double> sampleMapOfOne = toSampleMap(onesStore.getAsStringList(pairingIndex, ","), onesStore.getAsDoubleList(sampledValues, ","));
List<String> mergedSampleIDs = new LinkedList<>(sampleMapOfOne.keySet());
double[] one = new double[mergedSampleIDs.size()];
double meanOne = 0.0;
int counter = 0;
for (String sampleID : mergedSampleIDs) {
if (sampleMapOfOne.containsKey(sampleID)) {
one[counter] = sampleMapOfOne.get(sampleID);
meanOne += one[counter] / sampleMapOfOne.size();
} else {
one[counter] = Double.NaN;
}
counter++;
}
for (Entry<String, KVStoreCollection> sampleData : settingToSampleWisePartition.getValue().entrySet()) {
if (sampleData.getKey().equals(nameOfTestPopulation)) {
continue;
}
IKVStore otherStore = sampleData.getValue().get(0);
Map<String, Double> sampleMapOfOther = toSampleMap(otherStore.getAsStringList(pairingIndex, ","), otherStore.getAsDoubleList(sampledValues, ","));
double[] other = new double[mergedSampleIDs.size()];
double meanOther = 0.0;
for (int i = 0; i < mergedSampleIDs.size(); i++) {
String sampleID = mergedSampleIDs.get(i);
if (sampleMapOfOther.containsKey(sampleID)) {
other[i] = sampleMapOfOther.get(sampleID);
meanOther += other[i] / sampleMapOfOther.size();
} else {
other[i] = Double.NaN;
}
}
if (StatisticsUtil.wilcoxonSignedRankSumTestTwoSided(one, other)) {
if (meanOne < meanOther) {
otherStore.put(output, ESignificanceTestResult.INFERIOR);
} else {
otherStore.put(output, ESignificanceTestResult.SUPERIOR);
}
} else {
otherStore.put(output, ESignificanceTestResult.TIE);
}
}
}
return groupedCollection;
}
/**
* Computes a (pair-wise) 1-to-n MannWhitneyU statistic to compare a single sample from one population to each other sample of the other populations.
* For the significance test the MannWhitneyU test statistic is used to test the hypothesis whether the two considered
* related samples stem from the same distribution (H_0). As a result the tests KVStores have a sig-test result value in the output field. The output
* is to be interpreted as how the other population compares to the test population, if the value is superior the other population is significantly
* better than the tested population and vice versa.
*
* @param collection The collection of KVStores to carry out the MannWhitneyU test for.
* @param setting The field name of the setting description for each of which the MannWhitneyU has to be computed, e.g. dataset.
* @param sampleIDs The field name of the identifier of what is to be compared, e.g. the different approaches.
* @param pairingIndex The field name of the index according to which samples are internally paired, e.g. seed for the random object.
* @param nameOfTestPopulation The value of the targetOfComparison field that is to be used as the 1 sample which is compared to the n other samples.
* @param output The field name where to put the results of the significance tests.
*/
public static void mannWhitneyU(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues, final String nameOfTestPopulation, final String output) {
for (Entry<String, Map<String, KVStoreCollection>> settingWiseEntry : prepareGroupedTwoLayerPartition(collection, setting, sampleID)) {
KVStoreCollection testPopulation = settingWiseEntry.getValue().get(nameOfTestPopulation);
if (testPopulation == null || testPopulation.isEmpty()) {
continue;
}
testPopulation.get(0).put(output, ESignificanceTestResult.TIE);
List<Double> testValues = testPopulation.get(0).getAsDoubleList(sampledValues);
for (Entry<String, KVStoreCollection> otherEntry : settingWiseEntry.getValue().entrySet()) {
if (otherEntry.getKey().equals(nameOfTestPopulation)) {
continue;
}
IKVStore otherStore = otherEntry.getValue().get(0);
List<Double> otherValues = otherStore.getAsDoubleList(sampledValues);
annotateSigTestResult(otherStore, output, StatisticsUtil.mannWhitneyTwoSidedSignificance(testValues, otherValues), StatisticsUtil.mean(otherValues), StatisticsUtil.mean(testValues));
}
}
}
/**
* Computes a t-test for each setting comparing the best population to the others.
*
* @param collection The collection of KVStores.
* @param setting The field name of the setting description, e.g. dataset.
* @param sampleIDs The field name of the ids for the different populations, e.g. algorithm.
* @param sampledValues The field name of the values sampled from the populations, e.g. error rates.
* @param outputFieldName The name of the field where to store the result to.
*/
public static void bestTTest(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues, final String output) {
final String bestOutput = output + "_best";
best(collection, setting, sampleID, sampledValues, bestOutput);
KVStoreCollectionTwoLayerPartition partition = new KVStoreCollectionTwoLayerPartition(setting, sampleID, collection);
for (Entry<String, Map<String, KVStoreCollection>> partitionEntry : partition) {
Optional<Entry<String, KVStoreCollection>> best = partitionEntry.getValue().entrySet().stream().filter(x -> x.getValue().get(0).getAsBoolean(bestOutput)).findFirst();
if (best.isPresent()) {
KVStoreCollection merged = new KVStoreCollection();
partitionEntry.getValue().values().forEach(merged::addAll);
tTest(merged, setting, sampleID, sampledValues, best.get().getValue().get(0).getAsString(sampleID), output);
} else {
logger.warn("No best population available for setting {}", partitionEntry.getKey());
}
}
}
/**
* Carries out a t-test (which requires the tested populations to stem from a normal distribution) to make a pair-wise 1-to-n test.
*
* @param collection The collection of KVStores.
* @param setting The field name of the setting description, e.g. dataset.
* @param sampleID The field name of the ids for the different populations, e.g. algorithm.
* @param sampledValues The field name of the values sampled from the populations, e.g. error rates.
* @param nameOfTestPopulation The value of the targetOfComparison field that is to be used as the 1 sample which is compared to the n other samples.
* @param output The name of the field where to store the result to.
*/
public static void tTest(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues, final String nameOfTestPopulation, final String output) {
KVStoreCollection grouped = new KVStoreCollection(collection);
grouped.group(setting, sampleID);
KVStoreCollectionTwoLayerPartition partition = new KVStoreCollectionTwoLayerPartition(setting, sampleID, grouped);
for (Entry<String, Map<String, KVStoreCollection>> partitionEntry : partition) {
KVStoreCollection testCollection = partitionEntry.getValue().get(nameOfTestPopulation);
if (testCollection == null || testCollection.isEmpty()) {// skip this test as there is no population available to compare to the other populations.
continue;
}
IKVStore testStore = testCollection.get(0);
double testMean = StatisticsUtil.mean(testStore.getAsDoubleList(sampledValues));
annotateSigTestResult(testStore, output, false, 0, 0);
for (Entry<String, KVStoreCollection> comparedEntry : partitionEntry.getValue().entrySet()) {
if (comparedEntry.getKey().equals(nameOfTestPopulation) || comparedEntry.getValue().isEmpty()) { // skip the test population itself.
continue;
}
IKVStore otherStore = comparedEntry.getValue().get(0);
annotateSigTestResult(otherStore, output, StatisticsUtil.twoSampleTTestSignificance(testStore.getAsDoubleList(sampledValues), otherStore.getAsDoubleList(sampledValues)),
StatisticsUtil.mean(otherStore.getAsDoubleList(sampledValues)), testMean);
}
}
}
/**
* This method searches for the best performing KVStores and afterwards projects the collection to the subset of best KVStore per setting.
*
* @param collection The collection of KVStores.
* @param setting The field name of the setting description, e.g. dataset.
* @param sampleID The field name of the ids for the different populations, e.g. algorithm.
* @param sampledValues The field name of the values sampled from the populations, e.g. error rates.
*/
public static void bestFilter(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues) {
bestFilter(collection, setting, sampleID, sampledValues, DEFAULT_OUTPUT_BEST);
}
/**
* This method searches for the best performing KVStores and afterwards projects the collection to the subset of best KVStore per setting.
*
* @param collection The collection of KVStores.
* @param setting The field name of the setting description, e.g. dataset.
* @param sampleID The field name of the ids for the different populations, e.g. algorithm.
* @param sampledValues The field name of the values sampled from the populations, e.g. error rates.
* @param output The name of the field where to store the result to.
*/
public static void bestFilter(final KVStoreCollection collection, final String setting, final String sampleID, final String sampledValues, final String output) {
best(collection, setting, sampleID, sampledValues, output);
List<IKVStore> distinctTasks = new ArrayList<>();
Set<String> consideredKeys = new HashSet<>();
collection.forEach(t -> {
String keyValue = t.getAsString(setting);
if (!consideredKeys.contains(keyValue) && Boolean.TRUE.equals(t.getAsBoolean(output))) {
consideredKeys.add(keyValue);
distinctTasks.add(t);
}
});
collection.clear();
collection.addAll(distinctTasks);
}
/**
* Ensures that the provided KVStoreCollection is grouped according to the two keys and provides a two layer partition of the KVStoreCollection.
*
* @param collection The collection for which to create a partitioning.
* @param firstLayerKey The key name that is used to partition the first layer.
* @param secondLayerKey The key name that is used to partition the second layer.
* @return A partitioning of the given collection with respect to the first and second layer key.
*/
private static KVStoreCollectionTwoLayerPartition prepareGroupedTwoLayerPartition(final KVStoreCollection collection, final String firstLayerKey, final String secondLayerKey) {
KVStoreCollection copy = new KVStoreCollection(collection);
copy.group(firstLayerKey, secondLayerKey);
return new KVStoreCollectionTwoLayerPartition(firstLayerKey, secondLayerKey, copy);
}
/**
* Assigns the resulting flag for the significance test to the store to be annotated.
*
* @param storeToAnnotate The KVStore where the sig test result is meant to be stored.
* @param output The key for the KVStore where to put the result.
* @param sig Whether the result was significantly different.
* @param meanOfStore The mean of the store to be annotated.
* @param meanOfCompared The mean of the store to which storeToAnnotate is compared to.
*/
private static void annotateSigTestResult(final IKVStore storeToAnnotate, final String output, final boolean sig, final double meanOfStore, final double meanOfCompared) {
if (sig) {
if (meanOfStore < meanOfCompared) {
storeToAnnotate.put(output, ESignificanceTestResult.SUPERIOR);
} else {
storeToAnnotate.put(output, ESignificanceTestResult.INFERIOR);
}
} else {
storeToAnnotate.put(output, ESignificanceTestResult.TIE);
}
}
/**
* Convert the two given lists into a mapping. It is assumed that same index belongst to the same mapping.
*
* @param pairingIndices The list of pairing indices, e.g., seeds.
* @param sampledValues The list of sampled values, e.g. measured error rate etc.
* @return A mapping from pairing index to sampled value.
*/
private static Map<String, Double> toSampleMap(final List<String> pairingIndices, final List<Double> sampledValues) {
if (pairingIndices.size() != sampledValues.size()) {
throw new IllegalArgumentException("Number of sample ids deviates from number of sampled values");
}
Map<String, Double> sampleMap = new HashMap<>();
for (int i = 0; i < pairingIndices.size(); i++) {
sampleMap.put(pairingIndices.get(i), sampledValues.get(i));
}
return sampleMap;
}
/**
* Computes a statistic of average rankings for sampleIDs.
*
* @param groupedAll The collection of KVStores to compute the average rank for the respective sampleIDs.
* @param sampleIDs The name of the field distinguishing the different samples.
* @param rank The name of the field containing the rank information.
* @return
*/
public static Map<String, DescriptiveStatistics> averageRank(final KVStoreCollection groupedAll, final String sampleIDs, final String rank) {
Map<String, DescriptiveStatistics> averageRanks = new HashMap<>();
for (IKVStore s : groupedAll) {
DescriptiveStatistics stats = averageRanks.get(s.getAsString(sampleIDs));
if (stats == null) {
stats = new DescriptiveStatistics();
averageRanks.put(s.getAsString(sampleIDs), stats);
}
stats.addValue(s.getAsDouble(rank));
}
return averageRanks;
}
public static void bestWilcoxonSignedRankTest(final KVStoreCollection collection, final String setting, final String sampleID, final String pairingIndices, final String sampledValues, final String output) {
String bestField = output + "_best";
KVStoreCollectionOneLayerPartition bestPart = new KVStoreCollectionOneLayerPartition(setting, collection);
bestPart.forEach(x -> best(x.getValue(), setting, sampleID, sampledValues, bestField));
KVStoreCollectionTwoLayerPartition partition = new KVStoreCollectionTwoLayerPartition(setting, sampleID, collection);
for (Entry<String, Map<String, KVStoreCollection>> partitionEntry : partition) {
Optional<Entry<String, KVStoreCollection>> best = partitionEntry.getValue().entrySet().stream().filter(x -> x.getValue().get(0).getAsBoolean(bestField)).findFirst();
if (best.isPresent()) {
KVStoreCollection merged = new KVStoreCollection();
partitionEntry.getValue().values().forEach(merged::addAll);
KVStoreStatisticsUtil.wilcoxonSignedRankTest(merged, setting, sampleID, pairingIndices, sampledValues, best.get().getKey(), output);
}
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/KVStoreUtil.java
|
package ai.libs.jaicore.basic.kvstore;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.api4.java.datastructure.kvstore.IKVStore;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import ai.libs.jaicore.basic.FileUtil;
import ai.libs.jaicore.db.IDatabaseAdapter;
/**
* A util for serializing and deserializing {@link KVStoreCollection}s from and to certain formats.
* For example, one can read in a KVStoreCollection from SQL queries/result sets and csv data or generate
* csv-formatted or latex-formatted data tables.
*
* @author mwever
*/
public class KVStoreUtil {
private static final String DEF_SEP = ";";
private static final String UNDERSCORE = "\\_";
private static final String ESCAPED_UNDERSCORE = "\\\\_";
private KVStoreUtil() {
// prevent instantiation of this util class.
}
public static String kvStoreCollectionToLaTeXTable(final KVStoreCollection kvStoreCollection, final String rowIndex, final String columnIndex, final String cellFormatting) {
return kvStoreCollectionToLaTeXTable(kvStoreCollection, rowIndex, columnIndex, cellFormatting, "");
}
/**
* Transforms a {@link KVStoreCollection} into a LaTeX table (string).
* @param kvStoreCollection The {@link KVStoreCollection} to be transformed.
* @param rowIndex The key which shall be taken as a row index.
* @param columnIndex The key which shall be taken as a column index.
* @param cellFormatting A description of how a cell of the LaTeX table should be formatted.
* @param standardValue A default value for empty entries.
* @return A string representing the data of the {@link KVStoreCollection} in LaTeX formatting.
*/
public static String kvStoreCollectionToLaTeXTable(final KVStoreCollection kvStoreCollection, final String rowIndex, final String columnIndex, final String cellFormatting, final String missingEntry) {
return kvStoreCollectionToTable(kvStoreCollection, rowIndex, columnIndex, cellFormatting).toLaTeX(missingEntry);
}
/**
* Transforms a {@link KVStoreCollection} into a CSV table (string).
* @param kvStoreCollection The {@link KVStoreCollection} to be transformed.
* @param rowIndex The key which shall be taken as a row index.
* @param columnIndex The key which shall be taken as a column index.
* @param cellFormatting A description of how a cell of the CSV table should be formatted.
* @param standardValue A default value for empty entries.
* @return A string representing the data of the {@link KVStoreCollection} in CSV formatting.
*/
public static String kvStoreCollectionToCSVTable(final KVStoreCollection kvStoreCollection, final String rowIndex, final String columnIndex, final String cellFormatting, final String standardValue) {
return kvStoreCollectionToTable(kvStoreCollection, rowIndex, columnIndex, cellFormatting).toCSV(standardValue);
}
/**
* Translates a {@link KVStoreCollection} into a Table object.
* @param kvStoreCollection The collection of kvstores that is to be translated.
* @param rowIndex The key which shall be taken as a row index.
* @param columnIndex The key which shall be taken as a column index.
* @param cellFormatting A description on how a cell of the table should be formatted.
* @param standardValue A default value for empty cells of the table.
* @return A table object representing the KVStoreCollection's data for the column and row indices.
*/
public static Table<String> kvStoreCollectionToTable(final KVStoreCollection kvStoreCollection, final String rowIndex, final String columnIndex, final String cellFormatting) {
Table<String> table = new Table<>();
for (IKVStore store : kvStoreCollection) {
String[] cellFormattingSplit = store.getAsString(cellFormatting).split("#");
List<String> cleanedCellFormatting = Arrays.stream(cellFormattingSplit).filter(x -> !x.equals("")).collect(Collectors.toList());
String rowValue = store.getAsString(rowIndex).replace(UNDERSCORE, ESCAPED_UNDERSCORE);
String columnValue = store.getAsString(columnIndex).replace(UNDERSCORE, ESCAPED_UNDERSCORE);
StringBuilder tableEntryBuilder = new StringBuilder();
for (String cellKey : cleanedCellFormatting) {
if (!store.containsKey(cellKey)) {
tableEntryBuilder.append(cellKey);
} else {
tableEntryBuilder.append(store.getAsString(cellKey));
}
}
table.add(columnValue, rowValue, tableEntryBuilder.toString());
}
return table;
}
/**
* Parses a CSV file with a header line into a KVStoreCollection. Via the commonFields map static key-value pairs can be added to each entry.
*
* @param csvFile The file containing the csv data.
* @param commonFields Map containing static key-value pairs that are added to each {@link IKVStore}.
* @return A collection of {@link IKVStore}s containing the CSV data.
* @throws IOException Thrown if there are issues reading the csv file.
*/
public static KVStoreCollection readFromCSVWithHeader(final File csvFile, final Map<String, String> commonFields) throws IOException {
return readFromCSVWithHeader(csvFile, commonFields, DEF_SEP);
}
/**
* Parses a CSV file with a header line into a KVStoreCollection. Via the commonFields map static key-value pairs can be added to each entry.
*
* @param csvFile The file containing the csv data.
* @param commonFields Map containing static key-value pairs that are added to each {@link IKVStore}.
* @return A collection of {@link IKVStore}s containing the CSV data.
* @throws IOException Thrown if there are issues reading the csv file.
*/
public static KVStoreCollection readFromCSVWithHeader(final File csvFile, final Map<String, String> commonFields, final String separator) throws IOException {
return readFromCSVDataWithHeader(FileUtil.readFileAsList(csvFile), commonFields, separator);
}
/**
* Parses a CSV file with no header line into a KVStoreCollection. Via the commonFields map static key-value pairs can be added to each entry.
*
* @param columns A description of the columns of the csv file.
* @param csvFile The file containing the csv data.
* @param commonFields Map containing static key-value pairs that are added to each {@link IKVStore}.
* @return A collection of {@link IKVStore}s containing the CSV data.
* @throws IOException Thrown if there are issues reading the csv file.
*/
public static KVStoreCollection readFromCSV(final String[] columns, final File csvFile, final Map<String, String> commonFields) throws IOException {
return readFromCSV(columns, csvFile, commonFields, DEF_SEP);
}
/**
* Parses a CSV file with no header line into a KVStoreCollection. Via the commonFields map static key-value pairs can be added to each entry.
*
* @param columns A description of the columns of the csv file.
* @param csvFile The file containing the csv data.
* @param commonFields Map containing static key-value pairs that are added to each {@link IKVStore}.
* @param separator The separator dividing the respective entries.
* @return A collection of {@link IKVStore}s containing the CSV data.
* @throws IOException Thrown if there are issues reading the csv file.
*/
public static KVStoreCollection readFromCSV(final String[] columns, final File csvFile, final Map<String, String> commonFields, final String separator) throws IOException {
return readFromCSVData(FileUtil.readFileAsList(csvFile), columns, commonFields, separator);
}
/**
* Interprets a list of strings as a line-wise csv description and parases this into a {@link KVStoreCollection}. The first line is assumed to contain the columns' names.
*
* @param data The list of CSV-styled strings.
* @param commonFields Map containing static key-value pairs that are added to each {@link IKVStore}.
* @param separator The separator dividing the respective entries.
* @return A collection of {@link IKVStore}s containing the CSV data.
* @throws IOException Thrown if there are issues reading the csv file.
*/
public static KVStoreCollection readFromCSVDataWithHeader(final List<String> data, final Map<String, String> commonFields, final String separator) {
return readFromCSVData(data, data.remove(0).split(separator), commonFields, separator);
}
/**
* Interprets a list of strings as a line-wise csv description and parases this into a {@link KVStoreCollection}.
*
* @param columns A description of the columns of the csv data.
* @param data The list of CSV-styled strings.
* @param commonFields Map containing static key-value pairs that are added to each {@link IKVStore}.
* @param separator The separator dividing the respective entries.
* @return A collection of {@link IKVStore}s containing the CSV data.
* @throws IOException Thrown if there are issues reading the csv file.
*/
public static KVStoreCollection readFromCSVData(final List<String> data, final String[] columns, final Map<String, String> commonFields, final String separator) {
KVStoreCollection kvStoreCollection = new KVStoreCollection();
for (String line : data) {
if (skipLine(line)) {
continue;
}
// read the line as a task
KVStore t = readLine(columns, line, separator);
// additionally store all the common field values
for (Entry<String, String> commonEntry : commonFields.entrySet()) {
t.put(commonEntry.getKey(), commonEntry.getValue());
}
// add to chunk
t.setCollection(kvStoreCollection);
kvStoreCollection.add(t);
}
return kvStoreCollection;
}
private static KVStore readLine(final String[] columns, final String line, final String separator) {
String[] lineSplit = new String[columns.length];
String remainingString = line;
int currentI = 0;
while (remainingString.contains(separator)) {
int nextSepIndex = remainingString.indexOf(separator);
lineSplit[currentI++] = remainingString.substring(0, nextSepIndex);
remainingString = remainingString.substring(nextSepIndex + 1);
}
lineSplit[currentI] = remainingString;
if (lineSplit.length != columns.length) {
throw new IllegalArgumentException("Malformed line in csv file: " + "Number of column heads " + columns.length + " Number of columns in line: " + lineSplit.length + " " + line);
}
KVStore t = new KVStore();
for (int i = 0; i < columns.length; i++) {
t.put(columns[i], lineSplit[i]);
}
return t;
}
private static boolean skipLine(final String line) {
// discard comments starting with # and empty lines
return (line.trim().equals("") || line.trim().startsWith("#"));
}
/**
* Reads the result set of an sql query into a {@link KVStoreCollection}.
* @param rs The result set to be parsed into a {@link KVStoreCollection}.
* @param commonFields A map of key-value pairs that are common to each {@link IKVStore}
* @return A collection of {@link IKVStore}s containing the data of the result set.
* @throws SQLException Thrown, if there were problems regarding the processing of the SQL result set.
*/
public static KVStoreCollection readFromMySQLResultSet(final ResultSet rs, final Map<String, String> commonFields) throws SQLException {
KVStoreCollection kvStoreCollection = new KVStoreCollection();
int n = rs.getMetaData().getColumnCount();
while (rs.next()) {
KVStore t = new KVStore();
t.setCollection(kvStoreCollection);
for (int i = 1; i <= n; i++) {
t.put(rs.getMetaData().getColumnLabel(i), rs.getString(i));
for (Entry<String, String> commonEntry : commonFields.entrySet()) {
t.put(commonEntry.getKey(), commonEntry.getValue());
}
}
kvStoreCollection.add(t);
}
return kvStoreCollection;
}
/**
* Reads the result set of the given sql query into a {@link KVStoreCollection}.
* @param adapter The sql adapter which is to be used to execute the query.
* @param query The result set to be parsed into a {@link KVStoreCollection}.
* @param commonFields A map of key-value pairs that are common to each {@link IKVStore}
* @return A collection of {@link IKVStore}s containing the data of the result set.
* @throws SQLException Thrown, if there were problems regarding the processing of the SQL result set.
*/
public static KVStoreCollection readFromMySQLQuery(final IDatabaseAdapter adapter, final String query, final Map<String, String> commonFields) throws SQLException {
return addCommonFields(new KVStoreCollection(adapter.getResultsOfQuery(query)), commonFields);
}
/**
* Reads all rows of an SQL table into a collection of {@link IKVStore}s where each row corresponds to a IKVStore in this collection.
*
* @param adapter An {@link SQLAdapter} to issue the query to the database.
* @param table The table from which to read in the rows.
* @param commonFields Static key-value pairs which should be added to all read-in {@link IKVStore}s.
* @return
* @throws SQLException
* @throws Exception
*/
public static KVStoreCollection readFromMySQLTable(final IDatabaseAdapter adapter, final String table, final Map<String, String> commonFields) throws SQLException {
return addCommonFields(new KVStoreCollection(adapter.getRowsOfTable(table)), commonFields);
}
private static KVStoreCollection addCommonFields(final KVStoreCollection collection, final Map<String, String> commonFields) {
collection.stream().forEach(x -> x.putAll(commonFields));
return collection;
}
public static KVStoreCollection readFromJson(final JsonNode res) {
if (res instanceof ArrayNode) {
return readFromJsonArray((ArrayNode) res);
} else {
return readFromJsonArray((ArrayNode) res.get(0));
}
}
public static KVStoreCollection readFromJsonArray(final ArrayNode list) {
KVStoreCollection col = new KVStoreCollection();
for (JsonNode node : list) {
col.add(readObjectNodeToKVStore((ObjectNode) node));
}
return col;
}
private static IKVStore readObjectNodeToKVStore(final ObjectNode node) {
Iterator<String> fieldNameIt = node.fieldNames();
IKVStore store = new KVStore();
while (fieldNameIt.hasNext()) {
String fieldName = fieldNameIt.next();
JsonNode value = node.get(fieldName);
switch (value.getNodeType()) {
case BOOLEAN:
store.put(fieldName, value.asBoolean());
break;
case MISSING:
store.put(fieldName, null);
break;
case NULL:
store.put(fieldName, null);
break;
case NUMBER:
store.put(fieldName, value.asText());
break;
case STRING:
store.put(fieldName, value.asText());
break;
default:
store.put(fieldName, value.asText());
break;
}
}
return store;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/ParseKVStoreFromDescriptionFailedException.java
|
package ai.libs.jaicore.basic.kvstore;
public class ParseKVStoreFromDescriptionFailedException extends RuntimeException {
public ParseKVStoreFromDescriptionFailedException(final String msg, final Throwable cause) {
super(msg, cause);
}
public ParseKVStoreFromDescriptionFailedException(final String msg) {
super(msg);
}
public ParseKVStoreFromDescriptionFailedException(final Throwable cause) {
super(cause);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/kvstore/Table.java
|
package ai.libs.jaicore.basic.kvstore;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Allows to arrange data of type V into a matrix structure. Filling the table works providing a column key and a row key.
*
* @author wever
*
* @param <V>
* Datatype of an entry's value.
*/
public class Table<V> {
/** Standard separator for CSV data */
private static final String STANDARD_CSV_SEPARATOR = ";";
/** List of existing column names. */
private final List<String> columnIndex = new LinkedList<>();
/** List of existing row names. */
private final List<String> rowIndex = new LinkedList<>();
/** Data structure mapping rows to columns to data. */
private final Map<String, Map<String, V>> tableData = new HashMap<>();
/**
* Adds a value to the cell identified by the columnIndexValue and the rowIndexValue. Already existing values are overwritten.
*
* @param columnIndexValue
* The name of the column.
* @param rowIndexValue
* The name of the row.
* @param entry
* The entry to add to the table's cell.
*/
public void add(final String columnIndexValue, final String rowIndexValue, final V entry) {
if (!this.rowIndex.contains(rowIndexValue)) {
this.rowIndex.add(rowIndexValue);
}
if (!this.columnIndex.contains(columnIndexValue)) {
this.columnIndex.add(columnIndexValue);
}
Map<String, V> selectedRow = this.tableData.computeIfAbsent(rowIndexValue, t -> new HashMap<>());
selectedRow.put(columnIndexValue, entry);
}
/**
* Converts the table to latex code, empty cells are filled with an empty string.
*
* @return The latex code representing this table.
*/
public String toLaTeX() {
return this.toLaTeX("");
}
/**
* Converts the table to latex code, empty cells are filled with the provided missingEntry String.
*
* @param missingEntry
* Value of empty table cells.
* @return The latex code representing this table.
*/
public String toLaTeX(final String missingEntry) {
StringBuilder sb = new StringBuilder();
sb.append("\\begin{tabular}{");
for (int i = 0; i < this.columnIndex.size() + 1; i++) {
sb.append("l");
}
sb.append("}");
Collections.sort(this.columnIndex);
for (String c : this.columnIndex) {
sb.append("&");
sb.append(c);
}
sb.append("\\\\\n");
for (String r : this.rowIndex) {
sb.append(r);
for (String c : this.columnIndex) {
sb.append(" & ");
Map<String, V> selectRow = this.tableData.get(r);
if (selectRow != null) {
V entry = selectRow.get(c);
if (entry != null) {
sb.append(entry.toString().replace("_", "\\_"));
} else {
sb.append(missingEntry);
}
}
}
sb.append("\\\\\n");
}
sb.append("\\end{tabular}");
return sb.toString();
}
/**
* Converts the table into CSV format.
*
* @param standardValue
* Value to assign for non-existing entries.
* @return String in CSV format describing the data of the table.
*/
public String toCSV(final String standardValue) {
return this.toCSV(STANDARD_CSV_SEPARATOR, standardValue);
}
/**
* Converts the table into CSV format.
*
* @param separator
* The symbol to separate values in the CSV format.
* @param standardValue
* Value to assign for non-existing entries.
* @return String in CSV format describing the data of the table.
*/
public String toCSV(final String separator, final String standardValue) {
StringBuilder sb = new StringBuilder();
Collections.sort(this.rowIndex);
boolean first = true;
for (String c : this.columnIndex) {
if (first) {
first = false;
} else {
sb.append(separator);
}
sb.append(c);
}
sb.append("\n");
for (String r : this.rowIndex) {
first = true;
for (String c : this.columnIndex) {
if (first) {
first = false;
} else {
sb.append(separator);
}
Map<String, V> selectRow = this.tableData.get(r);
if (selectRow != null) {
V entry = selectRow.get(c);
if (entry != null) {
sb.append(entry.toString());
} else {
sb.append(standardValue);
}
}
}
sb.append("\n");
}
return sb.toString();
}
/**
* @return Returns the index of columns of this table.
*/
public List<String> getColumnsOfCSV() {
return this.columnIndex;
}
/**
* @return Returns the index of rows of this table.
*/
public List<String> getRowsOfCSV() {
return this.rowIndex;
}
/**
* Allows to sort the columns of the table.
*
* @param c
* The comparator to use for sorting.
*/
public void sortColumns(final Comparator<? super String> c) {
this.columnIndex.sort(c);
}
/**
* Allows to sort the rows of the table.
*
* @param c
* The comparator to use for sorting.
*/
public void sortRows(final Comparator<? super String> c) {
this.rowIndex.sort(c);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/AWeightedTrigometricDistance.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IDistanceMetric;
public abstract class AWeightedTrigometricDistance implements IDistanceMetric {
/**
* Alpha value that adjusts the parameters {@link a} and {@link b}, that is
* <code>a=cos(alpha)</code> and <code>b=sin(alpha)</code>. It holds, that
* <code>0 <= alpha <= pi/2</code>.
*/
private double alpha;
private double a;
private double b;
protected AWeightedTrigometricDistance(final double alpha) {
super();
// Parameter checks.
if (alpha > Math.PI / 2 || alpha < 0) {
throw new IllegalArgumentException("Parameter alpha has to be between 0 (inclusive) and pi/2 (inclusive).");
}
this.setAlpha(alpha);
}
/**
* Sets the alpha value and adjusts the measurement parameters
* <code>a = cos(alpha)<code> and <code>b = sin(alpha)</code> accordingly.
*
* @param alpha The alpha value, <code>0 <= alpha <= pi/2</code>.
*/
public void setAlpha(final double alpha) {
// Parameter checks.
if (alpha > Math.PI / 2 || alpha < 0) {
throw new IllegalArgumentException("Parameter alpha has to be between 0 (inclusive) and pi/2 (inclusive).");
}
this.alpha = alpha;
this.a = Math.cos(alpha);
this.b = Math.sin(alpha);
}
/**
* Getter for the alpha value. It holds, that <code>0 <= alpha <= pi/2</code>.
*/
public double getAlpha() {
return this.alpha;
}
/**
* Getter for the <code>a</code> parameter. @see #a
*/
public double getA() {
return this.a;
}
/**
* Getter for the <code>a</code> parameter. @see #b
*/
public double getB() {
return this.b;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/ComplexityInvariantDistance.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IDistanceMetric;
import org.api4.java.common.timeseries.ITimeSeriesComplexity;
/**
* Implementation of the Complexity Invariant Distance (CID) measure as
* published in "A Complexity-Invariant Distance Measure for Time Series" by
* Gustavo E.A.P.A. Batista, Xiaoyue Wang and Eamonn J. Keogh.
*
* The authors address the <i>complexity</i> invariant of time series distance
* measures. That is, that time series with higher complexity tend to be further
* apart under current distance measures than pairs of simple objects.
*
* Given a complexity measure <code>c</code> and a distance measure
* <code>d</code>, the Complexity Invariant Distance for the two time series
* <code>A</code> and <code>B</code> is:
* <code>d(A, B) * (max(c(A), c(B)) / min(c(A), c(B)))</code>.
*
* @author fischor
*/
public class ComplexityInvariantDistance implements IDistanceMetric {
/** The distance measure to make complexity invariant. */
private IDistanceMetric distanceMeasure;
/** The complexity measure. */
private ITimeSeriesComplexity complexityMeasure;
/**
* Constructor.
*
* @param distance The distance measure to make complexity invariant.
* @param complexity The complexity measure.
*/
ComplexityInvariantDistance(final IDistanceMetric distanceMeasure, final ITimeSeriesComplexity complexityMeasure) {
// Parameter checks.
if (distanceMeasure == null) {
throw new IllegalArgumentException("The distance measure must not be null.");
}
if (complexityMeasure == null) {
throw new IllegalArgumentException("The complexity measure must not be null.");
}
this.distanceMeasure = distanceMeasure;
this.complexityMeasure = complexityMeasure;
}
@Override
public double distance(final double[] a, final double[] b) {
double complexityA = this.complexityMeasure.complexity(a);
double complexityB = this.complexityMeasure.complexity(b);
double complexityCorrectionFactor = Math.max(complexityA, complexityB) / Math.min(complexityA, complexityB);
return this.distanceMeasure.distance(a, b) * complexityCorrectionFactor;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/ConfusionMetrics.java
|
package ai.libs.jaicore.basic.metric;
/**
* A util class for handling confusion matrix metrics that are solely based on counts of true positives (tp), false positives (fp), true negatives (tn), and false negatives (fn).
*
* @author mwever
*/
public class ConfusionMetrics {
private ConfusionMetrics() {
// hide constructor to preven instantiation
}
/**
* Precision aka. positive predictive value (PPV).
*
* @param tp Count of true positives.
* @param fp Count of false positives.
* @return The positive predictive value (PPV) aka. Precision. 1 iff both tp and fp are 0.
*/
public static double getPrecision(final int tp, final int fp) {
return (tp + fp == 0) ? 1.0 : (double) tp / (tp + fp);
}
/**
* Recall aka. sensitivity aka. hit rate aka. true positive rate (TPR).
*
* @param tp Count of true positives.
* @param fn Count of false negatives.
* @return The recall/sensitivity/hit rate/TPR.
*/
public static double getRecall(final int tp, final int fn) {
return (tp + fn == 0) ? 1.0 : (double) tp / (tp + fn);
}
/**
* Specificity, selectivity, true negative rate (TNR).
*
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @return The specificity/selectivity/TNR
*/
public static double getTrueNegativeRate(final int fp, final int tn) {
return (fp + tn == 0) ? 1.0 : (double) tn / (tn + fp);
}
/**
* Negative predictive value (NPV).
* @param tn Count of true negatives.
* @param fn Count of false negatives.
* @return The NPV.
*/
public static double getNegativePredictiveValue(final int tn, final int fn) {
return (tn + fn == 0) ? 1.0 : (double) tn / (tn + fn);
}
/**
* Miss rate, false negative rate (FNR).
*
* @param tp Count of true positives.
* @param fn Count of false negatives.
* @return The miss rate/FNR.
*/
public static double getFalseNegativeRate(final int tp, final int fn) {
return 1 - getRecall(tp, fn);
}
/**
* Fall-out aka. false positive rate (FPR).
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @return The fall-out, FPR.
*/
public static double getFallOut(final int fp, final int tn) {
return 1 - getTrueNegativeRate(fp, tn);
}
/**
* False discovery rate (FDR)
* @param tp Count of true positives.
* @param fp Count of false positives.
* @return The FDR.
*/
public static double getFalseDiscoveryRate(final int tp, final int fp) {
return 1 - getPrecision(tp, fp);
}
/**
* The false omission rate (FOR).
* @param tn Count of true negatives.
* @param fn Count of false negatives.
* @return The FOR.
*/
public static double getFalseOmissionRate(final int tn, final int fn) {
return 1 - getNegativePredictiveValue(tn, fn);
}
/**
* The prevalence threshold (PT).
*
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives
* @param fn Count of false negatives.
* @return The PT.
*/
public static double getPrevalenceThreshold(final int tp, final int fp, final int tn, final int fn) {
return (Math.sqrt(getRecall(tp, fn) * (-getTrueNegativeRate(fp, tn) + 1)) + getTrueNegativeRate(fp, tn) - 1) / (getRecall(tp, fn) + getTrueNegativeRate(fp, tn) - 1);
}
/**
* The threat score (TS) aka. critical success index (CSI).
*
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives
* @param fn Count of false negatives.
* @return The TS/CSI.
*/
public static double getCriticalSuccessIndex(final int tp, final int fp, final int fn) {
return (tp + fn + fp == 0) ? 1.0 : (double) tp / (tp + fn + fp);
}
/**
* The accuracy (ACC).
*
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives
* @param fn Count of false negatives.
* @return The ACC.
*/
public static double getAccuracy(final int tp, final int fp, final int tn, final int fn) {
return (tp + tn + fp + fn == 0) ? 1.0 : (double) (tp + tn) / (tp + fp + tn + fn);
}
/**
* The misclassification rate, error rate.
*
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives
* @param fn Count of false negatives.
* @return The misclassification rate/error rate.
*/
public static double getErrorRate(final int tp, final int fp, final int tn, final int fn) {
return 1 - getAccuracy(tp, fp, tn, fn);
}
/**
* The balanced accuracy (BA)
*
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @param fn Count of false negatives.
* @return The BA.
*/
public static double getBalancedAccuracy(final int tp, final int fp, final int tn, final int fn) {
return (getRecall(tp, fn) + getTrueNegativeRate(fp, tn)) / 2;
}
/**
* The F1-score, harmonic mean of precision and recall.
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param fn Count of false negatives.
* @return The F1-score.
*/
public static double getF1Score(final int tp, final int fp, final int fn) {
return getFMeasure(1.0, tp, fp, fn);
}
/**
* The general F-Measure being parameterized by a constant beta.
* @param beta The constant to weight precision and recall.
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param fn Count of false negatives.
* @return The F-Measure score.
*/
public static double getFMeasure(final double beta, final int tp, final int fp, final int fn) {
double precision = getPrecision(tp, fp);
double recall = getRecall(tp, fn);
double betaSquare = Math.pow(beta, 2);
if (precision + recall == 0.0) {
return 0.0;
}
return (1 + betaSquare) * precision * recall / (betaSquare * getPrecision(tp, fp) + getRecall(tp, fn));
}
/**
* The Matthews correlation coefficient (MCC).
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @param fn Count of false negatives.
* @return The MCC.
*/
public static double getMatthewsCorrelationCoefficient(final int tp, final int fp, final int tn, final int fn) {
double nominator = (double) tp * tn - fp * fn;
double denominator = Math.sqrt((double) (tp + fp) * (tp + fn) * (tn + fp) * (tn + fn));
return nominator / denominator;
}
/**
* The Fowlkes-Mallows index (FMI).
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param fn Count of false negatives.
* @return The FMI.
*/
public static double getFowlkesMallowsIndex(final int tp, final int fp, final int fn) {
return Math.sqrt(getPrecision(tp, fp) * getRecall(tp, fn));
}
/**
* The informedness or bookmaker informedness(BM)
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @param fn Count of false negatives.
* @return The informedness/BM.
*/
public static double getInformedness(final int tp, final int fp, final int tn, final int fn) {
return getRecall(tp, fn) + getTrueNegativeRate(fp, tn) - 1;
}
/**
* The markedness (MK) or deltaP.
*
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @param fn Count of false negatives.
*
* @return The MK/deltaP.
*/
public static double getMarkedness(final int tp, final int fp, final int tn, final int fn) {
return getPrecision(tp, fp) + getNegativePredictiveValue(tn, fn) - 1;
}
/**
* The predicted positive condition rate (PPCR).
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @param fn Count of false negatives.
* @return The PPCR.
*/
public static double getPredictedPositiveConditionRate(final int tp, final int fp, final int tn, final int fn) {
return (tp + fp + tn + fn == 0) ? 1.0 : (double) (tp + fp) / (tp + fp + tn + fn);
}
/**
* The positive likelihood ratio (PLR).
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @param fn Count of false negatives.
* @return The PLR.
*/
public static double getPositiveLikelihoodRatio(final int tp, final int fp, final int tn, final int fn) {
return getRecall(tp, fn) / getFallOut(fp, tn);
}
/**
* The negative likelihood ratio (NLR).
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @param fn Count of false negatives.
* @return The NLR.
*/
public static double getNegativeLikelihoodRatio(final int tp, final int fp, final int tn, final int fn) {
return getFalseNegativeRate(tp, fn) / getTrueNegativeRate(fp, tn);
}
/**
* The diagnostic odds ratio (DOR).
* @param tp Count of true positives.
* @param fp Count of false positives.
* @param tn Count of true negatives.
* @param fn Count of false negatives.
* @return The DOR.
*/
public static double getDiagnosticOddsRatio(final int tp, final int fp, final int tn, final int fn) {
return getPositiveLikelihoodRatio(tp, fp, tn, fn) / getNegativeLikelihoodRatio(tp, fp, tn, fn);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/DerivateDistance.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IDistanceMetric;
import ai.libs.jaicore.basic.transform.vector.derivate.ADerivateFilter;
import ai.libs.jaicore.basic.transform.vector.derivate.BackwardDifferenceDerivate;
/**
* Implementation of the Derivate Distance (DD) measure as published in "Using
* derivatives in time series classification" by Tomasz Gorecki and Maciej
* Luczak (2013).
*
* The authors wanted to create a distance measure which considers both, the
* function values of times series (point to point comparison) and the values of
* their derivates (general shape comparison).
*
* Given a distance measure <code>d</code>, the Derivate Distance for the two
* time series <code>A</code> and <code>B</code> is:
* <code>a * d(A, B) + b * d(A', B')</code>, where <code>A'</code> and
* <code>B'</code> are the derivates (@see jaicore.ml.tsc.filter.derivate) of
* <code>A</code> and <code>B</code> respec. and
* <code>0 <= a <= 1, 0 <= b <= 1></code> are parameters of the measure. The
* parameters <code>a</code> and <code>b</code> are set via an
* <code>alpha</code> value, that is <code>a=cos(alpha)</code> and
* <code>b=sin(alpha)</code>.
*
* The Derivate Distance that uses Dynamic Time Warping as underlying distance
* measure is commonly denoted as DD_DTW. The Derivate Distance that uses the
* Euclidean distance as underlying distance measure is commonly denoted as
* DD_ED.
* <p>
* It is also possible to use a distinct distance measure to calculate the
* distance between the time series and its derivates.
* </p>
*
* @author fischor
*/
public class DerivateDistance extends AWeightedTrigometricDistance {
/** The derivate calculation to use. */
private ADerivateFilter derivate;
/**
* The distance measure to use to calculate the distance of the function values.
*/
private IDistanceMetric timeSeriesDistance;
/**
* The distance measure to use to calculate the distance of the derivate values.
*/
private IDistanceMetric baseDerivateDistance;
/**
* Constructor with individual distance measures for the function and derivate
* values.
*
* @param alpha The distance measure to use to calculate the
* distance of the function values.
* <code>0 <= alpha <= pi/2</code>.
* @param derivate The derivate calculation to use.
* @param timeSeriesDistance The distance measure to use to calculate the
* distance of the derivate values.
* @param derivateDistance The distance measure to use to calculate the
* distance of the derivate values.
*/
public DerivateDistance(final double alpha, final ADerivateFilter derivate, final IDistanceMetric timeSeriesDistance, final IDistanceMetric derivateDistance) {
super(alpha);
if (derivate == null) {
throw new IllegalArgumentException("Parameter derivate must not be null.");
}
if (timeSeriesDistance == null) {
throw new IllegalArgumentException("Parameter timeSeriesDistance must not be null.");
}
if (derivateDistance == null) {
throw new IllegalArgumentException("Parameter derivateDistance must not be null.");
}
this.derivate = derivate;
this.timeSeriesDistance = timeSeriesDistance;
this.baseDerivateDistance = derivateDistance;
}
/**
* Constructor with individual distance measures for the function and derivate
* values that uses the {@link BackwardDifferenceDerivate} as derivation.
*
* @param alpha The distance measure to use to calculate the
* distance of the function values.
* <code>0 <= alpha <= pi/2</code>.
* @param timeSeriesDistance The distance measure to use to calculate the
* distance of the derivate values.
* @param derivateDistance The distance measure to use to calculate the
* distance of the derivate values.
*/
public DerivateDistance(final double alpha, final IDistanceMetric timeSeriesDistance, final IDistanceMetric derivateDistance) {
this(alpha, new BackwardDifferenceDerivate(), timeSeriesDistance, derivateDistance);
}
/**
* Constructor that uses the same distance measures for the function and
* derivate values.
*
* @param alpha The distance measure to use to calculate the distance of the
* function values. <code>0 <= alpha <= pi/2</code>.
* @param derivate The derivate calculation to use.
* @param distance The distance measure to use to calculate the distance of the
* function and derivate values.
*/
public DerivateDistance(final double alpha, final ADerivateFilter derivate, final IDistanceMetric distance) {
this(alpha, derivate, distance, distance);
}
/**
* Constructor that uses the same distance measures for the function and
* derivate values that uses the {@link BackwardDifferenceDerivate} as
* derivation.
*
* @param alpha The distance measure to use to calculate the distance of the
* function values. <code>0 <= alpha <= pi/2</code>.
* @param distance The distance measure to use to calculate the distance of the
* function and derivate values.
*/
public DerivateDistance(final double alpha, final IDistanceMetric distance) {
this(alpha, new BackwardDifferenceDerivate(), distance, distance);
}
/**
* @param a The influence of distance of the function values to the overall distance measure
* @param b The influence of distance of the derivates values to the overall distance measure.
*/
@Override
public double distance(final double[] a, final double[] b) {
double[] derivateA = this.derivate.transform(a);
double[] derivateB = this.derivate.transform(b);
return this.getA() * this.timeSeriesDistance.distance(a, b) + this.getB() * this.baseDerivateDistance.distance(derivateA, derivateB);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/DerivateTransformDistance.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IDistanceMetric;
import ai.libs.jaicore.basic.transform.vector.CosineTransform;
import ai.libs.jaicore.basic.transform.vector.IVectorTransform;
import ai.libs.jaicore.basic.transform.vector.derivate.ADerivateFilter;
import ai.libs.jaicore.basic.transform.vector.derivate.BackwardDifferenceDerivate;
/**
* Implementation of the Derivate Transform Distance (TD) measure as published
* in "Non-isometric transforms in time series classification using DTW" by
* Tomasz Gorecki and Maciej Luczak (2014).
*
* As the name suggests, with the Derivate Transform Distance the author combine
* their previously approaches of @see DerivateDistance and @see
* TransformDistance.
*
* Given a distance measure <code>d</code>, the Derivate Transform Distance for
* the two time series <code>A</code> and <code>B</code> is:
* <code>a * d(A, B) + b * d(A', B') + c * d(t(A), t(B))</code>, where
* <code>A'</code> and <code>B'</code> are the derivates (@see
* jaicore.ml.tsc.filter.derivate) and <code>t(A)</code> and <code>t(B)</code>
* are transforms (@see jaicore.ml.tsc.filter.transform) of <code>A</code> and
* <code>B</code> respec. and
* <code>0 <= a <= 1, 0 <= b <= 1, 0 <= c <= 1></code> are parameters of the
* measure.
*
* The Derivate Transform Distance that uses Dynamic Time Warping as underlying
* distance measure is commonly denoted as DTD_DTW. The Derivate Transform
* Distance that uses the Euclidean distance as underlying distance measure is
* commonly denoted as TD_ED.
* <p>
* It is also possible to use a distinct distance measure to calculate the
* distance between the time series, its transforms and its derivates.
* </p>
*
* @author fischor
*/
public class DerivateTransformDistance implements IDistanceMetric {
/**
* Determines the influence of distance of the function values to the overall
* distance measure.
*/
private double a;
/**
* Determines the influence of distance of the derivate values to the overall
* distance measure.
*/
private double b;
/**
* Determines the influence of distance of the transform values to the overall
* distance measure.
*/
private double c;
/** The derivate calculation to use. */
private ADerivateFilter derivate;
/** The transform calculation to use. */
private IVectorTransform transform;
/**
* The distance measure to use to calculate the distance of the function values.
*/
private IDistanceMetric timeSeriesDistance;
/**
* The distance measure to use to calculate the distance of the derivate values.
*/
private IDistanceMetric derivateDistance;
/**
* The distance measure to use to calculate the distance of the transform
* values.
*/
private IDistanceMetric transformDistance;
/**
* Constructor with individual distance measure for function, derivate and
* transform values.
*
* @param a Determines the influence of distance of the
* derivate values to the overall distance measure.
* @param b Determines the influence of distance of the
* transform values to the overall distance measure.
* @param c Determines the influence of distance of the
* transform values to the overall distance measure.
* @param derivate The derivate calculation to use.
* @param transform The transform calculation to use.
* @param timeSeriesDistance The distance measure to use to calculate the
* distance of the function values.
* @param derivateDistance The distance measure to use to calculate the
* distance of the derivate values.
* @param transformDistance The distance measure to use to calculate the
* distance of the transform values.
*/
public DerivateTransformDistance(final double a, final double b, final double c, final ADerivateFilter derivate, final IVectorTransform transform, final IDistanceMetric timeSeriesDistance, final IDistanceMetric derivateDistance,
final IDistanceMetric transformDistance) {
// Parameter checks.
if (derivate == null) {
throw new IllegalArgumentException("Parameter derivate must not be null.");
}
if (transform == null) {
throw new IllegalArgumentException("Parameter transform must not be null.");
}
if (timeSeriesDistance == null) {
throw new IllegalArgumentException("Parameter timeSeriesDistance must not be null.");
}
if (derivateDistance == null) {
throw new IllegalArgumentException("Parameter derivateDistance must not be null.");
}
if (transformDistance == null) {
throw new IllegalArgumentException("Parameter transformDistance must not be null.");
}
this.setA(a);
this.setB(b);
this.setC(c);
this.derivate = derivate;
this.transform = transform;
this.timeSeriesDistance = timeSeriesDistance;
this.derivateDistance = derivateDistance;
this.transformDistance = transformDistance;
}
/**
* Constructor with individual distance measure for function, derivate and
* transform values that uses the {@link BackwardDifferencetransform} as
* derivate and the {@link CosineTransform} as transformation.
*
* @param a Determines the influence of distance of the
* derivate values to the overall distance measure.
* @param b Determines the influence of distance of the
* transform values to the overall distance measure.
* @param c Determines the influence of distance of the
* transform values to the overall distance measure.
* @param timeSeriesDistance The distance measure to use to calculate the
* distance of the function values.
* @param derivateDistance The distance measure to use to calculate the
* distance of the derivate values.
* @param transformDistance The distance measure to use to calculate the
* distance of the transform values.
*/
public DerivateTransformDistance(final double a, final double b, final double c, final IDistanceMetric timeSeriesDistance, final IDistanceMetric derivateDistance, final IDistanceMetric transformDistance) {
this(a, b, c, new BackwardDifferenceDerivate(), new CosineTransform(), timeSeriesDistance, derivateDistance, transformDistance);
}
/**
* Constructor that uses the same distance measures for function, derivate and
* transform values.
*
* @param a Determines the influence of distance of the derivate values
* to the overall distance measure.
* @param b Determines the influence of distance of the transform values
* to the overall distance measure.
* @param c Determines the influence of distance of the transform values
* to the overall distance measure.
* @param derivate The derivate calculation to use.
* @param transform The transform calculation to use.
* @param distance The distance measure to use of the function, derivate and
* transform values.
*/
public DerivateTransformDistance(final double a, final double b, final double c, final ADerivateFilter derivate, final IVectorTransform transform, final IDistanceMetric distance) {
this(a, b, c, derivate, transform, distance, distance, distance);
}
/**
* Constructor that uses the same distance measures for function, derivate and
* transform values.
*
* @param a Determines the influence of distance of the derivate values
* to the overall distance measure.
* @param b Determines the influence of distance of the transform values
* to the overall distance measure.
* @param c Determines the influence of distance of the transform values
* to the overall distance measure.
* @param distance The distance measure to use of the function, derivate and
* transform values.
*/
public DerivateTransformDistance(final double a, final double b, final double c, final IDistanceMetric distance) {
this(a, b, c, new BackwardDifferenceDerivate(), new CosineTransform(), distance, distance, distance);
}
@Override
public double distance(final double[] a, final double[] b) {
double[] derivateA = this.derivate.transform(a);
double[] derivateB = this.derivate.transform(b);
double[] transformA = this.transform.transform(a);
double[] transformB = this.transform.transform(b);
return this.a * this.timeSeriesDistance.distance(a, b) + this.b * this.derivateDistance.distance(derivateA, derivateB) + this.c * this.transformDistance.distance(transformA, transformB);
}
/**
* Sets the <code>a</code> parameter. @see #a
*
* @param a The <code>a</code> parameter, <code>0 <= a <= 1</code>.
*/
public void setA(final double a) {
if (a < 0 || a > 1) {
throw new IllegalArgumentException("Parameter a must be in interval [0,1].");
}
this.a = a;
}
/**
* Sets the <code>b</code> parameter. @see #b
*
* @param a The <code>b</code> parameter, <code>0 <= b <= 1</code>.
*/
public void setB(final double b) {
if (b < 0 || b > 1) {
throw new IllegalArgumentException("Parameter b must be in interval [0,1].");
}
this.b = b;
}
/**
* Sets the <code>c</code> parameter. @see #c
*
* @param a The <code>c</code> parameter, <code>0 <= c <= 1</code>.
*/
public void setC(final double c) {
if (c < 0 || c > 1) {
throw new IllegalArgumentException("Parameter c must be in interval [0,1].");
}
this.c = c;
}
/**
* Getter for the <code>a</code> parameter. @see #a
*/
public double getA() {
return this.a;
}
/**
* Getter for the <code>b</code> parameter. @see #b
*/
public double getB() {
return this.b;
}
/**
* Getter for the <code>c</code> parameter. @see #c
*/
public double getC() {
return this.c;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/DynamicTimeWarping.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IDistanceMetric;
import org.api4.java.common.metric.IScalarDistance;
/**
* Implementation of the Dynamic Time Warping (DTW) measure as published in
* "Using Dynamic Time Warping to FindPatterns in Time Series" Donald J. Berndt
* and James Clifford.
*
* In DTW the time series are "warped" non-linearly in the time dimension to
* determine a measure of their similarity independent of certain non-linear
* variations in the time dimension.
*
* Given two time series <code>A</code> and <code>B</code> the dynamic
* programming formulation is based on the following recurrent definition:
* <code>gamma(i,j) = delta(i,j) + min {gamma(i-1, j), gamma(i-1,j-1), gamma(i, j-1)}</code>
* where <code>gamma(i,j)</code> is the cummulative distance up to
* <code>i,j</code> and
* <code>delta(i,j) is the point distance between <code>A_i</code> and
* <code>B_i</code>.
*
* @author fischor
*/
public class DynamicTimeWarping implements IDistanceMetric {
/** Distance measure for scalar points. */
private IScalarDistance delta;
/**
* Creates an instance with absolute distance as point distance.
*/
public DynamicTimeWarping() {
this((x, y) -> Math.abs(x - y));
}
/**
* Creates an instance with a given scalar distance measure.
*
* @param delta Scalar distance measure.
*/
public DynamicTimeWarping(final IScalarDistance delta) {
// Parameter checks.
if (delta == null) {
throw new IllegalArgumentException("Parameter delta must not be null.");
}
this.delta = delta;
}
@Override
public double distance(final double[] a, final double[] b) {
// Care in the most algorithm descriptions, the time series are 1-indexed.
int n = a.length;
int m = b.length;
double[][] matrix = new double[n + 1][m + 1]; // from 0 to n+1 incl. and 0 to m+1 incl.
// Initialize first row and column to infinity (except [0][0]).
for (int i = 1; i <= n; i++) {
matrix[i][0] = Double.MAX_VALUE;
}
for (int j = 1; j <= m; j++) {
matrix[0][j] = Double.MAX_VALUE;
}
// Initialize [0][0] with 0.
matrix[0][0] = 0d;
// Dynamic programming.
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
double cost = this.delta.distance(a[i - 1], b[j - 1]); // 1 indexed in algo.
double mini = Math.min(matrix[i - 1][j], Math.min(matrix[i][j - 1], matrix[i - 1][j - 1]));
matrix[i][j] = cost + mini;
}
}
return matrix[n][m];
}
public double distanceWithWindow(final double[] a, final double[] b, int w) {
int n = a.length;
int m = b.length;
double[][] matrix = new double[n + 1][m + 1];
w = Math.max(w, Math.abs(n - m));
// Initialize first row and column to infinity (except [0][0]).
for (int i = 1; i <= n; i++) {
matrix[i][0] = Double.MAX_VALUE;
}
for (int j = 1; j <= m; j++) {
matrix[0][j] = Double.MAX_VALUE;
}
// Initialize [0][0] with 0.
matrix[0][0] = 0d;
for (int i = 1; i <= n; i++) {
for (int j = Math.max(1, i - w); j <= Math.min(m, i + w); j++) {
double cost = this.delta.distance(a[i - 1], b[j - 1]);
double mini = Math.min(matrix[i - 1][j], Math.min(matrix[i][j - 1], matrix[i - 1][j - 1]));
matrix[i][j] = cost + mini;
}
}
return matrix[n][m];
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/EuclideanDistance.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IDistanceMetric;
import ai.libs.jaicore.basic.RobustnessUtil;
/**
* Implementation of the Euclidean distance for time series.
*
* The Euclidean distance for two time series <code>A</code> and <code>B</code>
* of length <code>n</code> is defined as
* <code>\sqrt{\sum_{i=0}^{n} (A_i - B_i)^2 }</code>. Therefore, it is required
* for <code>A</code> and <code>B</code> to be of the same length.
*
* @author fischor
*/
public class EuclideanDistance implements IDistanceMetric {
@Override
public double distance(final double[] a, final double[] b) {
// Parameter checks.
RobustnessUtil.sameLengthOrDie(a, b);
int n = a.length;
// Sum over all elements.
double result = 0;
for (int i = 0; i < n; i++) {
result += Math.pow((a[i] - b[i]), 2);
}
result = Math.sqrt(result);
return result;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/IAbandonable.java
|
package ai.libs.jaicore.basic.metric;
/**
* Interface for Distance measures that can make use of the Early Abandon
* technique.
*
* With Early Abandon the distance calculation will be abandoned once the
* calculation has exceed a bestSoFar distance.
*/
public interface IAbandonable {
/**
* Setter for the best-so-far value.
*
* @param limit The limit.
*/
public void setBestSoFar(double limit);
/**
* Getter for the best-so-far value.
*
* @return The limit.
*/
public double getBestSoFar();
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/ManhattanDistance.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IDistanceMetric;
import ai.libs.jaicore.basic.RobustnessUtil;
/**
* Implementation of the Manhattan distance for time series.
*
* The Manhattan distance for two time series <code>A</code> and <code>B</code>
* of length <code>n</code> is defined as
* <code>\sum_{i=0}^{n} |A_i - B_i|</code>. Therefore, it is required for
* <code>A</code> and <code>B</code> to be of the same length.
*
* @author fischor
*/
public class ManhattanDistance implements IDistanceMetric {
@Override
public double distance(final double[] a, final double[] b) {
// Parameter checks.
RobustnessUtil.sameLengthOrDie(a, b);
int n = a.length;
// Sum over all elements.
double result = 0;
for (int i = 0; i < n; i++) {
result += Math.abs(a[i] - b[i]);
}
return result;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/MoveSplitMerge.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IDistanceMetric;
/**
* Implementation of the Move-Split-Merge (MSM) measure as published in "The
* Move-Split-Merge Metric for Time Series" by Alexandra Stefan, Vassilis
* Athitsos and Gautam Das (2013).
*
* The idea behind the MSM metric is to define a set of operations that can be
* used to transform any time series into any other.
* <ul>
* <li>A <i>Move</i> operation changes the value of a single point of the time
* series.</li>
* <li>A <i>Split</i> operation splits a single point of the time series into
* two consecutive points that have the same value as the original point.</li>
* <li>A <i>Merge</i> operation merges two consecutive points that have the same
* value int a single point that has that value.</li>
* </ul>
* Each operation has an associated cost. The cost for a <i>Move</i> for
* <code>x</code> to <code>y</code> is <code>|x-y|</code>. The cost for a
* <i>Split</i> and <i>Merge</i> is defined by a constant <code>c</code>.
*
* Let <code>S = (s_1, s_2, .., s_n)</code> be a sequence of Move/Split/Merge
* operations with <code>s_i</code> either Move, Split or a Merge. The
* Move-Split-Merge distance between to time series <code>A</code> and
* <code>B</code> is defined be the cost of the lowest-cost transformation
* <code>S*</code>, such that <code>transform(S*, A) = B</code>.
*
* @author fischor
*/
public class MoveSplitMerge implements IDistanceMetric {
/** The constant cost for <i>Split</i> and <i>Merge</i> operations. */
private double c;
/**
* Constructor.
*
* @param c The constant cost for <i>Split</i> and <i>Merge</i> operations.
*/
public MoveSplitMerge(double c) {
this.c = c;
}
@Override
public double distance(double[] a, double[] b) {
int n = a.length;
int m = b.length;
double[][] cost = new double[n][m];
// Initialization.
cost[0][0] = Math.abs(a[0] - b[0]);
for (int i = 1; i < n; i++) {
cost[i][0] = cost[i - 1][0] + c(a[i], a[i - 1], b[0]);
}
for (int j = 1; j < m; j++) {
cost[0][j] = cost[0][j - 1] + c(b[j], a[0], b[j - 1]);
}
// Dynamic programming.
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
double costMove = cost[i - 1][j - 1] + Math.abs(a[i] - b[j]);
double cost2 = cost[i - 1][j] + c(a[i], a[i - 1], b[j]);
double cost3 = cost[i][j - 1] + c(b[j], a[i], b[j - 1]);
cost[i][j] = Math.min(costMove, Math.min(cost2, cost3));
}
}
return cost[n - 1][m - 1];
}
/**
* Functon C as defined in Equation 9 of the paper.
*
* @param a The point <code>a_i</code> of the time series <code>A</code>.
* @param aBefore The point <code>a_{i-1}</code> of the time series
* <code>A</code>.
* @param b The point <code>b_j</code> of the time series <code>B</code>.
*/
private double c(double a, double aBefore, double b) {
if ((aBefore <= a && a <= b) || (aBefore >= a && a >= b)) {
// x_{i-1} <= x_i <= y_j or x_{i-1} >= x_i >= y_j
return c;
} else {
return c + Math.min(Math.abs(a - aBefore), Math.abs(a - b));
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/ScalarDistanceUtil.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IScalarDistance;
/**
* ScalarDistanceUtil
*/
public class ScalarDistanceUtil {
private ScalarDistanceUtil() {
/* no instantiation desired */
}
public static IScalarDistance getAbsoluteDistance() {
return (x, y) -> Math.abs(x - y);
}
public static IScalarDistance getSquaredDistance() {
return (x, y) -> (x - y) * (x - y);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/ShotgunDistance.java
|
package ai.libs.jaicore.basic.metric;
import java.util.Arrays;
import org.api4.java.common.metric.IDistanceMetric;
import ai.libs.jaicore.basic.transform.vector.IVectorTransform;
import ai.libs.jaicore.basic.transform.vector.NormalizeByStdTransform;
import ai.libs.jaicore.basic.transform.vector.ZTransform;
/**
* Implementation of Shotgun Distance measure as published in "Towards Time
* Series Classfication without Human Preprocessing" by Patrick Schäfer (2014).
*
* To make many of the standard methods to calculate the distance betwenn two
* time series applicable, a lot of time and effort has to be spent by a domain
* expert to filter the data and extrdact equal-length, equal-scale and alighned
* patterns. The Shotgun Distance avoids preprocessing the data for alignment,
* scaling or length. This is achieved by breaking the query time series into
* disjoint windows (subsequences) of fixed length. These windows are slid along
* the sample time series (with stride 1) to find the best matching position in
* terms of minimizing a distance metric (e.g. Euclidean distance or DTW
* distance).
*
* @author fischor
* @author mwever
*/
public class ShotgunDistance implements IDistanceMetric {
/**
* The window length.
*/
private int windowLength;
/**
* Mean normalization. If false, no mean substraction at vertical alignment of
* windows.
*/
private boolean meanNormalization;
/**
* The euclidean distance used to calculate the distance between different
* windows.
*/
private EuclideanDistance euclideanDistance = new EuclideanDistance();
/**
* Constructor for the Shotgun Distance.
*
* @param windowLength The window length.
* @param meanNormalization Mean normalization. If false, no mean substraction
* at vertical alignment of windows.
*/
public ShotgunDistance(final int windowLength, final boolean meanNormalization) {
// Parameter checks.
if (windowLength <= 0) {
throw new IllegalArgumentException("The window length must not be less or equal to zero.");
}
this.windowLength = windowLength;
this.meanNormalization = meanNormalization;
}
@Override
public double distance(final double[] a, final double[] b) {
// Assure that max(A.length, B.length) <= windowLength, otherwise
// the result is undefined.
double totalDistance = 0;
IVectorTransform transform;
if (this.meanNormalization) {
transform = new ZTransform();
} else {
transform = new NormalizeByStdTransform();
}
// For each disjoint query window with lenth this.windowLength.
int numberOfDisjointWindows = a.length / this.windowLength;
for (int i = 0; i < numberOfDisjointWindows; i++) {
int startOfDisjointWindow = i * this.windowLength;
double[] disjointWindow = Arrays.copyOfRange(a, startOfDisjointWindow, startOfDisjointWindow + this.windowLength);
// Vertical alignment.
disjointWindow = transform.transform(disjointWindow);
// Holds the minumum distance between the current disjoint window and all
// sliding windows.
double windowDistance = Double.MAX_VALUE;
// Slide window with length windowLength and stride 1 over the time series B.
int numberOfSlidingWindows = b.length - this.windowLength + 1;
for (int j = 0; j < numberOfSlidingWindows; j++) {
int startOfSlidingWindow = j;
double[] slidingWindow = Arrays.copyOfRange(b, startOfSlidingWindow, startOfSlidingWindow + this.windowLength);
// Vertical alignment.
slidingWindow = transform.transform(slidingWindow);
// Calculate distance between disjoint and sliding window. For each disjoint
// window, keep the minumum distance to all sliding windows.
double distanceDisjointSliding = this.euclideanDistance.distance(disjointWindow, slidingWindow);
if (distanceDisjointSliding < windowDistance) {
windowDistance = distanceDisjointSliding;
}
}
// Aggregate the distance for all disjoint windows to the total distance.
totalDistance += windowDistance;
}
return totalDistance;
}
/**
* Sets the window length.
*
* @param windowLength @see #windowLength
*/
public void setWindowLength(final int windowLength) {
this.windowLength = windowLength;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/TimeWarpEditDistance.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IScalarDistance;
import org.api4.java.common.metric.ITimeseriesDistanceMetric;
/**
* Time Warp Edit Distance as published in "Time Warp Edit Distance with
* Stiffness Adjustment for Time Series Matching" by Pierre-Francois Marteau
* (2009).
*
* The similarity between two time series is measured as the minimum cost
* sequence of edit operations needed to transform one time series into another.
*
* @author fischor
*/
public class TimeWarpEditDistance implements ITimeseriesDistanceMetric {
/**
* Stiffness parameter. Used to parametrize the influence of the time stamp
* distance. Must be positive.
*/
private double nu;
/** Additional cost parameter for deletion. Must be positive. */
private double lambda;
/**
* Distance mesaure used for point distance calculation.
*/
private IScalarDistance d;
/**
* Constructor.
*
* @param lambda Additional cost parameter for deletion.
* @param nu Stiffness parameter. Used to parametrize the influence of the
* time stamp distance.
* @param d Distance mesaure used for point distance calculation.
*/
public TimeWarpEditDistance(final double lambda, final double nu, final IScalarDistance d) {
// Parameter checks.
if (lambda < 0) {
throw new IllegalArgumentException("Parameter lambda must be greater or equal to zero.");
}
if (nu < 0) {
throw new IllegalArgumentException("Parameter nu must be greater or equal to zero.");
}
if (d == null) {
throw new IllegalArgumentException("Parameter d must not be null.");
}
this.lambda = lambda;
this.nu = nu;
this.d = d;
}
/**
* Constructor. Creates a TimeWarpEditDistance with squared distance as point
* distance.
*
* @param lambda Additional cost parameter for deletion.
* @param nu Stiffness parameter.
*/
public TimeWarpEditDistance(final double lambda, final double nu) {
this(lambda, nu, ScalarDistanceUtil.getSquaredDistance());
}
@Override
public double distance(final double[] a, final double[] tA, final double[] b, final double[] tB) {
int n = a.length;
int m = b.length;
// DP[0..n, 0..m]
double[][] dp = new double[n + 1][m + 1];
// declare A[0] := 0, tA[0] := 0
// declare B[0] := 0, tB[0] := 0
// Note: Zero pad A and B, i.e. when referencing A[i] use A[i-1], when
// referencing A[i-1] use A[i-2]
// Dynamic Programming initialization.
for (int i = 1; i <= n; i++) {
dp[i][0] = Double.MAX_VALUE;
}
for (int i = 1; i <= m; i++) {
dp[0][i] = Double.MAX_VALUE;
}
dp[0][0] = 0d;
// Dynamic programming.
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// Cost for Deletion in A.
double c1;
// Cost for Deletion in B.
double c2;
// Cost for a match.
double c3;
if (i == 1 && j == 1) {
// Substitute A[i-2] with 0 and B[j-2] with 0.
c1 = dp[i - 1][j] + this.d.distance(0, a[i - 1]) + this.nu * tA[i - 1] + this.lambda;
c2 = dp[i][j - 1] + this.d.distance(0, b[j - 1]) + this.nu * tB[j - 1] + this.lambda;
c3 = dp[i - 1][j - 1] + this.d.distance(a[i - 1], b[i - 1]) + this.nu * Math.abs(tA[i - 1] - tB[j - 1]);
} else if (i == 1) {
// Substitute A[i-2] with 0.
c1 = dp[i - 1][j] + this.d.distance(0, a[i - 1]) + this.nu * tA[i - 1] + this.lambda;
c2 = dp[i][j - 1] + this.d.distance(b[j - 2], b[j - 1]) + this.nu * (tB[j - 1] - tB[j - 2]) + this.lambda;
c3 = dp[i - 1][j - 1] + this.d.distance(a[i - 1], b[i - 1]) + this.d.distance(0, b[j - 2]) + this.nu * (Math.abs(tA[i - 1] - tB[j - 1]) + tB[j - 2]);
} else if (j == 1) {
// Substitute B[j-2] with 0.
c1 = dp[i - 1][j] + this.d.distance(a[i - 2], a[i - 1]) + this.nu * (tA[i - 1] - tA[i - 2]) + this.lambda;
c2 = dp[i][j - 1] + this.d.distance(0, b[j - 1]) + this.nu * tB[j - 1] + this.lambda;
c3 = dp[i - 1][j - 1] + this.d.distance(a[i - 1], b[i - 1]) + this.d.distance(a[i - 2], 0) + this.nu * (Math.abs(tA[i - 1] - tB[j - 1]) + tA[i - 2]);
} else {
// No substitution.
c1 = dp[i - 1][j] + this.d.distance(a[i - 2], a[i - 1]) + this.nu * (tA[i - 1] - tA[i - 2]) + this.lambda;
c2 = dp[i][j - 1] + this.d.distance(b[j - 2], b[j - 1]) + this.nu * (tB[j - 1] - tB[j - 2]) + this.lambda;
c3 = dp[i - 1][j - 1] + this.d.distance(a[i - 1], b[i - 1]) + this.d.distance(a[i - 2], b[j - 2]) + this.nu * (Math.abs(tA[i - 1] - tB[j - 1]) + Math.abs(tA[i - 2] - tB[j - 2]));
}
// Minimum cost.
double minimum = Math.min(c1, Math.min(c2, c3));
dp[i][j] = minimum;
}
}
return dp[n][m];
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/TransformDistance.java
|
package ai.libs.jaicore.basic.metric;
import org.api4.java.common.metric.IDistanceMetric;
import ai.libs.jaicore.basic.transform.vector.CosineTransform;
import ai.libs.jaicore.basic.transform.vector.IVectorTransform;
/**
* Implementation of the Transform Distance (TD) measure as published in
* "Non-isometric transforms in time series classification using DTW" by Tomasz
* Gorecki and Maciej Luczak (2014).
*
* Building up on their work of the Derivate Distance, the authors were looking
* for functions other than the derivative which can be used in a similar
* manner, what leads them to use transform instead of derivates.
*
* Given a distance measure <code>d</code>, the Transform Distance for the two
* time series <code>A</code> and <code>B</code> is:
* <code>a * d(A, B) + b * d(t(A), t(B))</code>, where <code>t(A)</code> and
* <code>t(B)</code> are transforms (@see jaicore.ml.tsc.filter.transform) of
* <code>A</code> and <code>B</code> respec. and
* <code>0 <= a <= 1, 0 <= b <= 1></code> are parameters of the measure. The
* parameters <code>a</code> and <code>b</code> are set via an
* <code>alpha</code> value, that is <code>a=cos(alpha)</code> and
* <code>b=sin(alpha)</code>.
*
* The Transform Distance that uses Dynamic Time Warping as underlying distance
* measure is commonly denoted as TD_DTW. The Transform Distance that uses the
* Euclidean distance as underlying distance measure is commonly denoted as
* TD_ED.
* <p>
* It is also possible to use a distinct distance measure to calculate the
* distance between the time series and its transforms.
* </p>
*
* @author fischor
*/
public class TransformDistance extends AWeightedTrigometricDistance {
/** The transform calculation to use. */
private IVectorTransform transform;
/**
* The distance measure to use to calculate the distance of the function values.
*/
private IDistanceMetric timeSeriesDistance;
/**
* The distance measure to use to calculate the distance of the transform
* values.
*/
private IDistanceMetric baseTransformDistance;
/**
* Constructor with individual distance measures for the function and transform
* values.
*
* @param alpha @see #alpha ,<code>0 <= alpha <= pi/2</code>.
* @param transform The transform calculation to use.
* @param timeSeriesDistance The distance measure to use to calculate the
* distance of the transform values.
* @param transformDistance The distance measure to use to calculate the
* distance of the transform values.
*/
public TransformDistance(final double alpha, final IVectorTransform transform, final IDistanceMetric timeSeriesDistance, final IDistanceMetric transformDistance) {
super(alpha);
if (transform == null) {
throw new IllegalArgumentException("Parameter transform must not be null.");
}
if (timeSeriesDistance == null) {
throw new IllegalArgumentException("Parameter timeSeriesDistance must not be null.");
}
if (transformDistance == null) {
throw new IllegalArgumentException("Parameter transformDistance must not be null.");
}
this.transform = transform;
this.timeSeriesDistance = timeSeriesDistance;
this.baseTransformDistance = transformDistance;
}
/**
* Constructor with individual distance measures for the function and transform
* values that uses the {@link CosineTransform} as transformation.
*
* @param alpha The distance measure to use to calculate the
* distance of the function values.
* <code>0 <= alpha <= pi/2</code>.
* @param timeSeriesDistance The distance measure to use to calculate the
* distance of the transform values.
* @param transformDistance The distance measure to use to calculate the
* distance of the transform values.
*/
public TransformDistance(final double alpha, final IDistanceMetric timeSeriesDistance, final IDistanceMetric transformDistance) {
this(alpha, new CosineTransform(), timeSeriesDistance, transformDistance);
}
/**
* Constructor that uses the same distance measures for the function and
* transform values.
*
* @param alpha The distance measure to use to calculate the distance of the
* function values. <code>0 <= alpha <= pi/2</code>.
* @param transform The transform calculation to use.
* @param distance The distance measure to use to calculate the distance of the
* function and transform values.
*/
public TransformDistance(final double alpha, final IVectorTransform transform, final IDistanceMetric distance) {
this(alpha, transform, distance, distance);
}
/**
* Constructor that uses the same distance measures for the function and
* transform values that uses the {@link CosineTransform} as transformation.
*
* @param alpha The distance measure to use to calculate the distance of the
* function values. <code>0 <= alpha <= pi/2</code>.
* @param distance The distance measure to use to calculate the distance of the
* function and transform values.
*/
public TransformDistance(final double alpha, final IDistanceMetric distance) {
this(alpha, new CosineTransform(), distance);
}
/**
* @param a The influence of distance of the function values to the overall distance measure.
* @param b The influence of distance of the transform values to the overall distance measure.
*
*/
@Override
public double distance(final double[] a, final double[] b) {
double[] transformA = this.transform.transform(a);
double[] transformB = this.transform.transform(b);
return this.getA() * this.timeSeriesDistance.distance(a, b) + this.getB() * this.baseTransformDistance.distance(transformA, transformB);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/WeightedDynamicTimeWarping.java
|
package ai.libs.jaicore.basic.metric;
import java.util.HashMap;
import java.util.Map;
import org.api4.java.common.metric.IDistanceMetric;
import org.api4.java.common.metric.IScalarDistance;
/**
* Implementation of the Dynamic Time Warping (DTW) measure as published in
* "Weighted dynamic time warping for time series classification" by Young-Seon
* Jeong, Myong K. Jeong and Olufemi A. Omitaomu.
*
* DTW does not account for the relative importance regarding the phase
* difference between a reference point and a testing point. This may lead to
* misclassification especially in applications where the shape similarity
* between two sequences is a major consideration for an accurate recognition.
* Therefore, [the authors] propose a novel distance measure, called a weighted
* DTW (WDTW), which is a penalty-based DTW. [Their] approach penalizes points
* with higher phase difference between a reference point and a testing point in
* order to prevent minimum distance distortion caused by outliers.
*
* @author fischor
*/
public class WeightedDynamicTimeWarping implements IDistanceMetric {
/**
* Controls the level of penalization for the points with larger phase
* difference.
*/
private double g;
/**
* The desired upper bound for the weight parameter that is used to penalize
* points with higher phase difference.
*/
private double maximumWeight;
/** Distance measure for scalar points. */
private IScalarDistance d;
/** Memorizes the calculated weight vectors for a specific length. */
private Map<Integer, double[]> weightMemoization = new HashMap<>();
/**
* Constructor.
*
* @param g Controls the penelization in weights for points with
* larger phase difference.
* @param maximumWeight The desired upper bound for the weight parameter that is
* used to penalize points with higher phase difference.
*/
public WeightedDynamicTimeWarping(final double g, final double maximumWeight, final IScalarDistance d) {
this.g = g;
this.maximumWeight = maximumWeight;
this.d = d;
}
@Override
public double distance(final double[] a, final double[] b) {
int n = a.length;
int m = b.length;
double[][] matrix = new double[n + 1][m + 1];
double[] weights = this.calculateWeights(Math.max(n, m));
// Dynamic Programming initialization.
for (int i = 1; i <= n; i++) {
matrix[i][0] = Double.MAX_VALUE;
}
for (int j = 1; j <= m; j++) {
matrix[0][j] = Double.MAX_VALUE;
}
matrix[0][0] = 0d;
// Dynamic programming.
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// Paper: | w[i-j] (a_i - b_j) |^p
double cost = weights[Math.abs(i - j)] * this.d.distance(a[i - 1], b[j - 1]);
double minimum = Math.min(matrix[i - 1][j], Math.min(matrix[i][j - 1], matrix[i - 1][j - 1]));
matrix[i][j] = cost + minimum;
}
}
return matrix[n][m];
}
/**
* Calculates the weight vector via the Modified logistic weight function (see
* paper 4.2). Uses memoization to avoid multiple calculations for the same
* length.
*
* @param length Length of the time series, i.e. length of the weight vector. Is
* guaranteed to be greater 0 within this class.
* @return Resulting weight vector.
*/
protected double[] calculateWeights(final int length) {
// Use memoization.
double[] memoized = this.weightMemoization.get(length);
if (memoized != null) {
return memoized;
}
// Calculate weights when not memoized.
double[] weights = new double[length];
double halfLength = (double) length / 2; // center of time series.
for (int i = 0; i < length; i++) {
weights[i] = this.maximumWeight / (1 + Math.exp(-this.g * (i - halfLength)));
}
// Add to memoization-
this.weightMemoization.put(length, weights);
return weights;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/metric/package-info.java
|
/**
* This package contains implementations for time series distance measures.
*
* @author fischor
*/
package ai.libs.jaicore.basic.metric;
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/reconstruction/ReconstructionInstruction.java
|
package ai.libs.jaicore.basic.reconstruction;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.apache.commons.lang3.reflect.TypeUtils;
import org.api4.java.common.reconstruction.IReconstructible;
import org.api4.java.common.reconstruction.IReconstructionInstruction;
import org.api4.java.common.reconstruction.ReconstructionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ReconstructionInstruction implements IReconstructionInstruction {
/**
*
*/
private static final long serialVersionUID = -9034513607515486949L;
private transient Logger logger = LoggerFactory.getLogger(ReconstructionInstruction.class);
private final String clazzName;
private final String methodName;
private final Class<?>[] argumentTypes;
private final Object[] arguments;
public static boolean isArrayOfPrimitives(final Class<?> clazz) {
return clazz.isArray() && (boolean[].class.isAssignableFrom(clazz) || byte[].class.isAssignableFrom(clazz) || short[].class.isAssignableFrom(clazz) || int[].class.isAssignableFrom(clazz) || long[].class.isAssignableFrom(clazz)
|| float[].class.isAssignableFrom(clazz) || double[].class.isAssignableFrom(clazz) || char[].class.isAssignableFrom(clazz) || String[].class.isAssignableFrom(clazz));
}
@JsonCreator
public ReconstructionInstruction(@JsonProperty("clazzName") final String clazzName, @JsonProperty("methodName") final String methodName, @JsonProperty("argumentTypes") final Class<?>[] argumentTypes,
@JsonProperty("arguments") final Object[] arguments) {
super();
Objects.requireNonNull(clazzName);
Objects.requireNonNull(methodName);
this.clazzName = clazzName;
this.methodName = methodName;
this.argumentTypes = argumentTypes;
this.arguments = arguments;
int n = argumentTypes.length;
/* */
for (int i = 0; i < n; i++) {
Class<?> requiredType = argumentTypes[i];
boolean isNull = arguments[i] == null;
if (!isNull) {
boolean isThis = arguments[i].equals("this");
this.logger.debug("ARG {}: {} (required type: {})", i, arguments[i], requiredType);
/* if the required type is complex and requires serialization or deserialization, do this now */
if (this.doesTypeRequireSerializationDeserialization(requiredType)) {
try {
if (arguments[i] instanceof String) { // suppose that the object is given in serialized form, try to deserialize it
arguments[i] = requiredType.cast(new ObjectMapper().readValue(arguments[i].toString(), ReconstructionPlan.class).reconstructObject());
} else if (arguments[i] instanceof IReconstructible) { // if this is a reconstructible, serialize it
String reconstructionCommand = new ObjectMapper().writeValueAsString(((IReconstructible) arguments[i]).getConstructionPlan());
arguments[i] = reconstructionCommand;
continue; // if we are serializing the object, we can (in fact MUST) stop the processing of the parameter here
} else {
throw new IllegalArgumentException(
"The " + i + "-th argument \"" + arguments[i] + "\" is neither a primitive (it's a " + arguments[i].getClass().getName() + ") nor a class object nor \"this\" and also not a reconstructible object.");
}
} catch (IOException | ReconstructionException e) {
throw new IllegalArgumentException(e);
}
}
/* check that correct type is transmitted */
Class<?> givenType = arguments[i].getClass();
if (!isThis && !TypeUtils.isAssignable(givenType, requiredType)) {
/* if the required type is not a class, there is no excuse to deviate */
if (requiredType != Class.class) {
throw new IllegalArgumentException(
"Cannot create instruction. Required type for " + i + "-th argument is " + requiredType + ". But the given object is " + arguments[i] + " (type: " + arguments[i].getClass().getName() + ")");
}
/* here we know that the required type is a class. Then try to get a class object from the parameter */
if (givenType != String.class) {
throw new IllegalArgumentException(
"Cannot create instruction. " + i + "-th argument is required to be a class object (" + argumentTypes[i].getName() + "). The provided object is neither a Class nor a String and hence cannot be derived.");
}
/* now we know that the given param is a String. Try to find the class for it */
try {
String className = (String) arguments[i];
if (className.startsWith("class:")) {
className = className.substring("class:".length());
}
if (className.startsWith("class ")) {
className = className.substring("class ".length());
}
arguments[i] = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Cannot create instruction. " + i + "-th argument is required to be a class object (" + argumentTypes[i].getName() + "). The provided object " + arguments[i]
+ " is a String that points to a class that does not exist! Cannot derive hence a class object.");
}
}
}
}
}
public ReconstructionInstruction(final Method method, final Object... arguments) {
super();
this.clazzName = method.getDeclaringClass().getName();
this.methodName = method.getName();
this.argumentTypes = method.getParameterTypes();
this.arguments = arguments;
}
private boolean doesTypeRequireSerializationDeserialization(final Class<?> clazz) {
if (clazz.isPrimitive() || clazz.equals(String.class)) {
return false;
}
if (isArrayOfPrimitives(clazz)) {
return false;
}
if (clazz.equals(Class.class)) {
return false;
}
return !List.class.isAssignableFrom(clazz);
}
private Method getMethod() throws ClassNotFoundException, NoSuchMethodException {
String className = this.clazzName;
if (className.equals("Instances")) {
className = "weka.core.Instances";
}
Method m = MethodUtils.getMatchingAccessibleMethod(Class.forName(className), this.methodName, this.argumentTypes);
if (m == null) {
throw new NoSuchMethodException("Method " + this.methodName + " for class " + className + " not found!");
}
return m;
}
private Constructor<?> getConstructor() throws ClassNotFoundException, NoSuchMethodException {
String className = this.clazzName;
if (className.equals("Instances")) {
className = "weka.core.Instances";
}
Class<?> clazz = Class.forName(className);
return this.argumentTypes.length == 0 ? clazz.getConstructor() : clazz.getConstructor(this.argumentTypes);
}
@Override
public Object apply(final Object object) throws ReconstructionException {
int n = this.arguments.length;
Object[] replacedArguments = new Object[n];
try {
Method method = this.getMethod();
for (int i = 0; i < n; i++) {
Object val = this.arguments[i];
/* first replace the encoding strings by their true value */
if (val instanceof String) {
if (val.equals("this")) {
replacedArguments[i] = object;
} else {
String json = (String) val;
replacedArguments[i] = new ObjectMapper().readValue(json, ReconstructionPlan.class).reconstructObject();
}
} else {
replacedArguments[i] = this.arguments[i];
}
/* check whether the obtained argument value is compatible with the type required in the method */
Class<?> type = replacedArguments[i].getClass();
Class<?> requiredType = method.getParameterTypes()[i];
if (!ClassUtils.isAssignable(type, requiredType, true)) {
throw new IllegalStateException(
"Error in reconstructing object via method " + this.clazzName + "." + this.methodName + ".\nCannot assign parameter of type " + type.getName() + " to required type " + requiredType.getName());
}
}
int k = replacedArguments.length;
if (this.logger != null && this.logger.isDebugEnabled()) {
this.logger.debug("{}.{}", this.getMethod().getDeclaringClass().getName(), this.getMethod().getName());
for (int i = 0; i < k; i++) {
this.logger.debug("{}: {}: {}", i, replacedArguments[i].getClass().getName(), replacedArguments[i]);
}
}
return method.invoke(null, replacedArguments);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException | IOException e) {
throw new ReconstructionException(e);
}
}
@Override
public Object applyToCreate() throws ReconstructionException {
int m = this.arguments.length;
if (!this.methodName.equals("__construct")) {
Method method;
try {
method = this.getMethod();
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException e1) {
throw new ReconstructionException(e1);
}
if (this.logger != null) {
this.logger.info("Creating new object via {}.{}", method.getDeclaringClass().getName(), method.getName());
if (this.logger.isDebugEnabled()) {
for (int i = 0; i < m; i++) {
this.logger.debug("{}: {}: {}", i, this.arguments[i] != null ? this.arguments[i].getClass().getName() : null, this.arguments[i]);
}
}
}
try {
return method.invoke(null, this.arguments);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) {
if (this.logger != null) {
this.logger.error("Error in invoking {}.{} with arguments: {} with class types {}.", this.clazzName, this.methodName, this.arguments,
Arrays.stream(this.arguments).map(a -> a.getClass().getName()).collect(Collectors.toList()));
}
throw new ReconstructionException(e);
}
} else {
try {
Constructor<?> c = this.getConstructor();
return c.newInstance(this.arguments);
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new ReconstructionException(e);
}
}
}
public String getClazzName() {
return this.clazzName;
}
public String getMethodName() {
return this.methodName;
}
public Class<?>[] getArgumentTypes() {
return this.argumentTypes;
}
public Object[] getArguments() {
return this.arguments;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.argumentTypes);
result = prime * result + Arrays.deepHashCode(this.arguments);
result = prime * result + ((this.clazzName == null) ? 0 : this.clazzName.hashCode());
result = prime * result + ((this.methodName == null) ? 0 : this.methodName.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
ReconstructionInstruction other = (ReconstructionInstruction) obj;
if (!Arrays.equals(this.argumentTypes, other.argumentTypes)) {
return false;
}
if (!Arrays.deepEquals(this.arguments, other.arguments)) {
return false;
}
if (this.clazzName == null) {
if (other.clazzName != null) {
return false;
}
} else if (!this.clazzName.equals(other.clazzName)) {
return false;
}
if (this.methodName == null) {
if (other.methodName != null) {
return false;
}
} else if (!this.methodName.equals(other.methodName)) {
return false;
}
return true;
}
@Override
public String toString() {
return "ReconstructionInstruction [clazzName=" + this.clazzName + ", methodName=" + this.methodName + ", argumentTypes=" + Arrays.toString(this.argumentTypes) + ", arguments=" + Arrays.toString(this.arguments) + "]";
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/reconstruction/ReconstructionPlan.java
|
package ai.libs.jaicore.basic.reconstruction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.api4.java.common.reconstruction.IReconstructionInstruction;
import org.api4.java.common.reconstruction.IReconstructionPlan;
import org.api4.java.common.reconstruction.ReconstructionException;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ReconstructionPlan implements IReconstructionPlan {
/**
*
*/
private static final long serialVersionUID = 2149341607637260587L;
private final List<ReconstructionInstruction> instructions;
public ReconstructionPlan() {
super();
this.instructions = new ArrayList<>(0);
}
@JsonCreator
public ReconstructionPlan(@JsonProperty("instructions") final List<ReconstructionInstruction> instructions) {
super();
this.instructions = instructions;
}
@Override
public Object reconstructObject() throws ReconstructionException {
int n = this.instructions.size();
Object o = this.instructions.get(0).applyToCreate();
for (int i = 1; i < n; i++) {
o = this.instructions.get(i).apply(o);
}
return o;
}
@Override
public List<IReconstructionInstruction> getInstructions() {
return Collections.unmodifiableList(this.instructions);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.instructions == null) ? 0 : this.instructions.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
ReconstructionPlan other = (ReconstructionPlan) obj;
if (this.instructions == null) {
if (other.instructions != null) {
return false;
}
} else if (!this.instructions.equals(other.instructions)) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/reconstruction/ReconstructionUtil.java
|
package ai.libs.jaicore.basic.reconstruction;
import java.util.List;
import org.api4.java.common.reconstruction.IReconstructible;
import org.api4.java.common.reconstruction.IReconstructionInstruction;
public class ReconstructionUtil {
private ReconstructionUtil() {
/* empty constructor to avoid instantiation */
}
public static void requireNonEmptyInstructionsIfReconstructibilityClaimed(final Object object) {
if (!areInstructionsNonEmptyIfReconstructibilityClaimed(object)) {
throw new IllegalArgumentException("Object that is declared to be reconstructible does not carry any instructions.");
}
}
public static boolean areInstructionsNonEmptyIfReconstructibilityClaimed(final Object object) {
/* consistency check: check whether object, if reconstructible, already has a construction */
if (object instanceof IReconstructible) {
List<IReconstructionInstruction> instructions = ((IReconstructible) object).getConstructionPlan().getInstructions();
if (instructions == null || instructions.isEmpty()) {
return false;
}
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/CartesianProductComputationProblem.java
|
package ai.libs.jaicore.basic.sets;
import java.util.Collection;
import java.util.List;
public class CartesianProductComputationProblem<T> extends RelationComputationProblem<T> {
public CartesianProductComputationProblem(List<Collection<T>> sets) {
super(sets, n -> true);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/ElementDecorator.java
|
package ai.libs.jaicore.basic.sets;
import org.api4.java.common.attributedobjects.IElementDecorator;
public class ElementDecorator<E> implements IElementDecorator<E> {
private final E element;
public ElementDecorator(final E element) {
super();
this.element = element;
}
@Override
public E getElement() {
return this.element;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.getElement() == null) ? 0 : this.getElement().hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
IElementDecorator<?> other = (IElementDecorator<?>) obj;
if (this.element == null) {
if (other.getElement() != null) {
return false;
}
} else if (!this.element.equals(other.getElement())) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/EmptyIterator.java
|
package ai.libs.jaicore.basic.sets;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class EmptyIterator<E> implements Iterator<E> {
@Override
public boolean hasNext() {
return false;
}
@Override
public E next() {
throw new NoSuchElementException("Empty iterators have no elements.");
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/FilteredIterable.java
|
package ai.libs.jaicore.basic.sets;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* This class allows to iterate of any type of {@link Iterable} in a filtered way. More specifically, given a
* whitelist of indices, this class allows to iterate only over the elements listed in that whitelist.
* This util works for all kind of {@link Iterable}s. The basic idea is to avoid copying data for iterating
* over subsets only.
*
* Note that this does only work for iterables with a fixed order, i.e., no HashSets!
*
* @author mwever
*
* @param <X> The type of elements to iterate over.
*/
public class FilteredIterable<X> implements Iterable<X> {
private Iterable<X> wrappedIterable;
private List<Integer> filteredIndices;
/**
* Standard c'tor.
* @param wrappedIterable The iterable which is to be wrapped and filtered.
* @param filteredIndices The list of indices that are whitelisted and are expected to be returned when iterating over the iterable.
*/
public FilteredIterable(final Iterable<X> wrappedIterable, final List<Integer> filteredIndices) {
this.wrappedIterable = wrappedIterable;
this.filteredIndices = new LinkedList<>(filteredIndices);
Collections.sort(this.filteredIndices);
}
@Override
public Iterator<X> iterator() {
return new FilteredIterator(this.wrappedIterable.iterator(), this.getFilteredIndices());
}
/**
* Getter for the list of filtered indices.
* @return The list of filtered indices.
*/
public List<Integer> getFilteredIndices() {
return new LinkedList<>(this.filteredIndices);
}
/**
* The iterator which allows to iterate over the filtered subset only as described in the list of filtered indices.
*
* @author mwever
*/
private class FilteredIterator implements Iterator<X> {
private final Iterator<X> wrappedIterator;
private final List<Integer> remainingFilteredInstances;
private int currentIndex;
private FilteredIterator(final Iterator<X> wrappedIterator, final List<Integer> remainingFilteredInstances) {
this.wrappedIterator = wrappedIterator;
this.remainingFilteredInstances = remainingFilteredInstances;
this.currentIndex = 0;
}
@Override
public boolean hasNext() {
if (this.remainingFilteredInstances.isEmpty()) {
return false;
}
int nextIndex = this.remainingFilteredInstances.get(0);
while (this.currentIndex < nextIndex) {
this.wrappedIterator.next();
this.currentIndex++;
}
return true;
}
@Override
public X next() {
if (!this.hasNext()) {
throw new NoSuchElementException("There is no element left!");
}
int extractedIndex = this.remainingFilteredInstances.remove(0);
if (extractedIndex != this.currentIndex) {
throw new IllegalStateException("Current index does not match the extracted index from the list. Extracted: " + extractedIndex);
}
this.currentIndex++;
return this.wrappedIterator.next();
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/IntCoordinates.java
|
package ai.libs.jaicore.basic.sets;
public class IntCoordinates {
private final int x;
private final int y;
public IntCoordinates(final int x, final int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public IntCoordinates getUp() {
return new IntCoordinates(this.x, this.y + 1);
}
public IntCoordinates getDown() {
return new IntCoordinates(this.x, this.y - 1);
}
public IntCoordinates getLeft() {
return new IntCoordinates(this.x - 1, this.y);
}
public IntCoordinates getRight() {
return new IntCoordinates(this.x + 1, this.y);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.x;
result = prime * result + this.y;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
IntCoordinates other = (IntCoordinates) obj;
if (this.x != other.x) {
return false;
}
return this.y == other.y;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/Interval.java
|
package ai.libs.jaicore.basic.sets;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Interval implements Serializable {
private static final long serialVersionUID = -6928681531901708026L;
private boolean isInteger;
private double min;
private double max;
@SuppressWarnings("unused")
private Interval() {
// for serialization
this.isInteger = true;
this.min = 0;
this.max = 0;
}
@JsonCreator
public Interval(@JsonProperty("integer") final boolean isInteger, @JsonProperty("min") final double min, @JsonProperty("max") final double max) {
super();
this.isInteger = isInteger;
this.min = min;
this.max = max;
}
public boolean isInteger() {
return this.isInteger;
}
public double getMin() {
return this.min;
}
public double getMax() {
return this.max;
}
public void setInteger(final boolean isInteger) {
this.isInteger = isInteger;
}
public void setMin(final double min) {
this.min = min;
}
public void setMax(final double max) {
this.max = max;
}
@Override
public String toString() {
return "NumericParameterDomain [isInteger=" + this.isInteger + ", min=" + this.min + ", max=" + this.max + "]";
}
public boolean contains(final Object item) {
if (!(item instanceof Number)) {
return false;
}
Double n;
if (item instanceof Double) {
n = (double)item;
}
else if (item instanceof Long) {
n = (double)(Long)item;
}
else if (item instanceof Integer) {
n = (double)(int)item;
}
else {
throw new IllegalArgumentException("No support for number type " + item.getClass());
}
if (this.isInteger && n != n.intValue()) {
return false;
}
return n >= this.min && n <= this.max;
}
public boolean subsumes(final Interval otherInterval) {
if (this.isInteger && !otherInterval.isInteger) {
return false;
}
return this.min <= otherInterval.getMin() && this.max >= otherInterval.getMax();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.isInteger ? 1231 : 1237);
long temp;
temp = Double.doubleToLongBits(this.max);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.min);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Interval other = (Interval) obj;
if (this.isInteger != other.isInteger) {
return false;
}
if (Double.doubleToLongBits(this.max) != Double.doubleToLongBits(other.max)) {
return false;
}
return Double.doubleToLongBits(this.min) == Double.doubleToLongBits(other.min);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/LDSRelationComputer.java
|
package ai.libs.jaicore.basic.sets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.algorithm.AAlgorithm;
import ai.libs.jaicore.basic.algorithm.AlgorithmFinishedEvent;
import ai.libs.jaicore.basic.algorithm.AlgorithmInitializedEvent;
/**
* This algorithms allows to compute an ordered Cartesian product. It is ordered
* in the sense that it interprets the sets over which the product is built as
* ORDERED sets and first generates tuples with items that appear first in the
* sets.
*
* The algorithm also works for ordinary unordered sets but is a bit slower why
* another algorithm could be favorable.
*
* @author fmohr
*
* @param <T>
*/
public class LDSRelationComputer<T> extends AAlgorithm<RelationComputationProblem<T>, List<List<T>>> {
private Logger logger = LoggerFactory.getLogger(LDSRelationComputer.class);
private class Node {
private Node parent;
private int defficiency;
private int indexOfSet;
private int indexOfValue;
public Node() {
}
public Node(final Node parent, final int indexOfSet, final int defficiency, final int indexInSet) {
long start = System.currentTimeMillis();
this.parent = parent;
this.indexOfSet = indexOfSet;
this.defficiency = defficiency;
this.indexOfValue = indexInSet;
assert System.currentTimeMillis() - start <= 1 : "Constructor execution took more than 1ms: " + (System.currentTimeMillis() - start) + "ms";
}
public void fillTupleArrayWithValues(final List<T> tupleArray) {
tupleArray.clear();
this.fillTupleArrayWithValuesRec(tupleArray);
}
private void fillTupleArrayWithValuesRec(final List<T> tupleArray) {
if (this.parent == null) {
return;
}
tupleArray.add(0, this.getObject());
this.parent.fillTupleArrayWithValuesRec(tupleArray);
}
T getObject() {
return LDSRelationComputer.this.sets.get(this.indexOfSet).get(this.indexOfValue);
}
/**
* this method can be used to store old nodes in order to use them again later in the algorithm.
* This can be useful to avoid the creation of new objects all the time, which can be time consuming.
*/
public void recycle() {
if (this.indexOfSet >= LDSRelationComputer.this.numSets) {
LDSRelationComputer.this.recycledNodes.add(this);
}
}
}
private final List<List<T>> sets;
private final int numSets;
private final Predicate<List<T>> prefixFilter;
private int computedTuples = 0;
private final List<T> currentTuple;
private Queue<Node> open = new PriorityQueue<>((n1, n2) -> n1.defficiency - n2.defficiency);
private List<Node> recycledNodes = new ArrayList<>();
private int numRecycledNodes;
private int numCreatedNodes;
private int reportRate = 1000; // number of tuples after which a message is sent to the logger
public LDSRelationComputer(final List<Collection<T>> sets) {
this(new RelationComputationProblem<>(sets));
}
public LDSRelationComputer(final RelationComputationProblem<T> problem) {
super(problem);
this.sets = new ArrayList<>();
for (Collection<T> set : problem.getSets()) {
this.sets.add(set instanceof List ? (List<T>) set : new ArrayList<>(set));
}
this.numSets = this.sets.size();
this.prefixFilter = problem.getPrefixFilter();
this.currentTuple = new ArrayList<>();
}
@Override
public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
this.logger.debug("Conducting next algorithm step.");
switch (this.getState()) {
case CREATED:
this.open.add(new Node(null, -1, 0, 0));
this.numCreatedNodes++;
this.logger.info("Created algorithm for LDS Relation among {} sets with the following cardinalities: {}.", this.sets.size(), this.sets.stream().map(Collection::size).collect(Collectors.toList()));
return this.activate();
case ACTIVE:
this.checkAndConductTermination();
if (this.open.isEmpty()) {
this.logger.info("Nothing more to compute, return AlgorithmFinishedEvent.");
return this.terminate();
}
/* determine next cheapest path to a leaf */
Node next = null;
Node newNode;
while (!this.open.isEmpty() && (next = this.open.poll()).indexOfSet < this.numSets - 1) {
int i = 0;
int setIndex = next.indexOfSet + 1;
List<T> set = this.sets.get(setIndex);
int n = set.size();
next.fillTupleArrayWithValues(this.currentTuple); // get current tuple
for (int j = 0; j < n; j++) {
this.checkAndConductTermination();
long innerTimePoint = System.currentTimeMillis();
this.currentTuple.add(set.get(j));
assert (System.currentTimeMillis() - innerTimePoint) <= 20 : "Copying the " + (next.indexOfSet) + "-tuple " + this.currentTuple + " took " + (System.currentTimeMillis() - innerTimePoint) + "ms, which is way too much!";
innerTimePoint = System.currentTimeMillis();
boolean adopt = this.prefixFilter.test(this.currentTuple);
this.logger.debug("Prefix filter outputs {} tuple {}", adopt, this.currentTuple);
assert (System.currentTimeMillis() - innerTimePoint) < 1000 : "Testing the " + (next.indexOfSet) + "-tuple " + this.currentTuple + " took " + (System.currentTimeMillis() - innerTimePoint) + "ms, which is way too much!";
if (adopt) {
innerTimePoint = System.currentTimeMillis();
if (this.recycledNodes.isEmpty()) {
newNode = new Node();
this.numCreatedNodes++;
assert (System.currentTimeMillis() - innerTimePoint) < 5000 : "Creating a new node took " + (System.currentTimeMillis() - innerTimePoint) + "ms, which is way too much!\n" + this.computedTuples
+ " tuples have been computed already.\nRecycling list contains " + this.recycledNodes.size() + "\nOPEN contains " + this.open.size();
} else {
newNode = this.recycledNodes.remove(0);
assert (System.currentTimeMillis() - innerTimePoint) < 10 : "Retrieving node from recycle list " + (System.currentTimeMillis() - innerTimePoint) + "ms, which is way too much!\n" + this.computedTuples
+ " tuples have been computed already.\nRecycling list contains " + this.recycledNodes.size() + "\nOPEN contains " + this.open.size();
}
newNode.parent = next;
newNode.indexOfSet = next.indexOfSet + 1;
newNode.defficiency = next.defficiency + i++;
newNode.indexOfValue = j;
this.open.add(newNode);
}
this.currentTuple.remove(setIndex);
}
}
/* at this point, next should contain a fully specified tuple. If no next element exists, or the chosen node is not a leaf, terminate */
if (next == null || next.indexOfSet < this.sets.size() - 1) {
this.logger.info("No next tuple found, return AlgorithmFinishedEvent.");
return this.terminate();
}
this.computedTuples++;
if (this.computedTuples % this.reportRate == 0) {
this.logger.info("Status report: {} have been created.", this.computedTuples);
}
/* load tuple of selected leaf node */
next.fillTupleArrayWithValues(this.currentTuple);
/* recycle leaf node and possibly also inner nodes*/
next.recycle();
this.numRecycledNodes++;
List<T> tuple = new ArrayList<>(this.currentTuple);
assert this.currentTuple.size() == this.numSets : "Tuple " + this.currentTuple + " should contain " + this.numSets + " elements but has " + this.currentTuple.size();
this.logger.debug("Computed tuple {}", tuple);
return new TupleOfCartesianProductFoundEvent<>(this, tuple);
default:
throw new IllegalStateException();
}
}
@SuppressWarnings("unchecked")
public List<T> nextTuple() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
while (this.hasNext()) {
IAlgorithmEvent e = this.nextWithException();
if (e instanceof AlgorithmFinishedEvent) {
throw new NoSuchElementException();
} else if (e instanceof TupleOfCartesianProductFoundEvent) {
return ((TupleOfCartesianProductFoundEvent<T>) e).getTuple();
} else if (!(e instanceof AlgorithmInitializedEvent)) {
throw new IllegalStateException("Cannot handle event of type " + e.getClass());
}
}
throw new IllegalStateException("No more elements but no AlgorithmFinishedEvent was generated!");
}
@Override
public List<List<T>> call() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
List<List<T>> product = new ArrayList<>();
List<T> nextTuple;
try {
while (this.hasNext() && (nextTuple = this.nextTuple()) != null) {
assert nextTuple.size() == this.sets.size() : "The returned tuple " + nextTuple + " does not have " + this.sets.size() + " entries.";
product.add(nextTuple);
}
} catch (NoSuchElementException e) {
this.logger.info("No more solutions exist.");
}
this.logger.info("Returning a set of {} tuples.", product.size());
return product;
}
public int getNumRecycledNodes() {
return this.numRecycledNodes;
}
public int getNumCreatedNodes() {
return this.numCreatedNodes;
}
@Override
public void setLoggerName(final String name) {
super.setLoggerName(name + "._algorithm");
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Switched logger to {}", name);
if (this.prefixFilter instanceof ILoggingCustomizable) {
((ILoggingCustomizable) this.prefixFilter).setLoggerName(name + ".filter");
}
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/LDSRelationComputerFactory.java
|
package ai.libs.jaicore.basic.sets;
import java.util.List;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmFactory;
public class LDSRelationComputerFactory<T> extends AAlgorithmFactory<RelationComputationProblem<T>, List<List<T>>, IAlgorithm<RelationComputationProblem<T>, List<List<T>>>> {
@Override
public IAlgorithm<RelationComputationProblem<T>, List<List<T>>> getAlgorithm() {
return new LDSRelationComputer<>(this.getInput());
}
@Override
public IAlgorithm<RelationComputationProblem<T>, List<List<T>>> getAlgorithm(final RelationComputationProblem<T> input) {
return new LDSRelationComputer<>(input);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/ListDecorator.java
|
package ai.libs.jaicore.basic.sets;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.api4.java.common.attributedobjects.IListDecorator;
/**
* This class solves the following problem: Sometimes you want to use objects of a concrete List class L
* to be used in a context where some extension of the List interface L' is used, which is not implemented by L.
* To use objects of type L in such a context, it is a bad idea to cast and copy the items of L into an
* object of type L' but instead a decorator implementing L' should be used that forwards all operations to the
* original instance.
*
* The ListDecorator must be told how to create elements of the decorated list in order to insert
*
* @author fmohr
*
* @param <L>
* @param <E>
*/
public class ListDecorator<L extends List<E>, E, D extends ElementDecorator<E>> implements IListDecorator<L, E, D>, List<D> {
private final L list;
private final Class<E> typeOfDecoratedItems;
private final Class<D> typeOfDecoratingItems;
private final Constructor<D> constructorForDecoratedItems;
@SuppressWarnings("unchecked")
public ListDecorator(final L list) {
super();
try {
this.list = list;
Type[] genericTypes = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();
this.typeOfDecoratedItems = (Class<E>) this.getClassWithoutGenerics(genericTypes[1].getTypeName());
this.typeOfDecoratingItems = (Class<D>) this.getClassWithoutGenerics(genericTypes[2].getTypeName());
Constructor<D> vConstructorForDecoratedItems = null;
vConstructorForDecoratedItems = this.typeOfDecoratingItems.getConstructor(this.typeOfDecoratedItems);
this.constructorForDecoratedItems = vConstructorForDecoratedItems;
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Could not determin class without generics", e);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("The constructor of the list class could not be invoked.", e);
}
}
@Override
public Class<E> getTypeOfDecoratedItems() {
return this.typeOfDecoratedItems;
}
@Override
public Class<D> getTypeOfDecoratingItems() {
return this.typeOfDecoratingItems;
}
@Override
public Constructor<D> getConstructorForDecoratingItems() {
return this.constructorForDecoratedItems;
}
@Override
public L getList() {
return this.list;
}
private Class<?> getClassWithoutGenerics(final String className) throws ClassNotFoundException {
return Class.forName(className.replaceAll("(<[^>*]>)", ""));
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/ListView.java
|
package ai.libs.jaicore.basic.sets;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* This class allows to get a casted view on the items of a list.
*
* For example, if you have a list List<Number> l, it is not possible to cast l to List<Integer> even if you know that all items are integers.
* You can then use List<Integer> l2 = new ListView<>(l); to get a (read-only) list of integers with automated casts.
*
* @author Felix Mohr
*
* @param <T>
*/
public class ListView<T> implements List<T> {
private static final String MSG_READ_ONLY = "This is a read-only view.";
private List<?> list;
public ListView(final List<?> list) {
this.list = list;
}
public ListView(final List<?> list, final Class<T> clazz) {
this(list);
for (Object l : list) {
if (!clazz.isInstance(l)) {
throw new IllegalArgumentException();
}
}
}
@Override
public boolean add(final T arg0) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public void add(final int arg0, final T arg1) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public boolean addAll(final Collection<? extends T> arg0) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public boolean addAll(final int arg0, final Collection<? extends T> arg1) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public void clear() {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public boolean contains(final Object arg0) {
return this.list.contains(arg0);
}
@Override
public boolean containsAll(final Collection<?> arg0) {
return this.list.containsAll(arg0);
}
@Override
public T get(final int arg0) {
return (T)this.list.get(arg0);
}
@Override
public int indexOf(final Object arg0) {
return this.list.indexOf(arg0);
}
@Override
public boolean isEmpty() {
return this.list.isEmpty();
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private Iterator<?> it = ListView.this.list.iterator();
@Override
public boolean hasNext() {
return this.it.hasNext();
}
@Override
public T next() {
return (T)this.it.next();
}
};
}
@Override
public int lastIndexOf(final Object arg0) {
return this.list.lastIndexOf(arg0);
}
@Override
public ListIterator<T> listIterator() {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public ListIterator<T> listIterator(final int arg0) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public boolean remove(final Object arg0) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public T remove(final int arg0) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public boolean removeAll(final Collection<?> arg0) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public boolean retainAll(final Collection<?> arg0) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public T set(final int arg0, final T arg1) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public int size() {
return this.list.size();
}
@Override
public List<T> subList(final int arg0, final int arg1) {
throw new UnsupportedOperationException(MSG_READ_ONLY);
}
@Override
public Object[] toArray() {
return this.list.toArray();
}
@Override
public <S> S[] toArray(final S[] arg0) {
return this.list.toArray(arg0);
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/Pair.java
|
package ai.libs.jaicore.basic.sets;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Pair<X,Y> implements Serializable {
private static final long serialVersionUID = 5570679807997613881L;
@JsonProperty
private X x;
@JsonProperty
private Y y;
public Pair(@JsonProperty("x") final X x, @JsonProperty("y") final Y y) {
super();
this.x = x;
this.y = y;
}
public X getX() {
return this.x;
}
public Y getY() {
return this.y;
}
@Override
public String toString() {
return "<" + this.x + ", " + this.y + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.x == null) ? 0 : this.x.hashCode());
result = prime * result + ((this.y == null) ? 0 : this.y.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("unchecked")
Pair<X, Y> other = (Pair<X, Y>) obj;
if (this.x == null) {
if (other.x != null) {
return false;
}
} else if (!this.x.equals(other.x)) {
return false;
}
if (this.y == null) {
if (other.y != null) {
return false;
}
} else if (!this.y.equals(other.y)) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/PartialOrderedSet.java
|
package ai.libs.jaicore.basic.sets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* A {@link Set} with a partial order added to it.
*
* @author David Niehues - davnie@mail.upb.de
*/
public class PartialOrderedSet<E> extends HashSet<E> {
/**
* Automatically generated version UID for serialization.
*/
private static final long serialVersionUID = 5450009458863214917L;
/**
* The order of this set. For an a the b's with a < b are stored.
*/
private final Map<E, Set<E>> order;
/**
* Creates a new partial ordered set with the same elements as
* <code>original</code> and the same order.
*
* @param original
* The {@link PartialOrderedSet} to copy.
*/
public PartialOrderedSet(final PartialOrderedSet<E> original) {
super(original);
this.order = new HashMap<>();
original.order.forEach((k, v) -> this.order.put(k, new HashSet<>(v)));
}
/**
* Creates a new empty {@link PartialOrderedSet}.
*/
public PartialOrderedSet() {
this.order = new HashMap<>();
}
/**
* Adds the a < b to the relation.
*
* @param a
* the smaller element
* @param b
* the bigger element
*
* @throws IllegalStateException
* if b < a is in the relation.
*/
public void addABeforeB(final E a, final E b) {
if (!this.allowsABeforeB(a, b)) {
throw new IllegalStateException("By transitivity " + a + " before " + b + "isn't allowed.");
}
if (!this.contains(a)) {
this.add(a);
}
if (!this.contains(b)) {
this.add(b);
}
Set<E> directlyAfterA = this.order.computeIfAbsent(a, k -> new HashSet<>());
directlyAfterA.add(b);
}
/**
* Require that A is before b.
*
* @param a The A which is to be tested.
* @param b The B which is to be tested.
*/
public void requireABeforeB(final E a, final E b) {
if (!this.allowsABeforeB(a, b)) {
throw new IllegalStateException("By transitivity " + a + " before " + b + "isn't allowed.");
}
Set<E> directlyAfterA = this.order.computeIfAbsent(a, k -> new HashSet<>());
directlyAfterA.add(b);
}
/**
* Tests if the relation allows for a < b.
*
* @param a
* The element that is tested to be allowed before b.
* @param b
* The element that is tested to be allowed after a.
* @return
*/
public boolean allowsABeforeB(final E a, final E b) {
Set<E> transitiveClosure = this.getTransitiveClosure(b);
return !transitiveClosure.contains(a);
}
/**
* Returns the map containing the forward dependencies defining the order.
*
* @return The map containing the order.
*/
public Map<E, Set<E>> getOrder() {
return Collections.unmodifiableMap(this.order);
}
/**
* Tests whether a < b is directly, not just transitively, specified by the
* order.
*
* @param a
* The first element.
* @param b
* The second element.
* @return Whether the order specifies directly, that a < b has to hold.
*/
public boolean isADirectlyBeforeB(final E a, final E b) {
final Set<E> directlyAfterA = this.order.get(a);
if (directlyAfterA != null) {
return directlyAfterA.contains(b);
}
return false;
}
/**
* Gets the transitive closure of an element under this relation.
*
* @param e
* The element of which the transitive closure is asked for.
* @return The transitive closure of e.
* @throws NullPointerException
* if e is null.
*/
public Set<E> getTransitiveClosure(final E e) {
if (e == null) {
throw new NullPointerException("'e' mustn't be null.");
}
Set<E> set = new HashSet<>();
set.add(e);
return this.getTransitiveClosure(set);
}
/**
* Gets the transitive closure of a set.
*
* @param subSet
* The set of which the transitive closure is asked for.
* @return The transitive closure of subSet.
* @throws NullPointerException
* if subSet is null.
*/
public Set<E> getTransitiveClosure(final Set<E> subSet) {
if (subSet == null) {
throw new NullPointerException("subSet mustn't be null.");
}
Set<E> transitiveClosure = new HashSet<>(subSet);
for (E e : subSet) {
Set<E> directlyAfterE = this.order.get(e);
if (directlyAfterE != null) {
transitiveClosure.addAll(directlyAfterE);
}
}
if (subSet.containsAll(transitiveClosure)) {
return transitiveClosure;
}
return this.getTransitiveClosure(transitiveClosure);
}
/**
* Tests whether the relation is reflexive.
*
* @return Whether the relation is reflexive.
*/
public boolean isReflexive() {
for (E e : this) {
if (!this.order.containsKey(e)) {
return false;
}
if (!this.order.get(e).contains(e)) {
return false;
}
}
return true;
}
/**
* Creates a total order of the elements stored in this
* {@link PartialOrderedSet}. The order is created by iterating over all
* elements in the set and inserting each element in the list at the position of
* the element with the currently smallest index that has to be after the
* current element.
*
* If no elements needs to be after the current element, it is appended to the
* end. The runtime is O(n²).
*
*
* @return A total ordering of the elements in this {@link PartialOrderedSet}.
*/
public List<E> getTotalOrder() {
final List<E> list = new LinkedList<>();
for (E element : this) { // O(n)
Set<E> followingElements = this.order.get(element); // O(?)
int index = list.size();
if (followingElements != null) {
for (E followingElement : followingElements) {
int followingIndex = list.indexOf(followingElement); // O(n)
if (followingIndex != -1 && followingIndex < index) {
index = followingIndex;
}
}
}
list.add(index, element); // O(n)
}
return list;
}
/**
* If the collection is a {@link PartialOrderedSet}, the order will also be
* added. If the that would destroy asymmetry an {@link IllegalStateException}
* will be thrown.
*
* @throws IllegalStateException
* if adding the order of another {@link PartialOrderedSet} would
* destroy asymmetry.
*/
public void merge(final PartialOrderedSet<? extends E> set) {
super.addAll(set);
PartialOrderedSet<? extends E> tmpSet = set;
tmpSet.order.forEach((k, vSet) -> vSet.forEach(v -> this.addABeforeB(k, v)));
}
/**
* Adds all elements of the other partial order set.
*
* @param set The set to be added to this partial-order set.
*/
public void addAll(final PartialOrderedSet<? extends E> set) {
this.merge(set);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
Iterator<E> it = this.iterator();
while (it.hasNext()) {
sb.append(it.next().toString());
if (it.hasNext()) {
sb.append(", ");
}
}
sb.append("} with order ");
sb.append(this.order);
it = this.order.keySet().iterator();
while (it.hasNext()) {
E e = it.next();
Set<E> diretclyAfterE = this.order.get(e);
Iterator<E> innerIt = diretclyAfterE.iterator();
while (innerIt.hasNext()) {
sb.append(e.toString());
sb.append(" < ");
sb.append(innerIt.next().toString());
if (innerIt.hasNext()) {
sb.append(", ");
}
}
if (it.hasNext()) {
sb.append("; ");
}
}
return sb.toString();
}
/**
* Getter for a linearization of the partial order set.
*
* @return A list representing a linearization of the partial order set.
*/
public List<E> getLinearization() {
if (this.isEmpty()) {
return new ArrayList<>();
}
/* create a copy of all elements */
List<E> elements = new ArrayList<>();
Iterator<E> iterator = super.iterator();
while (iterator.hasNext()) {
elements.add(iterator.next());
}
/* compute initial values of working variables */
List<E> linearization = new ArrayList<>();
Map<E, Set<E>> workingCopyOfOrder = new HashMap<>();
this.order.forEach((k, v) -> workingCopyOfOrder.put(k, new HashSet<>(v))); // create a deep copy
Collection<E> itemsWithoutSuccessor = elements.stream().filter(s -> !workingCopyOfOrder.containsKey(s) || workingCopyOfOrder.get(s).isEmpty()).collect(Collectors.toList());
Collection<E> uninsertedItems = new HashSet<>(elements);
/* if all items have a successor, we have a cycle. Return that order then. */
if (itemsWithoutSuccessor.isEmpty()) {
throw new IllegalStateException("Partially Oredered Set contains a cycle: " + workingCopyOfOrder);
}
/* now compute the linearization from the back */
while (!itemsWithoutSuccessor.isEmpty()) {
List<E> itemsToInsert = new ArrayList<>(itemsWithoutSuccessor);
itemsWithoutSuccessor.clear();
for (E itemToInsert : itemsToInsert) {
if (linearization.contains(itemToInsert)) {
continue;
}
assert !linearization.contains(itemToInsert) : "The object " + itemToInsert + " is already contained in the linearization " + linearization;
linearization.add(0, itemToInsert);
uninsertedItems.remove(itemToInsert);
for (E uninsertedItem : uninsertedItems) {
if (workingCopyOfOrder.containsKey(uninsertedItem)) {
workingCopyOfOrder.get(uninsertedItem).remove(itemToInsert);
if (workingCopyOfOrder.get(uninsertedItem).isEmpty()) {
itemsWithoutSuccessor.add(uninsertedItem);
}
}
}
}
}
/* consistency check */
assert linearization.size() == super.size() : "The linearization of " + elements + " with order " + this.order + " has produced another number of elements: " + linearization.toString();
return linearization;
}
@Override
public Iterator<E> iterator() {
return this.getLinearization().iterator();
}
@Override
public void clear() {
super.clear();
this.order.clear();
}
@Override
public boolean removeAll(final Collection<?> c) {
for (Object o : c) {
this.order.remove(o);
}
return super.removeAll(c);
}
@Override
public boolean retainAll(final Collection<?> c) {
Iterator<E> it = this.order.keySet().iterator();
while (it.hasNext()) {
E e = it.next();
if (!c.contains(e)) {
// this also removes from the map, not just from the set.
it.remove();
}
}
return super.retainAll(c);
}
@Override
public boolean removeIf(final Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = this.order.keySet().iterator();
while (each.hasNext()) {
E next = each.next();
if (filter.test(next)) {
this.remove(next);
removed = true;
}
}
return removed;
}
@Override
public boolean remove(final Object e) {
this.order.remove(e);
List<E> emptyDependencies = new ArrayList<>();
for (Entry<E, Set<E>> dependency : this.order.entrySet()) {
dependency.getValue().remove(e);
if (dependency.getValue().isEmpty()) {
emptyDependencies.add(dependency.getKey());
}
}
emptyDependencies.forEach(this.order::remove);
return super.remove(e);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((this.order == null) ? 0 : this.order.hashCode());
return result;
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
PartialOrderedSet other = (PartialOrderedSet) obj;
if (this.order == null) {
if (other.order != null) {
return false;
}
} else if (!this.order.equals(other.order)) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/PartialOrderedSetUtil.java
|
package ai.libs.jaicore.basic.sets;
import java.util.LinkedList;
import java.util.List;
public class PartialOrderedSetUtil {
private final PartialOrderedSet<Integer> set;
public PartialOrderedSetUtil(final PartialOrderedSet<Integer> set) {
this.set = set;
}
public int calc() {
if (this.set.isEmpty()) {
return 0;
}
if (this.set.size() == 1) {
return 1;
}
final List<Integer> list = new LinkedList<>(this.set);
return this.getNumberOfAllowedPermutations(new LinkedList<>(), list);
}
private int getNumberOfAllowedPermutations(final List<Integer> prefix, final List<Integer> suffix) {
if (suffix.isEmpty()) {
return this.isCompatible(prefix) ? 1 : 0;
}
int numberOfCompatiblePermutations = 0;
for (int i = 0; i < suffix.size(); i++) {
final List<Integer> newPrefix = new LinkedList<>(prefix);
newPrefix.add(suffix.get(i));
}
return numberOfCompatiblePermutations;
}
private boolean isCompatible(final List<Integer> totalOrder) {
for (int i = 0; i < totalOrder.size() - 1; i++) {
for (int j = i+1; j < totalOrder.size(); j++) {
if (!this.set.allowsABeforeB(totalOrder.get(i), totalOrder.get(j))) {
return false;
}
}
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/RelationComputationProblem.java
|
package ai.libs.jaicore.basic.sets;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
public class RelationComputationProblem<T> {
private final List<? extends Collection<T>> sets;
private final Predicate<List<T>> prefixFilter; // decides for a tuple prefix whether any tuple being prefixed with it is part of the relation
public RelationComputationProblem(final List<? extends Collection<T>> sets) {
this (sets, t -> true);
}
public RelationComputationProblem(final List<? extends Collection<T>> sets, final Predicate<List<T>> prefixFilter) {
super();
this.sets = sets;
this.prefixFilter = prefixFilter;
}
public List<? extends Collection<T>> getSets() {
return this.sets;
}
public Predicate<List<T>> getPrefixFilter() {
return this.prefixFilter;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/SetUtil.java
|
package ai.libs.jaicore.basic.sets;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.math3.geometry.euclidean.oned.Interval;
import org.api4.java.common.attributedobjects.GetPropertyFailedException;
import org.api4.java.common.attributedobjects.IGetter;
import ai.libs.jaicore.basic.MathExt;
/**
* Utility class for sets.
*
* @author fmohr, mbunse, mwever
*/
public class SetUtil {
private static final String DEFAULT_LIST_ITEM_SEPARATOR = ",";
private SetUtil() {
// prevent instantiation of this util class
}
/* BASIC SET OPERATIONS */
@SafeVarargs
public static <T> Collection<T> union(final Collection<T>... set) {
Collection<T> union = new HashSet<>();
for (int i = 0; i < set.length; i++) {
Objects.requireNonNull(set[i]);
union.addAll(set[i]);
}
return union;
}
public static <T> List<T> union(final List<T>... lists) {
List<T> union = new ArrayList<>();
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) {
union.addAll(lists[i]);
}
}
return union;
}
public static <T> Collection<T> symmetricDifference(final Collection<T> a, final Collection<T> b) {
return SetUtil.union(SetUtil.difference(a, b), SetUtil.difference(b, a));
}
public static <T> Collection<T> getMultiplyContainedItems(final List<T> list) {
Set<T> doubleEntries = new HashSet<>();
Set<T> observed = new HashSet<>();
for (T item : list) {
if (observed.contains(item)) {
doubleEntries.add(item);
} else {
observed.add(item);
}
}
return doubleEntries;
}
/**
* @param a
* The set A.
* @param b
* The set B.
* @return The intersection of sets A and B.
*/
public static <S, T extends S, U extends S> Collection<S> intersection(final Collection<T> a, final Collection<U> b) {
List<S> out = new ArrayList<>();
Collection<? extends S> bigger = a.size() < b.size() ? b : a;
for (S item : ((a.size() >= b.size()) ? b : a)) {
if (bigger.contains(item)) {
out.add(item);
}
}
return out;
}
public static <S, T extends S, U extends S> boolean disjoint(final Collection<T> a, final Collection<U> b) {
Collection<? extends S> bigger = a.size() < b.size() ? b : a;
for (S item : ((a.size() >= b.size()) ? b : a)) {
if (bigger.contains(item)) {
return false;
}
}
return true;
}
public static <T> Collection<Collection<T>> getPotenceOfSet(final Collection<T> set, final byte exponent) {
Collection<Collection<T>> items = new ArrayList<>();
for (byte i = 0; i < exponent; i++) {
items.add(set);
}
return getCartesianProductOfSetsOfSameClass(items);
}
public static <T> Collection<Collection<T>> getCartesianProductOfSetsOfSameClass(final Collection<Collection<T>> items) {
/* recursion abortion */
if (items.isEmpty()) {
return new ArrayList<>();
}
if (items.size() == 1) {
Collection<Collection<T>> tuples = new ArrayList<>();
for (Collection<T> set : items) { // only one run exists here
for (T value : set) {
Collection<T> trivialTuple = new ArrayList<>();
trivialTuple.add(value);
tuples.add(trivialTuple);
}
}
return tuples;
}
/* compute cartesian product of n-1 */
Collection<Collection<T>> subproblem = new ArrayList<>();
Collection<T> unconsideredDomain = null;
int i = 0;
int limit = items.size();
for (Collection<T> set : items) {
if (i < limit - 1) {
subproblem.add(set);
} else if (i == limit - 1) {
unconsideredDomain = set;
break;
}
i++;
}
Collection<Collection<T>> subsolution = getCartesianProductOfSetsOfSameClass(subproblem);
/* compute solution */
Collection<Collection<T>> solution = new ArrayList<>();
for (Collection<T> tuple : subsolution) {
for (T value : unconsideredDomain) {
List<T> newTuple = new ArrayList<>();
newTuple.addAll(tuple);
newTuple.add(value);
solution.add(newTuple);
}
}
return solution;
}
/* SUBSETS */
public static <T> Collection<Collection<T>> powerset(final Collection<T> items) throws InterruptedException {
/* |M| = 0 */
if (items.isEmpty()) {
Collection<Collection<T>> setWithEmptySet = new ArrayList<>();
setWithEmptySet.add(new ArrayList<>());
return setWithEmptySet;
}
/* |M| >= 1 */
T baseElement = null;
Collection<T> restList = new ArrayList<>();
int i = 0;
for (T item : items) {
if (i == 0) {
baseElement = item;
} else {
restList.add(item);
}
i++;
}
Collection<Collection<T>> toAdd = new ArrayList<>();
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Interrupted during calculation of power set");
}
Collection<Collection<T>> subsets = powerset(restList);
for (Collection<T> existingSubset : subsets) {
Collection<T> additionalList = new ArrayList<>();
additionalList.addAll(existingSubset);
additionalList.add(baseElement);
toAdd.add(additionalList);
}
subsets.addAll(toAdd);
return subsets;
}
public static <T> Collection<Collection<T>> getAllPossibleSubsets(final Collection<T> items) {
/* |M| = 0 */
if (items.isEmpty()) {
Collection<Collection<T>> setWithEmptySet = new ArrayList<>();
setWithEmptySet.add(new ArrayList<>());
return setWithEmptySet;
}
/* |M| >= 1 */
T baseElement = null;
Collection<T> restList = new ArrayList<>();
int i = 0;
for (T item : items) {
if (i == 0) {
baseElement = item;
} else {
restList.add(item);
}
i++;
}
Collection<Collection<T>> subsets = getAllPossibleSubsets(restList);
Collection<Collection<T>> toAdd = new ArrayList<>();
for (Collection<T> existingSubset : subsets) {
Collection<T> additionalList = new ArrayList<>();
additionalList.addAll(existingSubset);
additionalList.add(baseElement);
toAdd.add(additionalList);
}
subsets.addAll(toAdd);
return subsets;
}
private static class SubSetComputer<T> implements Runnable {
private List<T> superSet;
private ExecutorService pool;
private int k;
private int idx;
private Set<T> current;
private List<Set<T>> allSolutions;
private Semaphore semThreads;
private Semaphore semComplete;
private long goalSize;
public SubSetComputer(final List<T> superSet, final int k, final int idx, final Set<T> current, final List<Set<T>> allSolutions, final ExecutorService pool, final Semaphore sem, final long goalSize, final Semaphore semComplete) {
super();
this.superSet = superSet;
this.pool = pool;
this.k = k;
this.idx = idx;
this.current = current;
this.allSolutions = allSolutions;
this.semThreads = sem;
this.semComplete = semComplete;
this.goalSize = goalSize;
}
@Override
public void run() {
List<Set<T>> localSolutions = new ArrayList<>();
this.performStep(this.superSet, this.k, this.idx, this.current, localSolutions);
synchronized (this.allSolutions) {
this.allSolutions.addAll(localSolutions);
if (this.allSolutions.size() == this.goalSize) {
this.semComplete.release();
}
}
this.semThreads.release();
}
public void performStep(final List<T> superSet, final int k, final int idx, final Set<T> current, final List<Set<T>> solution) {
// successful stop clause
if (current.size() == k) {
solution.add(new HashSet<>(current));
return;
}
// unseccessful stop clause
if (idx == superSet.size()) {
return;
}
T x = superSet.get(idx);
current.add(x);
// "guess" x is in the subset
if (this.semThreads.tryAcquire()) {
/* outsource first task in a new thread */
this.pool.submit(new SubSetComputer<T>(superSet, k, idx + 1, new HashSet<>(current), this.allSolutions, this.pool, this.semThreads, this.goalSize, this.semComplete));
/* also try to outsorce the second task into its own thread */
current.remove(x);
if (this.semThreads.tryAcquire()) {
this.pool.submit(new SubSetComputer<T>(superSet, k, idx + 1, new HashSet<>(current), this.allSolutions, this.pool, this.semThreads, this.goalSize, this.semComplete));
} else {
/* solve the second task in this same thread */
this.performStep(superSet, k, idx + 1, current, solution);
}
} else {
this.performStep(superSet, k, idx + 1, current, solution);
current.remove(x);
/* now check if a new thread is available for the second task */
if (this.semThreads.tryAcquire()) {
this.pool.submit(new SubSetComputer<T>(superSet, k, idx + 1, new HashSet<>(current), this.allSolutions, this.pool, this.semThreads, this.goalSize, this.semComplete));
} else {
this.performStep(superSet, k, idx + 1, current, solution);
}
}
}
}
public static <T> Collection<Set<T>> subsetsOfSize(final Collection<T> set, final int size) throws InterruptedException {
List<Set<T>> subsets = new ArrayList<>();
List<T> setAsList = new ArrayList<>(); // for easier access
setAsList.addAll(set);
getSubsetOfSizeRec(setAsList, size, 0, new HashSet<T>(), subsets);
return subsets;
}
private static <T> void getSubsetOfSizeRec(final List<T> superSet, final int k, final int idx, final Set<T> current, final Collection<Set<T>> solution) throws InterruptedException {
// successful stop clause
if (current.size() == k) {
solution.add(new HashSet<>(current));
return;
}
// unseccessful stop clause
if (idx == superSet.size()) {
return;
}
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Interrupted during calculation of subsets with special size");
}
T x = superSet.get(idx);
current.add(x);
// "guess" x is in the subset
getSubsetOfSizeRec(superSet, k, idx + 1, current, solution);
current.remove(x);
// "guess" x is not in the subset
getSubsetOfSizeRec(superSet, k, idx + 1, current, solution);
}
public static <T> List<Set<T>> getAllPossibleSubsetsWithSizeParallely(final Collection<T> superSet, final int k) throws InterruptedException {
List<Set<T>> res = new ArrayList<>();
int n = 1;
ExecutorService pool = Executors.newFixedThreadPool(n);
Semaphore solutionSemaphore = new Semaphore(1);
solutionSemaphore.acquire();
pool.submit(new SubSetComputer<>(new ArrayList<>(superSet), k, 0, new HashSet<>(), res, pool, new Semaphore(n - 1), MathExt.binomial(superSet.size(), k), solutionSemaphore));
solutionSemaphore.acquire();
pool.shutdown();
return res;
}
private static <T> void getAllPossibleSubsetsWithSizeRecursive(final List<T> superSet, final int k, final int idx, final Set<T> current, final List<Set<T>> solution) {
// successful stop clause
if (current.size() == k) {
solution.add(new HashSet<>(current));
return;
}
// unseccessful stop clause
if (idx == superSet.size()) {
return;
}
T x = superSet.get(idx);
current.add(x);
// "guess" x is in the subset
getAllPossibleSubsetsWithSizeRecursive(superSet, k, idx + 1, current, solution);
current.remove(x);
// "guess" x is not in the subset
getAllPossibleSubsetsWithSizeRecursive(superSet, k, idx + 1, current, solution);
}
public static <T> List<Set<T>> getAllPossibleSubsetsWithSize(final Collection<T> superSet, final int k) {
List<Set<T>> res = new ArrayList<>();
getAllPossibleSubsetsWithSizeRecursive(new ArrayList<>(superSet), k, 0, new HashSet<T>(), res);
return res;
}
public static List<Integer> invertPermutation(final List<Integer> permutation) {
int n = permutation.size();
List<Integer> inverse = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
inverse.add(permutation.indexOf(i));
}
return inverse;
}
/**
* Determines the permutation that makes l2 result from l1
**/
public static <T> List<Integer> getPermutation(final List<T> l1, final List<T> l2) {
int n = l1.size();
if (n != l2.size()) {
throw new IllegalArgumentException("Expecting two lists of same length!");
}
List<Integer> p = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
int pos = l1.indexOf(l2.get(i));
if (pos < 0) {
throw new IllegalArgumentException("The second list does not contain the element " + l1.get(i) + ". Cannot compute permutation between lists with different elements!");
}
p.add(pos);
}
return p;
}
/**
* Permutates the elements of the given list according to the given permutation
*
* @param <T>
* @param list
* @param permutation
* @return
*/
public static <T> List<T> applyPermutation(final List<T> list, final List<Integer> permutation) {
int n = list.size();
if (permutation.size() != n) {
throw new IllegalArgumentException("The permutation must have the same length as the list.");
}
List<T> out = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
out.add(list.get(permutation.get(i)));
}
return out;
}
public static <T> List<T> applyInvertedPermutation(final List<T> list, final List<Integer> permutation) {
return applyPermutation(list, invertPermutation(permutation));
}
public static <T> Collection<List<T>> getPermutations(final Collection<T> set) {
Collection<List<T>> permutations = new ArrayList<>();
List<T> setAsList = new ArrayList<>(set);
getPermutationsRec(setAsList, 0, permutations);
return permutations;
}
private static <T> void getPermutationsRec(final List<T> list, final int pointer, final Collection<List<T>> solution) {
if (pointer == list.size()) {
solution.add(list);
return;
}
for (int i = pointer; i < list.size(); i++) {
List<T> permutation = new ArrayList<>(list);
permutation.set(pointer, list.get(i));
permutation.set(i, list.get(pointer));
getPermutationsRec(permutation, pointer + 1, solution);
}
}
/**
* @param a
* The set A.
* @param b
* The set B.
* @return The difference A \ B.
*/
public static <S, T extends S, U extends S> Collection<S> difference(final Collection<T> a, final Collection<U> b) {
List<S> out = new ArrayList<>();
for (S item : a) {
if (b == null || !b.contains(item)) {
out.add(item);
}
}
return out;
}
/**
* Computes the set of elements which are disjoint, i.e., elements from the set (A \cup B) \ (A \cap B)
*
* @param a
* The set A.
* @param b
* The set B.
* @return The difference A \ B.
*/
public static <S, T extends S, U extends S> Collection<S> getDisjointSet(final Collection<T> a, final Collection<U> b) {
List<S> out = new ArrayList<>(difference(a, b));
for (S item : difference(b, a)) {
if (!out.contains(item)) {
out.add(item);
}
}
return out;
}
/**
* @param a
* The set A.
* @param b
* The set B.
* @return The difference A \ B.
*/
public static <S, T extends S, U extends S> List<S> difference(final List<T> a, final Collection<U> b) {
List<S> out = new ArrayList<>();
for (S item : a) {
if (b == null || !b.contains(item)) {
out.add(item);
}
}
return out;
}
public static <S, T extends S, U extends S> boolean differenceEmpty(final Collection<T> a, final Collection<U> b) {
if (a == null || a.isEmpty()) {
return true;
}
for (S item : a) {
if (!b.contains(item)) {
return false;
}
}
return true;
}
public static <S, T extends S, U extends S> boolean differenceNotEmpty(final Collection<T> a, final Collection<U> b) {
if (b == null) {
return !a.isEmpty();
}
for (S item : a) {
if (!b.contains(item)) {
return true;
}
}
return false;
}
/**
* @param a
* The set A.
* @param b
* The set B.
* @return The Cartesian product A x B.
*/
public static <S, T> Collection<Pair<S, T>> cartesianProduct(final Collection<S> a, final Collection<T> b) {
Set<Pair<S, T>> product = new HashSet<>();
for (S item1 : a) {
for (T item2 : b) {
product.add(new Pair<>(item1, item2));
}
}
return product;
}
public static <T> Collection<List<T>> cartesianProduct(final List<? extends Collection<T>> listOfSets) {
return cartesianProductReq(new ArrayList<>(listOfSets));
}
/**
* @param a
* The set A.
* @param b
* The set B.
* @return The Cartesian product A x B.
*/
private static <T> Collection<List<T>> cartesianProductReq(final List<? extends Collection<T>> listOfSets) {
/* compute expected number of items of the result */
int expectedSize = 1;
for (Collection<T> items : listOfSets) {
assert items.size() == new HashSet<>(items).size() : "One of the collection is effectively a multi-set, which is forbidden for CP computation: " + items;
expectedSize *= items.size();
}
/* there must be at least one set */
if (listOfSets.isEmpty()) {
throw new IllegalArgumentException("Empty list of sets");
}
/*
* if there is only one set, create tuples of size 1 and return the set of tuples
*/
if (listOfSets.size() == 1) {
Set<List<T>> product = new HashSet<>();
for (T obj : listOfSets.get(0)) {
List<T> tupleOfSize1 = new ArrayList<>();
tupleOfSize1.add(obj);
product.add(tupleOfSize1);
}
assert product.size() == expectedSize : "Invalid number of expected entries! Expected " + expectedSize + " but computed " + product.size() + " for a single set: " + listOfSets.get(0);
return product;
}
/*
* if there are more sets, remove the last one, compute the cartesian for the rest, and append the removed one afterwards
*/
Collection<T> removed = listOfSets.get(listOfSets.size() - 1);
listOfSets.remove(listOfSets.size() - 1);
Collection<List<T>> subSolution = cartesianProduct(listOfSets);
Set<List<T>> product = new HashSet<>();
for (List<T> tuple : subSolution) {
for (T item : removed) {
List<T> newTuple = new ArrayList<>(tuple);
newTuple.add(item);
product.add(newTuple);
}
}
assert product.size() == expectedSize : "Invalid number of expected entries! Expected " + expectedSize + " but computed " + product.size();
return product;
}
/**
* @param a
* The set A.
* @throws InterruptedException
*/
public static <S> Collection<List<S>> cartesianProduct(final Collection<S> set, final int number) throws InterruptedException {
List<List<S>> product = new ArrayList<>();
List<S> setAsList = new ArrayList<>(set);
if (number <= 1) {
for (S elem : set) {
List<S> tuple = new ArrayList<>();
tuple.add(elem);
product.add(tuple);
}
return product;
}
for (List<S> restProduct : cartesianProduct(setAsList, number - 1)) {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException();
}
for (S elem : set) {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException();
}
List<S> tuple = new ArrayList<>(restProduct.size() + 1);
for (S elementOfRestProduct : restProduct) {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException();
}
tuple.add(elementOfRestProduct);
}
tuple.add(0, elem);
product.add(tuple);
}
}
return product;
}
/* RELATIONS */
public static <K, V> Collection<Pair<K, V>> relation(final Collection<K> keys, final Collection<V> values, final Predicate<Pair<K, V>> relationPredicate) {
Collection<Pair<K, V>> relation = new HashSet<>();
for (K key : keys) {
for (V val : values) {
Pair<K, V> p = new Pair<>(key, val);
if (relationPredicate.test(p)) {
relation.add(p);
}
}
}
return relation;
}
public static <K, V> Map<K, Collection<V>> relationAsFunction(final Collection<K> keys, final Collection<V> values, final Predicate<Pair<K, V>> relationPredicate) {
Map<K, Collection<V>> relation = new HashMap<>();
for (K key : keys) {
relation.put(key, new HashSet<>());
for (V val : values) {
Pair<K, V> p = new Pair<>(key, val);
if (relationPredicate.test(p)) {
relation.get(key).add(val);
}
}
}
return relation;
}
/* FUNCTIONS */
public static <K, V> Collection<Map<K, V>> allMappings(final Collection<K> domain, final Collection<V> range, final boolean totalsOnly, final boolean injectivesOnly, final boolean surjectivesOnly) throws InterruptedException {
Collection<Map<K, V>> mappings = new ArrayList<>();
/* compute possible domains of the functions */
if (totalsOnly) {
if (domain.isEmpty()) {
return mappings;
}
List<K> domainAsList = new ArrayList<>(domain);
int n = domainAsList.size();
for (List<V> reducedRange : cartesianProduct(range, domain.size())) {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Interrupted during calculating all mappings");
}
/*
* create map that corresponds to this entry of the cartesian product
*/
boolean considerMap = true;
Map<K, V> map = new HashMap<>();
List<V> coveredRange = new ArrayList<>();
for (int i = 0; i < n; i++) {
V val = reducedRange.get(i);
/* check injectivity (if required) */
if (injectivesOnly && coveredRange.contains(val)) {
considerMap = false;
break;
}
coveredRange.add(val);
map.put(domainAsList.get(i), val);
}
/* check surjectivity (if required) */
if (surjectivesOnly && !coveredRange.containsAll(range)) {
considerMap = false;
}
/* if all criteria are satisfied, add map */
if (considerMap) {
mappings.add(map);
}
}
} else {
for (Collection<K> reducedDomain : powerset(domain)) {
mappings.addAll(allMappings(reducedDomain, range, true, injectivesOnly, surjectivesOnly));
}
if (!surjectivesOnly) {
mappings.add(new HashMap<>()); // add the empty mapping
}
}
return mappings;
}
public static <K, V> Collection<Map<K, V>> allTotalMappings(final Collection<K> domain, final Collection<V> range) throws InterruptedException {
return allMappings(domain, range, true, false, false);
}
public static <K, V> Collection<Map<K, V>> allPartialMappings(final Collection<K> domain, final Collection<V> range) throws InterruptedException {
return allMappings(domain, range, false, false, false);
}
/**
* Computes all total mappings that satisfy some given predicate. The predicate is already applied to the partial mappings from which the total mappings are computed in order to prune and speed up
* the computation.
*
* @param domain
* The domain set.
* @param range
* The range set.
* @param pPredicate
* The predicate that is evaluated for every partial
* @return All partial mappings from the domain set to the range set.
*/
public static <K, V> Set<Map<K, V>> allTotalAndInjectiveMappingsWithConstraint(final Collection<K> domain, final Collection<V> range, final Predicate<Map<K, V>> pPredicate) throws InterruptedException {
Set<Map<K, V>> mappings = new HashSet<>();
if (domain.isEmpty()) {
return mappings;
}
/* now run breadth first search */
List<K> domainAsList = new ArrayList<>(domain);
int domainSize = domainAsList.size();
List<Map<K, V>> open = new ArrayList<>();
open.add(new HashMap<>());
while (!open.isEmpty()) {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Interrupted during calculation of allTotalMappingsWithConstraint.");
}
Map<K, V> partialMap = open.get(0);
open.remove(0);
/* add partial map if each key has a value assigned (map is total) */
int index = partialMap.keySet().size();
if (index >= domainSize) {
mappings.add(partialMap);
continue;
}
/* add new assignment to partial map */
K key = domainAsList.get(index);
for (V val : range) {
/* due to injectivity, skip this option */
if (partialMap.containsValue(val)) {
continue;
}
Map<K, V> extendedMap = new HashMap<>(partialMap);
extendedMap.put(key, val);
if (pPredicate.test(extendedMap)) {
open.add(extendedMap);
}
}
}
return mappings;
}
public static <K, V> Set<Map<K, V>> allTotalMappingsWithLocalConstraints(final Collection<K> domain, final Collection<V> range, final Predicate<Pair<K, V>> pPredicate) throws InterruptedException {
Map<K, Collection<V>> pairsThatSatisfyCondition = relationAsFunction(domain, range, pPredicate);
return allFuntionsFromFunctionallyDenotedRelation(pairsThatSatisfyCondition);
} // allPartialMappings
public static <K, V> Set<Map<K, V>> allFuntionsFromFunctionallyDenotedRelation(final Map<K, Collection<V>> pRelation) throws InterruptedException {
return allFunctionsFromFunctionallyDenotedRelationRewritingReference(new HashMap<>(pRelation));
}
private static <K, V> Set<Map<K, V>> allFunctionsFromFunctionallyDenotedRelationRewritingReference(final Map<K, Collection<V>> pRelation) throws InterruptedException {
Set<Map<K, V>> out = new HashSet<>();
if (pRelation.isEmpty()) {
out.add(new HashMap<>(0, 1.0f));
return out;
}
/* compute all pairs that share one particular entry as key */
K firstKey = pRelation.keySet().iterator().next();
Collection<V> vals = pRelation.get(firstKey);
pRelation.remove(firstKey);
/* if the domain has size 1 or 0, return the set of mappings for the element in the domain */
if (pRelation.isEmpty()) {
for (V val : vals) {
final Map<K, V> mapWithOneEntry = new HashMap<>(1);
mapWithOneEntry.put(firstKey, val);
out.add(mapWithOneEntry);
}
}
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Interrupted during allFunctionsFromFunctionallyDenotedRelationRewritingReference");
}
/* otherwise decompose by recursion */
else {
Set<Map<K, V>> recursivelyObtainedFunctions = allFunctionsFromFunctionallyDenotedRelationRewritingReference(pRelation);
for (Map<K, V> func : recursivelyObtainedFunctions) {
for (V val : vals) {
Map<K, V> newFunc = new HashMap<>(func);
newFunc.put(firstKey, val);
out.add(newFunc);
}
}
}
return out;
}
/* ORDER OPERATIONS (SHUFFLE, SORT, PERMUTATE) */
public static <T> void shuffle(final List<T> list, final long seed) {
/* preliminaries */
List<Integer> unusedItems = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
unusedItems.add(i);
}
List<T> copy = new ArrayList<>();
copy.addAll(list);
list.clear();
/* select randomly from unusedItems until unusedItems is empty */
while (!unusedItems.isEmpty()) {
int index = new Random(seed).nextInt(unusedItems.size());
list.add(copy.get(unusedItems.get(index)));
}
}
public static <T> T getRandomElement(final Collection<T> set, final long seed) {
return getRandomElement(set, new Random(seed));
}
public static <T> T getRandomElement(final Collection<T> set, final Random random) {
int choice = random.nextInt(set.size());
if (set instanceof List) {
return ((List<T>) set).get(choice);
}
int i = 0;
for (T elem : set) {
if (i++ == choice) {
return elem;
}
}
return null;
}
public static <T> T getRandomElement(final List<T> list, final Random random, final List<Double> probabilityVector) {
/* sanity check */
int n = list.size();
if (probabilityVector.size() != n) {
throw new IllegalArgumentException("Probability vector should have length " + n + " but has " + probabilityVector.size());
}
/* normalize probabilities if necessary */
double alpha = probabilityVector.stream().reduce((a, b) -> a + b).get();
List<Double> probabilities = alpha == 1 ? probabilityVector : probabilityVector.stream().map(d -> d / alpha).collect(Collectors.toList());
/* draw random number and loop over elements until the accumulated density is the desired one */
double randomNumber = random.nextDouble();
double accumulatedProbability = 0;
for (int i = 0; i < n; i++) {
accumulatedProbability += probabilities.get(i);
if (accumulatedProbability >= randomNumber) {
return list.get(i);
}
}
throw new IllegalStateException("Probability has been accumulated to " + accumulatedProbability + " but no element was returned.");
}
public static <T> Collection<T> getRandomSubset(final Collection<T> set, final int k, final Random random) {
List<T> copy = new ArrayList<>(set);
Collections.shuffle(copy, random);
return copy.stream().limit(k).collect(Collectors.toList());
}
public static Collection<Integer> getRandomSetOfIntegers(final int maxExclusive, final int k, final Random random) {
List<Integer> ints = new ArrayList<>(k);
IntStream.range(0, maxExclusive).forEach(ints::add);
return getRandomSubset(ints, k, random);
}
public static <T extends Comparable<T>> List<T> mergeSort(final Collection<T> set) {
if (set.isEmpty()) {
return new ArrayList<>();
}
if (set.size() == 1) {
List<T> result = new ArrayList<>();
result.addAll(set);
return result;
}
/* create sublists */
List<T> sublist1 = new ArrayList<>();
List<T> sublist2 = new ArrayList<>();
int mid = (int) Math.ceil(set.size() / 2.0);
int i = 0;
for (T elem : set) {
if (i++ < mid) {
sublist1.add(elem);
} else {
sublist2.add(elem);
}
}
/* sort sublists */
return mergeLists(mergeSort(sublist1), mergeSort(sublist2));
}
private static <T extends Comparable<T>> List<T> mergeLists(final List<T> list1, final List<T> list2) {
List<T> result = new ArrayList<>();
while (!list1.isEmpty() && !list2.isEmpty()) {
if (list1.get(0).compareTo(list2.get(0)) < 0) {
result.add(list1.get(0));
list1.remove(0);
} else {
result.add(list2.get(0));
list2.remove(0);
}
}
while (!list1.isEmpty()) {
result.add(list1.get(0));
list1.remove(0);
}
while (!list2.isEmpty()) {
result.add(list2.get(0));
list2.remove(0);
}
return result;
}
public static <K, V extends Comparable<V>> List<K> keySetSortedByValues(final Map<K, V> map, final boolean asc) {
if (map.isEmpty()) {
return new ArrayList<>();
}
if (map.size() == 1) {
List<K> result = new ArrayList<>();
result.addAll(map.keySet());
return result;
}
/* create submaps */
Map<K, V> submap1 = new HashMap<>();
Map<K, V> submap2 = new HashMap<>();
int mid = (int) Math.ceil(map.size() / 2.0);
int i = 0;
for (Entry<K, V> entry : map.entrySet()) {
if (i++ < mid) {
submap1.put(entry.getKey(), entry.getValue());
} else {
submap2.put(entry.getKey(), entry.getValue());
}
}
/* sort sublists */
return mergeMaps(keySetSortedByValues(submap1, asc), keySetSortedByValues(submap2, asc), map, asc);
}
private static <K, V extends Comparable<V>> List<K> mergeMaps(final List<K> keys1, final List<K> keys2, final Map<K, V> map, final boolean asc) {
List<K> result = new ArrayList<>();
while (!keys1.isEmpty() && !keys2.isEmpty()) {
double comp = map.get(keys1.get(0)).compareTo(map.get(keys2.get(0)));
if (asc && comp < 0 || !asc && comp >= 0) {
result.add(keys1.get(0));
keys1.remove(0);
} else {
result.add(keys2.get(0));
keys2.remove(0);
}
}
while (!keys1.isEmpty()) {
result.add(keys1.get(0));
keys1.remove(0);
}
while (!keys2.isEmpty()) {
result.add(keys2.get(0));
keys2.remove(0);
}
return result;
}
public static int calculateNumberOfTotalOrderings(final PartialOrderedSet<?> set) throws InterruptedException {
return getAllTotalOrderings(set).size();
}
public static <E> Collection<List<E>> getAllTotalOrderings(final PartialOrderedSet<E> set) throws InterruptedException {
/* for an empty set, create a list that only contains the empty list */
if (set.isEmpty()) {
return Arrays.asList(new ArrayList<>());
}
/* otherwise get the list of all elements that could be the last item and fix them once */
Collection<List<E>> candidates = new ArrayList<>();
Map<E, Set<E>> order = new HashMap<>(set.getOrder());
set.getLinearization();
Collection<E> itemsWithoutSuccessor = set.stream().filter(s -> !order.containsKey(s) || order.get(s).isEmpty()).collect(Collectors.toList());
for (E item : itemsWithoutSuccessor) {
/* create a new set without the item; this basically means that we enforce that it will be the last item */
PartialOrderedSet<E> reducedSet = new PartialOrderedSet<>(set);
reducedSet.remove(item);
/* now get all ordering for the reduced set */
for (List<E> completionOfReducedSet : getAllTotalOrderings(reducedSet)) {
completionOfReducedSet.add(item);
candidates.add(completionOfReducedSet);
}
}
return candidates;
}
public static String serializeAsSet(final Collection<String> set) {
return set.toString().replace("\\[", "{").replace("\\]", "}");
}
public static Set<String> unserializeSet(final String setDescriptor) {
Set<String> items = new HashSet<>();
for (String item : setDescriptor.substring(1, setDescriptor.length() - 1).split(",")) {
if (!item.trim().isEmpty()) {
items.add(item.trim());
}
}
return items;
}
public static List<String> unserializeList(final String listDescriptor) {
if (listDescriptor == null) {
throw new IllegalArgumentException("Invalid list descriptor NULL.");
}
if (!listDescriptor.startsWith("[") || !listDescriptor.endsWith("]")) {
throw new IllegalArgumentException("Invalid list descriptor \"" + listDescriptor + "\". Must start with '[' and end with ']'");
}
List<String> items = new ArrayList<>();
for (String item : listDescriptor.substring(1, listDescriptor.length() - 1).split(",")) {
if (!item.trim().isEmpty()) {
items.add(item.trim());
}
}
return items;
}
public static Interval unserializeInterval(final String intervalDescriptor) {
List<String> interval = unserializeList(intervalDescriptor);
double min = Double.parseDouble(interval.get(0));
return new Interval(min, interval.size() == 1 ? min : Double.valueOf(interval.get(1)));
}
public static <T> List<T> getInvertedCopyOfList(final List<T> list) {
List<T> copy = new ArrayList<>();
int n = list.size();
for (int i = 0; i < n; i++) {
copy.add(list.get(n - i - 1));
}
return copy;
}
public static <T> List<T> addAndGet(final List<T> list, final T item) {
list.add(item);
return list;
}
public static <T, U> Map<U, Collection<T>> groupCollectionByAttribute(final Collection<T> collection, final IGetter<T, U> getter) throws InterruptedException, GetPropertyFailedException {
Map<U, Collection<T>> groupedCollection = new HashMap<>();
for (T i : collection) {
groupedCollection.computeIfAbsent(getter.getPropertyOf(i), t -> new ArrayList<>()).add(i);
}
return groupedCollection;
}
/**
* Splits a string into multiple strings using "," as a separator and returns the result as a list.
*
* @param stringList The list in the form of a string.
* @return
*/
public static List<String> explode(final String stringList) {
return explode(stringList, DEFAULT_LIST_ITEM_SEPARATOR);
}
/**
* Splits a string into multiple strings by the given separator and returns the result as a list.
*
* @param stringList The list in the form of a string.
* @param separator The separator to be used for splitting.
* @return The list representing the split string.
*/
public static List<String> explode(final String stringList, final String separator) {
return Arrays.stream(stringList.split(separator)).collect(Collectors.toList());
}
/**
* Concatenates toString representations of objects separated by the given separator to a single string.
* @param collection The collection of objects to be concatenated.
* @param separator The separator for separating elements.
* @return The collection of objects concatenated to a string.
*/
public static String implode(final Collection<? extends Object> collection, final String separator) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object o : collection) {
if (first) {
first = false;
} else {
sb.append(separator);
}
sb.append(o + "");
}
return sb.toString();
}
public static boolean doesStringCollectionOnlyContainNumbers(final Collection<String> strings) {
try {
for (String s : strings) {
Double.parseDouble(s);
}
} catch (NumberFormatException e) {
return false;
}
return true;
}
public static Type getGenericClass(final Collection<?> c) {
ParameterizedType stringListType = (ParameterizedType) c.getClass().getGenericSuperclass();
return stringListType.getActualTypeArguments()[0];
}
public static <T extends Comparable<T>> int argmax(final List<T> list) {
int n = list.size();
T best = null;
int index = -1;
for (int i = 0; i < n; i++) {
T x = list.get(i);
if (best == null || best.compareTo(x) > 0) {
best = x;
index = i;
}
}
return index;
}
public static <T extends Comparable<T>> int argmax(final T[] arr) {
return argmax(Arrays.asList(arr));
}
public static <T extends Comparable<T>> int argmin(final List<T> list) {
int n = list.size();
T best = null;
int index = -1;
for (int i = 0; i < n; i++) {
T x = list.get(i);
if (best == null || best.compareTo(x) < 0) {
best = x;
index = i;
}
}
return index;
}
public static <T extends Comparable<T>> int argmin(final T[] arr) {
return argmin(Arrays.asList(arr));
}
public static int argmin(final int[] arr) {
int minIndex = -1;
int min = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
minIndex = i;
}
}
return minIndex;
}
public static int argmax(final int[] arr) {
int maxIndex = -1;
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
maxIndex = i;
}
}
return maxIndex;
}
public static <T> Collection<List<T>> getSubGridRelationFromDomains(final List<List<T>> hypercubeDomains, final int numSamples) {
return getSubGridRelationFromRelation(cartesianProduct(hypercubeDomains), numSamples);
}
public static <T> Collection<List<T>> getSubGridRelationFromRelation(final Collection<List<T>> relation, final int numSamples) {
/* determine total number of entries of the hypercube */
long totalSize = relation.size();
if (totalSize < numSamples) {
throw new IllegalArgumentException("Cannot generate a sample of size " + numSamples + " for a hypercube with only " + totalSize + " entries.");
}
int stepSize = (int) Math.floor(totalSize * 1.0 / numSamples);
/* compute full hypercube */
int i = 0;
Collection<List<T>> subSample = new ArrayList<>();
for (List<T> tuple : relation) {
if (i % stepSize == 0) {
subSample.add(tuple);
}
i++;
if (subSample.size() == numSamples) {
break;
}
}
return subSample;
}
public static double sum(final Collection<? extends Number> nums) {
double sum = 0;
for (Number n : nums) {
if (n == null) {
return Double.NaN;
}
sum += n.doubleValue();
}
return sum;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/TupleFoundEvent.java
|
package ai.libs.jaicore.basic.sets;
import java.util.List;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
public class TupleFoundEvent<T> extends AAlgorithmEvent {
private final List<T> tuple;
public TupleFoundEvent(final IAlgorithm<?, ?> algorithm, final List<T> tuple) {
super(algorithm);
this.tuple = tuple;
}
public List<T> getTuple() {
return this.tuple;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/sets/TupleOfCartesianProductFoundEvent.java
|
package ai.libs.jaicore.basic.sets;
import java.util.List;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
public class TupleOfCartesianProductFoundEvent<T> extends AAlgorithmEvent {
private final List<T> tuple;
public TupleOfCartesianProductFoundEvent(final IAlgorithm<?, ?> algorithm, final List<T> tuple) {
super(algorithm);
this.tuple = tuple;
}
public List<T> getTuple() {
return this.tuple;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/ITransformation.java
|
package ai.libs.jaicore.basic.transform;
public interface ITransformation<V> {
public V transform(V input);
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/CosineTransform.java
|
package ai.libs.jaicore.basic.transform.vector;
/**
* Calculates the cosine transform of a time series. For this implementation,
* the definition as given in "Non-isometric transforms in time series
* classification using DTW" by Tomasz Gorecki and Maciej Luczak (2014) is used.
*
* The cosine transform <code>f = {f(k): k = 1 to n}</code> of a time series
* <code>T = {T(i): i = 1 to n }</code> is defined as
* <code>f(k) = sum_{i=1}^{n} T(i) * cos[(PI/n)*(i-0.5)*(k-1)]</code>.
*
* @author fischor
*/
public class CosineTransform implements IVectorTransform {
@Override
public double[] transform(final double[] input) {
double n = input.length;
double[] cosinusTransform = new double[input.length];
for (int k = 0; k < n; k++) {
// Sum over all points of the input.
double sum = 0;
for (int i = 0; i < n; i++) {
// Make (i - 0.5) to (i + 0.5) and (k-1) to k because of zero-indexing.
sum += input[i] * Math.cos((Math.PI / n) * (i + 0.5) * k);
}
cosinusTransform[k] = sum;
}
return cosinusTransform;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/HilbertTransform.java
|
package ai.libs.jaicore.basic.transform.vector;
/**
* Calculates the Hilbert transform of a time series. For this implementation,
* the definition as given in "Non-isometric transforms in time series
* classification using DTW" by Tomasz Gorecki and Maciej Luczak (2014) is used.
*
* The Hilbert transform <code>f = {f(k): k = 1 to n}</code> of a time series
* <code>T = {T(i): i = 1 to n }</code> is defined as
* <code>f(k) = sum_{i=1, i!=k}^{n} f(i) / (k-i)</code>.
*
* @author fischor
*/
public class HilbertTransform implements IVectorTransform {
@Override
public double[] transform(final double[] input) {
double n = input.length;
double[] hilbertTransform = new double[input.length];
for (int k = 0; k < n; k++) {
// Sum over all points of the input.
double sum = 0;
for (int i = 0; i < n; i++) {
if (i != k) {
sum += input[i] / (k - i);
}
}
hilbertTransform[k] = sum;
}
return hilbertTransform;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/IVectorTransform.java
|
package ai.libs.jaicore.basic.transform.vector;
import ai.libs.jaicore.basic.transform.ITransformation;
public interface IVectorTransform extends ITransformation<double[]> {
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/NormalizeByStdTransform.java
|
package ai.libs.jaicore.basic.transform.vector;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import ai.libs.jaicore.basic.StatisticsUtil;
public class NormalizeByStdTransform implements IVectorTransform {
@Override
public double[] transform(final double[] input) {
List<Double> t = Arrays.stream(input).mapToObj(Double::valueOf).collect(Collectors.toList());
double standardDeviation = StatisticsUtil.standardDeviation(t);
if (standardDeviation == 0) {
return new double[input.length];
}
double[] normalizedT = new double[input.length];
for (int i = 0; i < input.length; i++) {
normalizedT[i] = input[i] / standardDeviation;
}
return normalizedT;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/PiecewiseAggregateApproximationTransform.java
|
package ai.libs.jaicore.basic.transform.vector;
public class PiecewiseAggregateApproximationTransform implements IVectorTransform {
private final int reducedLength;
public PiecewiseAggregateApproximationTransform(final int reducedLength) {
this.reducedLength = reducedLength;
}
@Override
public double[] transform(final double[] input) {
double[] ppa = new double[this.reducedLength];
double n = input.length;
for (int i = 0; i < this.reducedLength; i++) {
double ppavalue = 0;
for (int j = (int) (n / ((this.reducedLength * (i - 1)) + 1)); j < ((n / this.reducedLength) * i); j++) {
ppavalue += input[j];
}
ppavalue = (this.reducedLength / n) * ppavalue;
ppa[i] = ppavalue;
}
return ppa;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/SineTransform.java
|
package ai.libs.jaicore.basic.transform.vector;
/**
* Calculates the sine transform of a time series. For this implementation, the
* definition as given in "Non-isometric transforms in time series
* classification using DTW" by Tomasz Gorecki and Maciej Luczak (2014) is used.
*
* The sine transform <code>f = {f(k): k = 1 to n}</code> of a time series
* <code>T = {T(i): i = 1 to n }</code> is defined as
* <code>f(k) = sum_{i=1}^{n} T(i) * sin[(PI/n)*(i-0.5)*k]</code>.
*
* @author fischor
*/
public class SineTransform implements IVectorTransform {
@Override
public double[] transform(final double[] input) {
double n = input.length;
double[] cosinusTransform = new double[input.length];
for (int k = 0; k < n; k++) {
// Sum over all points of the input.
double sum = 0;
for (int i = 0; i < n; i++) {
// Make (i-1) to (i+1) and k to (k+1) because of zero-indexing.
sum += input[i] * Math.sin((Math.PI / n) * (i + 0.5) * (k + 1));
}
cosinusTransform[k] = sum;
}
return cosinusTransform;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/ZTransform.java
|
package ai.libs.jaicore.basic.transform.vector;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import ai.libs.jaicore.basic.StatisticsUtil;
public class ZTransform implements IVectorTransform {
public static final double EPSILON = 0.0000001;
@Override
public double[] transform(final double[] input) {
List<Double> t = Arrays.stream(input).mapToObj(Double::valueOf).collect(Collectors.toList());
double mean = StatisticsUtil.mean(t);
double standardDeviation = StatisticsUtil.standardDeviation(t);
if ((-EPSILON < standardDeviation) && (standardDeviation < EPSILON)) {
return new double[input.length]; // All zeros.
}
double[] zTransformedT = new double[input.length];
for (int i = 0; i < input.length; i++) {
zTransformedT[i] = (input[i] - mean) / standardDeviation;
}
return zTransformedT;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/package-info.java
|
/**
* Package containing filters that calculate transforms of time series.
*
* @author fischor
*/
package ai.libs.jaicore.basic.transform.vector;
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/derivate/ADerivateFilter.java
|
package ai.libs.jaicore.basic.transform.vector.derivate;
import ai.libs.jaicore.basic.transform.vector.IVectorTransform;
/**
* Abstract superclass for all derivate filters.
*
* @author fischor
*/
public abstract class ADerivateFilter implements IVectorTransform {
/**
* Flag that states whether the filter should add a padding to the derivate
* assure that is has the same length as the origin time series or not.
*/
protected boolean withBoundaries;
protected ADerivateFilter(final boolean withBoundaries) {
this.withBoundaries = withBoundaries;
}
protected ADerivateFilter() {
this.withBoundaries = false;
}
/**
* Calculates the derivate of a time series.
*
* @param t The time series to calculate the derivate for.
* @return The derivate of the time series.
*/
protected abstract double[] derivate(double[] t);
/**
* Calcuates the derivates of a time series. In contrast to the normal
* {@link derivate} calculation, this method is guaranteed to return a derivate
* that has the same length than the original time series. This is accomplished
* via padding.
*
* @param t The time series to calculate the derivate for.
* @return The, possibly padded, derivate of the time series.
*/
protected abstract double[] derivateWithBoundaries(double[] t);
@Override
public double[] transform(final double[] input) {
if (this.withBoundaries) {
return this.derivateWithBoundaries(input);
} else {
return this.derivate(input);
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/derivate/BackwardDifferenceDerivate.java
|
package ai.libs.jaicore.basic.transform.vector.derivate;
/**
* Filter that calculate the Backward Difference derivate. The Backward
* Difference derivate <code>t'</code> for a time series
* <code>T = {T(1), T(2), .., T(n)}<code> is defined as <code>T'(i) = T(i) - T(i-1)</code>
* for <code>i = 1 to n</code>. When padded, <code>T'(0) = T'(1)</code>.
*
* @author fischor
*/
public class BackwardDifferenceDerivate extends ADerivateFilter {
public BackwardDifferenceDerivate() {
super();
}
public BackwardDifferenceDerivate(boolean withBoundaries) {
super(withBoundaries);
}
@Override
protected double[] derivate(double[] t) {
double[] derivate = new double[t.length - 1];
for (int i = 1; i < t.length; i++) {
derivate[i - 1] = t[i] - t[i - 1];
}
return derivate;
}
@Override
protected double[] derivateWithBoundaries(double[] t) {
double[] derivate = new double[t.length];
for (int i = 1; i < t.length; i++) {
derivate[i] = t[i] - t[i - 1];
}
derivate[0] = derivate[1];
return derivate;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/derivate/ForwardDifferenceDerivate.java
|
package ai.libs.jaicore.basic.transform.vector.derivate;
/**
* Filter that calculate the Forward Difference derivate. The Forward Difference
* derivate <code>T'</code> for a time series
* <code>T = {T(0), T(1), T(2), .., T(n)}<code> is defined as <code>T'(i) = T(i+1) - T(i)</code>
* for <code>i = 0 to n-1</code>. When padded, <code>T'(n) = T'(n-1)</code>.
*
* @author fischor
*/
public class ForwardDifferenceDerivate extends ADerivateFilter {
public ForwardDifferenceDerivate() {
super();
}
public ForwardDifferenceDerivate(final boolean withBoundaries) {
super(withBoundaries);
}
@Override
protected double[] derivate(final double[] t) {
double[] derivate = new double[t.length - 1];
for (int i = 0; i < t.length - 1; i++) {
derivate[i] = t[i + 1] - t[i];
}
return derivate;
}
@Override
protected double[] derivateWithBoundaries(final double[] t) {
double[] derivate = new double[t.length];
for (int i = 0; i < t.length - 1; i++) {
derivate[i] = t[i + 1] - t[i];
}
derivate[t.length - 1] = derivate[t.length - 2];
return derivate;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/derivate/GulloDerivate.java
|
package ai.libs.jaicore.basic.transform.vector.derivate;
/**
* Calculates the derivative of a timeseries as described first by Gullo et. al
* (2009).
*
* The Gullo derivate <code>T'</code> for a time series
* <code>T = {T(0), T(1), T(2), .., T(n)}<code> is defined as <code>T'(i) = (T(i+1) - T(i-1)) / 2</code>
* for <code>i = 1 to n-1</code>. When padded, <code>T'(0) = T'(1)</code> and
* <code>T'(n) = T'(n-1)</code>.
*
* @author fischor
*/
public class GulloDerivate extends ADerivateFilter {
public GulloDerivate() {
super();
}
public GulloDerivate(boolean withBoundaries) {
super(withBoundaries);
}
@Override
protected double[] derivate(double[] t) {
double[] derivate = new double[t.length - 2];
for (int i = 1; i < t.length - 1; i++) {
derivate[i - 1] = (t[i + 1] - t[i - 1]) / 2;
}
return derivate;
}
@Override
protected double[] derivateWithBoundaries(double[] t) {
double[] derivate = new double[t.length];
for (int i = 1; i < t.length - 1; i++) {
derivate[i] = (t[i + 1] - t[i - 1]) / 2;
}
derivate[0] = derivate[1];
derivate[t.length - 1] = derivate[t.length - 2];
return derivate;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/derivate/KeoghDerivate.java
|
package ai.libs.jaicore.basic.transform.vector.derivate;
/**
* Calculates the derivative of a timeseries as described first by Keogh and
* Pazzani (2001).
*
* The Keogh derivate <code>T'</code> for a time series
* <code>T = {T(0), T(1), T(2), .., T(n)}<code> is defined as <code>T'(i) = (T(i) - T(i-1) + (T(i+1) - T(i-1)) / 2)) / 2</code>
* for <code>i = 1 to n-1</code>. When padded, <code>T'(0) = T'(1)</code> and
* <code>T'(n) = T'(n-1)</code>.
*
* @author fischor
*/
public class KeoghDerivate extends ADerivateFilter {
public KeoghDerivate() {
super();
}
public KeoghDerivate(boolean withBoundaries) {
super(withBoundaries);
}
@Override
protected double[] derivate(double[] t) {
double[] derivate = new double[t.length - 2];
for (int i = 1; i < t.length - 1; i++) {
derivate[i - 1] = ((t[i] - t[i - 1]) + (t[i + 1] - t[i - 1]) / 2) / 2;
}
return derivate;
}
@Override
protected double[] derivateWithBoundaries(double[] t) {
double[] derivate = new double[t.length];
for (int i = 1; i < t.length - 1; i++) {
derivate[i] = ((t[i] - t[i - 1]) + (t[i + 1] - t[i - 1]) / 2) / 2;
}
derivate[0] = derivate[1];
derivate[t.length - 1] = derivate[t.length - 2];
return derivate;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/basic/transform/vector/derivate/package-info.java
|
/**
* Package containing filters that calculate derivates of time series.
*
* @author fischor
*/
package ai.libs.jaicore.basic.transform.vector.derivate;
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/concurrent/ANamedTimerTask.java
|
package ai.libs.jaicore.concurrent;
public abstract class ANamedTimerTask extends TrackableTimerTask {
private String descriptor;
protected ANamedTimerTask() {
this("<unnamed task>");
}
protected ANamedTimerTask(final String descriptor) {
super();
this.descriptor = descriptor;
}
public String getDescriptor() {
return this.descriptor;
}
public void setDescriptor(final String descriptor) {
this.descriptor = descriptor;
}
@Override
public String toString() {
return "NamedTimerTask: " + this.descriptor + ", canceled: " + this.isCanceled();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/concurrent/CancellationTimerTask.java
|
package ai.libs.jaicore.concurrent;
import org.api4.java.common.control.ICancelable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CancellationTimerTask extends ANamedTimerTask {
private static final Logger logger = LoggerFactory.getLogger(CancellationTimerTask.class);
private final ICancelable thingToBeCanceled;
private final Runnable hookToExecutePriorToCancel;
public CancellationTimerTask(final String descriptor, final ICancelable cancelable, final Runnable hookToExecutePriorToInterruption) {
super(descriptor);
this.thingToBeCanceled = cancelable;
this.hookToExecutePriorToCancel = hookToExecutePriorToInterruption;
}
public CancellationTimerTask(final String descriptor, final ICancelable thingToBeCanceled) {
this(descriptor, thingToBeCanceled, null);
}
public ICancelable getCancelable() {
return this.thingToBeCanceled;
}
public Runnable getHookToExecutePriorToInterruption() {
return this.hookToExecutePriorToCancel;
}
@Override
public void exec() {
if (this.hookToExecutePriorToCancel != null) {
logger.info("Executing pre-interruption hook.");
this.hookToExecutePriorToCancel.run();
}
logger.info("Executing cancel task {}. Canceling {}", this.getDescriptor(), this.thingToBeCanceled);
this.thingToBeCanceled.cancel();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/concurrent/GlobalTimer.java
|
package ai.libs.jaicore.concurrent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GlobalTimer extends TrackableTimer {
private static final Logger logger = LoggerFactory.getLogger(GlobalTimer.class);
public static final ANamedTimerTask INIT_TASK = new ANamedTimerTask("Init task") {
@Override
public void exec() {
Thread timerThread = Thread.currentThread();
logger.info("Changing global timer thread {} priority from {} to {}", timerThread, timerThread.getPriority(), Thread.MAX_PRIORITY);
timerThread.setPriority(Thread.MAX_PRIORITY);
logger.info("Priority of global timer thread {} is now {}", timerThread, timerThread.getPriority());
}
};
private static final GlobalTimer instance = new GlobalTimer();
private GlobalTimer() {
/* create a daemon with this name */
super("Global Timer", true);
/* immediately give the thread of the timer maximum priority */
this.schedule(INIT_TASK, 0);
}
public static GlobalTimer getInstance() {
return instance;
}
@Override
public void cancel() {
throw new UnsupportedOperationException("The TimeoutTimer must not be canceled manually!");
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/concurrent/ThreadGroupObserver.java
|
package ai.libs.jaicore.concurrent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThreadGroupObserver extends Thread {
private static final Logger L = LoggerFactory.getLogger(ThreadGroupObserver.class);
private final ThreadGroup group;
private int maxObservedThreads = 0;
private boolean active = true;
private final int maxAllowedThreads;
private final Runnable hookOnConstraintViolation;
private Thread[] threadsAtPointOfViolation;
public ThreadGroupObserver(final ThreadGroup group, final int maxAllowedThreads, final Runnable hookOnConstraintViolation) {
super("ThreadGroupObserver-" + hookOnConstraintViolation);
this.group = group;
this.maxAllowedThreads = maxAllowedThreads;
this.hookOnConstraintViolation = hookOnConstraintViolation;
if (maxAllowedThreads <= 0) {
this.active = false;
}
}
public void cancel() {
this.active = false;
this.interrupt(); // no controlled interrupt in run method
}
@Override
public void run() {
while (this.active && !Thread.currentThread().isInterrupted()) {
this.maxObservedThreads = Math.max(this.maxObservedThreads, this.group.activeCount());
if (this.isThreadConstraintViolated()) {
/* store all currently active threads */
this.threadsAtPointOfViolation = new Thread[this.group.activeCount()];
this.group.enumerate(this.threadsAtPointOfViolation, true);
L.info("Running violation hook!");
this.hookOnConstraintViolation.run();
return;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // no controlled interrupt needed, because execution will cease after this anyway
return;
}
}
}
public int getMaxObservedThreads() {
return this.maxObservedThreads;
}
public boolean isThreadConstraintViolated() {
return this.maxAllowedThreads > 0 && this.maxObservedThreads > this.maxAllowedThreads;
}
public Thread[] getThreadsAtPointOfViolation() {
return this.threadsAtPointOfViolation;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/concurrent/ThreadObserver.java
|
package ai.libs.jaicore.concurrent;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import ai.libs.jaicore.basic.sets.SetUtil;
public class ThreadObserver extends Thread {
private final List<Thread> threadsThatHaveBeenActiveAtLastObservation = new ArrayList<>();
private final PrintStream stream;
public ThreadObserver(final PrintStream stream) {
super("ThreadObserver");
this.stream = stream;
}
@Override
public void run() {
try {
while (true) {
List<Thread> currentlyActiveThreads = Thread.getAllStackTraces().keySet().stream()
.sorted((t1, t2) -> t1.getName().compareTo(t2.getName())).collect(Collectors.toList());
List<Thread> newThreads = SetUtil.difference(currentlyActiveThreads, this.threadsThatHaveBeenActiveAtLastObservation);
List<Thread> goneThreads = SetUtil.difference(this.threadsThatHaveBeenActiveAtLastObservation, currentlyActiveThreads);
if (!newThreads.isEmpty()) {
this.stream.println("" + System.currentTimeMillis());
this.stream.println("New Threads:");
for (Thread t : newThreads) {
this.stream.println("\t" + t.getName() + ": " + t.getThreadGroup());
}
}
if (!goneThreads.isEmpty()) {
this.stream.println("Gone Threads:");
for (Thread t : goneThreads) {
this.stream.println("\t" + t.getName() + ": " + t.getThreadGroup());
}
}
this.threadsThatHaveBeenActiveAtLastObservation.clear();
this.threadsThatHaveBeenActiveAtLastObservation.addAll(currentlyActiveThreads);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // no controlled interrupt necessary, because the execution will cease immediately after this anyway
}
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/concurrent/TrackableTimer.java
|
package ai.libs.jaicore.concurrent;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;
import org.api4.java.common.control.ICancelable;
import ai.libs.jaicore.basic.sets.SetUtil;
public class TrackableTimer extends Timer implements ICancelable {
private static final String MSG_ERROR = "TimerTasks are not trackable. Please create a TrackableTimerTask first and submit that one.";
private final Queue<TrackableTimerTask> scheduledSingleInvocationTasks = new LinkedList<>();
private final Queue<TrackableTimerTask> scheduledReocurringTasks = new LinkedList<>();
private final Map<TimerTask, Long> ratesOfReocurringTasks = new HashMap<>();
private boolean canceled;
public TrackableTimer() {
super();
}
public TrackableTimer(final boolean isDaemon) {
super(isDaemon);
}
public TrackableTimer(final String name, final boolean isDaemon) {
super(name, isDaemon);
}
public TrackableTimer(final String name) {
super(name);
}
/**
* @deprecated({@link TrackableTimer} do not allow to schedule ordinary {@link TimerTask} objects but only {@link TrackableTimerTask} objects)
*/
@Deprecated
@Override
public void schedule(final TimerTask task, final Date time) {
throw new UnsupportedOperationException(MSG_ERROR);
}
/**
* @deprecated({@link TrackableTimer} do not allow to schedule ordinary {@link TimerTask} objects but only {@link TrackableTimerTask} objects)
*/
@Override
@Deprecated
public void schedule(final TimerTask task, final Date time, final long period) {
throw new UnsupportedOperationException(MSG_ERROR);
}
/**
* @deprecated({@link TrackableTimer} do not allow to schedule ordinary {@link TimerTask} objects but only {@link TrackableTimerTask} objects)
*/
@Override
@Deprecated
public void schedule(final TimerTask task, final long delay) {
throw new UnsupportedOperationException(MSG_ERROR);
}
/**
* @deprecated({@link TrackableTimer} do not allow to schedule ordinary {@link TimerTask} objects but only {@link TrackableTimerTask} objects)
*/
@Override
@Deprecated
public void schedule(final TimerTask task, final long delay, final long period) {
throw new UnsupportedOperationException(MSG_ERROR);
}
/**
* @deprecated({@link TrackableTimer} do not allow to schedule ordinary {@link TimerTask} objects but only {@link TrackableTimerTask} objects)
*/
@Override
@Deprecated
public void scheduleAtFixedRate(final TimerTask task, final Date firstTime, final long period) {
throw new UnsupportedOperationException(MSG_ERROR);
}
/**
* @deprecated({@link TrackableTimer} do not allow to schedule ordinary {@link TimerTask} objects but only {@link TrackableTimerTask} objects)
*/
@Override
@Deprecated
public void scheduleAtFixedRate(final TimerTask task, final long delay, final long period) {
throw new UnsupportedOperationException(MSG_ERROR);
}
public void schedule(final TrackableTimerTask task, final Date time) {
super.schedule(task, time);
synchronized (this.scheduledSingleInvocationTasks) {
this.scheduledSingleInvocationTasks.add(task);
}
}
public void schedule(final TrackableTimerTask task, final Date time, final long period) {
super.schedule(task, time, period);
synchronized (this.scheduledReocurringTasks) {
this.scheduledReocurringTasks.add(task);
}
this.ratesOfReocurringTasks.put(task, period);
}
public void schedule(final TrackableTimerTask task, final long delay) {
super.schedule(task, delay);
synchronized (this.scheduledSingleInvocationTasks) {
this.scheduledSingleInvocationTasks.add(task);
}
}
public void schedule(final TrackableTimerTask task, final long delay, final long period) {
super.schedule(task, delay, period);
synchronized (this.scheduledReocurringTasks) {
this.scheduledReocurringTasks.add(task);
}
this.ratesOfReocurringTasks.put(task, period);
}
public void scheduleAtFixedRate(final TrackableTimerTask task, final Date firstTime, final long period) {
super.scheduleAtFixedRate(task, firstTime, period);
synchronized (this.scheduledReocurringTasks) {
this.scheduledReocurringTasks.add(task);
}
this.ratesOfReocurringTasks.put(task, period);
}
public void scheduleAtFixedRate(final TrackableTimerTask task, final long delay, final long period) {
super.scheduleAtFixedRate(task, delay, period);
synchronized (this.scheduledReocurringTasks) {
this.scheduledReocurringTasks.add(task);
}
this.ratesOfReocurringTasks.put(task, period);
}
public boolean hasTaskBeenExecutedInPast(final TrackableTimerTask task) {
return task.hasBeenExecuted();
}
public boolean willTaskBeExecutedInFuture(final TrackableTimerTask task) {
if (this.canceled || task.isCanceled()) {
return false;
}
if (this.scheduledSingleInvocationTasks.contains(task)) {
return !this.hasTaskBeenExecutedInPast(task);
}
/* if not contained here, the TimerTask has not been scheduled in this timer */
return (this.scheduledReocurringTasks.contains(task));
}
@Override
public void cancel() {
this.canceled = true;
super.cancel();
}
public boolean isCanceld() {
return this.canceled;
}
public List<TrackableTimerTask> getActiveTasks() {
synchronized (this.scheduledSingleInvocationTasks) {
synchronized (this.scheduledReocurringTasks) {
return SetUtil.union(this.scheduledSingleInvocationTasks, this.scheduledReocurringTasks).stream().filter(this::willTaskBeExecutedInFuture).collect(Collectors.toList());
}
}
}
public int getNumberOfActiveTasks() {
return this.getActiveTasks().size();
}
public boolean hasOpenTasks() {
return !this.getActiveTasks().isEmpty();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/concurrent/TrackableTimerTask.java
|
package ai.libs.jaicore.concurrent;
import java.util.TimerTask;
public abstract class TrackableTimerTask extends TimerTask {
public static TrackableTimerTask get(final TimerTask tt) {
return new WrappingTrackableTimerTask(tt);
}
private boolean canceled;
private long lastExecution = -1;
private boolean finished;
@Override
public final void run() {
this.lastExecution = System.currentTimeMillis();
this.exec();
this.finished = true;
}
public abstract void exec();
@Override
public boolean cancel() {
this.canceled = true;
return super.cancel();
}
public boolean isCanceled() {
return this.canceled;
}
public long getLastExecution() {
return this.lastExecution;
}
public boolean hasBeenExecuted() {
return this.lastExecution >= 0;
}
public boolean isFinished() {
return this.finished;
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/concurrent/WrappingTrackableTimerTask.java
|
package ai.libs.jaicore.concurrent;
import java.util.TimerTask;
public class WrappingTrackableTimerTask extends TrackableTimerTask {
private final TimerTask tt;
public WrappingTrackableTimerTask(final TimerTask tt) {
super();
this.tt = tt;
}
@Override
public void exec() {
this.tt.run();
}
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/EFieldType.java
|
package ai.libs.jaicore.db;
public enum EFieldType {
TEXT, DOUBLE, INT, BOOLEAN
}
|
0
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-basic/0.2.7/ai/libs/jaicore/db/IDatabaseAdapter.java
|
package ai.libs.jaicore.db;
import java.io.IOException;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.kvstore.IKVStore;
/**
* This is a simple util interface for easy database access and query execution in sql. You need to make sure that the respective JDBC connector is in the class path. By default, the adapter uses the mysql driver, but any jdbc driver can be
* used.
*
* @author fmohr, mwever
*
*/
public interface IDatabaseAdapter extends Serializable, AutoCloseable, ILoggingCustomizable {
/**
* Checks whether the connection to the database is still alive and re-establishs the connection if it is not.
*
* @throws SQLException
* Thrown, if there was an issue with reconnecting to the database server.
*/
public void checkConnection() throws SQLException;
public boolean doesTableExist(final String tablename) throws SQLException, IOException;
public void createTable(final String tablename, final String nameOfPrimaryField, final Collection<String> fieldnames, final Map<String, String> types, final Collection<String> keys) throws SQLException;
/**
* Retrieves all rows of a table.
*
* @param table
* The table for which all entries shall be returned.
* @return A list of {@link IKVStore}s containing the data of the table.
* @throws SQLException
* Thrown, if there was an issue with the connection to the database.
*/
default List<IKVStore> getRowsOfTable(final String table) throws SQLException {
return this.getRowsOfTable(table, new HashMap<>());
}
/**
* Retrieves all rows of a table which satisfy certain conditions (WHERE clause).
*
* @param table
* The table for which all entries shall be returned.
* @param conditions
* The conditions a result entry must satisfy.
* @return A list of {@link IKVStore}s containing the data of the table.
* @throws SQLException
* Thrown, if there was an issue with the connection to the database.
*/
public List<IKVStore> getRowsOfTable(final String table, final Map<String, String> conditions) throws SQLException;
/**
* Retrieves the select result for the given query.
*
* @param query
* The SQL query which is to be executed.
* @return A list of {@link IKVStore}s containing the result data of the query.
* @throws SQLException
* Thrown, if there was an issue with the connection to the database.
*/
default List<IKVStore> getResultsOfQuery(final String query) throws SQLException {
return this.getResultsOfQuery(query, new ArrayList<>());
}
/**
* Retrieves the select result for the given query that can have placeholders.
*
* @param query
* The SQL query which is to be executed (with placeholders).
* @param values
* An array of placeholder values that need to be filled in.
* @return A list of {@link IKVStore}s containing the result data of the query.
* @throws SQLException
* Thrown, if there was an issue with the connection to the database.
*/
default List<IKVStore> getResultsOfQuery(final String query, final String[] values) throws SQLException {
return this.getResultsOfQuery(query, Arrays.asList(values));
}
/**
* Retrieves the select result for the given query that can have placeholders.
*
* @param query
* The SQL query which is to be executed (with placeholders).
* @param values
* A list of placeholder values that need to be filled in.
* @return A list of {@link IKVStore}s containing the result data of the query.
* @throws SQLException
* Thrown, if there was an issue with the query format or the connection to the database.
*/
public List<IKVStore> getResultsOfQuery(final String query, final List<String> values) throws SQLException;
/**
* Executes an insert query
*
* @param sql
* @return
* @throws SQLException
*/
default int[] insert(final String sql) throws SQLException {
return this.insert(sql, Arrays.asList());
}
/**
* Executes an insert query and returns the row ids of the created entries.
*
* @param sql
* The insert statement which shall be executed that may have placeholders.
* @param values
* The values for the placeholders.
* @return An array of the row ids of the inserted entries.
* @throws SQLException
* Thrown, if there was an issue with the query format or the connection to the database.
*/
default int[] insert(final String sql, final String[] values) throws SQLException {
return this.insert(sql, Arrays.asList(values));
}
/**
* Executes an insert query and returns the row ids of the created entries.
*
* @param sql
* The insert statement which shall be executed that may have placeholders.
* @param values
* A list of values for the placeholders.
* @return An array of the row ids of the inserted entries.
* @throws SQLException
* Thrown, if there was an issue with the query format or the connection to the database.
*/
public int[] insert(final String sql, final List<? extends Object> values) throws SQLException;
/**
* Creates and executes an insert query for the given table and the values as specified in the map.
*
* @param table
* The table where to insert the data.
* @param map
* The map of key:value pairs to be inserted into the table.
* @return An array of the row ids of the inserted entries.
* @throws SQLException
* Thrown, if there was an issue with the query format or the connection to the database.
*/
public int[] insert(final String table, final Map<String, ? extends Object> map) throws SQLException;
/**
* Creates a multi-insert statement and executes it. The returned array contains the row id's of the inserted rows. (By default it creates chunks of size 10.000 rows per query to be inserted.)
*
* @param table
* The table to which the rows are to be added.
* @param keys
* The list of column keys for which values are set.
* @param datarows
* The list of value lists to be filled into the table.
* @return An array of row id's of the inserted rows.
* @throws SQLException
* Thrown, if the sql statement was malformed, could not be executed, or the connection to the database failed.
*/
default int[] insertMultiple(final String table, final List<String> keys, final List<List<? extends Object>> datarows) throws SQLException {
return this.insertMultiple(table, keys, datarows, 10000);
}
/**
* Creates a multi-insert statement and executes it. The returned array contains the row id's of the inserted rows.
*
* @param table
* The table to which the rows are to be added.
* @param keys
* The list of column keys for which values are set.
* @param datarows
* The list of value lists to be filled into the table.
* @param chunkSize
* The number of rows which are added within one single database transaction. (10,000 seems to be a good value for this)
* @return An array of row id's of the inserted rows.
* @throws SQLException
* Thrown, if the sql statement was malformed, could not be executed, or the connection to the database failed.
*/
public int[] insertMultiple(final String table, final List<String> keys, final List<List<? extends Object>> datarows, final int chunkSize) throws SQLException;
/**
* Execute the given sql statement as an update.
*
* @param sql
* The sql statement to be executed.
* @return The number of rows affected by the update statement.
* @throws SQLException
* Thrown if the statement is malformed or an issue while executing the sql statement occurs.
*/
default int update(final String sql) throws SQLException {
return this.update(sql, new ArrayList<>());
}
/**
* Execute the given sql statement with placeholders as an update filling the placeholders with the given values beforehand.
*
* @param sql
* The sql statement with placeholders to be executed.
* @param sql
* Array of values for the respective placeholders.
* @return The number of rows affected by the update statement.
* @throws SQLException
* Thrown if the statement is malformed or an issue while executing the sql statement occurs.
*/
default int update(final String sql, final String[] values) throws SQLException {
return this.update(sql, Arrays.asList(values));
}
/**
* Execute the given sql statement with placeholders as an update filling the placeholders with the given values beforehand.
*
* @param sql
* The sql statement with placeholders to be executed.
* @param values
* List of values for the respective placeholders.
* @return The number of rows affected by the update statement.
* @throws SQLException
* Thrown if the statement is malformed or an issue while executing the sql statement occurs.
*/
public int update(final String sql, final List<? extends Object> values) throws SQLException;
/**
* Create and execute an update statement for some table updating the values as described in <code>updateValues</code> and only affect those entries satisfying the <code>conditions</code>.
*
* @param table
* The table which is to be updated.
* @param updateValues
* The description how entries are to be updated.
* @param conditions
* The description of the where-clause, conditioning the entries which are to be updated.
* @return The number of rows affected by the update statement.
* @throws SQLException
* Thrown if the statement is malformed or an issue while executing the sql statement occurs.
*/
public int update(final String table, final Map<String, ? extends Object> updateValues, final Map<String, ? extends Object> conditions) throws SQLException;
/**
* Deletes all rows from the table that match the given conditions
*
* @param table
* @param conditions
* @return the number of deleted rows.
* @throws SQLException
*/
public int delete(String table, Map<String, ? extends Object> conditions) throws SQLException;
/**
* Executes the given statements atomically. Only works if no other statements are sent through this adapter in parallel! Only use for single-threaded applications, otherwise side effects may happen as this changes the auto commit
* settings of the connection temporarily.
*
* @param queries
* The queries to execute atomically
* @throws SQLException
* If the status of the connection cannot be changed. If something goes wrong while executing the given statements, they are rolled back before they are committed.
*/
public void executeQueriesAtomically(final List<PreparedStatement> queries) throws SQLException;
/**
* Sends a query to the database server which can be an arbitrary query.
*
* @param sqlStatement
* The sql statement to be executed.
* @return If there is a result set returned it will be parsed into a list of {@link IKVStore}s
* @throws SQLException
* Thrown, if the the sql statement cannot be executed for whatever reasons.
* @throws IOException
* Thrown, if the result set cannot be parsed into {@link IKVStore}s.
*/
public List<IKVStore> query(String sqlStatement) throws SQLException, IOException;
/**
* Close the connection. No more queries can be sent after having the access object closed
*/
@Override
public void close();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.