index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph/NodeParentSwitchEvent.java
package ai.libs.jaicore.graphvisualizer.events.graph; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; public class NodeParentSwitchEvent<T> extends AAlgorithmEvent implements GraphEvent { private final T node; private final T oldParent; private final T newParent; public NodeParentSwitchEvent(final IAlgorithm<?, ?> algorithm, final T node, final T oldParent, final T newParent) { super(algorithm); this.node = node; this.oldParent = oldParent; this.newParent = newParent; } public T getNode() { return this.node; } public T getOldParent() { return this.oldParent; } public T getNewParent() { return this.newParent; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph/NodePropertyChangedEvent.java
package ai.libs.jaicore.graphvisualizer.events.graph; import java.util.HashMap; import java.util.Map; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; public class NodePropertyChangedEvent<T> extends AAlgorithmEvent implements GraphEvent { private final T node; private final Map<String, Object> changedProperties; private static Map<String, Object> getMap(final String key, final Object val) { Map<String, Object> map = new HashMap<>(); map.put(key, val); return map; } public NodePropertyChangedEvent(final IAlgorithm<?, ?> algorithm, final T node, final String key, final Object val) { this(algorithm, node, getMap(key, val)); } public NodePropertyChangedEvent(final IAlgorithm<?, ?> algorithm, final T node, final Map<String, Object> changedProperties) { super(algorithm); this.node = node; this.changedProperties = changedProperties; } public T getNode() { return this.node; } public Map<String, Object> getChangedProperties() { return this.changedProperties; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.changedProperties == null) ? 0 : this.changedProperties.hashCode()); result = prime * result + ((this.node == null) ? 0 : this.node.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; } NodePropertyChangedEvent<?> other = (NodePropertyChangedEvent<?>) obj; if (this.changedProperties == null) { if (other.changedProperties != null) { return false; } } else if (!this.changedProperties.equals(other.changedProperties)) { return false; } if (this.node == null) { if (other.node != null) { return false; } } else if (!this.node.equals(other.node)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph/NodeRemovedEvent.java
package ai.libs.jaicore.graphvisualizer.events.graph; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; public class NodeRemovedEvent<T> extends AAlgorithmEvent implements GraphEvent { private final T node; public NodeRemovedEvent(final IAlgorithm<?, ?> algorithm, final T node) { super(algorithm); this.node = node; } public T getNode() { return this.node; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph/NodeTypeSwitchEvent.java
package ai.libs.jaicore.graphvisualizer.events.graph; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; public class NodeTypeSwitchEvent<T> extends AAlgorithmEvent implements GraphEvent { private final T node; private final String type; public NodeTypeSwitchEvent(final IAlgorithm<?, ?> algorithm, final T node, final String type) { super(algorithm); this.node = node; this.type = type; } public T getNode() { return this.node; } public String getType() { return this.type; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph/bus/AlgorithmEventBus.java
package ai.libs.jaicore.graphvisualizer.events.graph.bus; import org.api4.java.algorithm.events.IAlgorithmEvent; public interface AlgorithmEventBus extends AlgorithmEventSource { public void postEvent(IAlgorithmEvent algorithmEvent); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph/bus/AlgorithmEventListener.java
package ai.libs.jaicore.graphvisualizer.events.graph.bus; import org.api4.java.algorithm.events.IAlgorithmEvent; import com.google.common.eventbus.Subscribe; public interface AlgorithmEventListener { @Subscribe public void handleAlgorithmEvent(IAlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException; }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph/bus/AlgorithmEventSource.java
package ai.libs.jaicore.graphvisualizer.events.graph.bus; public interface AlgorithmEventSource { public void registerListener(AlgorithmEventListener algorithmEventListener); public void unregisterListener(AlgorithmEventListener algorithmEventListener); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/graph/bus/HandleAlgorithmEventException.java
package ai.libs.jaicore.graphvisualizer.events.graph.bus; public class HandleAlgorithmEventException extends Exception { private static final long serialVersionUID = 570998902568482515L; protected HandleAlgorithmEventException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public HandleAlgorithmEventException(String message, Throwable cause) { super(message, cause); } public HandleAlgorithmEventException(String message) { super(message); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/gui/DefaultGUIEventBus.java
package ai.libs.jaicore.graphvisualizer.events.gui; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.graphvisualizer.events.recorder.AlgorithmEventHistoryEntryDeliverer; public class DefaultGUIEventBus implements GUIEventBus { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultGUIEventBus.class); private static DefaultGUIEventBus singletonInstance; private List<GUIEventListener> guiEventListeners; private AlgorithmEventHistoryEntryDeliverer historyEntryDeliverer; private DefaultGUIEventBus() { this.guiEventListeners = Collections.synchronizedList(new LinkedList<>()); } @Override public void registerAlgorithmEventHistoryEntryDeliverer(final AlgorithmEventHistoryEntryDeliverer historyEntryDeliverer) { this.historyEntryDeliverer = historyEntryDeliverer; } @Override public void registerListener(final GUIEventListener graphEventListener) { this.guiEventListeners.add(graphEventListener); } @Override public void unregisterListener(final GUIEventListener graphEventListener) { this.guiEventListeners.remove(graphEventListener); } @Override public void postEvent(final GUIEvent guiEvent) { synchronized (this) { for (GUIEventListener listener : this.guiEventListeners) { this.passEventToListener(guiEvent, listener); } this.passEventToListener(guiEvent, this.historyEntryDeliverer); } } private void passEventToListener(final GUIEvent guiEvent, final GUIEventListener listener) { try { listener.handleGUIEvent(guiEvent); } catch (Exception exception) { LOGGER.error("Error while passing GUIEvent {} to handler {}.", guiEvent, listener, exception); } } public static synchronized GUIEventBus getInstance() { if (singletonInstance == null) { singletonInstance = new DefaultGUIEventBus(); } return singletonInstance; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/gui/GUIEvent.java
package ai.libs.jaicore.graphvisualizer.events.gui; public interface GUIEvent { }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/gui/GUIEventBus.java
package ai.libs.jaicore.graphvisualizer.events.gui; import ai.libs.jaicore.graphvisualizer.events.recorder.AlgorithmEventHistoryEntryDeliverer; public interface GUIEventBus extends GUIEventSource { public void registerAlgorithmEventHistoryEntryDeliverer(AlgorithmEventHistoryEntryDeliverer historyEntryDeliverer); public void postEvent(GUIEvent guiEvent); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/gui/GUIEventListener.java
package ai.libs.jaicore.graphvisualizer.events.gui; public interface GUIEventListener { public void handleGUIEvent(GUIEvent guiEvent); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/gui/GUIEventSource.java
package ai.libs.jaicore.graphvisualizer.events.gui; public interface GUIEventSource { public void registerListener(GUIEventListener guiEventListener); public void unregisterListener(GUIEventListener guiEventListener); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/gui/Histogram.java
package ai.libs.jaicore.graphvisualizer.events.gui; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import ai.libs.jaicore.graphvisualizer.IntegerAxisFormatter; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; public class Histogram extends BarChart<String, Number>{ private final XYChart.Series<String, Number> series = new XYChart.Series<>(); private final ObservableList<Data<String, Number>> histogramData; private int max; private int n; public Histogram(int n) { super(new CategoryAxis(), new NumberAxis()); this.n = n; this.getData().add(series); List<Data<String,Number>> values = new ArrayList<>(); for (int i = 0; i < n; i++) { values.add(new Data<>("" + i, 0)); } histogramData = FXCollections.observableList(values); series.setData(histogramData); ((NumberAxis)getYAxis()).setMinorTickVisible(false); // only show integers /* reasonable layout */ this.setAnimated(false); this.setLegendVisible(false); ((NumberAxis) getYAxis()).setTickUnit(1); ((NumberAxis) getYAxis()).setTickLabelFormatter(new IntegerAxisFormatter()); ((NumberAxis) getYAxis()).setMinorTickCount(0); } public void update(DescriptiveStatistics stats) { int[] histogram = new int[n]; double[] values = stats.getValues(); double min = stats.getMin(); double stepSize = (stats.getMax() - min) / n; for (int i = 0; i < values.length; i++) { for (int j = 0; j < n; j++) { if (values[i] <= min + (j * stepSize)) { histogram[j]++; break; } } } update(histogram); } public void update(List<? extends Number> values) { DescriptiveStatistics stats = new DescriptiveStatistics(); values.forEach(v -> stats.addValue((Double)v)); update(stats); } public void update(int[] values) { List<Data<String,Number>> transformedValues = new ArrayList<>(); for (int i = 0; i < values.length; i++) { if (values[i] > max) { max = values[i]; } transformedValues.add(new Data<>("" + i, values[i])); } this.histogramData.setAll(transformedValues); } public void clear() { max = 0; this.histogramData.clear(); } public int getN() { return n; } public void setN(int n) { this.n = n; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/AIndependentAlgorithmEventPropertyComputer.java
package ai.libs.jaicore.graphvisualizer.events.recorder; import java.util.Arrays; import java.util.List; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; public abstract class AIndependentAlgorithmEventPropertyComputer implements AlgorithmEventPropertyComputer { @Override public List<AlgorithmEventPropertyComputer> getRequiredPropertyComputers() { return Arrays.asList(); } @Override public void overwriteRequiredPropertyComputer(final AlgorithmEventPropertyComputer computer) { throw new UnsupportedOperationException(this.getClass().getCanonicalName() + " does not rely on other property computers, so overwriting makes no sense."); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/AlgorithmEventHistory.java
package ai.libs.jaicore.graphvisualizer.events.recorder; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringJoiner; import org.api4.java.algorithm.IAlgorithm; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An {@link AlgorithmEventHistory} stores {@link AlgorithmEventHistoryEntry}s constructed from {@link IPropertyProcessedAlgorithmEvent}s representing the recorded behavior of an {@link IAlgorithm}. Such an {@link AlgorithmEventHistory} can * be stored and loaded using an * {@link AlgorithmEventHistorySerializer}. * * @author atornede * */ public class AlgorithmEventHistory implements ILoggingCustomizable, Serializable { private static final long serialVersionUID = 8500970353937357648L; private transient Logger logger = LoggerFactory.getLogger(AlgorithmEventHistory.class); private transient String loggerName; private List<AlgorithmEventHistoryEntry> entries; /** * Creates a new {@link AlgorithmEventHistory}. */ public AlgorithmEventHistory() { this.entries = Collections.synchronizedList(new ArrayList<>()); } /** * Creates a new {@link AlgorithmEventHistory} with the given {@link List} of {@link AlgorithmEventHistoryEntry}s. * * @param algorithmEventHistoryEntries The list of {@link AlgorithmEventHistoryEntry}s to be stored in the history. */ public AlgorithmEventHistory(final List<AlgorithmEventHistoryEntry> algorithmEventHistoryEntries) { this(); for (AlgorithmEventHistoryEntry entry : algorithmEventHistoryEntries) { this.entries.add(entry); } } /** * Adds the given {@link IPropertyProcessedAlgorithmEvent} to this {@link AlgorithmEventHistoryEntry}. * * @param propertyProcessedAlgorithmEvent The {@link IPropertyProcessedAlgorithmEvent} to be added to this history. */ public void addEvent(final IPropertyProcessedAlgorithmEvent propertyProcessedAlgorithmEvent) { AlgorithmEventHistoryEntry entry = this.generateHistoryEntry(propertyProcessedAlgorithmEvent); this.entries.add(entry); this.logger.debug("Added entry {} for algorithm event {} to history at position {}.", entry, propertyProcessedAlgorithmEvent, this.entries.size() - 1); } private AlgorithmEventHistoryEntry generateHistoryEntry(final IPropertyProcessedAlgorithmEvent propertyProcessedAlgorithmEvent) { return new AlgorithmEventHistoryEntry(propertyProcessedAlgorithmEvent, this.getCurrentReceptionTime()); } private long getCurrentReceptionTime() { return System.currentTimeMillis(); } /** * Returns the {@link AlgorithmEventHistoryEntry} at the given timestep. * * @param timestep The timestep for which the {@link AlgorithmEventHistoryEntry} has to be returned. * @return The {@link AlgorithmEventHistoryEntry} at the given timestep. */ public AlgorithmEventHistoryEntry getEntryAtTimeStep(final int timestep) { return this.entries.get(timestep); } public long getLength() { return this.entries.size(); } @Override public String getLoggerName() { return this.loggerName; } @Override public void setLoggerName(final String name) { this.loggerName = name; this.logger.info("Switching logger name to {}", name); this.logger = LoggerFactory.getLogger(name); this.logger.info("Switched logger name to {}", name); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.entries == null) ? 0 : this.entries.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; } AlgorithmEventHistory other = (AlgorithmEventHistory) obj; if (this.entries == null) { if (other.entries != null) { return false; } } else if (!this.entries.equals(other.entries)) { return false; } return true; } @Override public String toString() { String header = "AlgorithmEventHistory \n"; StringJoiner joiner = new StringJoiner("\n"); for (AlgorithmEventHistoryEntry entry : this.entries) { joiner.add(entry.toString()); } return header + joiner.toString(); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/AlgorithmEventHistoryEntry.java
package ai.libs.jaicore.graphvisualizer.events.recorder; import java.io.Serializable; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; /** * {@link AlgorithmEventHistoryEntry}s are used to store {@link IPropertyProcessedAlgorithmEvent}s in an {@link AlgorithmEventHistory} combined with additional meta information. * * @author atornede * */ public class AlgorithmEventHistoryEntry implements Serializable { /** * Auto-generated serial version UID. */ private static final long serialVersionUID = 7213427866393560711L; private IPropertyProcessedAlgorithmEvent propertyProcessedAlgorithmEvent; private long timeEventWasReceived; @SuppressWarnings("unused") private AlgorithmEventHistoryEntry() { // for serialization purposes } /** * Creates a new {@link AlgorithmEventHistoryEntry} storing the given {@link IPropertyProcessedAlgorithmEvent} and the time at which the event was received. * * @param algorithmEvent The {@link IPropertyProcessedAlgorithmEvent} to be stored. * @param timeEventWasReceived The time at which the event was received. */ public AlgorithmEventHistoryEntry(final IPropertyProcessedAlgorithmEvent algorithmEvent, final long timeEventWasReceived) { this.propertyProcessedAlgorithmEvent = algorithmEvent; this.timeEventWasReceived = timeEventWasReceived; } /** * Returns the {@link IPropertyProcessedAlgorithmEvent} stored as part of this entry. * * @return The {@link IPropertyProcessedAlgorithmEvent} stored as part of this entry. */ public IPropertyProcessedAlgorithmEvent getAlgorithmEvent() { return this.propertyProcessedAlgorithmEvent; } /** * Returns the time at which this event was received. * * @return The time at which this event was received. */ public long getTimeEventWasReceived() { return this.timeEventWasReceived; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.propertyProcessedAlgorithmEvent == null) ? 0 : this.propertyProcessedAlgorithmEvent.hashCode()); result = prime * result + (int) (this.timeEventWasReceived ^ (this.timeEventWasReceived >>> 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; } AlgorithmEventHistoryEntry other = (AlgorithmEventHistoryEntry) obj; if (this.propertyProcessedAlgorithmEvent == null) { if (other.propertyProcessedAlgorithmEvent != null) { return false; } } else if (!this.propertyProcessedAlgorithmEvent.equals(other.propertyProcessedAlgorithmEvent)) { return false; } return this.timeEventWasReceived == other.timeEventWasReceived; } @Override public String toString() { return "<" + this.propertyProcessedAlgorithmEvent + ", t=" + this.timeEventWasReceived + ">"; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/AlgorithmEventHistoryEntryDeliverer.java
package ai.libs.jaicore.graphvisualizer.events.recorder; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventListener; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventListener; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyProcessedAlgorithmEventListener; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyProcessedAlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.PauseEvent; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.PlayEvent; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.speedslider.ChangeSpeedEvent; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; /** * The {@link AlgorithmEventHistoryEntryDeliverer} is {@link Thread} constantly pulling events from a given {@link AlgorithmEventHistory} and sending these to all registered * {@link AlgorithmEventListener}s. * * @author atornede * */ public class AlgorithmEventHistoryEntryDeliverer extends Thread implements PropertyProcessedAlgorithmEventSource, GUIEventListener { private Logger logger = LoggerFactory.getLogger(AlgorithmEventHistoryEntryDeliverer.class); private Set<PropertyProcessedAlgorithmEventListener> algorithmEventListeners; private AlgorithmEventHistory eventHistory; private int maximumSleepTimeInMilliseconds; private int timestep; private boolean paused; private double sleepTimeMultiplier; /** * Creates a new {@link AlgorithmEventHistoryEntryDeliverer} with the given {@link AlgorithmEventHistory} and the maximum sleep time between checking for new events from the history and sending them to the registered listeners. * * @param eventHistory The {@link AlgorithmEventHistory} from which the events are pulled. * @param maximumSleepTimeInMilliseconds The maximum sleep time between checking for new events from the history and sending them to the registered listeners */ public AlgorithmEventHistoryEntryDeliverer(final AlgorithmEventHistory eventHistory, final int maximumSleepTimeInMilliseconds) { this.eventHistory = eventHistory; this.maximumSleepTimeInMilliseconds = maximumSleepTimeInMilliseconds; this.timestep = 0; this.paused = true; this.algorithmEventListeners = ConcurrentHashMap.newKeySet(); this.sleepTimeMultiplier = 1; this.setName(this.getClass().getName()); this.setDaemon(true); this.logger.info("{} started with thread {}", this.getClass().getSimpleName(), this.getName()); } /** * Creates a new {@link AlgorithmEventHistoryEntryDeliverer} with the given {@link AlgorithmEventHistory}. * * @param eventHistory The {@link AlgorithmEventHistory} from which the events are pulled. */ public AlgorithmEventHistoryEntryDeliverer(final AlgorithmEventHistory eventHistory) { this(eventHistory, 30); } @Override public void registerListener(final PropertyProcessedAlgorithmEventListener algorithmEventListener) { this.algorithmEventListeners.add(algorithmEventListener); } @Override public void unregisterListener(final PropertyProcessedAlgorithmEventListener algorithmEventListener) { this.algorithmEventListeners.remove(algorithmEventListener); } @Override public void run() { while (!Thread.currentThread().isInterrupted()) { if (!this.paused && this.timestep < this.eventHistory.getLength()) { AlgorithmEventHistoryEntry historyEntry = this.eventHistory.getEntryAtTimeStep(this.timestep); IPropertyProcessedAlgorithmEvent algorithmEvent = historyEntry.getAlgorithmEvent(); this.logger.debug("Pulled event entry {} associated with event {} at position {}.", historyEntry, algorithmEvent, this.timestep); this.sendAlgorithmEventToListeners(algorithmEvent); this.timestep++; } else if (this.paused) { this.logger.debug("Not processing events since visualization is paused."); } else if (this.timestep >= this.eventHistory.getLength()) { this.logger.debug("Not processing events since no unpublished events are known."); } this.goToSleep(); } } private void goToSleep() { try { int sleepTime = (int) (this.sleepTimeMultiplier * this.maximumSleepTimeInMilliseconds); this.logger.trace("Sleeping {}ms.", sleepTime); sleep(sleepTime); } catch (InterruptedException e) { this.logger.info("{} was interrupted due to exception: {}.", this.getClass().getSimpleName(), e); Thread.currentThread().interrupt(); } } private void sendAlgorithmEventToListeners(final IPropertyProcessedAlgorithmEvent algorithmEvent) { for (PropertyProcessedAlgorithmEventListener eventListener : this.algorithmEventListeners) { try { this.sendAlgorithmEventToListener(algorithmEvent, eventListener); } catch (Exception e) { this.logger.error("Error in dispatching event {} due to error.", algorithmEvent, e); } } this.logger.info("Pulled and sent event {} as entry at time step {}.", algorithmEvent, this.timestep); } private void sendAlgorithmEventToListener(final IPropertyProcessedAlgorithmEvent algorithmEvent, final PropertyProcessedAlgorithmEventListener eventListener) throws HandleAlgorithmEventException { this.logger.debug("Sending event {} to listener {}.", algorithmEvent, eventListener); long startTime = System.currentTimeMillis(); eventListener.handleSerializableAlgorithmEvent(algorithmEvent); long dispatchTime = System.currentTimeMillis() - startTime; if (dispatchTime > 10) { this.logger.warn("Dispatch time for event {} to listener {} took {}ms!", algorithmEvent, eventListener, dispatchTime); } } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof PauseEvent) { this.pause(); } else if (guiEvent instanceof PlayEvent) { this.unpause(); } else if (guiEvent instanceof ResetEvent) { this.handleResetEvent(); } else if (guiEvent instanceof GoToTimeStepEvent) { this.handleGoToTimeStepEvent(guiEvent); } else if (guiEvent instanceof ChangeSpeedEvent) { this.handleChangeSpeedEvent(guiEvent); } } private void pause() { this.paused = true; } private void unpause() { this.paused = false; } private void handleResetEvent() { this.resetTimeStep(); this.pause(); } private void resetTimeStep() { this.timestep = 0; } private void handleGoToTimeStepEvent(final GUIEvent guiEvent) { this.resetTimeStep(); GoToTimeStepEvent goToTimeStepEvent = (GoToTimeStepEvent) guiEvent; while (this.timestep < goToTimeStepEvent.getNewTimeStep() && this.timestep < this.eventHistory.getLength()) { IPropertyProcessedAlgorithmEvent algorithmEvent = this.eventHistory.getEntryAtTimeStep(this.timestep).getAlgorithmEvent(); this.sendAlgorithmEventToListeners(algorithmEvent); this.timestep++; } } private void handleChangeSpeedEvent(final GUIEvent guiEvent) { ChangeSpeedEvent changeSpeedEvent = (ChangeSpeedEvent) guiEvent; this.sleepTimeMultiplier = 1 - changeSpeedEvent.getNewSpeedPercentage() / 100.0; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/AlgorithmEventHistoryRecorder.java
package ai.libs.jaicore.graphvisualizer.events.recorder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.events.serializable.DefaultPropertyProcessedAlgorithmEvent; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventListener; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyComputationFailedException; /** * An {@link AlgorithmEventHistoryRecorder} is responsible for recording {@link IAlgorithmEvent}s and storing them in the form of {@link IPropertyProcessedAlgorithmEvent}s. For doing so it requires a list of * {@link AlgorithmEventPropertyComputer}s which can extract information from {@link IAlgorithmEvent}s which in turn is stored in the {@link IPropertyProcessedAlgorithmEvent}s. * * @author atornede * */ public class AlgorithmEventHistoryRecorder implements AlgorithmEventListener { private static final Logger LOGGER = LoggerFactory.getLogger(AlgorithmEventHistoryRecorder.class); private AlgorithmEventHistory algorithmEventHistory; private final List<AlgorithmEventPropertyComputer> eventPropertyComputers = new ArrayList<>(); public AlgorithmEventHistoryRecorder() { this.algorithmEventHistory = new AlgorithmEventHistory(); } /** * Creates a new {@link AlgorithmEventHistoryRecorder} with the given {@link AlgorithmEventPropertyComputer}s. * * @param eventPropertyComputers A list of {@link AlgorithmEventPropertyComputer}s which can extract information from {@link IAlgorithmEvent}s which in turn is stored in the {@link IPropertyProcessedAlgorithmEvent}s. */ public AlgorithmEventHistoryRecorder(final List<AlgorithmEventPropertyComputer> eventPropertyComputers) { this(); this.eventPropertyComputers.addAll(eventPropertyComputers); } public boolean hasPropertyComputerInstalled(final AlgorithmEventPropertyComputer propertyComputer) { return this.eventPropertyComputers.stream().anyMatch(pc -> pc.getPropertyName().equals(propertyComputer.getPropertyName())); } public AlgorithmEventPropertyComputer getInstalledCopyOfPropertyComputer(final AlgorithmEventPropertyComputer propertyComputer) { return this.eventPropertyComputers.stream().filter(pc -> pc.getClass().equals(propertyComputer.getClass())).findAny().get(); } public void addPropertyComputer(final Collection<AlgorithmEventPropertyComputer> computers) { for (AlgorithmEventPropertyComputer computer : computers) { if (this.hasPropertyComputerInstalled(computer)) { LOGGER.info("Not adding a second instance of property computer {}. One is already installed. Make sure that they are not computing semantically different things.", computer.getClass().getName()); } else { /* first extend property computer graph if necessary or overwrite the required property computers bythe existing ones */ for (AlgorithmEventPropertyComputer requiredComputer : computer.getRequiredPropertyComputers()) { if (this.hasPropertyComputerInstalled(requiredComputer)) { computer.overwriteRequiredPropertyComputer(this.getInstalledCopyOfPropertyComputer(requiredComputer)); } else { this.addPropertyComputer(requiredComputer); } } /* check required other computers and if they have already been installed */ this.eventPropertyComputers.add(computer); } } } public void addPropertyComputer(final AlgorithmEventPropertyComputer... computer) { Collections.addAll(this.eventPropertyComputers, computer); } @Subscribe @Override public void handleAlgorithmEvent(final IAlgorithmEvent algorithmEvent) { synchronized (this) { IPropertyProcessedAlgorithmEvent propertyProcessedAlgorithmEvent = this.convertAlgorithmEventToPropertyProcessedAlgorithmEvent(algorithmEvent); this.algorithmEventHistory.addEvent(propertyProcessedAlgorithmEvent); } } private IPropertyProcessedAlgorithmEvent convertAlgorithmEventToPropertyProcessedAlgorithmEvent(final IAlgorithmEvent algorithmEvent) { Map<String, Object> properties = new HashMap<>(); for (AlgorithmEventPropertyComputer algorithmEventPropertyComputer : this.eventPropertyComputers) { try { Object computedProperty = algorithmEventPropertyComputer.computeAlgorithmEventProperty(algorithmEvent); if (computedProperty != null) { properties.put(algorithmEventPropertyComputer.getPropertyName(), computedProperty); } } catch (PropertyComputationFailedException e) { LOGGER.error("Could not compute property \"{}\".", algorithmEventPropertyComputer.getPropertyName(), e); } } return new DefaultPropertyProcessedAlgorithmEvent(algorithmEvent.getClass().getSimpleName(), properties, algorithmEvent, algorithmEvent.getTimestamp()); } /** * Returns the {@link AlgorithmEventHistory} which is produced up to this point by this {@link AlgorithmEventHistoryRecorder}. * * @return The {@link AlgorithmEventHistory} which is produced up to this point by this {@link AlgorithmEventHistoryRecorder}. */ public AlgorithmEventHistory getHistory() { return this.algorithmEventHistory; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/AlgorithmEventHistorySerializer.java
package ai.libs.jaicore.graphvisualizer.events.recorder; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import java.util.StringJoiner; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyProcessedAlgorithmEventHistory; /** * An {@link AlgorithmEventHistorySerializer} can be used to read and store {@link AlgorithmEventHistory}s in the form of JSON files. * * @author atornede * */ public class AlgorithmEventHistorySerializer { private ObjectMapper objectMapper; /** * Creates a new {@link AlgorithmEventHistorySerializer}. */ public AlgorithmEventHistorySerializer() { this.initializeObjectMapper(); } private void initializeObjectMapper() { this.objectMapper = new ObjectMapper(); // make sure that the object mapper sees all fields this.objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE); this.objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); // make sure that the object mapper stores type information when serializing objects this.objectMapper.enableDefaultTyping(); } /** * Serializes the given {@link AlgorithmEventHistory} into a JSON {@link String}. * * @param algorithmEventHistory The {@link AlgorithmEventHistory} to be serialized. * @return The JSON {@link String} representing the serialized {@link AlgorithmEventHistory}. * @throws JsonProcessingException If something went wrong during the transformation to JSON. */ public String serializeAlgorithmEventHistory(final AlgorithmEventHistory algorithmEventHistory) throws JsonProcessingException { List<AlgorithmEventHistoryEntry> algorithmEventHistoryEntries = new LinkedList<>(); for (int i = 0; i < algorithmEventHistory.getLength(); i++) { AlgorithmEventHistoryEntry entry = algorithmEventHistory.getEntryAtTimeStep(i); algorithmEventHistoryEntries.add(entry); } PropertyProcessedAlgorithmEventHistory serializableAlgorithmEventHistory = new PropertyProcessedAlgorithmEventHistory(algorithmEventHistoryEntries); return this.objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(serializableAlgorithmEventHistory); } /** * Deserializes the given JSON {@link String} into an {@link AlgorithmEventHistory} assuming it represents such an {@link AlgorithmEventHistory}. * * @param serializedAlgorithmEventHistory A JSON {@link String} representing an {@link AlgorithmEventHistory}. * @return An {@link AlgorithmEventHistory} constructed from the given serialized algorithm event history. * @throws JsonParseException If something went wrong during the transformation to JSON. * @throws JsonMappingException If something went wrong during the transformation to JSON. * @throws IOException If something went wrong during the transformation to JSON. */ public AlgorithmEventHistory deserializeAlgorithmEventHistory(final String serializedAlgorithmEventHistory) throws IOException { PropertyProcessedAlgorithmEventHistory serializableAlgorithmEventHistory = this.objectMapper.readValue(serializedAlgorithmEventHistory, PropertyProcessedAlgorithmEventHistory.class); return new AlgorithmEventHistory(serializableAlgorithmEventHistory.getEntries()); } /** * Deserializes the given JSON {@link File} into an {@link AlgorithmEventHistory} assuming it represents such an {@link AlgorithmEventHistory}. * * @param serializedAlgorithmEventHistory A JSON {@link String} representing an {@link AlgorithmEventHistory}. * @return An {@link AlgorithmEventHistory} constructed from the given serialized algorithm event history. * @throws JsonParseException If something went wrong during the transformation to JSON. * @throws JsonMappingException If something went wrong during the transformation to JSON. * @throws IOException If something went wrong during the transformation to JSON. */ public AlgorithmEventHistory deserializeAlgorithmEventHistory(final File serializedAlgorithmEventHistory) throws IOException { List<String> lines = Files.readAllLines(Paths.get(serializedAlgorithmEventHistory.toURI())); StringJoiner joiner = new StringJoiner(" "); for (String line : lines) { joiner.add(line); } return this.deserializeAlgorithmEventHistory(joiner.toString()); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/property/AlgorithmEventPropertyComputer.java
package ai.libs.jaicore.graphvisualizer.events.recorder.property; import java.util.List; import org.api4.java.algorithm.events.IAlgorithmEvent; public interface AlgorithmEventPropertyComputer { public List<AlgorithmEventPropertyComputer> getRequiredPropertyComputers(); /** * Overwrites (one of the) built-in required property computers of this property computer. * * @param computer */ public void overwriteRequiredPropertyComputer(AlgorithmEventPropertyComputer computer); public Object computeAlgorithmEventProperty(IAlgorithmEvent algorithmEvent) throws PropertyComputationFailedException; public String getPropertyName(); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/property/PropertyComputationFailedException.java
package ai.libs.jaicore.graphvisualizer.events.recorder.property; public class PropertyComputationFailedException extends Exception { private static final long serialVersionUID = 2855501913630309292L; public PropertyComputationFailedException() { super(); } public PropertyComputationFailedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public PropertyComputationFailedException(String message, Throwable cause) { super(message, cause); } public PropertyComputationFailedException(String message) { super(message); } public PropertyComputationFailedException(Throwable cause) { super(cause); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/property/PropertyProcessedAlgorithmEventHistory.java
package ai.libs.jaicore.graphvisualizer.events.recorder.property; import java.util.ArrayList; import java.util.List; import ai.libs.jaicore.graphvisualizer.events.recorder.AlgorithmEventHistoryEntry; public class PropertyProcessedAlgorithmEventHistory { private List<AlgorithmEventHistoryEntry> entries; public PropertyProcessedAlgorithmEventHistory() { this.entries = new ArrayList<>(); } public PropertyProcessedAlgorithmEventHistory(int size) { this.entries = new ArrayList<>(size); } public PropertyProcessedAlgorithmEventHistory(List<AlgorithmEventHistoryEntry> algorithmEventHistoryEntries) { this(algorithmEventHistoryEntries.size()); for (AlgorithmEventHistoryEntry entry : algorithmEventHistoryEntries) { entries.add(entry); } } public List<AlgorithmEventHistoryEntry> getEntries() { return entries; } public AlgorithmEventHistoryEntry getEntryAtTimeStep(final int timestep) { return this.entries.get(timestep); } public long getLength() { return this.entries.size(); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/property/PropertyProcessedAlgorithmEventListener.java
package ai.libs.jaicore.graphvisualizer.events.recorder.property; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; public interface PropertyProcessedAlgorithmEventListener { public void handleSerializableAlgorithmEvent(IPropertyProcessedAlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException; }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/events/recorder/property/PropertyProcessedAlgorithmEventSource.java
package ai.libs.jaicore.graphvisualizer.events.recorder.property; public interface PropertyProcessedAlgorithmEventSource { public void registerListener(PropertyProcessedAlgorithmEventListener algorithmEventListener); public void unregisterListener(PropertyProcessedAlgorithmEventListener algorithmEventListener); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/ASimpleMVCPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Objects; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventSource; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyProcessedAlgorithmEventSource; public abstract class ASimpleMVCPlugin<M extends ASimpleMVCPluginModel<V, C>, V extends ASimpleMVCPluginView<M, C, ?>, C extends ASimpleMVCPluginController<M, V>> implements IComputedGUIPlugin, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(ASimpleMVCPlugin.class); private final String title; private final M model; private final V view; private final C controller; protected ASimpleMVCPlugin() { this(null); } @SuppressWarnings("unchecked") protected ASimpleMVCPlugin(final String title) { super(); if (title == null) { this.title = this.getClass().getSimpleName(); } else { this.title = title; } Type[] mvcPatternClasses = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments(); M myModel; V myView; C myController; try { if (this.logger.isDebugEnabled()) { this.logger.debug(mvcPatternClasses[0].getTypeName().replaceAll("(<.*>)", "")); } Class<M> modelClass = ((Class<M>) Class.forName(this.getClassNameWithoutGenerics(mvcPatternClasses[0].getTypeName()))); Class<V> viewClass = ((Class<V>) Class.forName(this.getClassNameWithoutGenerics(mvcPatternClasses[1].getTypeName()))); Class<C> controllerClass = ((Class<C>) Class.forName(this.getClassNameWithoutGenerics(mvcPatternClasses[2].getTypeName()))); myModel = modelClass.getConstructor().newInstance(); myView = viewClass.getDeclaredConstructor(modelClass).newInstance(myModel); myController = controllerClass.getDeclaredConstructor(modelClass, viewClass).newInstance(myModel, myView); myController.setDaemon(true); myController.start(); } catch (Exception e) { this.logger.error("Could not initialize {} due to exception in building MVC.", this, e); this.model = null; this.view = null; this.controller = null; return; } Objects.requireNonNull(myController); Objects.requireNonNull(myView); Objects.requireNonNull(myModel); this.model = myModel; this.view = myView; this.controller = myController; this.model.setController(myController); this.model.setView(myView); this.view.setController(myController); } @Override public C getController() { return this.controller; } @Override public M getModel() { return this.view.getModel(); } @Override public V getView() { return this.view; } @Override public void setAlgorithmEventSource(final PropertyProcessedAlgorithmEventSource algorithmEventSource) { Objects.requireNonNull(this.controller); algorithmEventSource.registerListener(this.controller); } @Override public void setGUIEventSource(final GUIEventSource guiEventSource) { guiEventSource.registerListener(this.controller); } private String getClassNameWithoutGenerics(final String className) { return className.replaceAll("(<.*>)", ""); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); this.model.setLoggerName(name + ".model"); this.view.setLoggerName(name + ".view"); this.controller.setLoggerName(name + ".controller"); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void stop() { this.logger.info("Interrupting controller thread {}", this.controller.getName()); this.controller.interrupt(); } @Override public String getTitle() { return this.title; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/ASimpleMVCPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; public abstract class ASimpleMVCPluginController<M extends ASimpleMVCPluginModel<?, ?>, V extends ASimpleMVCPluginView<?, ?, ?>> extends Thread implements IGUIPluginController, ILoggingCustomizable { protected static final Logger STATIC_LOGGER = LoggerFactory.getLogger(ASimpleMVCPluginController.class); protected Logger logger = LoggerFactory.getLogger("gui.control." + this.getClass().getName()); private final BlockingQueue<IPropertyProcessedAlgorithmEvent> eventQueue; private final V view; private final M model; protected ASimpleMVCPluginController(final M model, final V view) { super(); this.setName(this.getClass().getName()); this.model = model; this.view = view; this.eventQueue = new LinkedBlockingQueue<>(); this.setDaemon(true); } public M getModel() { return this.model; } public V getView() { return this.view; } @Override public final void handleSerializableAlgorithmEvent(final IPropertyProcessedAlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { this.eventQueue.add(algorithmEvent); } @Override public void run() { IPropertyProcessedAlgorithmEvent event = null; while (!Thread.currentThread().isInterrupted()) { try { event = this.eventQueue.take(); this.handleAlgorithmEventInternally(event); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } catch (HandleAlgorithmEventException e) { STATIC_LOGGER.error("An error occurred while handling event {}.", event, e); } } } protected abstract void handleAlgorithmEventInternally(IPropertyProcessedAlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException; @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent || guiEvent instanceof GoToTimeStepEvent) { this.getModel().clear(); this.getView().clear(); } } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/ASimpleMVCPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author fmohr * */ public abstract class ASimpleMVCPluginModel<V extends ASimpleMVCPluginView<?, ?, ?>, C extends ASimpleMVCPluginController<?, ?>> implements IGUIPluginModel, ILoggingCustomizable { private V view; private C controller; private Logger logger = LoggerFactory.getLogger("gui.model." + this.getClass().getName()); public void setView(final V view) { this.view = view; } public V getView() { return this.view; } public C getController() { return this.controller; } public void setController(final C controller) { this.controller = controller; } public abstract void clear(); @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/ASimpleMVCPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javafx.scene.Node; /** * * @author fmohr * */ public abstract class ASimpleMVCPluginView<M extends IGUIPluginModel, C extends IGUIPluginController, N extends Node> implements IGUIPluginView, ILoggingCustomizable { private final N node; private final M model; private C controller; protected Logger logger = LoggerFactory.getLogger("gui.view." + this.getClass().getName()); protected ASimpleMVCPluginView(final M model, final N node) { this.model = model; this.node = node; } public M getModel() { return this.model; } public C getController() { return this.controller; } public void setController(final C controller) { this.controller = controller; } public abstract void clear(); /** * Gets the node that represents this view */ @Override public N getNode() { return this.node; } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/IComputedGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; public interface IComputedGUIPlugin extends IGUIPlugin { /** * Gets the property computers that are necessary to run this plugin * * @return The {@link AlgorithmEventPropertyComputer} collection */ public Collection<AlgorithmEventPropertyComputer> getPropertyComputers(); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/IGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin; import org.api4.java.algorithm.IAlgorithm; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventSource; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyProcessedAlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.window.AlgorithmVisualizationWindow; /** * {@link IGUIPlugin}s can be used to display information about an {@link IAlgorithm} or its behavior in an {@link AlgorithmVisualizationWindow}. Such a plugin consists of an {@link IGUIPluginController} responsible for handling * {@link GUIEvent}s provided by the underlying window and {@link IPropertyProcessedAlgorithmEvent}s which are constructed from the {@link IAlgorithmEvent}s provided by the underlying {@link IAlgorithm} based on the information computed by * {@link AlgorithmEventPropertyComputer}s. Furthermore, an {@link IGUIPlugin} has an {@link IGUIPluginModel} which serves as the model for the actual view, i.e. the {@link IGUIPluginView}, which is the last part of such a plugin. The * {@link IGUIPluginView} is responsible for creating the actually displayable content. * * @author atornede * */ public interface IGUIPlugin { /** * Returns the underlying {@link IGUIPluginController}. * * @return The underlying {@link IGUIPluginController}. */ public IGUIPluginController getController(); /** * Returns the underlying {@link IGUIPluginModel}. * * @return The underlying {@link IGUIPluginModel}. */ public IGUIPluginModel getModel(); /** * Returns the underlying {@link IGUIPluginView}. * * @return The underlying {@link IGUIPluginView}. */ public IGUIPluginView getView(); /** * Sets the {@link PropertyProcessedAlgorithmEventSource} yielding {@link IPropertyProcessedAlgorithmEvent}s which are handled by the {@link IGUIPluginController}. * * @param propertyProcessedAlgorithmEventSource The {@link PropertyProcessedAlgorithmEventSource} yielding {@link IPropertyProcessedAlgorithmEvent}s which are handled by the {@link IGUIPluginController}. */ public void setAlgorithmEventSource(PropertyProcessedAlgorithmEventSource propertyProcessedAlgorithmEventSource); /** * Sets the {@link GUIEventSource} yielding {@link GUIEvent}s which are handled by the {@link IGUIPluginController}. * * @param guiEventSource The {@link GUIEventSource} yielding {@link GUIEvent}s which are handled by the {@link IGUIPluginController}. */ public void setGUIEventSource(GUIEventSource guiEventSource); /** * Stops execution of all threads in this plugin (irrevocable). **/ public void stop(); /** * @return The title of the plugin as to be displayed in the window. */ public String getTitle(); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/IGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventListener; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyProcessedAlgorithmEventListener; /** * An {@link IGUIPluginController} is part of an {@link IGUIPlugin} and is reponsible for handling {@link IPropertyProcessedAlgorithmEvent}s and {@link GUIEvent}s it is provided. This usually involves either directly reacting to these * events, e.g. a mouse click, or extract required information from a {@link IPropertyProcessedAlgorithmEvent} and store it inside a {@link IGUIPluginModel}. * * @author atornede * */ public interface IGUIPluginController extends PropertyProcessedAlgorithmEventListener, GUIEventListener { }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/IGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin; /** * An {@link IGUIPluginModel} is part of an {@link IGUIPlugin} and is responsible for storing information which is displayed by the associated {@link IGUIPluginView}. * * @author atornede * */ public interface IGUIPluginModel { }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/IGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin; import ai.libs.jaicore.graphvisualizer.window.AlgorithmVisualizationWindow; import javafx.scene.Node; /** * An {@link IGUIPluginView} is part of an {@link IGUIPlugin} and is responsible displaying the information stored in the {@link IGUIPluginModel}. * * @author atornede * */ public interface IGUIPluginView { /** * Returns the JavaFX Scene {@link Node} which will be displayed inside the {@link AlgorithmVisualizationWindow}. * * @return The JavaFX Scene {@link Node} which will be displayed inside the {@link AlgorithmVisualizationWindow} */ public Node getNode(); /** * Requests this view to update itself, i.e. pull the latest information from the associated {@link IGUIPluginModel} and display it. */ public void update(); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/MVCInitializationFailedException.java
package ai.libs.jaicore.graphvisualizer.plugin; @SuppressWarnings("serial") public class MVCInitializationFailedException extends Exception { public MVCInitializationFailedException() { super(); } public MVCInitializationFailedException(String message) { super(message); } public MVCInitializationFailedException(Throwable throwable) { super(throwable); } public MVCInitializationFailedException(String message, Throwable throwable) { super(message, throwable); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/controlbar/ControlBarGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; public class ControlBarGUIPlugin extends ASimpleMVCPlugin<ControlBarGUIPluginModel, ControlBarGUIPluginView, ControlBarGUIPluginController> { public ControlBarGUIPlugin() { this("Control Bar"); } public ControlBarGUIPlugin(final String title) { super(title); } @Override public void stop() { this.getController().interrupt(); } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(); // no computers required } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/controlbar/ControlBarGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; public class ControlBarGUIPluginController extends ASimpleMVCPluginController<ControlBarGUIPluginModel, ControlBarGUIPluginView> { public ControlBarGUIPluginController(final ControlBarGUIPluginModel model, final ControlBarGUIPluginView view) { super(model, view); } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof PauseEvent || guiEvent instanceof ResetEvent) { this.getModel().setPaused(); } else if (guiEvent instanceof PlayEvent) { this.getModel().setUnpaused(); } } @Override protected void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { // nothing to do here as the control bar does not need to handle any algorithm event } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/controlbar/ControlBarGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; public class ControlBarGUIPluginModel extends ASimpleMVCPluginModel<ControlBarGUIPluginView, ControlBarGUIPluginController> { private boolean visualizationPaused = true; public void setPaused() { this.visualizationPaused = true; this.getView().update(); } public void setUnpaused() { this.visualizationPaused = false; this.getView().update(); } public boolean isPaused() { return this.visualizationPaused; } @Override public void clear() { /* nothing to do here */ } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/controlbar/ControlBarGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import javafx.application.Platform; import javafx.scene.control.Button; import javafx.scene.control.Separator; import javafx.scene.control.ToolBar; public class ControlBarGUIPluginView extends ASimpleMVCPluginView<ControlBarGUIPluginModel, ControlBarGUIPluginController, ToolBar> { private Button startButton; public ControlBarGUIPluginView(final ControlBarGUIPluginModel model) { super(model, new ToolBar()); Platform.runLater(() -> { ToolBar topButtonToolBar = this.getNode(); this.startButton = new Button("Play"); this.startButton.setMinWidth(70); // this is the size which we need for the "resume" text this.startButton.setOnMouseClicked(event -> this.handleStartResumePauseButtonClick()); topButtonToolBar.getItems().add(this.startButton); Button resetButton = new Button("Reset"); resetButton.setOnMouseClicked(event -> this.handleResetButtonClick()); topButtonToolBar.getItems().add(resetButton); topButtonToolBar.getItems().add(new Separator()); }); } public void handleStartResumePauseButtonClick() { if (this.getModel().isPaused()) { DefaultGUIEventBus.getInstance().postEvent(new PlayEvent()); } else { DefaultGUIEventBus.getInstance().postEvent(new PauseEvent()); } } public void handleResetButtonClick() { DefaultGUIEventBus.getInstance().postEvent(new ResetEvent()); } @Override public void update() { if (this.getModel().isPaused()) { this.startButton.setText("Resume"); } else { this.startButton.setText("Pause "); } } @Override public void clear() { /* nothing to do */ } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/controlbar/PauseEvent.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; public class PauseEvent implements GUIEvent { }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/controlbar/PlayEvent.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; public class PlayEvent implements GUIEvent { }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/controlbar/ResetEvent.java
package ai.libs.jaicore.graphvisualizer.plugin.controlbar; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; public class ResetEvent implements GUIEvent { }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphMouseListener.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import org.graphstream.graph.Node; import org.graphstream.ui.view.ViewerListener; import org.graphstream.ui.view.ViewerPipe; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; public class GraphMouseListener implements ViewerListener, Runnable { private boolean active; private GraphViewPluginModel viewModel; private ViewerPipe viewerPipe; public GraphMouseListener(final GraphViewPluginModel viewModel, final ViewerPipe viewerPipe) { this.viewModel = viewModel; this.viewerPipe = viewerPipe; this.active = true; } @Override public void buttonPushed(final String id) { Node viewGraphNode = this.viewModel.getGraph().getNode(id); String searchGraphNode = this.viewModel.getSearchGraphNodeMappedToViewGraphNode(viewGraphNode); DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(viewGraphNode, searchGraphNode)); } @Override public void buttonReleased(final String id) { // nothing to do here } @Override public void mouseLeft(final String id) { // nothing to do here } @Override public void mouseOver(final String id) { // nothing to do here } @Override public void viewClosed(final String id) { // this.active = false; // This is not good here. This directly closes the listener and thus the pump thread. } @Override public void run() { while (this.active) { if (Thread.currentThread().isInterrupted()) { this.active = false; return; } this.viewerPipe.pump(); } } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphViewPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.IColorMap; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoAlgorithmEventPropertyComputer; public class GraphViewPlugin extends ASimpleMVCPlugin<GraphViewPluginModel, GraphViewPluginView, GraphViewPluginController> { public GraphViewPlugin() { this("Search Graph Viewer"); } public GraphViewPlugin(final String title) { super(title); } @Override public void stop() { super.stop(); this.getView().stop(); } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(new NodeInfoAlgorithmEventPropertyComputer()); } public GraphViewPlugin withNodeColoringBasedOnProperty(final String propertyName, final IColorMap colorScheme, final double min, final double max) { this.getModel().setPropertyBasedNodeColoring(propertyName, colorScheme, min, max); return this; } public GraphViewPlugin withLabelsForNodeProperties() { this.getModel().setWithPropertyLabels(true); return this; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphViewPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import java.util.Collections; import java.util.stream.Collectors; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodePropertyChangedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeRemovedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeTypeSwitchEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfo; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoAlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; public class GraphViewPluginController extends ASimpleMVCPluginController<GraphViewPluginModel, GraphViewPluginView> { public GraphViewPluginController(final GraphViewPluginModel model, final GraphViewPluginView view) { super(model, view); } @Override protected void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { try { if (this.correspondsToGraphInitializedEvent(algorithmEvent)) { this.handleGraphInitializedEvent(algorithmEvent); } else if (this.correspondsToNodeAddedEvent(algorithmEvent)) { this.handleNodeAddedEvent(algorithmEvent); } else if (this.correspondsToNodeRemovedEvent(algorithmEvent)) { this.handleNodeRemovedEvent(algorithmEvent); } else if (this.correspondsToNodeTypSwitchEvent(algorithmEvent)) { this.handleNodeTypeSwitchEvent(algorithmEvent); } else if (this.correspondsToNodePropertySwitchEvent(algorithmEvent)) { this.handleNodePropertySwitchEvent(algorithmEvent); } } catch (ViewGraphManipulationException exception) { throw new HandleAlgorithmEventException("Encountered a problem while handling graph event " + algorithmEvent + " .", exception); } } private boolean correspondsToNodeTypSwitchEvent(final IPropertyProcessedAlgorithmEvent algorithmEvent) { return algorithmEvent.getEventName().equalsIgnoreCase(NodeTypeSwitchEvent.class.getSimpleName()); } private boolean correspondsToNodePropertySwitchEvent(final IPropertyProcessedAlgorithmEvent algorithmEvent) { return algorithmEvent.getEventName().equalsIgnoreCase(NodePropertyChangedEvent.class.getSimpleName()); } private boolean correspondsToNodeRemovedEvent(final IPropertyProcessedAlgorithmEvent algorithmEvent) { return algorithmEvent.getEventName().equalsIgnoreCase(NodeRemovedEvent.class.getSimpleName()); } private boolean correspondsToNodeAddedEvent(final IPropertyProcessedAlgorithmEvent algorithmEvent) { return algorithmEvent.getEventName().equalsIgnoreCase(NodeAddedEvent.class.getSimpleName()); } private boolean correspondsToGraphInitializedEvent(final IPropertyProcessedAlgorithmEvent algorithmEvent) { return algorithmEvent.getEventName().equalsIgnoreCase(GraphInitializedEvent.class.getSimpleName()); } private void handleGraphInitializedEvent(final IPropertyProcessedAlgorithmEvent graphInitializedEvent) throws ViewGraphManipulationException { NodeInfo nodeInfo = graphInitializedEvent.getProperty(NodeInfoAlgorithmEventPropertyComputer.NODE_INFO_PROPERTY_NAME, NodeInfo.class); this.getModel().addNode(nodeInfo.getMainNodeId(), Collections.emptyList(), "root"); } private void handleNodeAddedEvent(final IPropertyProcessedAlgorithmEvent nodeReachedEvent) throws ViewGraphManipulationException { NodeInfo nodeInfo = nodeReachedEvent.getProperty(NodeInfoAlgorithmEventPropertyComputer.NODE_INFO_PROPERTY_NAME, NodeInfo.class); this.getModel().addNode(nodeInfo.getMainNodeId(), nodeInfo.getParentNodeIds().stream().map(Object.class::cast).collect(Collectors.toList()), nodeInfo.getNodeType()); } private void handleNodeTypeSwitchEvent(final IPropertyProcessedAlgorithmEvent nodeTypeSwitchEvent) throws ViewGraphManipulationException { NodeInfo nodeInfo = nodeTypeSwitchEvent.getProperty(NodeInfoAlgorithmEventPropertyComputer.NODE_INFO_PROPERTY_NAME, NodeInfo.class); this.getModel().switchNodeType(nodeInfo.getMainNodeId(), nodeInfo.getNodeType()); } private void handleNodePropertySwitchEvent(final IPropertyProcessedAlgorithmEvent nodePropertySwitchEvent) throws ViewGraphManipulationException { NodeInfo nodeInfo = nodePropertySwitchEvent.getProperty(NodeInfoAlgorithmEventPropertyComputer.NODE_INFO_PROPERTY_NAME, NodeInfo.class); this.getModel().updateNodeProperties(nodeInfo.getMainNodeId(), nodeInfo.getProperties()); } private void handleNodeRemovedEvent(final IPropertyProcessedAlgorithmEvent nodeRemovedEvent) throws ViewGraphManipulationException { NodeInfo nodeInfo = nodeRemovedEvent.getProperty(NodeInfoAlgorithmEventPropertyComputer.NODE_INFO_PROPERTY_NAME, NodeInfo.class); this.getModel().removeNode(nodeInfo.getMainNodeId()); } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent || guiEvent instanceof GoToTimeStepEvent) { this.getModel().clear(); } } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphViewPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import java.awt.Color; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.graphstream.graph.Edge; import org.graphstream.graph.Graph; import org.graphstream.graph.IdAlreadyInUseException; import org.graphstream.graph.Node; import org.graphstream.graph.implementations.SingleGraph; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.FileUtil; import ai.libs.jaicore.basic.ResourceUtil; import ai.libs.jaicore.graphvisualizer.IColorMap; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; public class GraphViewPluginModel extends ASimpleMVCPluginModel<GraphViewPluginView, GraphViewPluginController> { private Logger logger = LoggerFactory.getLogger(GraphViewPluginModel.class); private static final String L_UI_CLASS = "ui.class"; private static final String DEFAULT_RESSOURCE_STYLESHEET_PATH = "searchgraph.css"; private static final String STYLESHEET_PATH = "conf/searchgraph.css"; private static final File DEFAULT_STYLESHEET_FILE = FileUtil.getExistingFileWithHighestPriority(DEFAULT_RESSOURCE_STYLESHEET_PATH, STYLESHEET_PATH); private final AtomicInteger nodeIdCounter = new AtomicInteger(0); private Graph graph; private final ConcurrentMap<String, Node> searchGraphNodesToViewGraphNodesMap; private final ConcurrentMap<Node, String> viewGraphNodesToSearchGraphNodesMap; private final ConcurrentMap<Node, Set<Edge>> nodeToConnectedEdgesMap; private final ConcurrentMap<Node, Map<String, Object>> nodeProperties; /* node color scheme */ private double nodeColoringMin; private double nodeColoringMax; private IColorMap colormap; private String propertyToUseForColoring; private boolean withPropertyLabels = false; public GraphViewPluginModel() { this(DEFAULT_STYLESHEET_FILE); } private GraphViewPluginModel(final File searchGraphCSSPath) { this.searchGraphNodesToViewGraphNodesMap = new ConcurrentHashMap<>(); this.viewGraphNodesToSearchGraphNodesMap = new ConcurrentHashMap<>(); this.nodeToConnectedEdgesMap = new ConcurrentHashMap<>(); this.nodeProperties = new ConcurrentHashMap<>(); this.initializeGraph(searchGraphCSSPath); } private void initializeGraph(final File searchGraphCSSPath) { this.graph = new SingleGraph("Search Graph"); try { this.graph.setAttribute("ui.stylesheet", FileUtil.readFileAsString(searchGraphCSSPath.getPath())); } catch (IOException e) { this.logger.warn("Could not load css stylesheet for graph view plugin. Continue without stylesheet", e); } } public synchronized void addNode(final String node, final List<Object> predecessorNodes, final String typeOfNode) throws ViewGraphManipulationException { try { this.logger.debug("Adding node with external id {}", node); Node viewNode = this.graph.addNode(String.valueOf(this.nodeIdCounter.getAndIncrement())); this.registerNodeMapping(node, viewNode); for (Object predecessorNode : predecessorNodes) { this.createEdge(node, predecessorNode); } this.switchNodeType(viewNode, typeOfNode); this.getView().update(); this.logger.debug("Added node with external id {}. Internal id is {}", node, viewNode.getId()); } catch (IdAlreadyInUseException exception) { throw new ViewGraphManipulationException("Cannot add node " + node + " as the id " + this.nodeIdCounter + " is already in use."); } } private synchronized void createEdge(final Object node, final Object predecessorNode) throws ViewGraphManipulationException { Node viewNode = this.searchGraphNodesToViewGraphNodesMap.get(node); Node viewPredecessorNode = this.searchGraphNodesToViewGraphNodesMap.get(predecessorNode); if (viewPredecessorNode == null) { throw new ViewGraphManipulationException("Cannot add edge from node " + predecessorNode + " to node " + viewNode + " due to missing view node of predecessor."); } String edgeId = viewPredecessorNode.getId() + "-" + viewNode.getId(); Edge edge = this.graph.addEdge(edgeId, viewPredecessorNode, viewNode, true); this.registerEdgeConnectedToNodesInMap(edge); } private void registerNodeMapping(final String node, final Node viewNode) { this.searchGraphNodesToViewGraphNodesMap.put(node, viewNode); this.viewGraphNodesToSearchGraphNodesMap.put(viewNode, node); } private void registerEdgeConnectedToNodesInMap(final Edge edge) { if (!this.nodeToConnectedEdgesMap.containsKey(edge.getNode0())) { this.nodeToConnectedEdgesMap.put(edge.getNode0(), new HashSet<>()); } this.nodeToConnectedEdgesMap.get(edge.getNode0()).add(edge); if (!this.nodeToConnectedEdgesMap.containsKey(edge.getNode1())) { this.nodeToConnectedEdgesMap.put(edge.getNode1(), new HashSet<>()); } this.nodeToConnectedEdgesMap.get(edge.getNode1()).add(edge); } public void switchNodeType(final Object node, final String newType) throws ViewGraphManipulationException { if (node == null) { throw new ViewGraphManipulationException("Cannot switch type of null node."); } Node viewNode = this.searchGraphNodesToViewGraphNodesMap.get(node); if (viewNode == null) { throw new ViewGraphManipulationException("Cannot switch type of node " + node + " without corresponding view node."); } this.switchNodeType(viewNode, newType); this.getView().update(); } private void switchNodeType(final Node node, final String newType) { if (!this.isLabeledAsRootNode(node)) { node.setAttribute(L_UI_CLASS, newType); } } public void updateNodeProperties(final Object node, final Map<String, Object> properties) throws ViewGraphManipulationException { if (node == null) { throw new ViewGraphManipulationException("Cannot switch type of null node."); } Node viewNode = this.searchGraphNodesToViewGraphNodesMap.get(node); this.updateNodeProperties(viewNode, properties); } public void updateNodeProperties(final Node node, final Map<String, Object> properties) { this.nodeProperties.computeIfAbsent(node, n -> new HashMap<>()).putAll(properties); if (properties.containsKey(this.propertyToUseForColoring)) { Object valAsObject = properties.get(this.propertyToUseForColoring); double val = valAsObject instanceof Double ? (double) valAsObject : Double.valueOf("" + valAsObject); Color c = this.colormap.get(this.nodeColoringMin, this.nodeColoringMax, val); node.setAttribute("ui.style", "fill-color: rgb(" + c.getRed() + "," + c.getGreen() + ", " + c.getBlue() + ");"); if (this.withPropertyLabels) { node.setAttribute("ui.label", this.nodeProperties.get(node).entrySet().stream().map(e -> e.getKey() + ": " + e.getValue()).collect(Collectors.joining("\n"))); } } } private boolean isLabeledAsRootNode(final Node node) { return node.getAttribute(L_UI_CLASS) != null && node.getAttribute(L_UI_CLASS).equals("root"); } public void removeNode(final Object node) throws ViewGraphManipulationException { if (node == null) { throw new ViewGraphManipulationException("Cannot remove null node."); } Node viewNode = this.searchGraphNodesToViewGraphNodesMap.remove(node); if (viewNode == null) { throw new ViewGraphManipulationException("Cannot remove node " + node + " without corresponding view node."); } this.viewGraphNodesToSearchGraphNodesMap.remove(viewNode); Set<Edge> connectedEdges = this.nodeToConnectedEdgesMap.remove(viewNode); this.graph.removeNode(viewNode); for (Edge edge : connectedEdges) { Node otherNode = edge.getNode0().equals(viewNode) ? edge.getNode1() : edge.getNode0(); Set<Edge> connectedEdgesOfOtherNode = this.nodeToConnectedEdgesMap.get(otherNode); connectedEdgesOfOtherNode.remove(edge); } } public Graph getGraph() { return this.graph; } public String getSearchGraphNodeMappedToViewGraphNode(final Object viewGraphNode) { return this.viewGraphNodesToSearchGraphNodesMap.get(viewGraphNode); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } @Override public void clear() { this.graph.clear(); try { this.graph.setAttribute("ui.stylesheet", ResourceUtil.readResourceFileToString(DEFAULT_STYLESHEET_FILE.getPath())); } catch (IOException e) { this.logger.warn("Could not load css stylesheet for graph view plugin. Continue without stylesheet", e); } this.searchGraphNodesToViewGraphNodesMap.clear(); this.viewGraphNodesToSearchGraphNodesMap.clear(); this.nodeToConnectedEdgesMap.clear(); this.getView().update(); } public void setPropertyBasedNodeColoring(final String propertyName, final IColorMap colorScheme, final double min, final double max) { this.propertyToUseForColoring = propertyName; this.colormap = colorScheme; this.nodeColoringMin = min; this.nodeColoringMax = max; } public boolean isWithPropertyLabels() { return this.withPropertyLabels; } public void setWithPropertyLabels(final boolean withPropertyLabels) { this.withPropertyLabels = withPropertyLabels; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/graphview/GraphViewPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import org.graphstream.ui.fx_viewer.FxViewPanel; import org.graphstream.ui.fx_viewer.FxViewer; import org.graphstream.ui.view.Viewer.ThreadingModel; import org.graphstream.ui.view.ViewerPipe; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import javafx.scene.layout.BorderPane; public class GraphViewPluginView extends ASimpleMVCPluginView<GraphViewPluginModel, GraphViewPluginController, BorderPane> { private FxViewer fxViewer; private Thread listenerThread; public GraphViewPluginView(final GraphViewPluginModel model) { super(model, new BorderPane()); this.fxViewer = new FxViewer(model.getGraph(), ThreadingModel.GRAPH_IN_ANOTHER_THREAD); this.fxViewer.enableAutoLayout(); FxViewPanel fxViewPanel = (FxViewPanel) this.fxViewer.addDefaultView(false); this.getNode().setCenter(fxViewPanel); this.initializeGraphMouseListener(); } private void initializeGraphMouseListener() { ViewerPipe viewerPipe = this.fxViewer.newViewerPipe(); GraphMouseListener graphMouseListener = new GraphMouseListener(this.getModel(), viewerPipe); viewerPipe.addViewerListener(graphMouseListener); viewerPipe.addSink(this.getModel().getGraph()); this.listenerThread = new Thread(graphMouseListener, "Graph View Plugin"); this.listenerThread.setDaemon(true); this.listenerThread.start(); } @Override public void update() { // No need for code here as the update happens automatically via the graphstream graph } public void stop() { this.listenerThread.interrupt(); this.fxViewer.close(); } @Override public void clear() { // No need for code here as the update happens automatically via the graphstream graph } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/graphview/NodeClickedEvent.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; import org.graphstream.graph.Node; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; public class NodeClickedEvent implements GUIEvent { private Node viewerNode; private String searchGraphNode; public NodeClickedEvent(Node viewerNode, String searchGraphNode) { this.viewerNode = viewerNode; this.searchGraphNode = searchGraphNode; } public Node getViewerNode() { return viewerNode; } public String getSearchGraphNode() { return searchGraphNode; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/graphview/ViewGraphManipulationException.java
package ai.libs.jaicore.graphvisualizer.plugin.graphview; public class ViewGraphManipulationException extends Exception { private static final long serialVersionUID = -3854909479243383118L; protected ViewGraphManipulationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ViewGraphManipulationException(String message, Throwable cause) { super(message, cause); } public ViewGraphManipulationException(Throwable cause) { super(cause); } public ViewGraphManipulationException(String message) { super(message); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeDisplayInfoAlgorithmEventPropertyComputer.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import java.util.Arrays; import java.util.List; import org.api4.java.algorithm.events.IAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeInfoAlteredEvent; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyComputationFailedException; public class NodeDisplayInfoAlgorithmEventPropertyComputer<N> implements AlgorithmEventPropertyComputer { public static final String NODE_DISPLAY_INFO_PROPERTY_NAME = "node_display_info"; private NodeInfoGenerator<N> nodeInfoGenerator; private String propertyName; public NodeDisplayInfoAlgorithmEventPropertyComputer(final NodeInfoGenerator<N> nodeInfoGenerator) { this(NODE_DISPLAY_INFO_PROPERTY_NAME + "_" + nodeInfoGenerator.getName(), nodeInfoGenerator); } public NodeDisplayInfoAlgorithmEventPropertyComputer(final String propertyName, final NodeInfoGenerator<N> nodeInfoGenerator) { this.propertyName = propertyName; this.nodeInfoGenerator = nodeInfoGenerator; } @SuppressWarnings("unchecked") @Override public String computeAlgorithmEventProperty(final IAlgorithmEvent algorithmEvent) throws PropertyComputationFailedException { String nodeInfo = null; if (algorithmEvent instanceof GraphInitializedEvent) { GraphInitializedEvent<N> graphInitializedEvent = (GraphInitializedEvent<N>) algorithmEvent; return this.getNodeInfoForNodeIfTypeFits(graphInitializedEvent.getRoot()); } else if (algorithmEvent instanceof NodeAddedEvent) { NodeAddedEvent<N> nodeAddedEvent = (NodeAddedEvent<N>) algorithmEvent; return this.getNodeInfoForNodeIfTypeFits(nodeAddedEvent.getNode()); } else if (algorithmEvent instanceof NodeInfoAlteredEvent) { NodeInfoAlteredEvent<N> nodeAddedEvent = (NodeInfoAlteredEvent<N>) algorithmEvent; return this.getNodeInfoForNodeIfTypeFits(nodeAddedEvent.getNode()); } return nodeInfo; } @Override public String getPropertyName() { return this.propertyName; } private String getNodeInfoForNodeIfTypeFits(final N node) { return this.nodeInfoGenerator.generateInfoForNode(node); } @Override public List<AlgorithmEventPropertyComputer> getRequiredPropertyComputers() { return Arrays.asList(); } @Override public void overwriteRequiredPropertyComputer(final AlgorithmEventPropertyComputer computer) { throw new UnsupportedOperationException(this.getClass().getCanonicalName() + " has no dependencies to other property computers."); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfo.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import java.util.ArrayList; import java.util.List; import java.util.Map; public class NodeInfo { private String mainNodeId; private List<String> parentNodeIds; private List<String> childrenNodeIds; private String nodeType; private Map<String, Object> properties; @SuppressWarnings("unused") private NodeInfo() { // for serialization purposes } public NodeInfo(final String mainNodeId, final List<String> parentNodeIds, final List<String> childrenNodeIds, final String nodeType) { this(mainNodeId, parentNodeIds, childrenNodeIds, nodeType, null); } public NodeInfo(final String mainNodeId, final List<String> parentNodeIds, final List<String> childrenNodeIds, final String nodeType, final Map<String, Object> properties) { super(); this.mainNodeId = mainNodeId; if (parentNodeIds != null) { this.parentNodeIds = new ArrayList<>(parentNodeIds); } if (childrenNodeIds != null) { this.childrenNodeIds = new ArrayList<>(childrenNodeIds); } this.nodeType = nodeType; this.properties = properties; } public String getMainNodeId() { return this.mainNodeId; } public List<String> getParentNodeIds() { return this.parentNodeIds; } public List<String> getChildrenNodeIds() { return this.childrenNodeIds; } public String getNodeType() { return this.nodeType; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.childrenNodeIds == null) ? 0 : this.childrenNodeIds.hashCode()); result = prime * result + ((this.mainNodeId == null) ? 0 : this.mainNodeId.hashCode()); result = prime * result + ((this.nodeType == null) ? 0 : this.nodeType.hashCode()); result = prime * result + ((this.parentNodeIds == null) ? 0 : this.parentNodeIds.hashCode()); result = prime * result + ((this.properties == null) ? 0 : this.properties.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; } NodeInfo other = (NodeInfo) obj; if (this.childrenNodeIds == null) { if (other.childrenNodeIds != null) { return false; } } else if (!this.childrenNodeIds.equals(other.childrenNodeIds)) { return false; } if (this.mainNodeId == null) { if (other.mainNodeId != null) { return false; } } else if (!this.mainNodeId.equals(other.mainNodeId)) { return false; } if (this.nodeType == null) { if (other.nodeType != null) { return false; } } else if (!this.nodeType.equals(other.nodeType)) { return false; } if (this.parentNodeIds == null) { if (other.parentNodeIds != null) { return false; } } else if (!this.parentNodeIds.equals(other.parentNodeIds)) { return false; } if (this.properties == null) { if (other.properties != null) { return false; } } else if (!this.properties.equals(other.properties)) { return false; } return true; } @Override public String toString() { return "NodeInfo [mainNodeId=" + this.mainNodeId + ", parentNodeIds=" + this.parentNodeIds + ", childrenNodeIds=" + this.childrenNodeIds + ", nodeType=" + this.nodeType + ", properties=" + this.properties + "]"; } public Map<String, Object> getProperties() { return this.properties; } public void setProperties(final Map<String, Object> properties) { this.properties = properties; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoAlgorithmEventPropertyComputer.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.api4.java.algorithm.events.IAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeInfoAlteredEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodePropertyChangedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeRemovedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeTypeSwitchEvent; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyComputationFailedException; public class NodeInfoAlgorithmEventPropertyComputer implements AlgorithmEventPropertyComputer { public static final String NODE_INFO_PROPERTY_NAME = "node_info"; private Map<Object, Integer> nodeToIdMap; private AtomicInteger idCounter; public NodeInfoAlgorithmEventPropertyComputer() { this.nodeToIdMap = new ConcurrentHashMap<>(); this.idCounter = new AtomicInteger(); } @Override public NodeInfo computeAlgorithmEventProperty(final IAlgorithmEvent algorithmEvent) throws PropertyComputationFailedException { if (algorithmEvent instanceof GraphInitializedEvent) { GraphInitializedEvent<?> graphInitializedEvent = (GraphInitializedEvent<?>) algorithmEvent; Object mainNode = graphInitializedEvent.getRoot(); return new NodeInfo(this.getIdOfNode(mainNode), null, null, null); } else if (algorithmEvent instanceof NodeAddedEvent) { NodeAddedEvent<?> nodeAddedEvent = (NodeAddedEvent<?>) algorithmEvent; Object mainNode = nodeAddedEvent.getNode(); String mainNodeId = this.getIdOfNode(mainNode); String parentNodeId = this.getIdOfNode(nodeAddedEvent.getParent()); String nodeType = nodeAddedEvent.getType(); return new NodeInfo(mainNodeId, Arrays.asList(parentNodeId), null, nodeType); } else if (algorithmEvent instanceof NodeInfoAlteredEvent) { NodeInfoAlteredEvent<?> nodeAddedEvent = (NodeInfoAlteredEvent<?>) algorithmEvent; Object mainNode = nodeAddedEvent.getNode(); String mainNodeId = this.getIdOfNode(mainNode); return new NodeInfo(mainNodeId, null, null, null); } else if (algorithmEvent instanceof NodeRemovedEvent) { NodeRemovedEvent<?> nodeRemovedEvent = (NodeRemovedEvent<?>) algorithmEvent; String mainNodeId = this.getIdOfNode(nodeRemovedEvent.getNode()); return new NodeInfo(mainNodeId, null, null, null); } else if (algorithmEvent instanceof NodeTypeSwitchEvent) { NodeTypeSwitchEvent<?> nodeAddedEvent = (NodeTypeSwitchEvent<?>) algorithmEvent; Object mainNode = nodeAddedEvent.getNode(); String mainNodeId = this.getIdOfNode(mainNode); String nodeType = nodeAddedEvent.getType(); return new NodeInfo(mainNodeId, null, null, nodeType); } else if (algorithmEvent instanceof NodePropertyChangedEvent) { NodePropertyChangedEvent<?> propertyChangedEvent = (NodePropertyChangedEvent<?>) algorithmEvent; Object mainNode = propertyChangedEvent.getNode(); String mainNodeId = this.getIdOfNode(mainNode); Map<String, Object> properties = propertyChangedEvent.getChangedProperties(); return new NodeInfo(mainNodeId, null, null, null, properties); } return null; } @Override public String getPropertyName() { return NODE_INFO_PROPERTY_NAME; } private String getIdOfNode(final Object node) { return String.valueOf(this.nodeToIdMap.computeIfAbsent(node, t -> this.idCounter.getAndIncrement())); } public String getIdOfNodeIfExistent(final Object node) { return String.valueOf(this.nodeToIdMap.get(node)); } @Override public List<AlgorithmEventPropertyComputer> getRequiredPropertyComputers() { return Arrays.asList(); } @Override public void overwriteRequiredPropertyComputer(final AlgorithmEventPropertyComputer computer) { throw new UnsupportedOperationException(this.getClass().getCanonicalName() + " does not rely on other property computers"); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; public class NodeInfoGUIPlugin extends ASimpleMVCPlugin<NodeInfoGUIPluginModel, NodeInfoGUIPluginView, NodeInfoGUIPluginController> { private final NodeInfoGenerator<?> infoGenerator; public NodeInfoGUIPlugin(final NodeInfoGenerator<?> infoGenerator) { this("Node Info", infoGenerator); } public NodeInfoGUIPlugin(final String title, final NodeInfoGenerator<?> infoGenerator) { super(title); this.infoGenerator = infoGenerator; this.getController().setInfoGenerator(infoGenerator); } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(new NodeDisplayInfoAlgorithmEventPropertyComputer<>(this.infoGenerator)); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; import ai.libs.jaicore.graphvisualizer.plugin.graphview.NodeClickedEvent; public class NodeInfoGUIPluginController extends ASimpleMVCPluginController<NodeInfoGUIPluginModel, NodeInfoGUIPluginView> { private NodeInfoGenerator<?> infoGenerator; public NodeInfoGUIPluginController(final NodeInfoGUIPluginModel model, final NodeInfoGUIPluginView view) { super(model, view); } @Override public void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { Object rawNodeDisplayInfoProperty = algorithmEvent.getProperty(NodeDisplayInfoAlgorithmEventPropertyComputer.NODE_DISPLAY_INFO_PROPERTY_NAME + "_" + this.infoGenerator.getName()); Object rawNodeInfoProperty = algorithmEvent.getProperty(NodeInfoAlgorithmEventPropertyComputer.NODE_INFO_PROPERTY_NAME); if (rawNodeDisplayInfoProperty != null && rawNodeInfoProperty != null) { NodeInfo nodeInfo = (NodeInfo) rawNodeInfoProperty; String nodeInfoText = (String) rawNodeDisplayInfoProperty; this.getModel().addNodeIdToNodeInfoMapping(nodeInfo.getMainNodeId(), nodeInfoText); } } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof NodeClickedEvent) { NodeClickedEvent nodeClickedEvent = (NodeClickedEvent) guiEvent; String searchGraphNodeCorrespondingToClickedViewGraphNode = nodeClickedEvent.getSearchGraphNode(); this.getModel().setCurrentlySelectedNode(searchGraphNodeCorrespondingToClickedViewGraphNode); } } public NodeInfoGenerator<?> getInfoGenerator() { return this.infoGenerator; } public void setInfoGenerator(final NodeInfoGenerator<?> infoGenerator) { this.infoGenerator = infoGenerator; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import java.util.HashMap; import java.util.Map; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; /** * * @author Felix Mohr * */ public class NodeInfoGUIPluginModel extends ASimpleMVCPluginModel<NodeInfoGUIPluginView, NodeInfoGUIPluginController> { private Map<String, String> nodeIdToNodeInfoMap; private String currentlySelectedNode; public NodeInfoGUIPluginModel() { this.nodeIdToNodeInfoMap = new HashMap<>(); } public void addNodeIdToNodeInfoMapping(final String nodeId, final String nodeInfo) { this.nodeIdToNodeInfoMap.put(nodeId, nodeInfo); } public String getNodeInfoForNodeId(final String nodeId) { return this.nodeIdToNodeInfoMap.get(nodeId); } public String getCurrentlySelectedNode() { return this.currentlySelectedNode; } public void setCurrentlySelectedNode(final String currentlySelectedNode) { this.currentlySelectedNode = currentlySelectedNode; this.getView().update(); } public String getNodeInfoForCurrentlySelectedNode() { return this.getNodeInfoForNodeId(this.getCurrentlySelectedNode()); } @Override public void clear() { /* ignore this */ } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import javafx.application.Platform; import javafx.scene.layout.StackPane; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; /** * * @author Felix Mohr * */ public class NodeInfoGUIPluginView extends ASimpleMVCPluginView<NodeInfoGUIPluginModel, NodeInfoGUIPluginController, StackPane> { private WebEngine webViewEngine; public NodeInfoGUIPluginView(final NodeInfoGUIPluginModel model) { super(model, new StackPane()); Platform.runLater(() -> { WebView view = new WebView(); StackPane node = this.getNode(); node.getChildren().add(view); this.webViewEngine = view.getEngine(); this.webViewEngine.loadContent("<i>No node selected</i>"); }); } @Override public void update() { String nodeInfoOfCurrentlySelectedNode = this.getModel().getNodeInfoForCurrentlySelectedNode(); Platform.runLater(() -> this.webViewEngine.loadContent(nodeInfoOfCurrentlySelectedNode)); } @Override public void clear() { /* don't do anything */ } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/nodeinfo/NodeInfoGenerator.java
package ai.libs.jaicore.graphvisualizer.plugin.nodeinfo; /** * * @author hetzer * * @param <N> * The node class for which information is provided */ public interface NodeInfoGenerator<N> { public String getName(); public String generateInfoForNode(N node); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/ScoredSolutionCandidateInfo.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; public class ScoredSolutionCandidateInfo { private String solutionCandidateRepresentation; private String score; protected ScoredSolutionCandidateInfo() { // for serialization purposes } public ScoredSolutionCandidateInfo(String solutionCandidateRepresentation, String score) { super(); this.solutionCandidateRepresentation = solutionCandidateRepresentation; this.score = score; } public String getSolutionCandidateRepresentation() { return solutionCandidateRepresentation; } public String getScore() { return score; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((score == null) ? 0 : score.hashCode()); result = prime * result + ((solutionCandidateRepresentation == null) ? 0 : solutionCandidateRepresentation.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ScoredSolutionCandidateInfo other = (ScoredSolutionCandidateInfo) obj; if (score == null) { if (other.score != null) { return false; } } else if (!score.equals(other.score)) { return false; } if (solutionCandidateRepresentation == null) { if (other.solutionCandidateRepresentation != null) { return false; } } else if (!solutionCandidateRepresentation.equals(other.solutionCandidateRepresentation)) { return false; } return true; } @Override public String toString() { return "ScoredSolutionCandidateInfo [solutionCandidateRepresentation=" + solutionCandidateRepresentation + ", score=" + score + "]"; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/ScoredSolutionCandidateInfoAlgorithmEventPropertyComputer.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.events.result.IScoredSolutionCandidateFoundEvent; import ai.libs.jaicore.graphvisualizer.events.recorder.AIndependentAlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyComputationFailedException; public class ScoredSolutionCandidateInfoAlgorithmEventPropertyComputer extends AIndependentAlgorithmEventPropertyComputer { public static final String SCORED_SOLUTION_CANDIDATE_INFO_PROPERTY_NAME = "scored_solution_candidate_info"; private SolutionCandidateRepresenter solutionCandidateRepresenter; public ScoredSolutionCandidateInfoAlgorithmEventPropertyComputer(final SolutionCandidateRepresenter solutionCandidateRepresenter) { this.solutionCandidateRepresenter = solutionCandidateRepresenter; } public ScoredSolutionCandidateInfoAlgorithmEventPropertyComputer() { this(null); } @Override public Object computeAlgorithmEventProperty(final IAlgorithmEvent algorithmEvent) throws PropertyComputationFailedException { if (algorithmEvent instanceof IScoredSolutionCandidateFoundEvent) { IScoredSolutionCandidateFoundEvent<?, ?> solutionCandidateFoundEvent = (IScoredSolutionCandidateFoundEvent<?, ?>) algorithmEvent; String solutionCandidateRepresentation = this.getStringRepresentationOfSolutionCandidate(solutionCandidateFoundEvent.getSolutionCandidate()); String score = solutionCandidateFoundEvent.getScore().toString(); return new ScoredSolutionCandidateInfo(solutionCandidateRepresentation, score); } return null; } private String getStringRepresentationOfSolutionCandidate(final Object solutionCandidate) { if (this.solutionCandidateRepresenter == null) { return solutionCandidate.toString(); } return this.solutionCandidateRepresenter.getStringRepresentationOfSolutionCandidate(solutionCandidate); } @Override public String getPropertyName() { return SCORED_SOLUTION_CANDIDATE_INFO_PROPERTY_NAME; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/SolutionCandidateRepresenter.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; public interface SolutionCandidateRepresenter { public String getStringRepresentationOfSolutionCandidate(Object solutionCandidate); }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/SolutionPerformanceTimelinePlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; public class SolutionPerformanceTimelinePlugin extends ASimpleMVCPlugin<SolutionPerformanceTimelinePluginModel, SolutionPerformanceTimelinePluginView, SolutionPerformanceTimelinePluginController> { private final SolutionCandidateRepresenter solutionRepresenter; public SolutionPerformanceTimelinePlugin(final SolutionCandidateRepresenter solutionRepresenter) { this("Solution Performance Timeline", solutionRepresenter); } public SolutionPerformanceTimelinePlugin(final String title, final SolutionCandidateRepresenter solutionRepresenter) { super(title); this.solutionRepresenter = solutionRepresenter; } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(new ScoredSolutionCandidateInfoAlgorithmEventPropertyComputer(this.solutionRepresenter)); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/SolutionPerformanceTimelinePluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; import org.api4.java.algorithm.events.result.IScoredSolutionCandidateFoundEvent; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; public class SolutionPerformanceTimelinePluginController extends ASimpleMVCPluginController<SolutionPerformanceTimelinePluginModel, SolutionPerformanceTimelinePluginView> { public SolutionPerformanceTimelinePluginController(final SolutionPerformanceTimelinePluginModel model, final SolutionPerformanceTimelinePluginView view) { super(model, view); } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent || guiEvent instanceof GoToTimeStepEvent) { this.getModel().clear(); } } @Override public void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) { if (algorithmEvent.correspondsToEventOfClass(IScoredSolutionCandidateFoundEvent.class)) { this.logger.debug("Received solution event {}", algorithmEvent); Object rawScoredSolutionCandidateInfo = algorithmEvent.getProperty(ScoredSolutionCandidateInfoAlgorithmEventPropertyComputer.SCORED_SOLUTION_CANDIDATE_INFO_PROPERTY_NAME); if (rawScoredSolutionCandidateInfo != null) { ScoredSolutionCandidateInfo scoredSolutionCandidateInfo = (ScoredSolutionCandidateInfo) rawScoredSolutionCandidateInfo; try { this.logger.debug("Adding solution to model and updating view."); this.getModel().addEntry(algorithmEvent.getTimestampOfEvent(), this.parseScoreToDouble(scoredSolutionCandidateInfo.getScore())); this.logger.debug("Added solution to model."); } catch (NumberFormatException exception) { this.logger.warn("Received processed SolutionCandidateFoundEvent, but the score {} cannot be parsed to a double.", scoredSolutionCandidateInfo.getScore()); } } } } private double parseScoreToDouble(final String score) { return Double.parseDouble(score); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/SolutionPerformanceTimelinePluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.util.Pair; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; public class SolutionPerformanceTimelinePluginModel extends ASimpleMVCPluginModel<SolutionPerformanceTimelinePluginView, SolutionPerformanceTimelinePluginController> { private final List<Pair<Integer, Double>> timedPerformances = new ArrayList<>(); private long timestampOfFirstEvent = -1; public final void addEntry(final long timestampOfEvent, final double score) { int offset = 0; if (this.timestampOfFirstEvent == -1) { this.timestampOfFirstEvent = timestampOfEvent; } else { offset = (int) (timestampOfEvent - this.timestampOfFirstEvent); } this.timedPerformances.add(new Pair<>(offset, score)); this.getView().update(); } public long getTimestampOfFirstEvent() { return this.timestampOfFirstEvent; } public List<Pair<Integer, Double>> getTimedPerformances() { return this.timedPerformances; } @Override public void clear() { this.timedPerformances.clear(); this.timestampOfFirstEvent = -1; this.getView().clear(); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/solutionperformanceplotter/SolutionPerformanceTimelinePluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.solutionperformanceplotter; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.util.Pair; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import javafx.application.Platform; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart.Data; import javafx.scene.chart.XYChart.Series; /** * * @author fmohr * */ public class SolutionPerformanceTimelinePluginView extends ASimpleMVCPluginView<SolutionPerformanceTimelinePluginModel, SolutionPerformanceTimelinePluginController, LineChart<Number, Number>> { private Series<Number, Number> performanceSeries; private int nextIndexToDisplay = 0; public SolutionPerformanceTimelinePluginView(final SolutionPerformanceTimelinePluginModel model) { super(model, new LineChart<>(new NumberAxis(), new NumberAxis())); // defining the axes this.getNode().getXAxis().setLabel("Elapsed time (s)"); // creating the chart this.getNode().setAnimated(false); // defining a series this.performanceSeries = new Series<>(); this.getNode().getData().add(this.performanceSeries); } @Override public void update() { /* compute data to add */ List<Pair<Integer, Double>> events = this.getModel().getTimedPerformances(); List<Data<Number, Number>> values = new ArrayList<>(); for (; this.nextIndexToDisplay < events.size(); this.nextIndexToDisplay++) { Pair<Integer, Double> entry = events.get(this.nextIndexToDisplay); values.add(new Data<>(entry.getKey() / 1000.0, entry.getValue())); } this.logger.info("Adding {} values to chart.", values.size()); Platform.runLater(() -> this.performanceSeries.getData().addAll(values)); } @Override public void clear() { this.nextIndexToDisplay = 0; this.performanceSeries.getData().clear(); // remove the series completely due to a bug in rendering the line chart. This is a workaround. this.getNode().getData().remove(0); this.performanceSeries = new Series<>(); this.getNode().getData().add(this.performanceSeries); } public int getNextIndexToDisplay() { return this.nextIndexToDisplay; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/speedslider/ChangeSpeedEvent.java
package ai.libs.jaicore.graphvisualizer.plugin.speedslider; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; public class ChangeSpeedEvent implements GUIEvent { private int newSpeedPercentage; public ChangeSpeedEvent(int newSpeedPercentage) { this.newSpeedPercentage = newSpeedPercentage; } public int getNewSpeedPercentage() { return newSpeedPercentage; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/speedslider/SpeedSliderGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.speedslider; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; public class SpeedSliderGUIPlugin extends ASimpleMVCPlugin<SpeedSliderGUIPluginModel, SpeedSliderGUIPluginView, SpeedSliderGUIPluginController> { public SpeedSliderGUIPlugin() { super("Speed Slider"); } @Override public void stop() { /* nothing to do here */ } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(); // no properties required } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/speedslider/SpeedSliderGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.speedslider; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; public class SpeedSliderGUIPluginController extends ASimpleMVCPluginController<SpeedSliderGUIPluginModel, SpeedSliderGUIPluginView> { public SpeedSliderGUIPluginController(final SpeedSliderGUIPluginModel model, final SpeedSliderGUIPluginView view) { super (model, view); } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ChangeSpeedEvent) { ChangeSpeedEvent changeSpeedEvent = (ChangeSpeedEvent) guiEvent; this.getModel().setCurrentSpeedPercentage(changeSpeedEvent.getNewSpeedPercentage()); } } @Override protected void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { /* no need to handle any algorithm events */ } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/speedslider/SpeedSliderGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.speedslider; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; public class SpeedSliderGUIPluginModel extends ASimpleMVCPluginModel<SpeedSliderGUIPluginView, SpeedSliderGUIPluginController> { private int currentSpeedPercentage; public SpeedSliderGUIPluginModel() { this.currentSpeedPercentage = 95; } public int getCurrentSpeedPercentage() { return this.currentSpeedPercentage; } public void setCurrentSpeedPercentage(final int currentSpeedPercentage) { this.currentSpeedPercentage = currentSpeedPercentage; this.getView().update(); } @Override public void clear() { /* nothing to do */ } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/speedslider/SpeedSliderGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.speedslider; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import javafx.application.Platform; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.VBox; public class SpeedSliderGUIPluginView extends ASimpleMVCPluginView<SpeedSliderGUIPluginModel, SpeedSliderGUIPluginController, VBox> { private Slider visualizationSpeedSlider; public SpeedSliderGUIPluginView(final SpeedSliderGUIPluginModel model) { super(model, new VBox()); Platform.runLater(() -> { VBox visualizationSpeedSliderLayout = this.getNode(); visualizationSpeedSliderLayout.setAlignment(Pos.CENTER); this.visualizationSpeedSlider = new Slider(0, 100, this.getModel().getCurrentSpeedPercentage()); this.visualizationSpeedSlider.setShowTickLabels(true); this.visualizationSpeedSlider.setShowTickMarks(true); this.visualizationSpeedSlider.setMajorTickUnit(5); this.visualizationSpeedSlider.setMinorTickCount(4); this.visualizationSpeedSlider.setBlockIncrement(1); this.visualizationSpeedSlider.setSnapToTicks(true); this.visualizationSpeedSlider.setOnMouseReleased(event -> this.handleInputEvent()); this.visualizationSpeedSlider.setOnKeyPressed(event -> this.handleInputEvent()); visualizationSpeedSliderLayout.getChildren().add(this.visualizationSpeedSlider); Label visualizationSpeedSliderLabel = new Label("Visualization Speed (%)"); visualizationSpeedSliderLayout.getChildren().add(visualizationSpeedSliderLabel); }); } private void handleInputEvent() { ChangeSpeedEvent changeSpeedEvent = new ChangeSpeedEvent((int) this.visualizationSpeedSlider.getValue()); DefaultGUIEventBus.getInstance().postEvent(changeSpeedEvent); } @Override public void update() { this.visualizationSpeedSlider.setValue(this.getModel().getCurrentSpeedPercentage()); } @Override public void clear() { /* nothing to do */ } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/timeslider/GoToTimeStepEvent.java
package ai.libs.jaicore.graphvisualizer.plugin.timeslider; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; public class GoToTimeStepEvent implements GUIEvent { private int newTimeStep; public GoToTimeStepEvent(int newTimeStep) { this.newTimeStep = newTimeStep; } public int getNewTimeStep() { return newTimeStep; } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/timeslider/TimeSliderGUIPlugin.java
package ai.libs.jaicore.graphvisualizer.plugin.timeslider; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; public class TimeSliderGUIPlugin extends ASimpleMVCPlugin<TimeSliderGUIPluginModel, TimeSliderGUIPluginView, TimeSliderGUIPluginController> { public TimeSliderGUIPlugin() { this("Time Slider"); } public TimeSliderGUIPlugin(final String title) { super(title); } @Override public void stop() { this.getController().interrupt(); } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(); } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/timeslider/TimeSliderGUIPluginController.java
package ai.libs.jaicore.graphvisualizer.plugin.timeslider; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.PauseEvent; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.PlayEvent; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; public class TimeSliderGUIPluginController extends ASimpleMVCPluginController<TimeSliderGUIPluginModel, TimeSliderGUIPluginView> { private int amountOfEventsToIgnore; public TimeSliderGUIPluginController(final TimeSliderGUIPluginModel model, final TimeSliderGUIPluginView view) { super (model, view); this.amountOfEventsToIgnore = 0; } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent) { this.getModel().reset(); } else if (guiEvent instanceof PauseEvent) { this.getModel().pause(); } else if (guiEvent instanceof PlayEvent) { this.getModel().unpause(); } else if (guiEvent instanceof GoToTimeStepEvent) { int newTimeStep = ((GoToTimeStepEvent) guiEvent).getNewTimeStep(); this.amountOfEventsToIgnore = newTimeStep; this.getModel().setCurrentTimeStep(newTimeStep); } } @Override protected void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException { if (this.amountOfEventsToIgnore <= 0) { this.getModel().increaseCurrentTimeStep(); this.getModel().increaseMaximumTimeStep(); } else { this.amountOfEventsToIgnore--; } } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/timeslider/TimeSliderGUIPluginModel.java
package ai.libs.jaicore.graphvisualizer.plugin.timeslider; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; public class TimeSliderGUIPluginModel extends ASimpleMVCPluginModel<TimeSliderGUIPluginView, TimeSliderGUIPluginController> { private int currentTimeStep; private int maximumTimeStep; private boolean paused; public TimeSliderGUIPluginModel() { this.currentTimeStep = 0; this.maximumTimeStep = 0; this.paused = true; } public void increaseMaximumTimeStep() { this.maximumTimeStep++; this.getView().update(); } public void reset() { this.currentTimeStep = 0; this.maximumTimeStep = 0; this.getView().update(); } public int getCurrentTimeStep() { return this.currentTimeStep; } public int getMaximumTimeStep() { return this.maximumTimeStep; } public void pause() { this.paused = true; this.getView().update(); } public void unpause() { this.paused = false; this.getView().update(); } public void increaseCurrentTimeStep() { this.currentTimeStep++; this.getView().update(); } public void setCurrentTimeStep(final int currentTimeStep) { this.currentTimeStep = currentTimeStep; this.getView().update(); } public boolean isPaused() { return this.paused; } @Override public void clear() { /* do nothing */ } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/plugin/timeslider/TimeSliderGUIPluginView.java
package ai.libs.jaicore.graphvisualizer.plugin.timeslider; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import javafx.application.Platform; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.VBox; public class TimeSliderGUIPluginView extends ASimpleMVCPluginView<TimeSliderGUIPluginModel, TimeSliderGUIPluginController, VBox> { private static final String BASE_TEXT = "Timestep"; private Slider timestepSlider; private Label timestepSliderLabel; public TimeSliderGUIPluginView(final TimeSliderGUIPluginModel model) { super(model, new VBox()); Platform.runLater(() -> { VBox timestepSliderLayout = this.getNode(); timestepSliderLayout.setAlignment(Pos.CENTER); this.timestepSlider = new Slider(0, 1, 0); this.timestepSlider.setShowTickLabels(true); this.timestepSlider.setShowTickMarks(true); this.timestepSlider.setMajorTickUnit(10); this.timestepSlider.setMinorTickCount(9); this.timestepSlider.setBlockIncrement(1); this.timestepSlider.setSnapToTicks(true); this.timestepSlider.setOnMouseReleased(event -> this.handleInputEvent()); this.timestepSlider.setOnKeyPressed(event -> this.handleInputEvent()); timestepSliderLayout.getChildren().add(this.timestepSlider); this.timestepSliderLabel = new Label(BASE_TEXT + ": " + 0 + "/" + model.getMaximumTimeStep()); timestepSliderLayout.getChildren().add(this.timestepSliderLabel); Label spacer = new Label(" "); timestepSliderLayout.getChildren().add(spacer); }); } public synchronized void handleInputEvent() { DefaultGUIEventBus.getInstance().postEvent(new GoToTimeStepEvent((int) this.timestepSlider.getValue())); } @Override public void update() { TimeSliderGUIPluginModel model = this.getModel(); this.timestepSlider.setMax(model.getMaximumTimeStep()); this.timestepSlider.setValue(model.getCurrentTimeStep()); int amountOfStepsBetweenMajorTicks = Math.max(10, model.getMaximumTimeStep() / 20); this.timestepSlider.setMajorTickUnit(amountOfStepsBetweenMajorTicks); this.timestepSlider.setMinorTickCount(amountOfStepsBetweenMajorTicks - 1); if (model.isPaused() && this.timestepSlider.isDisabled()) { this.timestepSlider.setDisable(false); } else if (!model.isPaused() && !this.timestepSlider.isDisabled()) { this.timestepSlider.setDisable(true); } Platform.runLater(() -> this.timestepSliderLabel.setText(BASE_TEXT + ": " + model.getCurrentTimeStep() + "/" + model.getMaximumTimeStep())); } @Override public void clear() { /* nothing to do */ } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/view/DescriptiveStatisticsTimelineView.java
package ai.libs.jaicore.graphvisualizer.view; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javafx.application.Platform; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; /** * * @author fmohr * */ public class DescriptiveStatisticsTimelineView extends LineChart<Number, Number> { private Logger logger = LoggerFactory.getLogger(DescriptiveStatisticsTimelineView.class); private final DescriptiveStatistics stats = new DescriptiveStatistics(); private final ObservableList<Double> scores; private final Series<Number, Number> performanceSeries; public DescriptiveStatisticsTimelineView(final ObservableList<Double> scores) { super(new NumberAxis(), new NumberAxis()); // defining the axes this.getXAxis().setLabel("elapsed time (s)"); // defining a series this.scores = scores; this.performanceSeries = new Series<>(); this.getData().add(this.performanceSeries); this.update(); scores.addListener(new ListChangeListener<Double>() { @Override public void onChanged(final Change<? extends Double> c) { DescriptiveStatisticsTimelineView.this.update(); } }); } public void clear() { this.performanceSeries.getData().clear(); this.scores.clear(); } public void update() { if (this.scores.isEmpty()) { this.performanceSeries.getData().clear(); } else { int m = this.scores.size(); int n = this.performanceSeries.getData().size(); List<Data<Number, Number>> values = new ArrayList<>(); for (int i = n; i < m; i++) { this.stats.addValue(this.scores.get(i)); values.add(new Data<>((i + 1), this.stats.getMean())); } this.logger.info("Adding {} values to chart.", values.size()); Platform.runLater(() -> this.performanceSeries.getData().addAll(values)); } } }
0
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer
java-sources/ai/libs/jaicore-algorithminspector/0.2.7/ai/libs/jaicore/graphvisualizer/window/AlgorithmVisualizationWindow.java
package ai.libs.jaicore.graphvisualizer.window; import java.util.ArrayList; import java.util.List; import org.api4.java.algorithm.IAlgorithm; import org.api4.java.algorithm.events.IAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.events.recorder.AlgorithmEventHistory; import ai.libs.jaicore.graphvisualizer.events.recorder.AlgorithmEventHistoryEntryDeliverer; import ai.libs.jaicore.graphvisualizer.events.recorder.AlgorithmEventHistoryRecorder; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyProcessedAlgorithmEventSource; import ai.libs.jaicore.graphvisualizer.plugin.IComputedGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.IGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ControlBarGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.speedslider.SpeedSliderGUIPlugin; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.TimeSliderGUIPlugin; import javafx.application.Platform; import javafx.embed.swing.JFXPanel; import javafx.scene.Scene; import javafx.scene.control.SplitPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; /** * An {@link AlgorithmVisualizationWindow} can be created to have a visualization of the behavior of an algorithm. We generally differentiate between a live version of an {@link IAlgorithm} run for which an instance of that algorithm and a * list of {@link AlgorithmEventPropertyComputer}s is required and an offline run, for which only an {@link AlgorithmEventHistory} is required. In the first case, the property computers are used to extract relevant information which is * required by the {@link IGUIPlugin}s (to be displayed) from the underlying {@link IAlgorithmEvent}s which are provided by the actual algorithm. When playing a recording, these computers are not required as the data was already computed as * is stored as part of the replay in the {@link AlgorithmEventHistory}. Furthermore it requires a main {@link IGUIPlugin} which will * be displayed as the main element and optionally an unbounded amount of additional {@link IGUIPlugin} which will be displayed in order to provide additional information. * * @author atornede * */ public class AlgorithmVisualizationWindow implements Runnable { private PropertyProcessedAlgorithmEventSource algorithmEventSource; private final AlgorithmEventHistoryRecorder historyRecorder; private AlgorithmEventHistoryEntryDeliverer algorithmEventHistoryPuller; private AlgorithmEventHistory algorithmEventHistory; private final List<IGUIPlugin> visualizationPlugins = new ArrayList<>(); private IGUIPlugin mainPlugin; private TimeSliderGUIPlugin timeSliderGUIPlugin; private ControlBarGUIPlugin controlBarGUIPlugin; private SpeedSliderGUIPlugin speedSliderGUIPlugin; private String title = "MLPlan Graph Search Visualization"; private Stage stage; private BorderPane rootLayout; private BorderPane topLayout; private TabPane pluginTabPane; private AlgorithmVisualizationWindow() { this.historyRecorder = new AlgorithmEventHistoryRecorder(); this.setup(this.historyRecorder.getHistory()); } public AlgorithmVisualizationWindow(final AlgorithmEventHistory history) { this.historyRecorder = null; this.setup(history); } private void setup(final AlgorithmEventHistory algorithmEventHistory) { new JFXPanel(); // dummy to initialize JavaFX if this has not happened before /* define event sources */ this.algorithmEventHistory = algorithmEventHistory; this.algorithmEventHistoryPuller = new AlgorithmEventHistoryEntryDeliverer(algorithmEventHistory); this.algorithmEventSource = this.algorithmEventHistoryPuller; /* initialize controls and launch the window */ this.initializeControls(); DefaultGUIEventBus.getInstance().registerAlgorithmEventHistoryEntryDeliverer(this.algorithmEventHistoryPuller); Platform.runLater(this); } /** * Creates a new {@link AlgorithmVisualizationWindow} based on the given {@link AlgorithmEventHistory} (i.e. offline version), the main {@link IGUIPlugin} and optionally additional plugins. * * @param algorithmEventHistory The {@link AlgorithmEventHistory} providing data to be displayed. * @param mainPlugin The main {@link IGUIPlugin} which will be displayed as the main information source. * @param visualizationPlugins A list of additional {@link IGUIPlugin}s displaying side information. */ public AlgorithmVisualizationWindow(final AlgorithmEventHistory algorithmEventHistory, final IGUIPlugin mainPlugin, final IGUIPlugin... visualizationPlugins) { this(algorithmEventHistory); this.withMainPlugin(mainPlugin); this.withPlugin(visualizationPlugins); } /** * Creates a new {@link AlgorithmVisualizationWindow} based on the given {@link IAlgorithm}, the list of {@link AlgorithmEventPropertyComputer}s, a main {@link IGUIPlugin} and optionally additional plugins. This constructor should be * used when using a visualization in an online run. * * @param algorithm The {@link IAlgorithm} yielding information to be displayed. * @param algorithmEventPropertyComputers The {@link AlgorithmEventPropertyComputer}s computing all information from the {@link IAlgorithmEvent}s provided by the {@link IAlgorithm} which are required by the {@link IGUIPlugin}s which are * registered. * @param mainPlugin The main {@link IGUIPlugin} which will be displayed as the main information source. * @param visualizationPlugins A list of additional {@link IGUIPlugin}s displaying side information. */ public AlgorithmVisualizationWindow(final IAlgorithm<?, ?> algorithm) { this(); algorithm.registerListener(this.historyRecorder); } public AlgorithmVisualizationWindow withMainPlugin(final IGUIPlugin plugin) { /* first register property computers if we record the history */ if (this.historyRecorder != null && plugin instanceof IComputedGUIPlugin) { this.historyRecorder.addPropertyComputer(((IComputedGUIPlugin) plugin).getPropertyComputers()); } /* now register the plugin itself */ this.mainPlugin = plugin; this.mainPlugin.setAlgorithmEventSource(this.algorithmEventSource); this.mainPlugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); Platform.runLater(() -> ((SplitPane) this.rootLayout.getCenter()).getItems().add(this.mainPlugin.getView().getNode())); return this; } public AlgorithmVisualizationWindow withPlugin(final IGUIPlugin... pluginArray) { for (IGUIPlugin plugin : pluginArray) { /* first register property computers if we record the history */ if (this.historyRecorder != null && plugin instanceof IComputedGUIPlugin) { this.historyRecorder.addPropertyComputer(((IComputedGUIPlugin) plugin).getPropertyComputers()); } /* now register and start the plugin itself */ this.visualizationPlugins.add(plugin); plugin.setAlgorithmEventSource(this.algorithmEventSource); plugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); this.addPluginToTabList(plugin); } return this; } private void initializeControls() { this.timeSliderGUIPlugin = new TimeSliderGUIPlugin(); this.timeSliderGUIPlugin.setAlgorithmEventSource(this.algorithmEventSource); this.timeSliderGUIPlugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); this.controlBarGUIPlugin = new ControlBarGUIPlugin(); this.controlBarGUIPlugin.setAlgorithmEventSource(this.algorithmEventSource); this.controlBarGUIPlugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); this.speedSliderGUIPlugin = new SpeedSliderGUIPlugin(); this.speedSliderGUIPlugin.setAlgorithmEventSource(this.algorithmEventSource); this.speedSliderGUIPlugin.setGUIEventSource(DefaultGUIEventBus.getInstance()); } @Override public void run() { this.rootLayout = new BorderPane(); this.initializeTopLayout(); this.initializeCenterLayout(); this.initializeBottomLayout(); this.initializePluginTabs(); Scene scene = new Scene(this.rootLayout, 800, 300); this.stage = new Stage(); this.stage.setScene(scene); this.stage.setTitle(this.title); this.stage.setMaximized(true); this.stage.show(); this.stage.setOnCloseRequest(e -> { this.mainPlugin.stop(); this.visualizationPlugins.forEach(IGUIPlugin::stop); this.algorithmEventHistoryPuller.interrupt(); Platform.runLater(Platform::exit); }); this.algorithmEventHistoryPuller.start(); } private void initializeTopLayout() { this.topLayout = new BorderPane(); this.initializeTopButtonToolBar(); this.initializeVisualizationSpeedSlider(); this.rootLayout.setTop(this.topLayout); } private void initializeTopButtonToolBar() { this.topLayout.setTop(this.controlBarGUIPlugin.getView().getNode()); } private void initializeVisualizationSpeedSlider() { this.topLayout.setBottom(this.speedSliderGUIPlugin.getView().getNode()); } private void initializeCenterLayout() { SplitPane centerSplitLayout = new SplitPane(); centerSplitLayout.setDividerPosition(0, 0.25); this.pluginTabPane = new TabPane(); centerSplitLayout.getItems().add(this.pluginTabPane); this.rootLayout.setCenter(centerSplitLayout); } private void initializeBottomLayout() { this.rootLayout.setBottom(this.timeSliderGUIPlugin.getView().getNode()); } private void initializePluginTabs() { for (IGUIPlugin plugin : this.visualizationPlugins) { this.addPluginToTabList(plugin); } } private void addPluginToTabList(final IGUIPlugin plugin) { Tab pluginTab = new Tab(plugin.getTitle(), plugin.getView().getNode()); Platform.runLater(() -> this.pluginTabPane.getTabs().add(pluginTab)); } /** * Sets the title of this window to the given {@link String}. * * @param title The new title of this window. */ public void setTitle(final String title) { this.title = title; this.stage.setTitle(title); } /** * Returns the underlying {@link AlgorithmEventHistory}. * * @return The underlying {@link AlgorithmEventHistory}. */ public AlgorithmEventHistory getAlgorithmEventHistory() { return this.algorithmEventHistory; } }
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/AEntitySelector.java
package ai.libs.jaicore.basic; import java.util.Collection; import java.util.HashSet; import java.util.Set; public abstract class AEntitySelector<T> { protected final Set<T> init; protected final Set<T> current; protected AEntitySelector(final Collection<T> items) { this.init = new HashSet<>(items); this.current = new HashSet<>(items); } public Set<T> get() { return new HashSet<>(this.current); } public Set<T> getInverted() { Set<T> inverted = new HashSet<>(); this.init.forEach(i -> { if (!this.current.contains(i)) { inverted.add(i); } }); return inverted; } public AEntitySelector<T> invert() { Set<T> tmp = new HashSet<>(this.current); this.current.clear(); this.init.forEach(i -> { if (!tmp.contains(i)) { this.current.add(i); } }); return this; } }
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/ArrayUtil.java
package ai.libs.jaicore.basic; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class ArrayUtil { private ArrayUtil() { // Prevent instantiation of this util class. } private static void columnSanityCheck(final int arrayLength, final Collection<Integer> columnIndices) { if (columnIndices.stream().anyMatch(x -> x >= arrayLength || x < 0)) { throw new IllegalArgumentException("Cannot exclude non existing columns (" + columnIndices + "), array length: " + arrayLength); } } /** * Copies an array of type <T> without copying the columns in columnsToExclude. * * @param <T> The data type of objects contained in the array. * @param array The array to copy excluding the given columns. * @param columnsToExclude The columns to exclude when copying. * @param clazz The class object for the type T. * @return The copy of the original array without the excluded values. */ public static <T> T[] copyArrayExlcuding(final T[] array, final Collection<Integer> columnsToExclude) { columnSanityCheck(array.length, columnsToExclude); T[] arrayCopy = Arrays.copyOf(array, array.length - columnsToExclude.size()); int pointer = 0; for (int i = 0; i < array.length; i++) { if (columnsToExclude.contains(i)) { continue; } arrayCopy[pointer++] = array[i]; } return arrayCopy; } /** * Copies an array of type <T> retaining the columns in columnsToRetain. * * @param <T> The data type of objects contained in the array. * @param array The array to copy retaining the given columns. * @param columnsToExclude The columns to retain when copying. * @param clazz The class object for the type T. * @return The copy of the original array retaining the given column values only. */ public static <T> T[] copyArrayRetaining(final T[] array, final Collection<Integer> columnsToRetain) { columnSanityCheck(array.length, columnsToRetain); T[] arrayCopy = Arrays.copyOf(array, columnsToRetain.size()); int pointer = 0; for (int i = 0; i < array.length; i++) { if (!columnsToRetain.contains(i)) { continue; } arrayCopy[pointer++] = array[i]; } return arrayCopy; } /** * Transposes a matrix A and returns A^T. * @param matrix The given matrix A. * @return The transposed matrix A^T originating from A. */ public static double[][] transposeDoubleMatrix(final double[][] matrix) { double[][] transposed = new double[matrix[0].length][matrix.length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { transposed[j][i] = matrix[i][j]; } } return transposed; } public static int[][] transposeIntegerMatrix(final int[][] matrix) { int[][] transposed = new int[matrix[0].length][matrix.length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { transposed[j][i] = matrix[i][j]; } } return transposed; } private static String cleanArrayString(final String arrayString) { String cleanArrayString = arrayString.trim(); if (cleanArrayString.startsWith("[") && cleanArrayString.endsWith("]")) { cleanArrayString = cleanArrayString.substring(1, cleanArrayString.length() - 1); } return cleanArrayString; } public static double[] parseStringToDoubleArray(final String arrayString) { return Arrays.stream(cleanArrayString(arrayString).split(",")).mapToDouble(Double::parseDouble).toArray(); } public static int[] parseStringToIntArray(final String arrayString) { return Arrays.stream(cleanArrayString(arrayString).split(",")).mapToInt(Integer::parseInt).toArray(); } public static String[] parseStringToStringArray(final String arrayString) { return (String[]) Arrays.stream(cleanArrayString(arrayString).split(",")).toArray(); } public static List<Integer> argMax(final double[] array) { int argMax = argMaxFirst(array); return IntStream.range(0, array.length).filter(x -> array[x] == array[argMax]).mapToObj(Integer::valueOf).collect(Collectors.toList()); } public static List<Integer> argMax(final int[] array) { int argMax = argMaxFirst(array); return IntStream.range(0, array.length).filter(x -> array[x] == array[argMax]).mapToObj(Integer::valueOf).collect(Collectors.toList()); } public static int argMaxFirst(final int[] array) { Integer argMax = null; for (int i = 0; i < array.length; i++) { if (argMax == null || array[i] > array[argMax]) { argMax = i; } } return argMax; } public static int argMaxFirst(final double[] array) { Integer argMax = null; for (int i = 0; i < array.length; i++) { if (argMax == null || array[i] > array[argMax]) { argMax = i; } } return argMax; } public static List<Integer> argMin(final int[] array) { int argMin = argMinFirst(array); return IntStream.range(0, array.length).filter(x -> array[x] == array[argMin]).mapToObj(Integer::valueOf).collect(Collectors.toList()); } public static int argMinFirst(final int[] array) { Integer argMin = null; for (int i = 0; i < array.length; i++) { if (argMin == null || array[i] < array[argMin]) { argMin = i; } } return argMin; } /** * Transposes a double matrix A and returns A^T. * @param matrix The given double matrix A. * @return The transposed double matrix A^T originating from A. */ public static double[][] transposeMatrix(final double[][] matrix) { double[][] transposed = new double[matrix[0].length][matrix.length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { transposed[j][i] = matrix[i][j]; } } return transposed; } /** * Transposes an int matrix A and returns A^T. * @param matrix The given int matrix A. * @return The transposed int matrix A^T originating from A. */ public static int[][] transposeMatrix(final int[][] matrix) { int[][] transposed = new int[matrix[0].length][matrix.length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { transposed[j][i] = matrix[i][j]; } } return transposed; } /** * Transposes a generic matrix A and returns A^T. * @param matrix The given generic matrix A with entries of type <T>. * @return The transposed generic matrix A^T originating from A. * <T> The type of objects contained in the matrix. */ public static <T> T[][] transposeMatrix(final T[][] matrix) { @SuppressWarnings("unchecked") T[][] transposed = (T[][]) Array.newInstance(matrix.getClass(), matrix[0].length, matrix.length); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { transposed[j][i] = matrix[i][j]; } } return transposed; } public static int[] thresholdDoubleToBinaryArray(final double[] array, final double threshold) { return Arrays.stream(array).mapToInt(x -> x >= threshold ? 1 : 0).toArray(); } public static int[][] thresholdDoubleToBinaryMatrix(final double[][] matrix, final double threshold) { return thresholdDoubleToBinaryMatrix(matrix, IntStream.range(0, matrix[0].length).mapToDouble(x -> threshold).toArray()); } public static int[][] thresholdDoubleToBinaryMatrix(final double[][] matrix, final double[] threshold) { int[][] thresholdedMatrix = new int[matrix[0].length][]; IntStream.range(0, matrix[0].length).forEach(l -> thresholdedMatrix[l] = ArrayUtil.thresholdDoubleToBinaryArray(ArrayUtil.extractColumn(matrix, l), threshold[l])); return ArrayUtil.transposeMatrix(thresholdedMatrix); } public static double[] extractColumn(final double[][] matrix, final int columnIndex) { double[] column = new double[matrix.length]; IntStream.range(0, matrix.length).forEach(x -> column[x] = matrix[x][columnIndex]); return column; } public static int[] extractColumn(final int[][] matrix, final int columnIndex) { int[] column = new int[matrix.length]; IntStream.range(0, matrix.length).forEach(x -> column[x] = matrix[x][columnIndex]); return column; } public static void add(final double[] sum, final double[] summand) { if (sum.length != summand.length) { throw new IllegalArgumentException("The array must be of the same length."); } IntStream.range(0, sum.length).forEach(x -> sum[x] += summand[x]); } public static <T> T[] mergeArrays(final T[] array0, final T[] array1) { @SuppressWarnings("unchecked") T[] merged = (T[]) Array.newInstance(array0.getClass(), array0.length + array1.length); System.arraycopy(array0, 0, merged, 0, array0.length); System.arraycopy(array1, 0, merged, array0.length, array1.length); return merged; } }
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/Combinatorics.java
package ai.libs.jaicore.basic; public class Combinatorics { private Combinatorics() { // prevent instantiation of this util class } /** * Returns a complete truth table for n variables. Meaning, a matrix of all possible true false combinations of n variables is generated. * * @param n The number of variables for the truth table. * @return The truth table for the specified n variables. */ public static boolean[][] getTruthTable(final int n) { int rowCount = (int) Math.pow(2, n); boolean[][] table = new boolean[rowCount][n]; for (int i = 0; i < rowCount; i++) { for (int j = n - 1; j >= 0; j--) { table[i][j] = (i / (int) Math.pow(2, j)) % 2 == 1; } } return table; } }
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/FileIsDirectoryException.java
package ai.libs.jaicore.basic; import java.io.IOException; /** * This exception may be thrown if a File object points to a directory * instead of a file. * * @author mwever */ public class FileIsDirectoryException extends IOException { /** * Automatically generated version UID for serialization. */ private static final long serialVersionUID = 5313365636204532994L; /** * Standard c'tor. */ public FileIsDirectoryException() { super(); } /** * Constructor with a message. * @param message The message. */ public FileIsDirectoryException(final String message) { super(message); } /** * Constructor with message and a throwable as a cause. * @param message The message. * @param cause The cause of this exception. */ public FileIsDirectoryException(final String message, final Throwable cause) { super(message, 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/FileUtil.java
package ai.libs.jaicore.basic; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Util class for handling file I/O. * * @author fmohr, mwever * */ public class FileUtil { /* Logging. */ private static final Logger logger = LoggerFactory.getLogger(FileUtil.class); private FileUtil() { /* Intentionally left blank to prevent instantiation of this class. */ } /** * Reads the content of the given file as a list of strings. * * @param file The file to be read. * @return The list of strings representing the content of the file. * @throws IOException Thrown, if there are issues reading the file. */ public static List<String> readFileAsList(final File file) throws IOException { if (file instanceof ResourceFile) { return ResourceUtil.readResourceFileToStringList((ResourceFile) file); } else { return readFileAsList(file.getAbsolutePath()); } } /** * Reads the content of the given file as a list of strings. * * @param filename The path to the file to be read. * @return The list of strings representing the content of the file. * @throws IOException Thrown, if there are issues reading the file. */ public static List<String> readFileAsList(final String filename) throws IOException { try (BufferedReader r = Files.newBufferedReader(Paths.get(filename), StandardCharsets.UTF_8)) { String line; final List<String> lines = new LinkedList<>(); while ((line = r.readLine()) != null) { lines.add(line); } return lines; } } /** * Reads the content of the given file into a single string. * * @param file The file to be read. * @return The String representing the content of the file. * @throws IOException Thrown, if there are issues reading the file. */ public static String readFileAsString(final File file) throws IOException { return readFileAsString(file.getAbsolutePath()); } /** * Reads the content of the given file into a single string. * * @param filename The path to the file to be read. * @return The String representing the content of the file. * @throws IOException Thrown, if there are issues reading the file. */ public static String readFileAsString(final String filename) throws IOException { final StringBuilder sb = new StringBuilder(); try (BufferedReader r = Files.newBufferedReader(Paths.get(filename), StandardCharsets.UTF_8)) { String line; while ((line = r.readLine()) != null) { sb.append(line).append("\n"); } } return sb.toString(); } /** * Reads the content of the given file as a matrix of string which are separated by the given separation string. * * @param filename The path to the file to be read. * @param separation The string separating the matrix entries of a row. * @return The matrix of strings. * @throws IOException Thrown, if there are issues reading the file. */ public static List<List<String>> readFileAsMatrix(final String filename, final String separation) throws IOException { final List<String> content = readFileAsList(filename); final List<List<String>> matrix = new ArrayList<>(content.size()); for (final String line : content) { final String[] lineAsArray = line.split(separation); final List<String> lineAsList = new ArrayList<>(lineAsArray.length); for (final String field : lineAsArray) { lineAsList.add(field.trim()); } matrix.add(lineAsList); } return matrix; } /** * Reads the given file into a Properties object. * * @param propertiesFile The file to be read. * @return The properties object loaded from the specified file. * @throws IOException Thrown, if there are issues reading the file. */ public static Properties readPropertiesFile(final File propertiesFile) throws IOException { Properties props = new Properties(); try (FileInputStream fis = new FileInputStream(propertiesFile)) { props.load(fis); } return props; } /** * Archives a collection of files specified by their paths into a zip-file. * * @param files The files to be archived in a zip file. * @param archive The path to output the zipped files. * @throws IOException Thrown, if an issue occurs while creating zip entries or writing the zip file to disk. */ public static void zipFiles(final Collection<String> files, final String archive) throws IOException { try (final FileOutputStream fos = new FileOutputStream(archive); final ZipOutputStream zos = new ZipOutputStream(fos)) { final int total = files.size(); int i = 0; for (final String fileName : files) { final File file = new File(fileName); try (final FileInputStream fis = new FileInputStream(file)) { final ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry); final byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } zos.closeEntry(); } i++; logger.debug("{} / {} ready.", i, total); } } } /** * This method helps to serialize class objects as files. * * @param object The object to be serialized. * @param pathname The path where to store the serialized object. * @throws IOException Thrown if the object cannot be serialized or the serialized object cannot be written to disk. */ public static synchronized void serializeObject(final Object object, final String pathname) throws IOException { File file = new File(pathname); if (file.getParentFile() != null && !file.getParentFile().exists()) { file.getParentFile().mkdirs(); } try (ObjectOutputStream os2 = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file.getAbsolutePath())))) { os2.writeObject(object); } catch (NotSerializableException e) { Files.delete(file.toPath()); throw e; } } /** * This method can be used to unserialize an object from disk (located at the specified path) and restore the original object. * * @param pathname The path from where to unserialize the object. * @return The unserialized object. * @throws IOException Thrown, if the binary file cannot be read. * @throws ClassNotFoundException Thrown, if the class of the object which is unserialized cannot be found on the classpath. */ public static Object unserializeObject(final String pathname) throws IOException, ClassNotFoundException { try (ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(pathname)))) { return is.readObject(); } } /** * Creates an empty file for the given path if it does not already exist. * * @param filename The path of the file. */ public static void touch(final String filename) { try (FileWriter fw = new FileWriter(filename)) { fw.write(""); } catch (IOException e) { logger.error("Could not create file {}.", filename, e); } } /** * This operation moves a file "from" to a destination "to". * @param from The original file. * @param to The destination of the file. * @return Returns true, iff the move operation was successful. */ public static boolean move(final File from, final File to) { return from.renameTo(to); } /** * Moves the path "from" to a destination path "to". * @param from The original path. * @param to The destination path where to move the original path to. * @return Returns true, iff the move operation was successful. */ public static boolean move(final String from, final String to) { return move(new File(from), new File(to)); } /** * Returns a list of files contained in the specified folder. * @param folder The folder for which the list of files shall be returned. * @return A list of files contained in the given folder. */ public static List<File> getFilesOfFolder(final File folder) { List<File> files = new ArrayList<>(); for (File file : folder.listFiles()) { if (!file.isDirectory()) { files.add(file); } } return files; } /** * Checks whetehr a given file exists and if so, whether it is actually a file and not a directory. * @param file The file to be checked. * @throws FileIsDirectoryException Is thrown if the file exists but is a directory. * @throws FileNotFoundException Is thrown if there exists no such file. */ public static void requireFileExists(final File file) throws FileIsDirectoryException, FileNotFoundException { Objects.requireNonNull(file); if (file.getAbsolutePath().trim().isEmpty()) { throw new IllegalArgumentException("The given file objects encodes an empty path."); } if (file instanceof ResourceFile) { return; } if (!file.exists()) { throw new FileNotFoundException("File " + file.getAbsolutePath() + " does not exist"); } if (!file.isFile()) { throw new FileIsDirectoryException("The file " + file.getAbsolutePath() + " is not a file but a directory."); } } /** * Returns the file for a given path with the highest priority which also exists; the resource path is the backup solution with lowest priority. * The getter iterates over the fileSytemPaths array and returns the first existing file, i.e. paths with a lower array index have higher priority. * If there is no element in the array or none of the given paths exists as a file, the file corresponding to the resource path will be returned as * a fall-back, i.e., the resource path has the lowest priority. * * @param resourcePath The resource path that is to be taken as a fall-back. * @param fileSystemPaths An array of paths with descending priority. * @return The existing file with highest priority. */ public static File getExistingFileWithHighestPriority(final String resourcePath, final String... fileSystemPaths) { if (fileSystemPaths.length > 0) { for (String fileSystemConfig : fileSystemPaths) { File configFile = new File(fileSystemConfig); if (configFile.exists()) { return configFile; } } } Objects.requireNonNull(resourcePath, "The file was not found on any of the given paths in the file system, and no resource has been specified."); return ResourceUtil.getResourceAsFile(resourcePath); } /** * Helper method to delete non-empty folders, i.e., recursively deleting all contained files and sub-folders. * * @param dir The folder to be deleted. * @throws IOException Thrown, if there an issue arises while deleting all the files and sub-folders. */ public static void deleteFolderRecursively(final File dir) throws IOException { if (dir.isDirectory()) { final String[] children = dir.list(); for (int i = 0; i < children.length; i++) { deleteFolderRecursively(new File(dir, children[i])); } } Files.delete(dir.toPath());// The directory is empty now and can be deleted. } /** * Writes List of strings as lines to given file * @param lines * @param filename * @throws IOException */ public static void writeFileAsList(final List<String> lines, final String filename) throws IOException { try (FileWriter writer = new FileWriter(filename)) { for (String line : lines) { writer.write(line + System.lineSeparator()); } } } }
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/IAnnotatable.java
package ai.libs.jaicore.basic; public interface IAnnotatable { /** * Add an annotation to this component instance. * @param key The key of how to address this annotation. * @param annotation The annotation value. */ public void putAnnotation(final String key, final String annotation); /** * Appends an annotation to a potentially previously annotated string. * @param key The key for which to append the annotation. * @param annotation The annotation value. */ public void appendAnnotation(final String key, final String annotation); /** * Retrieve an annotation by its key. * @param key The key for which to retrieve the annotation. * @return The annotation value. */ public String getAnnotation(final String key); }
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/IOwnerBasedAlgorithmConfig.java
package ai.libs.jaicore.basic; import java.util.concurrent.TimeUnit; import org.aeonbits.owner.Reloadable; import org.api4.java.algorithm.IAlgorithmConfig; import org.api4.java.algorithm.Timeout; /** * Configuration interface to defined the access properties for a database connection * * @author fmohr * */ public interface IOwnerBasedAlgorithmConfig extends IOwnerBasedConfig, IAlgorithmConfig, Reloadable { public static final String K_CPUS = "cpus"; public static final String K_THREADS = "threads"; public static final String K_MEMORY = "memory"; public static final String K_TIMEOUT = "timeout"; /** * @return Number of CPU cores available for parallelization. */ @Override @Key(K_CPUS) @DefaultValue("1") public int cpus(); /** * @return Number of threads that may be spawned by the algorithm. If set to -1, the number of CPUs is used as the number of threads. If set to 0, parallelization is deactivated. */ @Override @Key(K_THREADS) @DefaultValue("-1") public int threads(); /** * @return The main memory that is available to be used. This is merely a documentation variable since the true memory must be set over the JVM initialization anyway and cannot be restricted inside of it. */ @Override @Key(K_MEMORY) @DefaultValue("256") public int memory(); /** * @return Overall timeout for the algorithm in milliseconds. */ @Override @Key(K_TIMEOUT) @DefaultValue("-1") public long timeout(); /** * This is just a shortcut to avoid confusions about the semantics of the defined timeout, which is always defined in milliseconds. * * @return The correct Timeout object for the specified timeout. */ public default Timeout getTimeout() { return new Timeout(this.timeout(), TimeUnit.MILLISECONDS); } }
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/IOwnerBasedConfig.java
package ai.libs.jaicore.basic; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.aeonbits.owner.Accessible; import org.aeonbits.owner.ConfigFactory; import org.aeonbits.owner.Mutable; import org.api4.java.common.control.IConfig; public interface IOwnerBasedConfig extends Mutable, Accessible, IConfig { /** * Reads properties of a config from a config file. * @param file The file to read in as properties. * @throws IOException Throws an IOException if an issue occurs while reading in the properties from the given file. */ @Override default IOwnerBasedConfig loadPropertiesFromFile(final File file) { return this.loadPropertiesFromFileArray(file); } default IOwnerBasedConfig loadPropertiesFromFileArray(final File... files) { try { List<String> configLines = new ArrayList<>(); for (File f : files) { configLines.addAll(FileUtil.readFileAsList(f)); } return this.loadPropertiesFromList(configLines); } catch (IOException e) { throw new PropertiesLoadFailedException("Could not load properties from the given file.", e); } } /** * Loads properties from a resource (instead of a file). * @param resourcePath The path to the resource. * @throws IOException Throws an IOException if an issue occurs while reading in the properties from the given resource. */ @Override default IOwnerBasedConfig loadPropertiesFromResource(final String resourcePath) throws IOException { // Get file from resources folder ClassLoader classLoader = FileUtil.class.getClassLoader(); String content = null; try (InputStream inputStream = classLoader.getResourceAsStream(resourcePath)) { ByteArrayOutputStream result = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { result.write(buffer, 0, length); } content = result.toString(StandardCharsets.UTF_8.name()); } if (content != null) { return this.loadPropertiesFromList(Arrays.asList(content.split("\n"))); } return this; } /** * Loads a properties config from a list of property assignments. * * @param propertiesList The list of property assignments. */ @Override default IOwnerBasedConfig loadPropertiesFromList(final List<String> propertiesList) { for (String line : propertiesList) { line = line.trim(); if (!line.contains("=") || line.startsWith("#")) { continue; } String[] split = line.split("="); if (split.length > 2) { throw new IllegalArgumentException("Property line " + line + " contains more than one \"=\" symbol and cannot be parsed."); } this.setProperty(split[0].trim(), split.length > 1 ? split[1].trim() : null); } return this; } default <T extends IOwnerBasedAlgorithmConfig> T copy(final Class<T> configInterface) { if (!configInterface.isInstance(this)) { throw new IllegalArgumentException("The config " + this + " does not implement the interface " + configInterface.getClass().getName()); } T clone = ConfigFactory.create(configInterface); for (String property : this.propertyNames()) { clone.setProperty(property, this.getProperty(property)); } return clone; } }
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/IOwnerBasedRandomConfig.java
package ai.libs.jaicore.basic; import org.api4.java.algorithm.IRandomAlgorithmConfig; /** * Random configurations can be used to provide a random seed. * Random can occur in both an underlying problem instance, an algorithm used to tackle the problem, or both * * @author fmohr * */ public interface IOwnerBasedRandomConfig extends IRandomAlgorithmConfig { public static final String K_SEED = "seed"; @Override public long seed(); }
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/IOwnerBasedRandomizedAlgorithmConfig.java
package ai.libs.jaicore.basic; import org.api4.java.algorithm.IRandomAlgorithmConfig; public interface IOwnerBasedRandomizedAlgorithmConfig extends IOwnerBasedAlgorithmConfig, IRandomAlgorithmConfig { public static final String K_SEED = "seed"; @Override public long seed(); }
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/IRandomizable.java
package ai.libs.jaicore.basic; import java.util.Random; public interface IRandomizable { public Random getRandom(); public void setRandom(Random random); }
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/LoadResourceAsFileFailedException.java
package ai.libs.jaicore.basic; public class LoadResourceAsFileFailedException extends RuntimeException { public LoadResourceAsFileFailedException(final String msg) { super(msg); } public LoadResourceAsFileFailedException(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/MappingIterator.java
package ai.libs.jaicore.basic; import java.util.Iterator; import java.util.function.Function; /** * Turns an iterator over elements of type A into an iterator of elements of type B * * @author Felix Mohr * * @param <A> * @param <B> */ public class MappingIterator<A, B> implements Iterator<B> { private final Iterator<A> iterator; private final Function<A, B> map; public MappingIterator(final Iterator<A> iterator, final Function<A, B> map) { super(); this.iterator = iterator; this.map = map; } @Override public boolean hasNext() { return this.iterator.hasNext(); } @Override public B next() { return this.map.apply(this.iterator.next()); } }
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/Maps.java
package ai.libs.jaicore.basic; import java.util.Map; public class Maps { /** * Forbid to create an object of ListHelper as there are only static methods allowed here. */ private Maps() { // intentionally do nothing } public static <K> void increaseCounterInMap(final Map<K, Integer> counterMap, final K key) { if (counterMap.containsKey(key)) { counterMap.put(key, counterMap.get(key) + 1); } else { counterMap.put(key, 1); } } public static <K> void increaseCounterInMap(final Map<K, Integer> counterMap, final K key, final int summand) { if (counterMap.containsKey(key)) { counterMap.put(key, counterMap.get(key) + summand); } else { counterMap.put(key, summand); } } public static <K> void increaseCounterInDoubleMap(final Map<K, Double> counterMap, final K key) { if (counterMap.containsKey(key)) { counterMap.put(key, counterMap.get(key) + 1.0); } else { counterMap.put(key, 1.0); } } public static <K> void increaseCounterInDoubleMap(final Map<K, Double> counterMap, final K key, final double summand) { if (counterMap.containsKey(key)) { counterMap.put(key, counterMap.get(key) + summand); } else { counterMap.put(key, summand); } } }
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/MathExt.java
package ai.libs.jaicore.basic; import java.util.HashSet; import java.util.Set; /** * A util class for some simple mathematical helpers. * * @author fmohr, mwever */ public class MathExt { private MathExt() { // prevent instantiation of this util class } /** * Computes the binomial of n choose k. * @param n The size of the whole set. * @param k The size of the chosen subset. * @return The number of all possible combinations of how to choose k elements from a set of n elements. */ public static long binomial(final int n, int k) { if (k > n - k) { k = n - k; } long b = 1; for (int i = 1, m = n; i <= k; i++, m--) { b = b * m / i; } return b; } /** * Gets a list of all integers for a certain range "from" to "to" (both inclusively). * * @param from The lower bound (included). * @param to The upper bound (included). * @return The set of all integers of the specified range. */ public static Set<Integer> getIntegersFromTo(final int from, final int to) { Set<Integer> set = new HashSet<>(); for (int i = from; i <= to; i++) { set.add(i); } return set; } /** * Computes the double factorial of k, i.e. k!!. * * @param k The k for which to compute the double factorial for. * @return The double factorial for the specified number k. */ public static int doubleFactorial(final int k) { if (k <= 0) { return 1; } return k * doubleFactorial(k - 2); } /** * Rounds a double value to a certain number of decimal places. * @param d The value to be rounded. * @param precision The number of decimal places. * @return The rounded value. */ public static double round(final double d, final int precision) { return (Math.round(d * Math.pow(10, precision)) / Math.pow(10, precision)); } /** * Takes the logarithm with respect to some given base. * @param v The value to take the logarithm of. * @param base The base of the logarithm. */ public static double logBase(final double v, final double base) { return Math.log(v) / Math.log(base); } }
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/OptionsParser.java
package ai.libs.jaicore.basic; import ai.libs.jaicore.basic.kvstore.KVStore; public class OptionsParser extends KVStore { private static final String OPTION_PREFIX_1 = "-"; private static final String OPTION_PREFIX_2 = "--"; /** * */ private static final long serialVersionUID = 2868523552636687194L; public OptionsParser(final String optionsString) { String[] optionsSplit = optionsString.trim().split(" "); for (int i = 0; i < optionsSplit.length; i++) { String currentKey = optionsSplit[i].trim(); String nextValue = null; if (i < optionsSplit.length - 1) { nextValue = optionsSplit[i + 1].trim(); } if (this.isOptionKey(currentKey)) { if (this.isOptionKey(nextValue)) { this.put(this.stripOptionKey(currentKey), "true"); } else { this.put(this.stripOptionKey(currentKey), nextValue); } } } } private boolean isOptionKey(final String string) { if (string == null) { return false; } return (string.startsWith(OPTION_PREFIX_1) || string.startsWith(OPTION_PREFIX_2)); } private String stripOptionKey(final String optionKey) { if (optionKey.startsWith(OPTION_PREFIX_2)) { return optionKey.substring(OPTION_PREFIX_2.length()); } else if (optionKey.startsWith(OPTION_PREFIX_1)) { return optionKey.substring(OPTION_PREFIX_1.length()); } return optionKey; } }
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/PropertiesLoadFailedException.java
package ai.libs.jaicore.basic; /** * Exception can be thrown if properties could not be loaded properly. * * @author mwever */ public class PropertiesLoadFailedException extends RuntimeException { public PropertiesLoadFailedException(final String message, final Throwable cause) { super(message, cause); } /** * Automatically generated version UID for serialization. */ private static final long serialVersionUID = 1433423547742787695L; }
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/ResourceFile.java
package ai.libs.jaicore.basic; import java.io.File; import java.io.InputStream; import java.util.LinkedList; import java.util.List; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import ai.libs.jaicore.basic.sets.SetUtil; /** * ResourceFile may be used to encapsulate files to be loaded from resources, i.e. from the build directory or from inside of a jar. * * @author mwever */ public class ResourceFile extends File { /** * */ private static final long serialVersionUID = -404232145050366072L; /* The path to the resource */ private final String pathName; /** * C'tor for instantiating a resource file. * @param pathname The path to the resource */ public ResourceFile(final String pathname) { super(pathname); this.pathName = pathname; } /** * C'tor for instantiating a resource file relative to another resource file. * @param baseFile The base file to which the relative path is to be considered. * @param pathname The relative path to the resource with respect to the base file. */ public ResourceFile(final ResourceFile baseFile, final String pathname) { super(getPathName(baseFile, pathname)); this.pathName = getPathName(baseFile, pathname); } private static String getPathName(final ResourceFile baseFile, final String pathName) { List<String> pathConstruct = new LinkedList<>(); List<String> concatPaths = new LinkedList<>(); concatPaths.addAll(SetUtil.explode(baseFile.getPathName(), "/")); concatPaths.addAll(SetUtil.explode(pathName, "/")); for (String pathElement : concatPaths) { if (pathElement.equals(".")) { // do nothing } else if (pathElement.equals("..")) { if (pathConstruct.isEmpty()) { throw new IllegalArgumentException("Cannot construct path from " + baseFile.getPathName() + " and " + pathName); } else { pathConstruct.remove(pathConstruct.size() - 1); } } else { pathConstruct.add(pathElement); } } return SetUtil.implode(pathConstruct, "/"); } /** * Getter for an input stream to read this resource file. * @return The input stream to read the contents of this resource file. */ public InputStream getInputStream() { return this.getClass().getClassLoader().getResourceAsStream(this.pathName); } /** * Getter for the resource's path. * @return The path of the resource file. */ public final String getPathName() { return this.pathName; } @Override public final String getPath() { return this.getPathName(); } @Override public final ResourceFile getParentFile() { List<String> stringList = SetUtil.explode(this.pathName, "/"); if (!stringList.isEmpty()) { stringList.remove(stringList.size() - 1); return new ResourceFile(SetUtil.implode(stringList, "/")); } else { return null; } } @Override public boolean exists() { return true; } @Override public boolean equals(final Object obj) { if (!(obj instanceof ResourceFile)) { return false; } ResourceFile other = (ResourceFile) obj; return new EqualsBuilder().append(this.pathName, other.pathName).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder().append(this.pathName).toHashCode(); } }
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/ResourceUtil.java
package ai.libs.jaicore.basic; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.LinkedList; import java.util.List; import ai.libs.jaicore.basic.sets.SetUtil; /** * Utils for handling resource access in a more convenient way. * * @author mwever */ public class ResourceUtil { private ResourceUtil() { /* Intentionally left blank; simply prevent this util class to be instantiated. */ } /** * Reads the contents of a resource to a string. * * @param path The path of the resource that shall be read. * @return The contents of the resource parsed to a string. * @throws IOException Throws an IOException if the file could not be read. */ public static String readResourceFileToString(final String path) throws IOException { return SetUtil.implode(readResourceFileToStringList(path), "\n"); } /** * Reads the contents of a resource to a list of strings. * * @param path The path of the resource that shall be read. * @return The contents of the resource parsed to a string. * @throws IOException Throws an IOException if the file could not be read. */ public static List<String> readResourceFileToStringList(final String path) throws IOException { List<String> list = new LinkedList<>(); InputStream resourceStream = ResourceUtil.class.getClassLoader().getResourceAsStream(path); if (resourceStream == null) { throw new FileNotFoundException("Could not find resource file '" + path + "'"); } try (BufferedReader br = new BufferedReader(new InputStreamReader(ResourceUtil.class.getClassLoader().getResourceAsStream(path)))) { String line; while ((line = br.readLine()) != null) { list.add(line); } } return list; } /** * Reads the contents of a resource to a list of strings. * * @param resourceFile The resource file to read. * @return The contents of the resource parsed to a string. * @throws IOException Throws an IOException if the file could not be read. */ public static List<String> readResourceFileToStringList(final ResourceFile resourceFile) throws IOException { return readResourceFileToStringList(resourceFile.getPathName()); } /** * Returns the file corresponding to the given path. * * @param path The path for which a resource shall be retrieved. * @return The resource file corresponding to the given path. * @throws IOException */ public static ResourceFile getResourceAsFile(final String path) { return new ResourceFile(path); } /** * Returns the file corresponding to the given path. * * @param path The path for which a resource shall be retrieved. * @return The resource file corresponding to the given path. * @throws IOException */ public static URL getResourceAsURL(final String path) { return ResourceUtil.class.getClassLoader().getResource(path); } /** * Creates a temporary file from the resource to load. * @param resourcePath The path to the resource. * @return The canonical path to the temporary file reflecting the contents of the resource. */ public static String getResourceAsTempFile(final String resourcePath) { try { File tempFile = File.createTempFile("ai.libs-", ".res"); tempFile.deleteOnExit(); try (BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile))) { bw.write(ResourceUtil.readResourceFileToString(resourcePath)); } return tempFile.getCanonicalPath(); } catch (IOException e) { throw new LoadResourceAsFileFailedException("Could not load resource as a temporary file", e); } } }
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/RobustnessUtil.java
package ai.libs.jaicore.basic; import java.util.Collection; public class RobustnessUtil { private RobustnessUtil() { // intentionally left blank. } public static void sameSizeOrDie(final Collection<?> collectionA, final Collection<?> collectionB) { if (collectionA.size() != collectionB.size()) { throw new IllegalArgumentException("The collections must be of the same size"); } } public static void sameLengthOrDie(final String stringA, final String stringB) { if (stringA.length() != stringB.length()) { throw new IllegalArgumentException("The two strings must be of the same length"); } } public static void sameLengthOrDie(final double[] arrayA, final double[] arrayB) { arraysOfSameLength(arrayA.length != arrayB.length); } public static void sameLengthOrDie(final int[] arrayA, final int[] arrayB) { arraysOfSameLength(arrayA.length != arrayB.length); } public static void sameLengthOrDie(final boolean[] arrayA, final boolean[] arrayB) { arraysOfSameLength(arrayA.length != arrayB.length); } public static void sameLengthOrDie(final Object[] arrayA, final Object[] arrayB) { arraysOfSameLength(arrayA.length != arrayB.length); } private static void arraysOfSameLength(final boolean sameLength) { if (sameLength) { throw new IllegalArgumentException("The two arrays must be of the same length"); } } }
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/StatisticsUtil.java
package ai.libs.jaicore.basic; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.math3.stat.inference.MannWhitneyUTest; import org.apache.commons.math3.stat.inference.TTest; import org.apache.commons.math3.stat.inference.WilcoxonSignedRankTest; /** * Utils for computing some statistics from collections of doubles or arrays. * * @author mwever */ public class StatisticsUtil { /** * Forbid to create an object of ListHelper as there are only static methods allowed here. */ private StatisticsUtil() { // intentionally do nothing } /** * Filters the maximum value of the given collection. * * @param values Values to take the maximum from. * @return The maximum value of the provided collection. */ public static double max(final Collection<? extends Number> values) { if (values.isEmpty()) { return Double.NaN; } return values.stream().mapToDouble(Number::doubleValue).max().getAsDouble(); } /** * Filters the minimum value of the given collection. * * @param values Values to take the minimum from. * @return The minimum value of the provided collection. */ public static double min(final Collection<? extends Number> values) { if (values.isEmpty()) { return Double.NaN; } return values.stream().mapToDouble(Number::doubleValue).min().getAsDouble(); } /** * Computes the mean of the given collection. * * @param values Values to take the mean of. * @return The mean of the provided values. */ public static double mean(final Collection<? extends Number> values) { if (values.isEmpty()) { return Double.NaN; } return values.stream().mapToDouble(Number::doubleValue).average().getAsDouble(); } /** * Computes the median of the given collection. * * @param values Values to take the mean of. * @return The mean of the provided values. */ public static double median(final Collection<? extends Number> values) { if (values.isEmpty()) { return Double.NaN; } List<? extends Number> list = new ArrayList<>(values); list.sort((o1, o2) -> Double.compare(o1.doubleValue(), o2.doubleValue())); if (list.size() > 1) { int upperIndex = (int) Math.ceil(((double) values.size() + 1) / 2) - 1; int lowerIndex = (int) Math.floor(((double) values.size() + 1) / 2) - 1; return (list.get(lowerIndex).doubleValue() + list.get(upperIndex).doubleValue()) / 2; } else { return list.get(0).doubleValue(); } } /** * Computes the sum of the given collection. * * @param values Values to take the sum of. * @return The sum of the provided values. */ public static double sum(final Collection<? extends Number> values) { return values.stream().mapToDouble(Number::doubleValue).sum(); } /** * Computes the variance of the given collection. * * @param values Values to compute the variance for. * @return The variance of the provided values. */ public static double variance(final Collection<? extends Number> values) { if (values.isEmpty()) { return 0.0; } final double mean = mean(values); return values.stream().mapToDouble(Number::doubleValue).map(x -> Math.pow(x - mean, 2) / values.size()).sum(); } /** * Computes the standard deviation of the given collection. * * @param values Values to compute the standard deviation for. * @return The standard deviation of the provided values. */ public static double standardDeviation(final Collection<? extends Number> values) { if (values.isEmpty()) { return 0.0; } return Math.sqrt(variance(values)); } /** * Computes the p-value according to the Wilcoxon signed rank test for related samples A and B. * * @param sampleA The first sample. * @param sampleB The second sample. * @return The p-value of the test for the given two samples. */ public static double wilcoxonSignedRankSumTestP(final double[] sampleA, final double[] sampleB) { return new WilcoxonSignedRankTest().wilcoxonSignedRankTest(sampleA, sampleB, false); } /** * Uses the Wilcoxon Signed Rank test to determine whether the difference of the distributions of the the two given samples is significantly different (two-sided test). * * @param sampleA The first sample. * @param sampleB The second sample. * @return True iff the difference is significant (p-value &lt; 0.05) */ public static boolean wilcoxonSignedRankSumTestTwoSided(final double[] sampleA, final double[] sampleB) { return wilcoxonSignedRankSumTestP(sampleA, sampleB) < 0.05; } /** * Uses the Wilcoxon Signed Rank test to carry out a single-sided significance test. * * @param sampleA The first sample. * @param sampleB The second sample. * @return True iff the difference is significant (p-value &lt; 0.01) */ public static boolean wilcoxonSignedRankSumTestSingleSided(final double[] sampleA, final double[] sampleB) { return wilcoxonSignedRankSumTestP(sampleA, sampleB) < 0.01; } /** * Computes the p-value according to the MannWhitneyU test for iid. samples A and B. * * @param sampleA The first sample. * @param sampleB The second sample. * @return The p-value of the test for the given two samples. */ public static double mannWhitneyTwoSidedSignificanceP(final double[] sampleA, final double[] sampleB) { return new MannWhitneyUTest().mannWhitneyUTest(sampleA, sampleB); } /** * Uses the MannWhitneyU test to determine whether the distributions of the the two given samples is significantly different (two-sided test). * * @param sampleA The first sample. * @param sampleB The second sample. * @return True iff the difference is significant (p-value &lt; 0.05) */ public static boolean mannWhitneyTwoSidedSignificance(final double[] sampleA, final double[] sampleB) { return mannWhitneyTwoSidedSignificanceP(sampleA, sampleB) < 0.05; } /** * Uses the MannWhitneyU test to determine whether the distributions of the the two given samples is significantly different (two-sided test). * * @param sampleA The first sample. * @param sampleB The second sample. * @return True iff the difference is significant (p-value &lt; 0.05) */ public static boolean mannWhitneyTwoSidedSignificance(final Collection<Double> sampleA, final Collection<Double> sampleB) { return mannWhitneyTwoSidedSignificance(collectionToArray(sampleA), collectionToArray(sampleB)); } /** * Uses the MannWhitneyU test to carry out a single-sided significance test. * * @param sampleA The first sample. * @param sampleB The second sample. * @return True iff the difference is significant (p-value &lt; 0.01) */ public static boolean mannWhitneyOneSidedSignificance(final double[] sampleA, final double[] sampleB) { return mannWhitneyTwoSidedSignificanceP(sampleA, sampleB) < 0.01; } /** * Carries out a two sample ttest to determine whether the distributions of the two given samples are significantly different. Requires the distributions to be a normal distribution respectively. * * @param valuesA The first sample.. * @param valuesB The second sample. * @return True iff the difference is significant (p-value &lt; 0.05) */ public static boolean twoSampleTTestSignificance(final Collection<Double> valuesA, final Collection<Double> valuesB) { return twoSampleTTestSignificance(collectionToArray(valuesA), collectionToArray(valuesB)); } /** * Carries out a two sample ttest to determine whether the distributions of the two given samples are significantly different. Requires the distributions to be a normal distribution respectively. * * @param valuesA The first sample.. * @param valuesB The second sample. * @return True iff the difference is significant (p-value &lt; 0.05) */ public static boolean twoSampleTTestSignificance(final double[] valuesA, final double[] valuesB) { return new TTest().tTest(valuesA, valuesB, 0.05); } /** * * @param valuesA The first sample.. * @param valuesB The second sample. * @return True iff the difference is significant (p-value &lt; 0.05) */ /** * Carries out a two sample ttest when the sampled values have already been aggregated to mean, variance, and n, to determine whether the distributions of the two given samples are significantly different. Requires the distributions to be a normal distribution respectively. * * @param mean1 The mean of the first sample. * @param variance1 The variance of the first sample. * @param n1 The sample size of the first sample. * @param mean2 The mean of the second sample. * @param variance2 The variance of the second sample. * @param n2 The sample size of the second sample. * @return True iff the difference is significant (p-value &lt; 0.05) */ public static boolean twoSampleTTestSignificance(final double mean1, final double variance1, final double n1, final double mean2, final double variance2, final double n2) { double meanDifference = mean1 - mean2; double sP = Math.sqrt(((n1 - 1) * variance1 + (n2 - 1) * variance2) / (n1 + n2 - 2)); double t = meanDifference / (sP * Math.sqrt(1 / n1 + 1 / n2)); return t < 0.05; } /* Helper method to transform double collections into arrays. */ private static double[] collectionToArray(final Collection<Double> collection) { return collection.stream().mapToDouble(x -> x).toArray(); } }
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/StringUtil.java
package ai.libs.jaicore.basic; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.stream.IntStream; /** * This class provides handy utility functions when dealing with Strings. * * @author fmohr, mwever * */ public class StringUtil { private StringUtil() { // prevent instantiation of this util class. } /** * Getter for all available common characters of the system. Digits can be included if desired. * * @param includeDigits Flag whether to include digits in the array of the system's common characters. * @return An array of the system's common characters. */ public static char[] getCommonChars(final boolean includeDigits) { /* create char array */ List<Character> chars = new LinkedList<>(); for (int i = 65; i <= 90; i++) { chars.add((char) i); } for (int i = 97; i <= 122; i++) { chars.add((char) i); } if (includeDigits) { for (int i = 48; i <= 57; i++) { chars.add((char) i); } } char[] charsAsArray = new char[chars.size()]; for (int i = 0; i < charsAsArray.length; i++) { charsAsArray[i] = chars.get(i); } return charsAsArray; } /** * Returns a random string of a desired length and from a given set of characters. * * @param length The length of the resulting random string. * @param chars The set of characters to be used to generate a random string. * @return The generated random string. */ public static String getRandomString(final int length, final char[] chars, final long seed) { StringBuilder s = new StringBuilder(); Random rand = new Random(seed); for (int i = 0; i < length; i++) { s.append(chars[rand.nextInt(chars.length)]); } return s.toString(); } /** * Concatenates the string representations of an array of objects using ", " as a separator. * @param array The array of objects of which the string representation is to be concatenated. * @return The concatenated string of the given objects' string representation. */ public static String implode(final Object[] array) { return implode(array, ", "); } /** * Concatenates the string representations of a set of objects using ", " as a separator. * @param set The set of objects of which the string representation is to be concatenated. * @return The concatenated string of the given objects' string representation. */ public static String implode(final Set<Object> set) { return implode(set, ", "); } /** * Concatenates the string representations of a set of objects using the specified delimiter as a separator. * @param set The set of objects of which the string representation is to be concatenated. * @param delimter A string separating the respective string representations. * @return The concatenated string of the given objects' string representation. */ public static String implode(final Collection<?> set, final String delimiter) { if (set.isEmpty()) { return ""; } StringBuilder s = new StringBuilder(); for (Object elem : set) { s.append(delimiter + elem.toString()); } String result = s.toString(); return result.substring(delimiter.length(), result.length()); } /** * Concatenates the string representations of a collection of objects using ", " as a separator. * @param collection The set of objects of which the string representation is to be concatenated. * @return The concatenated string of the given objects' string representation. */ public static String implode(final Collection<Object> collection) { Object[] array = new Object[collection.size()]; collection.toArray(array); return implode(array); } /** * Concatenates the string representations of an array of objects using the specified delimiter as a separator. * @param array The array of objects of which the string representation is to be concatenated. * @param delimter A string separating the respective string representations. * @return The concatenated string of the given objects' string representation. */ public static String implode(final Object[] array, final String delimiter) { StringBuilder s = new StringBuilder(); if (array == null || array.length == 0) { return s.toString(); } for (int i = 0; i < array.length - 1; i++) { if (array[i] == null) { s.append("NULL" + delimiter); } else { s.append(array[i].toString() + delimiter); } } if (array[array.length - 1] == null) { s.append("NULL"); } else { s.append(array[array.length - 1].toString()); } return s.toString(); } /** * Splits a string using delimiter as a separator of elements into an array. * @param string The string to be split. * @param delimiter A string separating the sub-strings. * @return An array of sub-string which were formerly separeted by the specified delimiter. */ public static String[] explode(final String string, final String delimiter) { return string.split(delimiter); } /** * Merges two string arrays into one single array. * Note: This is a duplicate for apache-commons-lang: ArrayUtils.addAll(array1, array2); * * @param array1 The first array. * @param array2 The second array. * @return Concatenated array of Strings. */ public static String[] merge(final String[] array1, final String[] array2) { String[] output = new String[array1.length + array2.length]; for (int i = 0; i < output.length; i++) { output[i] = (i < array1.length ? array1[i] : array2[i - array1.length]); } return output; } public static String[] getArrayWithValues(final int size, final String value) { String[] array = new String[size]; for (int i = 0; i < size; i++) { array[i] = value.replace("%", "" + (i + 1)).replace("$", String.valueOf((char) (i + 97))); } return array; } /** * Strips a specific character from a string. * * @param str The string from which the character shall be stripped. * @param c The character to strip. * @return The stripped string where the specified character does not occur any longer. */ public static String stripChar(final String str, final char c) { int length = str.length(); StringBuilder s = new StringBuilder(); for (int i = 0; i < length; i++) { if (str.charAt(i) != c) { s.append(str.charAt(i)); } } return s.toString(); } /** * Removes the first entry of the value and returns an array containing all values but the first one. * * @param input The array of values to be shifted. * @return The resulting shifted array. */ public static String[] shiftFirst(final String[] input) { String[] output = new String[input.length - 1]; for (int i = 1; i < input.length; i++) { output[i - 1] = input[i]; } return output; } /** * Translates a binary representation of a string to the respective string. * @param binarySequence The binary encoding of the string. * @return The translated string. */ public static String fromBinary(String binarySequence) { StringBuilder sb = new StringBuilder(); // Some place to store the chars binarySequence = binarySequence.replace(" ", ""); Arrays.stream( // Create a Stream binarySequence.split("(?<=\\G.{8})") // Splits the input string into 8-char-sections (Since a char has 8 bits = 1 byte) ).forEach(s -> // Go through each 8-char-section... sb.append((char) Integer.parseInt(s, 2)) // ...and turn it into an int and then to a char ); return sb.toString(); // Output text (t) } /** * Limits the toString output of an object to a specified length. * * @param o The object for which a string limited string representation is to be obtained. * @param limit The maximum length of the toString output. * @return The resulting (potentially cut) string. */ public static String toStringLimited(final Object o, final int limit) { String str = o.toString(); if (str.length() <= limit) { return str; } return str.substring(0, limit - 4) + " ..."; } /** * Finds the first String starting with the given prefix in a collection of Strings. * @param collection The collection of Strings to search in. * @param prefix The prefix of the searched-for element. * @return The first element of the collection starting with the desired prefix. */ public static String firstElementWithPrefix(final Collection<String> collection, final String prefix) { Optional<String> resultOpt = collection.stream().filter(x -> x.startsWith(prefix)).findFirst(); if (resultOpt.isPresent()) { return resultOpt.get(); } else { throw new NoSuchElementException("Could not find an element with prefix " + prefix + " in the given collection."); } } /** * Returns a string consisting of the given number of spaces. * @param numSpaces The number of spaces to output. * @return The string of numSpaces many spaces. */ public static String spaces(final int numSpaces) { if (numSpaces == 0) { return ""; } else { return IntStream.range(0, numSpaces).mapToObj(x -> " ").reduce((a, b) -> a + b).get(); } } /** * Returns a string which is padded with spaces to obtain a string of length <code>length</code>. Spaces are prepended to the given string. * @param stringToPad The string to pad with spaces. * @param length The desired length of the padded string. * @return The given string padded with spaces prior to the provided string. */ public static String prepaddedString(final String stringToPad, final int length) { return spaces(length - stringToPad.length()).concat(stringToPad); } /** * Returns a string which is padded with spaces to obtain a string of length <code>length</code>. Spaces are appended to the given string. * @param stringToPad The string to pad with spaces. * @param length The desired length of the padded string. * @return The given string padded with spaces prior to the provided string. */ public static String postpaddedString(final String stringToPad, final int length) { return stringToPad.concat(spaces(length - stringToPad.length())); } }
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/SystemRequirementsNotMetException.java
package ai.libs.jaicore.basic; public class SystemRequirementsNotMetException extends RuntimeException { /** * Automatically generated version UID for serialization. */ private static final long serialVersionUID = -7591975042606762847L; public SystemRequirementsNotMetException(final String msg) { super(msg); } public SystemRequirementsNotMetException(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/TempFileHandler.java
package ai.libs.jaicore.basic; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utility Class for managing temporary files and corresponding readers/writers. * A directory for the temporary files can be given, otherwise a new one in the * Home Directory is created. * * @author Lukas Brandt * */ public class TempFileHandler implements Closeable { private static final String ERR_MSG_CANNOT_CLOSE_READER = "Cannot close reader"; private Logger logger = LoggerFactory.getLogger(TempFileHandler.class); // Directory where the temporary files will be saved private File tempFileDirectory; // Map of all temporary files identified with an UUID private Map<String, File> tempFiles; // Maps of the readers/writers for the corresponding files identified by UUID private Map<String, BufferedReader> tempFileReaders; private Map<String, FileWriter> tempFileWriters; public TempFileHandler(final File tempFileDirectory) { this.tempFileDirectory = tempFileDirectory; this.tempFiles = new HashMap<>(); this.tempFileReaders = new HashMap<>(); this.tempFileWriters = new HashMap<>(); if (!tempFileDirectory.exists()) { tempFileDirectory.mkdirs(); } } public TempFileHandler() { this(new File(System.getProperty("user.home") + "/.ailibs")); } /** * Create a new temporary file in the given directory. * * @return UUID associated with the new temporary file. */ public File createTempFile() { return this.createTempFile(UUID.randomUUID().toString()); } public File createTempFile(final String name) { String path = this.tempFileDirectory.getAbsolutePath() + File.separator + name; FileUtil.touch(path); File file = new File(path); file.deleteOnExit(); this.tempFiles.put(name, file); return file; } public boolean doesTempFileExist(final String name) { return new File(this.tempFileDirectory + File.separator + name).exists(); } /** * Get the temporary file with some name. * * @param name * name of the temporary file. * @return File object associated with the name. */ public File getTempFile(final String name) { if (!this.tempFiles.containsKey(name)) { if (!this.doesTempFileExist(name)) { throw new IllegalArgumentException("The temporary file " + name + " does not exist!"); } this.tempFiles.put(name, new File(this.tempFileDirectory.getAbsolutePath() + File.separator + name)); } return this.tempFiles.get(name); } /** * Create or retrieve an existing file reader for a temporary file by UUID. * * @param uuid * UUID of the temporary file. * @return An existing or new file reader for the given temporary file. * @throws FileNotFoundException */ public BufferedReader getFileReaderForTempFile(final String uuid) throws FileNotFoundException { if (this.tempFileReaders.containsKey(uuid)) { try { this.tempFileReaders.get(uuid).close(); } catch (IOException e) { this.logger.error(ERR_MSG_CANNOT_CLOSE_READER, e); } this.tempFileReaders.remove(uuid); } BufferedReader reader = new BufferedReader(new FileReader(this.tempFiles.get(uuid))); this.tempFileReaders.put(uuid, reader); return reader; } /** * Create or retrieve an existing file writer for a temporary file by UUID. * * @param uuid * UUID of the temporary file. * @return An existing or new file writer for the given temporary file. * @throws IOException */ public FileWriter getFileWriterForTempFile(final String uuid) throws IOException { if (this.tempFileWriters.containsKey(uuid)) { return this.tempFileWriters.get(uuid); } else { FileWriter writer = new FileWriter(this.tempFiles.get(uuid)); this.tempFileWriters.put(uuid, writer); return writer; } } /*** * Delete a temporary file by UUID and if created the corresponding * reader/writer. * * @param uuid * UUID of the file. */ public void deleteTempFile(final String uuid) { if (this.tempFileReaders.containsKey(uuid)) { try { this.tempFileReaders.get(uuid).close(); } catch (IOException e) { this.logger.error(ERR_MSG_CANNOT_CLOSE_READER, e); } this.tempFileReaders.remove(uuid); } if (this.tempFileWriters.containsKey(uuid)) { try { this.tempFileWriters.get(uuid).close(); } catch (IOException e) { this.logger.error(ERR_MSG_CANNOT_CLOSE_READER, e); } this.tempFileWriters.remove(uuid); } if (this.tempFiles.containsKey(uuid)) { try { Files.delete(this.tempFiles.get(uuid).toPath()); } catch (IOException e) { this.logger.error(String.format("Cannot delete file for UUID %s", uuid), e); } this.tempFiles.remove(uuid); } } /*** * Removes all temporary files and close all readers/writers. */ public void cleanUp() { Set<String> uuids = new HashSet<>(this.tempFiles.keySet()); for (String uuid : uuids) { this.deleteTempFile(uuid); } } @Override public void close() throws IOException { this.cleanUp(); } /** * Returns the absolute path of the temporary file directory. * * @return The absolute path of the temporary file directory. */ public String getTempFileDirPath() { return this.tempFileDirectory.getAbsolutePath(); } }