index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/DyadRankedBestFirstFactory.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst;
import ai.libs.jaicore.search.model.travesaltree.ReducedGraphGenerator;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
/**
* Factory for a best first search with a dyad ranked OPEN list.
*
* @author Helena Graf
*
* @param <N>
* @param <A>
* @param <V>
*/
public class DyadRankedBestFirstFactory<N, A, V extends Comparable<V>> extends StandardBestFirstFactory<N, A, V> {
/**
* the used config
*/
private IBestFirstQueueConfiguration<GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V> openConfig;
/**
* Construct a new factory that makes best first search objects using the given
* config.
*
* @param openConfig
* parameters for the OPEN list ranking
*/
public DyadRankedBestFirstFactory(
final IBestFirstQueueConfiguration<GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V> openConfig) {
this.openConfig = openConfig;
}
@Override
public BestFirst<GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V> getAlgorithm() {
// Replace graph generator in problem
this.setProblemInput(new GraphSearchWithSubpathEvaluationsInput<>(
new ReducedGraphGenerator<>(this.getInput().getGraphGenerator()), this.getInput().getGoalTester(), this.getInput().getPathEvaluator()));
// Configure and return best first
BestFirst<GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V> bestFirst = super.getAlgorithm();
this.openConfig.configureBestFirst(bestFirst);
return bestFirst;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/ENodeAnnotation.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst;
public enum ENodeAnnotation {
F_SCORE("f"), F_ERROR("fError"), F_MESSAGE("fMessage"), F_TIME("fTime"), F_UNCERTAINTY("fUncertainty");
private String name;
private ENodeAnnotation(final String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/IBestFirstConfig.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst;
import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.BestFirst.ParentDiscarding;
public interface IBestFirstConfig extends IOwnerBasedAlgorithmConfig {
public static final String K_PD = "bestfirst.parentdiscarding";
public static final String K_OE = "bestfirst.optimisticheuristic";
/**
* @return Whether or not parent discarding should be used
*/
@Key(K_PD)
@DefaultValue("NONE")
public ParentDiscarding parentDiscarding();
@Key(K_OE)
@DefaultValue("false")
public boolean optimisticHeuristic();
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/IBestFirstQueueConfiguration.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
/**
* @author Helena Graf
*
* Interface for configuring the queue of {@link BestFirst} (and
* possibly other parts as well).
*
* @param <I>
* @param <N>
* @param <A>
*/
public interface IBestFirstQueueConfiguration<I extends GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V extends Comparable<V>> {
public void configureBestFirst(BestFirst<I, N, A, V> bestFirst);
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/StandardBestFirst.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
public class StandardBestFirst<N, A, V extends Comparable<V>> extends BestFirst<GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V> {
public StandardBestFirst(final GraphSearchWithSubpathEvaluationsInput<N, A, V> problem) {
super(problem);
}
public StandardBestFirst(final IBestFirstConfig config, final GraphSearchWithSubpathEvaluationsInput<N, A, V> problem) {
super(config, problem);
}
public StandardBestFirst(final IBestFirstConfig config, final GraphSearchWithSubpathEvaluationsInput<N, A, V> problem, final IPathEvaluator<N, A, V> lowerBoundEvaluator) {
super(config, problem ,lowerBoundEvaluator);
}
public StandardBestFirst(final GraphSearchWithSubpathEvaluationsInput<N, A, V> problem, final IPathEvaluator<N, A, V> lowerBoundEvaluator) {
super(problem ,lowerBoundEvaluator);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/StandardBestFirstFactory.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst;
import java.util.Objects;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
public class StandardBestFirstFactory<N, A, V extends Comparable<V>> extends BestFirstFactory<GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V> implements ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(StandardBestFirstFactory.class);
public void setNodeEvaluator(final IPathEvaluator<N, A, V> nodeEvaluator) {
GraphSearchWithSubpathEvaluationsInput<N, A, V> problem = this.getInput();
IGraphGenerator<N, A> gg = problem != null ? problem.getGraphGenerator() : null;
IPathGoalTester<N, A> gt = problem != null ? problem.getGoalTester() : null;
this.setProblemInput(new GraphSearchWithSubpathEvaluationsInput<>(gg, gt, nodeEvaluator));
}
public void setGraphGenerator(final IGraphGenerator<N, A> graphGenerator) {
GraphSearchWithSubpathEvaluationsInput<N, A, V> problem = this.getInput();
Objects.requireNonNull(problem);
IPathGoalTester<N, A> gt = problem.getGoalTester();
IPathEvaluator<N, A, V> evaluator = problem.getPathEvaluator();
this.setProblemInput(new GraphSearchWithSubpathEvaluationsInput<>(graphGenerator, gt, evaluator));
}
@Override
public BestFirst<GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V> getAlgorithm() {
if (this.getInput().getGraphGenerator() == null) {
throw new IllegalStateException("Cannot produce BestFirst searches before the graph generator is set in the problem.");
}
if (this.getInput().getPathEvaluator() == null) {
throw new IllegalStateException("Cannot produce BestFirst searches before the node evaluator is set.");
}
/* determine search problem */
GraphSearchWithSubpathEvaluationsInput<N, A, V> problem = this.getInput();
this.logger.debug("Created algorithm input with\n\tgraph generator: {}\n\tnode evaluator: {}", problem.getGraphGenerator(), problem.getPathEvaluator());
BestFirst<GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V> search = new BestFirst<>(problem);
search.setTimeoutForComputationOfF(this.getTimeoutForFInMS(), this.getTimeoutEvaluator());
if (this.getLoggerName() != null && this.getLoggerName().length() > 0) {
search.setLoggerName(this.getLoggerName());
}
return search;
}
@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-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/BestFirstEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
public class BestFirstEvent extends AAlgorithmEvent {
public BestFirstEvent(final IAlgorithm<?, ?> algorithm) {
super(algorithm);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/EvaluatedSearchSolutionCandidateFoundEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.events.result.IScoredSolutionCandidateFoundEvent;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
public class EvaluatedSearchSolutionCandidateFoundEvent<N, A, V extends Comparable<V>> extends GraphSearchSolutionCandidateFoundEvent<N, A, EvaluatedSearchGraphPath<N, A, V>> implements IScoredSolutionCandidateFoundEvent<EvaluatedSearchGraphPath<N, A, V>, V> {
public EvaluatedSearchSolutionCandidateFoundEvent(final IAlgorithm<?, ?> algorithm, final EvaluatedSearchGraphPath<N, A, V> solutionCandidate) {
super(algorithm, solutionCandidate);
}
@Override
public V getScore() {
return this.getSolutionCandidate().getScore();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/FValueEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
public class FValueEvent<V> extends AAlgorithmEvent {
private V fValue;
private double timeUnitlFound;
public FValueEvent(final IAlgorithm<?, ?> algorithm, final V fValue, final double timeUnitlFound) {
super(algorithm);
this.fValue = fValue;
this.timeUnitlFound = timeUnitlFound;
}
public V getfValue() {
return this.fValue;
}
public double getTimeUnitlFound() {
return this.timeUnitlFound;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/GraphSearchSolutionCandidateFoundEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.ASolutionCandidateFoundEvent;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
/**
*
* @author fmohr
*
* @param <N> the node class
* @param <A> the arc class
* @param <S> the solution coding class
*/
public class GraphSearchSolutionCandidateFoundEvent<N, A, S extends SearchGraphPath<N, A>> extends ASolutionCandidateFoundEvent<S> {
public GraphSearchSolutionCandidateFoundEvent(final IAlgorithm<?, ?> algorithm, final S solution) {
super(algorithm, solution);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/LastEventBeforeTermination.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
public class LastEventBeforeTermination extends AAlgorithmEvent {
public LastEventBeforeTermination(final IAlgorithm<?, ?> algorithm) {
super(algorithm);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/NodeAnnotationEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import org.api4.java.algorithm.IAlgorithm;
public class NodeAnnotationEvent<T> extends BestFirstEvent {
private final T node;
private final String annotationName;
private final Object annotationValue;
public NodeAnnotationEvent(final IAlgorithm<?, ?> algorithm, final T node, final String annotationName, final Object annotationValue) {
super(algorithm);
this.node = node;
this.annotationName = annotationName;
this.annotationValue = annotationValue;
}
public T getNode() {
return this.node;
}
public String getAnnotationName() {
return this.annotationName;
}
public Object getAnnotationValue() {
return this.annotationValue;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/NodeExpansionCompletedEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
public class NodeExpansionCompletedEvent<N> extends AAlgorithmEvent {
private final N expandedNode;
public NodeExpansionCompletedEvent(final IAlgorithm<?, ?> algorithm, final N expandedNode) {
super(algorithm);
this.expandedNode = expandedNode;
}
public N getExpandedNode() {
return this.expandedNode;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/NodeExpansionJobSubmittedEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import java.util.List;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public class NodeExpansionJobSubmittedEvent<T, A, V extends Comparable<V>> extends BestFirstEvent {
private final BackPointerPath<T, A, V> expandedNode;
private final List<INewNodeDescription<T, A>> children;
public NodeExpansionJobSubmittedEvent(final IAlgorithm<?, ?> algorithm, final BackPointerPath<T, A, V> expandedNode, final List<INewNodeDescription<T, A>> children) {
super(algorithm);
this.expandedNode = expandedNode;
this.children = children;
}
public BackPointerPath<T, A, V> getExpandedNode() {
return this.expandedNode;
}
public List<INewNodeDescription<T, A>> getChildren() {
return this.children;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/RemovedGoalNodeFromOpenEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public class RemovedGoalNodeFromOpenEvent<N,A, V extends Comparable<V>> extends AAlgorithmEvent {
private final BackPointerPath<N, A, V> goalNode;
public RemovedGoalNodeFromOpenEvent(final IAlgorithm<?, ?> algorithm, final BackPointerPath<N, A, V> goalNode) {
super(algorithm);
this.goalNode = goalNode;
}
public BackPointerPath<N, A, V> getGoalNode() {
return this.goalNode;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/RolloutEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import java.util.List;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
public class RolloutEvent<N, V extends Comparable<V>> extends AAlgorithmEvent {
private final List<N> path;
private final V score;
public RolloutEvent(final IAlgorithm<?, ?> algorithm, final List<N> path, final V score) {
super(algorithm);
this.path = path;
this.score = score;
}
public List<N> getPath() {
return this.path;
}
public V getScore() {
return this.score;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/SolutionAnnotationEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
public class SolutionAnnotationEvent<T, A, V extends Comparable<V>> extends BestFirstEvent {
private final EvaluatedSearchGraphPath<T,A,V> solution;
private final String annotationName;
private final Object annotationValue;
public SolutionAnnotationEvent(final IAlgorithm<?, ?> algorithm, final EvaluatedSearchGraphPath<T,A,V> solution, final String annotationName, final Object annotationValue) {
super(algorithm);
this.solution = solution;
this.annotationName = annotationName;
this.annotationValue = annotationValue;
}
public EvaluatedSearchGraphPath<T,A,V> getSolution() {
return this.solution;
}
public String getAnnotationName() {
return this.annotationName;
}
public Object getAnnotationValue() {
return this.annotationValue;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/events/SuccessorComputationCompletedEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.events;
import java.util.List;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public class SuccessorComputationCompletedEvent<T, A, V extends Comparable<V>> extends BestFirstEvent {
private BackPointerPath<T, A, V> path;
private List<INewNodeDescription<T, A>> successorDescriptions;
public SuccessorComputationCompletedEvent(final IAlgorithm<?, ?> algorithm, final BackPointerPath<T, A, V> path,
final List<INewNodeDescription<T, A>> successorDescriptions) {
super(algorithm);
this.path = path;
this.successorDescriptions = successorDescriptions;
}
public BackPointerPath<T, A, V> getNode() {
return this.path;
}
public void setNode(final BackPointerPath<T, A, V> node) {
this.path = node;
}
public List<INewNodeDescription<T, A>> getSuccessorDescriptions() {
return this.successorDescriptions;
}
public void setSuccessorDescriptions(final List<INewNodeDescription<T, A>> successorDescriptions) {
this.successorDescriptions = successorDescriptions;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/exceptions/ControlledNodeEvaluationException.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.exceptions;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
/**
* Use this exception if the node evaluation was rejected on purpose.
*
* @author fmohr
*
*/
@SuppressWarnings("serial")
public class ControlledNodeEvaluationException extends PathEvaluationException {
public ControlledNodeEvaluationException(String message) {
super(message);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/exceptions/RCNEPathCompletionFailedException.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.exceptions;
public class RCNEPathCompletionFailedException extends Exception {
public RCNEPathCompletionFailedException(Exception e) {
super(e);
}
public RCNEPathCompletionFailedException(String message) {
super(message);
}
public RCNEPathCompletionFailedException(String message, Exception e) {
super(message, e);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/AlternativeNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import java.util.HashMap;
import java.util.Map;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallyGraphDependentPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallySolutionReportingPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.ILabeledPath;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import ai.libs.jaicore.logging.ToJSONStringUtil;
/**
* This node evaluator can be used
* a) if there is a prioritized node evaluator that should be used unless it returns NULL
* b) to realize dead-end recognition
* c) to use different node evaluators in different regions of the search graph
*
* @author fmohr
*
* @param <N>
* @param <V>
*/
public class AlternativeNodeEvaluator<N, A, V extends Comparable<V>> extends DecoratingNodeEvaluator<N, A, V> implements ILoggingCustomizable {
private String loggerName;
private final IPathEvaluator<N, A, V> ne1;
private final boolean enforceExecutionOfSecondEvaluator;
public AlternativeNodeEvaluator(final IPathEvaluator<N, A, V> ne1, final IPathEvaluator<N, A, V> ne2) {
this (ne1, ne2, false);
}
public AlternativeNodeEvaluator(final IPathEvaluator<N, A, V> ne1, final IPathEvaluator<N, A, V> ne2, final boolean enforceExecutionOfSecondEvaluator) {
super(ne2);
if (ne1 == null) {
throw new IllegalArgumentException("The alternativ evaluator in node evaluator must not be null!");
}
this.ne1 = ne1;
this.enforceExecutionOfSecondEvaluator = enforceExecutionOfSecondEvaluator;
}
@Override
public boolean requiresGraphGenerator() {
if (super.requiresGraphGenerator()) {
return true;
}
return (this.ne1 instanceof IPotentiallyGraphDependentPathEvaluator) && ((IPotentiallyGraphDependentPathEvaluator<?, ?, ?>) this.ne1).requiresGraphGenerator();
}
public boolean doesPrimaryNodeEvaluatorReportSolutions() {
return (this.ne1 instanceof IPotentiallySolutionReportingPathEvaluator) && ((IPotentiallySolutionReportingPathEvaluator<?, ?, ?>) this.ne1).reportsSolutions();
}
public IPathEvaluator<N, A, V> getPrimaryNodeEvaluator() {
return this.ne1;
}
@Override
public boolean reportsSolutions() {
if (super.reportsSolutions()) {
return true;
}
return this.ne1 instanceof IPotentiallySolutionReportingPathEvaluator && ((IPotentiallySolutionReportingPathEvaluator<?, ?, ?>) this.ne1).reportsSolutions();
}
@Override
public void setGenerator(final IGraphGenerator<N, A> generator, final IPathGoalTester<N, A> goalTester) {
super.setGenerator(generator, goalTester);
if (!(this.ne1 instanceof IPotentiallyGraphDependentPathEvaluator)) {
return;
}
IPotentiallyGraphDependentPathEvaluator<N, A, V> castedNE1 = (IPotentiallyGraphDependentPathEvaluator<N, A, V>) this.ne1;
if (castedNE1.requiresGraphGenerator()) {
castedNE1.setGenerator(generator, goalTester);
}
}
@Override
public void registerSolutionListener(final Object listener) {
if (super.doesDecoratedEvaluatorReportSolutions()) {
super.registerSolutionListener(listener);
}
if (this.doesPrimaryNodeEvaluatorReportSolutions()) {
((IPotentiallySolutionReportingPathEvaluator<?, ?, ?>) this.ne1).registerSolutionListener(listener);
}
}
@Override
public V evaluate(final ILabeledPath<N, A> node) throws PathEvaluationException, InterruptedException {
V f1 = this.ne1.evaluate(node);
if (!this.enforceExecutionOfSecondEvaluator && f1 != null) {
return f1;
}
return super.evaluate(node);
}
@Override
public String toString() {
Map<String, Object> fields = new HashMap<>();
fields.put("primary", this.ne1);
fields.put("secondary", super.getEvaluator());
return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields);
}
@Override
public String getLoggerName() {
return this.loggerName;
}
@Override
public void setLoggerName(final String name) {
this.loggerName = name;
super.setLoggerName(name + "._decorating");
if (this.ne1 instanceof ILoggingCustomizable) {
((ILoggingCustomizable) this.ne1).setLoggerName(name + ".primary");
}
if (this.getEvaluator() instanceof ILoggingCustomizable) {
((ILoggingCustomizable) this.getEvaluator()).setLoggerName(name + ".secondary");
}
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/CoveringNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.common.control.ILoggingCustomizable;
/**
* This node evaluator allows to use pair of two node evaluators of which the first is HIDDEN by the second.
* The first evaluator is executed and its events are published via the event bus, but its result is not returned.
*
* This can be useful, for example, to collect solutions via a random completions within a node evaluation but using a different computation to return the true score.
* A typical case of application is a Branch and Bound algorithm, where the returned value is an optimistic heuristic, but a set of solutions is computed to maybe
* register new best solutions.
*
* @author Felix Mohr
*
* @param <N>
* @param <V>
*/
public class CoveringNodeEvaluator<N, A, V extends Comparable<V>> extends AlternativeNodeEvaluator<N, A, V> implements ILoggingCustomizable {
public CoveringNodeEvaluator(final IPathEvaluator<N, A, V> ne1, final IPathEvaluator<N, A, V> ne2) {
super(ne1, ne2, true);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/DecoratingNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.ICancelablePathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallyGraphDependentPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallySolutionReportingPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.ILabeledPath;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class DecoratingNodeEvaluator<N, A, V extends Comparable<V>>
implements IPathEvaluator<N, A, V>, ICancelablePathEvaluator, ILoggingCustomizable, IPotentiallyGraphDependentPathEvaluator<N, A, V>, IPotentiallySolutionReportingPathEvaluator<N, A, V> {
private boolean canceled = false;
private Logger logger = LoggerFactory.getLogger(DecoratingNodeEvaluator.class);
private final IPathEvaluator<N, A, V> decoratedEvaluator;
public DecoratingNodeEvaluator(final IPathEvaluator<N, A, V> evaluator) {
super();
if (evaluator == null) {
throw new IllegalArgumentException("The decorated evaluator must not be null!");
}
this.decoratedEvaluator = evaluator;
}
public IPathEvaluator<N, A, V> getEvaluator() {
return this.decoratedEvaluator;
}
@Override
public V evaluate(final ILabeledPath<N, A> node) throws PathEvaluationException, InterruptedException {
return this.decoratedEvaluator.evaluate(node);
}
public boolean isDecoratedEvaluatorCancelable() {
return this.decoratedEvaluator instanceof ICancelablePathEvaluator;
}
public boolean isDecoratedEvaluatorGraphDependent() {
return this.decoratedEvaluator instanceof IPotentiallyGraphDependentPathEvaluator && ((IPotentiallyGraphDependentPathEvaluator<?, ?, ?>) this.decoratedEvaluator).requiresGraphGenerator();
}
public boolean doesDecoratedEvaluatorReportSolutions() {
return this.decoratedEvaluator instanceof IPotentiallySolutionReportingPathEvaluator && ((IPotentiallySolutionReportingPathEvaluator<?, ?, ?>) this.decoratedEvaluator).reportsSolutions();
}
/**
* default implementation that is just correct with respect to the decorated node evaluator.
* If the node evaluator that inherits from DecoratingNodeEvaluator itself may require the graph, this method should be overwritten.
*
*/
@Override
public boolean requiresGraphGenerator() {
return this.isDecoratedEvaluatorGraphDependent();
}
/**
* default implementation that is just correct with respect to the decorated node evaluator.
* If the node evaluator that inherits from DecoratingNodeEvaluator itself may be solution reporting, this method should be overwritten.
*
*/
@Override
public boolean reportsSolutions() {
return this.doesDecoratedEvaluatorReportSolutions();
}
@Override
public void setGenerator(final IGraphGenerator<N, A> generator, final IPathGoalTester<N, A> goalTester) {
this.logger.info("Setting graph generator of {} to {}", this, generator);
if (!this.requiresGraphGenerator()) {
throw new UnsupportedOperationException("This node evaluator is not graph dependent");
}
if (!this.isDecoratedEvaluatorGraphDependent()) {
return;
}
((IPotentiallyGraphDependentPathEvaluator<N, A, V>) this.decoratedEvaluator).setGenerator(generator, goalTester);
}
@Override
public void registerSolutionListener(final Object listener) {
if (!this.doesDecoratedEvaluatorReportSolutions()) {
throw new UnsupportedOperationException(this.getClass().getName() + " is not a solution reporting node evaluator");
}
((IPotentiallySolutionReportingPathEvaluator<N, A, V>) this.decoratedEvaluator).registerSolutionListener(listener);
}
@Override
public void cancelActiveTasks() {
if (this.canceled) {
return;
}
this.canceled = true;
if (this.isDecoratedEvaluatorCancelable()) {
((ICancelablePathEvaluator) this.decoratedEvaluator).cancelActiveTasks();
}
}
@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-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/DelayingNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.algorithm.Timeout;
import org.api4.java.datastructure.graph.ILabeledPath;
/**
* This path evaluator can be used to artificially delay the computation of scores.
* This can be a helpful property in the simulated benchmarking of algorithms for costly evaluations.
*
* @author fmohr
*
* @param <N>
* @param <A>
* @param <V>
*/
public class DelayingNodeEvaluator<N, A, V extends Comparable<V>> extends DecoratingNodeEvaluator<N, A, V> {
private final Timeout delay;
public DelayingNodeEvaluator(final IPathEvaluator<N, A, V> evaluator, final Timeout delay) {
super(evaluator);
this.delay = delay;
}
@Override
public V evaluate(final ILabeledPath<N, A> path) throws PathEvaluationException, InterruptedException {
V score = super.getEvaluator().evaluate(path);
Thread.sleep(this.delay.milliseconds());
return score;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/LinearCombiningNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import java.util.Map;
import java.util.Map.Entry;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.datastructure.graph.ILabeledPath;
public class LinearCombiningNodeEvaluator<T, A> implements IPathEvaluator<T, A, Double> {
private final Map<IPathEvaluator<T, A, Double>, Double> evaluatorsWithWeights;
public LinearCombiningNodeEvaluator(final Map<IPathEvaluator<T, A, Double>, Double> evaluators) {
super();
this.evaluatorsWithWeights = evaluators;
}
@Override
public Double evaluate(final ILabeledPath<T, A> path) throws PathEvaluationException, InterruptedException {
double score = 0;
double incr;
for (Entry<IPathEvaluator<T, A, Double>, Double> evaluatorWeightPair : this.evaluatorsWithWeights.entrySet()) {
if (evaluatorWeightPair.getValue() != 0) {
incr = evaluatorWeightPair.getKey().evaluate(path);
if (incr == Integer.MAX_VALUE) {
score = Integer.MAX_VALUE;
break;
} else {
score += incr * evaluatorWeightPair.getValue();
}
}
}
return score;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/PathVsSubpathNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
public class PathVsSubpathNodeEvaluator<N, A, V extends Comparable<V>> extends AlternativeNodeEvaluator<N, A, V> {
public PathVsSubpathNodeEvaluator(final IPathEvaluator<N, A, V> goalPathEvaluator, final IPathEvaluator<N, A, V> subPathEvaluator, final IPathGoalTester<N, A> goalTester) {
super(p -> goalTester.isGoal(p) ? goalPathEvaluator.evaluate(p) : null, subPathEvaluator);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/RandomCompletionBasedNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.ICancelablePathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallyGraphDependentPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallySolutionReportingPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallyUncertaintyAnnotatingPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IUncertaintySource;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.attributedobjects.IObjectEvaluator;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.ILabeledPath;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import ai.libs.jaicore.basic.algorithm.AlgorithmInitializedEvent;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.logging.LoggerUtil;
import ai.libs.jaicore.logging.ToJSONStringUtil;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.ENodeAnnotation;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.NodeAnnotationEvent;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.NodeExpansionCompletedEvent;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RolloutEvent;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.exceptions.RCNEPathCompletionFailedException;
import ai.libs.jaicore.search.algorithms.standard.gbf.SolutionEventBus;
import ai.libs.jaicore.search.algorithms.standard.random.RandomSearch;
import ai.libs.jaicore.search.algorithms.standard.random.RandomSearchUtil;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
import ai.libs.jaicore.timing.TimedComputation;
public class RandomCompletionBasedNodeEvaluator<T, A, V extends Comparable<V>> extends TimeAwareNodeEvaluator<T, A, V>
implements IPotentiallyGraphDependentPathEvaluator<T, A, V>, IPotentiallySolutionReportingPathEvaluator<T, A, V>, ICancelablePathEvaluator, IPotentiallyUncertaintyAnnotatingPathEvaluator<T, A, V>, ILoggingCustomizable {
private static final IAlgorithm<?, ?> ALGORITHM = null;
private static final boolean LOG_FAILURES_AS_ERRORS = false;
private String loggerName;
private Logger logger = LoggerFactory.getLogger(RandomCompletionBasedNodeEvaluator.class);
private final int timeoutForSingleCompletionEvaluationInMS;
protected Set<List<T>> unsuccessfulPaths = Collections.synchronizedSet(new HashSet<>());
protected Set<ILabeledPath<T, A>> postedSolutions = new HashSet<>();
protected Map<List<T>, Integer> timesToComputeEvaluations = new HashMap<>();
protected Map<List<T>, V> scoresOfSolutionPaths = new ConcurrentHashMap<>();
protected Map<ILabeledPath<T, A>, V> fValues = new ConcurrentHashMap<>();
protected Map<String, Integer> ppFails = new ConcurrentHashMap<>();
protected Map<String, Integer> plFails = new ConcurrentHashMap<>();
protected Map<String, Integer> plSuccesses = new ConcurrentHashMap<>();
protected T root;
protected IGraphGenerator<T, A> generator;
protected IPathGoalTester<T, A> goalTester;
protected long timestampOfFirstEvaluation;
/* algorithm parameters */
protected final Random random;
protected final int desiredNumberOfSuccesfulSamples;
protected final int maxSamples;
private final Predicate<T> priorityPredicateForRDFS;
private RandomSearch<T, A> completer;
private final Semaphore completerInsertionSemaphore = new Semaphore(0); // this is required since the step-method of the completer is asynchronous
protected final IObjectEvaluator<ILabeledPath<T, A>, V> solutionEvaluator;
protected IUncertaintySource<T, A, V> uncertaintySource;
protected SolutionEventBus<T> eventBus = new SolutionEventBus<>();
private final List<Object> solutionListeners = new ArrayList<>();
private final Map<List<T>, V> bestKnownScoreUnderNodeInCompleterGraph = new HashMap<>();
private boolean visualizeSubSearch;
public RandomCompletionBasedNodeEvaluator(final Random random, final int samples, final IObjectEvaluator<ILabeledPath<T, A>, V> solutionEvaluator) {
this(random, samples, samples, solutionEvaluator, -1, -1);
}
public RandomCompletionBasedNodeEvaluator(final Random random, final int desiredNumberOfSuccessfulSamples, final int maxSamples, final IObjectEvaluator<ILabeledPath<T, A>, V> solutionEvaluator) {
this(random, desiredNumberOfSuccessfulSamples, maxSamples, solutionEvaluator, -1, -1);
}
public RandomCompletionBasedNodeEvaluator(final Random random, final int desiredNumberOfSuccessfulSamples, final int maxSamples, final IObjectEvaluator<ILabeledPath<T, A>, V> solutionEvaluator,
final int timeoutForSingleCompletionEvaluationInMS, final int timeoutForNodeEvaluationInMS) {
this(random, desiredNumberOfSuccessfulSamples, maxSamples, solutionEvaluator, timeoutForSingleCompletionEvaluationInMS, timeoutForNodeEvaluationInMS, null);
}
public RandomCompletionBasedNodeEvaluator(final Random random, final int desiredNumberOfSuccessfulSamples, final int maxSamples, final IObjectEvaluator<ILabeledPath<T, A>, V> solutionEvaluator,
final int timeoutForSingleCompletionEvaluationInMS, final int timeoutForNodeEvaluationInMS, final Predicate<T> priorityPredicateForRDFS) {
super(timeoutForNodeEvaluationInMS);
if (random == null) {
throw new IllegalArgumentException("Random source must not be null!");
}
if (desiredNumberOfSuccessfulSamples <= 0) {
throw new IllegalArgumentException("Sample size must be greater than 0!");
}
if (solutionEvaluator == null) {
throw new IllegalArgumentException("Solution evaluator must not be null!");
}
this.random = random;
this.desiredNumberOfSuccesfulSamples = desiredNumberOfSuccessfulSamples;
this.maxSamples = maxSamples;
this.solutionEvaluator = solutionEvaluator;
this.timeoutForSingleCompletionEvaluationInMS = timeoutForSingleCompletionEvaluationInMS;
this.priorityPredicateForRDFS = priorityPredicateForRDFS;
this.logger.info("Initialized RandomCompletionEvaluator with timeout {}ms for single evaluations and {}ms in total per node. Prioriziting predicate: {}", timeoutForSingleCompletionEvaluationInMS, timeoutForNodeEvaluationInMS,
priorityPredicateForRDFS);
/* check whether assertions are on */
assert this.logAssertionActivation();
}
private boolean logAssertionActivation() {
StringBuilder sb = new StringBuilder();
sb.append("Assertion remark:\n--------------------------------------------------------\n");
sb.append("Assertions are activated.\n");
sb.append("This may cause significant performance loss using ");
sb.append(RandomCompletionBasedNodeEvaluator.class.getName());
sb.append(".\nIf you are not in debugging mode, we strongly suggest to disable assertions.\n");
sb.append("--------------------------------------------------------");
this.logger.info("{}", sb);
return true;
}
@SuppressWarnings("unchecked")
@Override
protected V evaluateTimeouted(final ILabeledPath<T, A> path, final int timeout) throws InterruptedException, PathEvaluationException {
assert this.generator != null : "Cannot compute f as no generator has been set!";
if (!(path instanceof BackPointerPath)) {
throw new IllegalArgumentException("Random Completer currently can only work with backpointer-based paths.");
}
BackPointerPath<T, A, V> n = (BackPointerPath<T, A, V>) path;
this.eventBus.post(new NodeAnnotationEvent<>(ALGORITHM, n.getHead(), "f-computing thread", Thread.currentThread().getName()));
this.logger.info("Received request for f-value of node with hashCode {}. Number of subsamples will be {}, timeout for node evaluation is {}ms and for a single candidate is {}ms. Enable DEBUG for node details.", n.hashCode(),
this.desiredNumberOfSuccesfulSamples, this.getTimeoutForNodeEvaluationInMS(), this.timeoutForSingleCompletionEvaluationInMS);
this.logger.debug("Node details: {}", n);
long startOfComputation = System.currentTimeMillis();
long deadline = timeout > 0 ? startOfComputation + timeout : -1;
if (this.timestampOfFirstEvaluation == 0) {
this.timestampOfFirstEvaluation = startOfComputation;
}
if (!this.fValues.containsKey(n)) {
/* abort if not graph generator is set */
if (this.generator == null) {
throw new IllegalStateException("Cannot compute f-values before the generator is set!");
}
/* compute path and partial plan belonging to the node */
List<T> nodeList = n.getNodes();
/* annotate node with estimated relative distance to optimal solution */
if (this.eventBus == null) { // this is necessary if the node evaluator was stored to the disc
this.eventBus = new SolutionEventBus<>();
}
double uncertainty = 0.0;
if (!n.isGoal()) {
/* if the node has no sibling (parent has no other child than this node), apply parent's f. This only works if the parent is already part of the explored graph, which is not necessarily the case */
if (n.getParent() != null && this.completer.getExploredGraph().hasItem(n.getParent().getHead())) {
boolean parentHasFValue = this.fValues.containsKey(n.getParent());
assert parentHasFValue || n.getParent().getParent() == null : "No f-value has been stored for the parent of node with hash code " + n.hashCode() + " (hash code of parent is " + n.getParent().hashCode()
+ ") whose f-value we may want to reuse.\nThis is only allowed for top-level nodes, but the actual path is: "
+ n.path().stream().map(k -> "\n\t" + k.hashCode() + "\t(f-value: " + k.getScore() + ")").collect(Collectors.joining());
boolean nodeHasSibling = this.completer.getExploredGraph().getSuccessors(n.getParent().getHead()).size() > 1;
if (!n.isPoint() && !nodeHasSibling && parentHasFValue) {
V score = this.fValues.get(n.getParent());
this.fValues.put(n, score);
this.logger.debug("Score {} of parent can be used since the last action did not affect the performance.", score);
if (score == null) {
this.logger.warn("Returning score NULL inherited from parent, this should not happen.");
}
if (this.uncertaintySource != null) { // inherit uncertainty from parent
n.setAnnotation(ENodeAnnotation.F_UNCERTAINTY.name(), n.getParent().getAnnotation(ENodeAnnotation.F_UNCERTAINTY.name()));
}
assert !this.annotatesUncertainty() || n.getAnnotation(ENodeAnnotation.F_UNCERTAINTY.name()) != null : "No uncertainty has been annotated to node " + n + " even though we claim to annotate!";
return score;
}
}
/* draw random completions and determine best solution */
AtomicInteger drawnSamples = new AtomicInteger();
AtomicInteger successfulSamples = new AtomicInteger();
int countedExceptions = 0;
List<V> evaluations = new ArrayList<>();
List<ILabeledPath<T, A>> completedPaths = new ArrayList<>();
this.logger.debug("Now drawing {} successful examples but no more than {}", this.desiredNumberOfSuccesfulSamples, this.maxSamples);
while (successfulSamples.get() < this.desiredNumberOfSuccesfulSamples) {
this.logger.debug("Drawing next sample. {} samples have been drawn already, {} have been successful. Thread interruption state is: {}", drawnSamples, successfulSamples, Thread.currentThread().isInterrupted());
this.checkInterruption();
if (deadline > 0 && deadline < System.currentTimeMillis()) {
this.logger.info("Deadline for random completions hit! Finishing node evaluation.");
break;
}
/* determine time that is available to conduct next computation */
long remainingTimeForNodeEvaluation = deadline > 0 ? deadline - System.currentTimeMillis() : -1; // this value is positive or -1 due to the previous check
long timeoutForJob;
if (remainingTimeForNodeEvaluation >= 0 && this.timeoutForSingleCompletionEvaluationInMS >= 0) {
timeoutForJob = Math.min(remainingTimeForNodeEvaluation, this.timeoutForSingleCompletionEvaluationInMS);
} else if (remainingTimeForNodeEvaluation >= 0) {
timeoutForJob = remainingTimeForNodeEvaluation;
} else if (this.timeoutForSingleCompletionEvaluationInMS >= 0) {
timeoutForJob = this.timeoutForSingleCompletionEvaluationInMS;
} else {
timeoutForJob = -1;
}
/* complete the current path by the dfs-solution; we assume that this goes quickly */
ILabeledPath<T, A> tmpCompletedPath = null;
try {
this.logger.debug("Computed remaining time for evaluation: {}ms. Timeout for the job is hence {}ms. Now drawing new solution.", remainingTimeForNodeEvaluation, timeoutForJob);
tmpCompletedPath = this.getNextRandomPathCompletionForNode(n);
} catch (RCNEPathCompletionFailedException e1) {
if (e1.getCause() instanceof InterruptedException) {
throw (InterruptedException) e1.getCause();
}
this.logger.info("Stopping sampling.");
break;
}
final ILabeledPath<T, A> completedPath = tmpCompletedPath;
completedPaths.add(completedPath);
final int evaluationId = this.random.nextInt(1000000);
this.logger.debug("Identified complete path with {} nodes. Now evaluating the path; assigning evaluation id {}", completedPath.getNumberOfNodes(), evaluationId);
/* evaluate the found solution and update internal value model */
try {
this.logger.debug("Enqueuing timed computation with timeout {} and evaluation id {}", timeoutForJob, evaluationId);
TimedComputation.compute(() -> {
this.logger.debug("Starting timed computation with timeout {} and evaluation id {}", timeoutForJob, evaluationId);
drawnSamples.incrementAndGet();
V val = this.getFValueOfSolutionPath(completedPath);
this.logger.debug("Completed path evaluation with id {}. Score is {}", evaluationId, val);
successfulSamples.incrementAndGet();
this.eventBus.post(new RolloutEvent<>(ALGORITHM, n.path(), val));
if (val != null) {
evaluations.add(val);
this.updateMapOfBestScoreFoundSoFar(completedPath, val);
} else {
this.logger.warn("Got NULL result as score for evaluation with id {}", evaluationId);
}
return true;
}, new Timeout(timeoutForJob, TimeUnit.MILLISECONDS), "RCNE-timeout for evaluation with id " + evaluationId);
} catch (InterruptedException e) { // Interrupts are directly re-thrown
this.logger.debug("Path evaluation has been interrupted.");
throw e;
} catch (Exception ex) {
if (countedExceptions == this.maxSamples) {
this.logger.warn("Too many retry attempts, giving up. {} samples were drawn, {} were successful. Head of path is: {}.", drawnSamples, successfulSamples, path.getHead());
throw new PathEvaluationException("Error in the evaluation of a node!", ex);
} else {
countedExceptions++;
if (ex instanceof AlgorithmTimeoutedException) {
this.logger.debug("Candidate evaluation failed due to timeout (either for this candidate or for the whole node).");
} else {
if (LOG_FAILURES_AS_ERRORS) {
this.logger.error("Could not evaluate solution candidate ... retry another completion. {}", LoggerUtil.getExceptionInfo(ex));
} else {
this.logger.warn("Could not evaluate solution candidate ... retry another completion. {}", LoggerUtil.getExceptionInfo(ex));
}
}
}
} finally { // make sure that the abortion task is definitely killed
this.logger.debug("Finished process for sample {}.", drawnSamples);
}
}
/* the only reason why we have no score at this point is that all evaluations have failed with exception or were interrupted */
V best = this.bestKnownScoreUnderNodeInCompleterGraph.get(n.getNodes());
this.logger.debug("Finished sampling. {} samples were drawn, {} were successful. Best seen score is {}", drawnSamples, successfulSamples, best);
if (best == null) {
if (n.getHead().equals(this.root)) {
this.logger.error("No completion could be drawn for the root. Apparently there is no solution in this graph!");
}
this.checkInterruption();
if (countedExceptions > 0) {
throw new NoSuchElementException("Among " + drawnSamples + " evaluated candidates, we could not identify any candidate that did not throw an exception.");
} else {
return null;
}
}
/* if we are still interrupted, throw an exception */
this.logger.debug("Checking interruption.");
this.checkInterruption();
this.logger.debug("Not interrupted.");
/* add number of samples to node */
n.setAnnotation("fRPSamples", successfulSamples);
if (this.uncertaintySource != null) {
uncertainty = this.uncertaintySource.calculateUncertainty(n, completedPaths, evaluations);
this.logger.debug("Setting uncertainty to {}", uncertainty);
} else {
this.logger.debug("Not setting uncertainty, because no uncertainty source has been defined.");
}
this.fValues.put(n, best);
}
/* the node is a goal node */
else {
V score = this.getFValueOfSolutionPath(path);
if (score == null) {
this.logger.warn("No score was computed");
return null;
}
this.fValues.put(n, score);
if (!this.postedSolutions.contains(n)) {
this.logger.error("Found a goal node whose solution has not been posted before!");
}
uncertainty = 0.0;
}
/* set uncertainty if an uncertainty source has been set */
if (this.uncertaintySource != null) {
n.setAnnotation(ENodeAnnotation.F_UNCERTAINTY.name(), uncertainty);
}
}
assert this.fValues.containsKey(n);
V f = this.fValues.get(n);
this.logger.info("Returning f-value: {}. Annotated uncertainty is {}", f, n.getAnnotation(ENodeAnnotation.F_UNCERTAINTY.name()));
return f;
}
public ILabeledPath<T, A> getNextRandomPathCompletionForNode(final BackPointerPath<T, A, ?> n) throws InterruptedException, RCNEPathCompletionFailedException {
/* make sure that the completer has the path from the root to the node in question and that the f-values of the nodes above are added to the map */
this.logger.debug("Starting completion for path of size {}. Enable TRACE for exact path.", n.getNumberOfNodes());
this.logger.trace("Path for which completion is drawn: {}", n.getNodes());
if (!this.completer.knowsNode(n.getHead())) {
synchronized (this.completer) {
this.completer.appendPathToNode(n);
}
BackPointerPath<T, A, ?> current = n.getParent();
while (current != null && !this.fValues.containsKey(current)) {
this.fValues.put(current, (V) current.getScore());
this.logger.debug("Filling up the f-value of {} with {}", current.hashCode(), current.getScore());
current = current.getParent();
}
}
/* now draw random completion */
ILabeledPath<T, A> completedPath = null;
synchronized (this.completer) {
long startCompletion = System.currentTimeMillis();
if (this.completer.isCanceled()) {
this.logger.info("Completer has been canceled (perhaps due a cancel on the evaluator). Canceling sampling.");
throw new RCNEPathCompletionFailedException("Completer has been canceled.");
}
this.logger.debug("Starting search for next solution ...");
try {
if (!this.completer.getExploredGraph().hasItem(n.getHead())) {
throw new IllegalStateException("The completer does not know hte head.");
}
completedPath = this.completer.nextSolutionUnderSubPath(n);
} catch (AlgorithmExecutionCanceledException | TimeoutException e) {
this.logger.info("Completer has been canceled or timeouted. Returning control.");
throw new RCNEPathCompletionFailedException(e);
}
if (completedPath == null) {
this.logger.info("No completion was found for path {}.", n.getNodes());
throw new RCNEPathCompletionFailedException("No completion found for path " + n.getNodes());
}
assert completedPath.getArcs() != null : "The RandomSearch has returned a solution path with a null pointer for the edges.";
assert completedPath.getNumberOfNodes() == completedPath.getArcs().size() + 1;
assert RandomSearchUtil.checkValidityOfPathCompletion(n, completedPath);
long finishedCompletion = System.currentTimeMillis();
this.logger.debug("Found completion of length {} in {}ms. Enable TRACE for details.", completedPath.getNumberOfNodes(), finishedCompletion - startCompletion);
this.logger.trace("Completion is {}", completedPath);
}
return completedPath;
}
private void updateMapOfBestScoreFoundSoFar(final ILabeledPath<T, A> nodeInCompleterGraph, final V scoreOnOriginalBenchmark) {
V bestKnownScore = this.bestKnownScoreUnderNodeInCompleterGraph.get(nodeInCompleterGraph.getNodes());
if (bestKnownScore == null || scoreOnOriginalBenchmark.compareTo(bestKnownScore) < 0) {
this.logger.debug("Updating best score of path, because score {} is better than previously observed best score {}", scoreOnOriginalBenchmark, bestKnownScore);
this.bestKnownScoreUnderNodeInCompleterGraph.put(nodeInCompleterGraph.getNodes(), scoreOnOriginalBenchmark);
if (!nodeInCompleterGraph.isPoint()) {
this.updateMapOfBestScoreFoundSoFar(nodeInCompleterGraph.getPathToParentOfHead(), scoreOnOriginalBenchmark);
}
}
}
protected V getFValueOfSolutionPath(final ILabeledPath<T, A> path) throws InterruptedException, PathEvaluationException {
boolean knownPath = this.scoresOfSolutionPaths.containsKey(path.getNodes());
if (!knownPath) {
if (this.unsuccessfulPaths.contains(path.getNodes())) {
this.logger.warn("Asking again for the reevaluation of a path that was evaluated unsuccessfully in a previous run; returning NULL: {}", path);
return null;
}
this.logger.debug("Associated plan is new. Calling solution evaluator {} to compute f-value for path of length {}. Enable TRACE for exact plan.", this.solutionEvaluator.getClass().getName(), path.getNumberOfNodes());
if (this.logger.isTraceEnabled()) {
this.logger.trace("The hash code of the path is {}", path.hashCode());
}
/* compute value of solution */
long start = System.currentTimeMillis();
V val = null;
try {
val = this.solutionEvaluator.evaluate(new SearchGraphPath<>(path));
} catch (InterruptedException e) {
this.logger.info("Received interrupt during computation of f-value.");
throw e;
} catch (Exception e) {
this.unsuccessfulPaths.add(path.getNodes());
throw new PathEvaluationException("Error in evaluating node!", e);
}
long duration = System.currentTimeMillis() - start;
if (this.timeoutForSingleCompletionEvaluationInMS > 0 && duration >= this.timeoutForSingleCompletionEvaluationInMS) {
this.logger.warn("Evaluation took {}ms, but timeout is {}", duration, this.timeoutForSingleCompletionEvaluationInMS);
assert duration < this.timeoutForSingleCompletionEvaluationInMS + 10000 : "Evaluation took " + duration + "ms, but timeout is " + this.timeoutForSingleCompletionEvaluationInMS;
}
/* at this point, the value should not be NULL */
this.logger.info("Result: {}, Size: {}", val, this.scoresOfSolutionPaths.size());
if (val == null) {
this.logger.warn("The solution evaluator has returned NULL, which should not happen.");
this.unsuccessfulPaths.add(path.getNodes());
return null;
}
this.scoresOfSolutionPaths.put(path.getNodes(), val);
this.timesToComputeEvaluations.put(path.getNodes(), (int) duration);
this.postSolution(path);
} else {
this.logger.info("Associated plan is known. Reading score from cache.");
if (this.logger.isTraceEnabled()) {
for (List<T> existingPath : this.scoresOfSolutionPaths.keySet()) {
if (existingPath.equals(path)) {
this.logger.trace("The following plans appear equal:\n\t{}\n\t{}", existingPath, path);
}
}
}
if (!this.postedSolutions.contains(path)) {
throw new IllegalStateException("Reading cached score of a plan whose path has not been posted as a solution! Are there several paths to a plan?");
}
}
V score = this.scoresOfSolutionPaths.get(path.getNodes());
this.logger.debug("Determined value {} for path of length {}.", score, path.getNumberOfNodes());
assert score != null : "Stored scores must never be null";
this.logger.trace("Full path is {}", path);
return score;
}
protected void postSolution(final ILabeledPath<T, A> solution) {
assert !this.postedSolutions.contains(solution) : "Solution " + solution.toString() + " already posted!";
assert this.goalTester.isGoal(solution) : "Last node is not a goal node!";
this.postedSolutions.add(solution);
try {
/* now post the solution to the event bus */
int numberOfComputedFValues = this.scoresOfSolutionPaths.size();
/* post solution and then the annotations */
if (this.eventBus == null) {
this.eventBus = new SolutionEventBus<>();
}
EvaluatedSearchGraphPath<T, ?, V> solutionObject = new EvaluatedSearchGraphPath<>(solution, this.scoresOfSolutionPaths.get(solution.getNodes()));
solutionObject.setAnnotation("fTime", this.timesToComputeEvaluations.get(solution.getNodes()));
solutionObject.setAnnotation("timeToSolution", (int) (System.currentTimeMillis() - this.timestampOfFirstEvaluation));
solutionObject.setAnnotation("nodesEvaluatedToSolution", numberOfComputedFValues);
this.logger.debug("Posting solution {} to {} listeners: {}", solutionObject, this.solutionListeners.size(), this.solutionListeners);
this.eventBus.post(new EvaluatedSearchSolutionCandidateFoundEvent<>(ALGORITHM, solutionObject));
this.logger.debug("Posted solution {} to event bus.", solutionObject);
} catch (Exception e) {
List<Pair<String, Object>> explanations = new ArrayList<>();
if (this.logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
solution.getNodes().forEach(n -> sb.append(n.toString() + "\n"));
explanations.add(new Pair<>("The path that has been tried to convert is as follows:", sb.toString()));
}
this.logger.error("Cannot post solution, because no valid MLPipeline object could be derived from it:\n{}", LoggerUtil.getExceptionInfo(e, explanations));
}
}
@Override
public void setGenerator(final IGraphGenerator<T, A> generator, final IPathGoalTester<T, A> goalTester) {
this.generator = generator;
this.root = generator.getRootGenerator().getRoots().iterator().next();
this.goalTester = goalTester;
/* create the completion algorithm and initialize it */
IPathEvaluator<T, A, Double> nodeEvaluator = new RandomizedDepthFirstNodeEvaluator<>(this.random);
GraphSearchWithSubpathEvaluationsInput<T, A, Double> completionProblem = new GraphSearchWithSubpathEvaluationsInput<>(this.generator, this.goalTester, nodeEvaluator);
this.completer = new RandomSearch<>(completionProblem, this.priorityPredicateForRDFS, this.random);
if (this.getTotalDeadline() >= 0) {
this.completer.setTimeout(new Timeout(this.getTotalDeadline() - System.currentTimeMillis(), TimeUnit.MILLISECONDS));
}
if (this.loggerName != null) {
this.completer.setLoggerName(this.loggerName + ".completer");
}
IAlgorithmEvent e = this.completer.next();
assert e instanceof AlgorithmInitializedEvent : "First event of completer is not the initialization event!";
this.logger.info("Generator has been set, and completer has been initialized");
}
@Subscribe
public void receiveCompleterEvent(final NodeExpansionCompletedEvent<BackPointerPath<T, A, Double>> event) {
this.completerInsertionSemaphore.release();
}
@Override
public void registerSolutionListener(final Object listener) {
this.eventBus.register(listener);
this.solutionListeners.add(listener);
}
@Override
public void cancelActiveTasks() {
this.logger.info("Receive cancel signal. Canceling the completer.");
this.completer.cancel();
}
@Override
public void setUncertaintySource(final IUncertaintySource<T, A, V> uncertaintySource) {
this.uncertaintySource = uncertaintySource;
}
public IObjectEvaluator<ILabeledPath<T, A>, V> getSolutionEvaluator() {
return this.solutionEvaluator;
}
public boolean isVisualizeSubSearch() {
return this.visualizeSubSearch;
}
public void setVisualizeSubSearch(final boolean visualizeSubSearch) {
this.visualizeSubSearch = visualizeSubSearch;
}
@Override
public void setLoggerName(final String name) {
this.loggerName = name;
this.logger.info("Switching logger (name) of object of class {} to {}", this.getClass().getName(), name);
this.logger = LoggerFactory.getLogger(name);
super.setLoggerName(name + "._parent");
if (this.completer != null) {
this.completer.setLoggerName(name + ".randomsearch");
}
if (this.solutionEvaluator instanceof ILoggingCustomizable) {
this.logger.info("Setting logger of evaluator {} to {}.evaluator", this.solutionEvaluator.getClass().getName(), name);
((ILoggingCustomizable) this.solutionEvaluator).setLoggerName(name + ".evaluator");
} else {
this.logger.info("Evaluator {} is not customizable for logger, so not configuring it.", this.solutionEvaluator.getClass().getName());
}
this.logger.info("Switched logger (name) of {} to {}", this, name);
this.logger.info("Reprinting RandomCompletionEvaluator configuration after logger switch: timeout {}ms for single evaluations and {}ms in total per node", this.timeoutForSingleCompletionEvaluationInMS,
this.getTimeoutForNodeEvaluationInMS());
}
@Override
public String getLoggerName() {
return this.loggerName;
}
@Override
public String toString() {
Map<String, Object> fields = new HashMap<>();
fields.put("solutionEvaluator", this.solutionEvaluator);
fields.put("priorizing predicate", this.priorityPredicateForRDFS);
return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields);
}
@Override
public boolean requiresGraphGenerator() {
return true;
}
@Override
public boolean reportsSolutions() {
return true;
}
@Override
public boolean annotatesUncertainty() {
return this.uncertaintySource != null;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/RandomizedDepthFirstNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import java.util.Random;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.datastructure.graph.ILabeledPath;
public class RandomizedDepthFirstNodeEvaluator<T, A> implements IPathEvaluator<T, A, Double> {
private final Random rand;
public RandomizedDepthFirstNodeEvaluator(final Random rand) {
super();
this.rand = rand;
}
@Override
public Double evaluate(final ILabeledPath<T, A> node) {
return (double) (-1 * (node.getNodes().size() * 1000 + this.rand.nextInt(100)));
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/SkippingNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.datastructure.graph.ILabeledPath;
public class SkippingNodeEvaluator<T, A, V extends Comparable<V>> implements IPathEvaluator<T, A, V> {
private final IPathEvaluator<T,A, V> actualEvaluator;
private final Random rand;
private final float coin;
private final Map<ILabeledPath<T, A>, V> fCache = new HashMap<>();
public SkippingNodeEvaluator(final IPathEvaluator<T, A, V> actualEvaluator, final Random rand, final float coin) {
super();
this.actualEvaluator = actualEvaluator;
this.rand = rand;
this.coin = coin;
}
@Override
public V evaluate(final ILabeledPath<T, A> path) throws PathEvaluationException, InterruptedException {
int depth = path.getNodes().size() - 1;
if (!this.fCache.containsKey(path)) {
if (depth == 0) {
this.fCache.put(path, this.actualEvaluator.evaluate(path));
} else {
if (this.rand.nextFloat() >= this.coin) {
this.fCache.put(path, this.actualEvaluator.evaluate(path));
} else {
this.fCache.put(path, this.evaluate(path.getPathToParentOfHead()));
}
}
}
return this.fCache.get(path);
}
@Override
public String toString() {
return "SkippingEvaluator [actualEvaluator=" + this.actualEvaluator + "]";
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/TimeAwareNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.ILabeledPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.timing.TimedComputation;
/**
* This class can be used to create node evaluators with a time limit for the evaluation of each node.
* The remaining time for the evaluation of the node is given with the call of f.
*
* The thread will be interrupted after the timeout if it has not returned control in time.
*
* @author fmohr
*
* @param <T>
* @param <V>
*/
public abstract class TimeAwareNodeEvaluator<T, A, V extends Comparable<V>> implements IPathEvaluator<T, A, V>, ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(TimeAwareNodeEvaluator.class);
private final int timeoutForNodeEvaluationInMS;
private long totalDeadline = -1; // this deadline can be set to guarantee that there will be no activity after this timestamp
private final IPathEvaluator<T, A, V> fallbackNodeEvaluator;
public TimeAwareNodeEvaluator(final int pTimeoutInMS) {
this(pTimeoutInMS, n -> null);
}
public TimeAwareNodeEvaluator(final int pTimeoutInMS, final IPathEvaluator<T, A, V> pFallbackNodeEvaluator) {
super();
this.timeoutForNodeEvaluationInMS = pTimeoutInMS;
this.fallbackNodeEvaluator = pFallbackNodeEvaluator;
}
protected abstract V evaluateTimeouted(ILabeledPath<T, A> node, int timeoutInMS) throws PathEvaluationException, InterruptedException;
@Override
public final V evaluate(final ILabeledPath<T, A> path) throws PathEvaluationException, InterruptedException {
/* determine time available and granted for node evaluation */
int remainingTime;
if (this.totalDeadline >= 0 && this.timeoutForNodeEvaluationInMS >= 0) {
remainingTime = Math.min(this.timeoutForNodeEvaluationInMS, (int) (this.totalDeadline - System.currentTimeMillis()));
} else if (this.totalDeadline >= 0) {
remainingTime = (int) (this.totalDeadline - System.currentTimeMillis());
} else if (this.timeoutForNodeEvaluationInMS >= 0) {
remainingTime = this.timeoutForNodeEvaluationInMS;
} else {
remainingTime = Integer.MAX_VALUE - 1000;
}
int grantedTime = remainingTime - 50;
int interruptionTime = remainingTime + 150;
/* execute evaluation */
try {
return TimedComputation.compute(() -> this.evaluateTimeouted(path, grantedTime), new Timeout(interruptionTime, TimeUnit.MILLISECONDS),
"Node evaluation has timed out (" + TimeAwareNodeEvaluator.class.getName() + "::" + Thread.currentThread() + "-" + System.currentTimeMillis() + ")");
} catch (AlgorithmTimeoutedException e) {
this.logger.warn("Computation of f-value for {} failed due to exception {} with message {}", path, e.getClass().getName(), e.getMessage());
return this.fallbackNodeEvaluator.evaluate(path);
} catch (InterruptedException e) {
this.logger.info("Got interrupted during node evaluation. Throwing an InterruptedException");
throw e;
} catch (ExecutionException e) {
if (e.getCause() instanceof PathEvaluationException) {
throw (PathEvaluationException) e.getCause();
} else {
throw new PathEvaluationException("Could not evaluate path.", e.getCause());
}
}
}
public int getTimeoutForNodeEvaluationInMS() {
return this.timeoutForNodeEvaluationInMS;
}
public IPathEvaluator<T, A, V> getFallbackNodeEvaluator() {
return this.fallbackNodeEvaluator;
}
public long getTotalDeadline() {
return this.totalDeadline;
}
public void setTotalDeadline(final long totalDeadline) {
this.totalDeadline = totalDeadline;
}
protected void checkInterruption() throws InterruptedException {
boolean interrupted = Thread.currentThread().isInterrupted();
this.logger.debug("Checking interruption of RCNE: {}", interrupted);
if (interrupted) {
Thread.interrupted(); // reset flag
throw new InterruptedException("Node evaluation of " + this.getClass().getName() + " has been interrupted.");
}
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Switched logger name to {}", name);
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/nodeevaluation/TimeLoggingNodeEvaluator.java
|
package ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.datastructure.graph.ILabeledPath;
public class TimeLoggingNodeEvaluator<T, A, V extends Comparable<V>> extends DecoratingNodeEvaluator<T, A, V> {
private final Map<ILabeledPath<T, A>, Integer> times = new ConcurrentHashMap<>();
public TimeLoggingNodeEvaluator(final IPathEvaluator<T, A,V> baseEvaluator) {
super(baseEvaluator);
}
public int getMSRequiredForComputation(final ILabeledPath<T, A> path) {
if (!this.times.containsKey(path)) {
throw new IllegalArgumentException("No f-value has been computed for node: " + path);
}
return this.times.get(path);
}
@Override
public V evaluate(final ILabeledPath<T, A> path) throws PathEvaluationException, InterruptedException {
long start = System.currentTimeMillis();
V f = super.evaluate(path);
this.times.put(path, (int) (System.currentTimeMillis() - start));
return f;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bnb/BoundPropagator.java
|
package ai.libs.jaicore.search.algorithms.standard.bnb;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallySolutionReportingPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.datastructure.graph.ILabeledPath;
import com.google.common.eventbus.EventBus;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
public class BoundPropagator<N, A> implements IPathEvaluator<N, A, Double>, IPotentiallySolutionReportingPathEvaluator<N, A, Double> {
private final IPathEvaluator<N, A, Double> lowerBoundComputer;
private final EventBus bus = new EventBus();
public BoundPropagator(final IPathEvaluator<N, A, Double> lowerBoundComputer) {
super();
this.lowerBoundComputer = lowerBoundComputer;
}
@Override
public void registerSolutionListener(final Object listener) {
this.bus.register(listener);
}
@Override
public boolean reportsSolutions() {
return true;
}
@Override
public Double evaluate(final ILabeledPath<N, A> path) throws PathEvaluationException, InterruptedException {
double bound = this.lowerBoundComputer.evaluate(path);
this.bus.post(new EvaluatedSearchSolutionCandidateFoundEvent<>(null, new EvaluatedSearchGraphPath<>(new SearchGraphPath<>(path.getRoot()), bound)));
return bound;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bnb/BranchAndBound.java
|
package ai.libs.jaicore.search.algorithms.standard.bnb;
import java.util.Random;
import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.StandardBestFirst;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
import ai.libs.jaicore.search.problemtransformers.GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformerViaRDFS;
/**
* Branch and Bound algorithm. The evaluations given for each node must be optimistic (lower bounds).
*
* @author Felix Mohr
*
* @param <N>
* @param <A>
*/
public class BranchAndBound<N, A> extends StandardBestFirst<N, A, Double> {
public static <N, A> GraphSearchWithSubpathEvaluationsInput<N, A, Double> encodeBoundsIntoProblem(final IPathSearchWithPathEvaluationsInput<N, A, Double> problem, final int numSamplesPerNode) {
GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformerViaRDFS<N, A, Double> trans = new GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformerViaRDFS<>(n -> null, n -> false,
new Random(), numSamplesPerNode, 100000, 100000);
return trans.encodeProblem(problem);
}
public BranchAndBound(final IPathSearchWithPathEvaluationsInput<N, A, Double> problem, final IPathEvaluator<N, A, Double> lowerBoundComputer, final int numSamplesPerNode) {
super(encodeBoundsIntoProblem(problem, numSamplesPerNode), lowerBoundComputer);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/dfs/DepthFirstSearch.java
|
package ai.libs.jaicore.search.algorithms.standard.dfs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.ILabeledPath;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent;
import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent;
import ai.libs.jaicore.graphvisualizer.events.graph.NodeTypeSwitchEvent;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.GraphSearchSolutionCandidateFoundEvent;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.NodeExpansionCompletedEvent;
import ai.libs.jaicore.search.core.interfaces.AAnyPathInORGraphSearch;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
/**
*
* @author fmohr
*
* @param <N>
* @param <A>
*/
public class DepthFirstSearch<N, A> extends AAnyPathInORGraphSearch<IPathSearchInput<N, A>, SearchGraphPath<N, A>, N, A> implements ILoggingCustomizable {
/* logging */
private String loggerName;
private Logger logger = LoggerFactory.getLogger(DepthFirstSearch.class);
private final IPathGoalTester<N, A> goalTester;
/* state of the algorithm */
private SearchGraphPath<N, A> currentPath;
private boolean lastNodeWasTrueLeaf = false;
private Map<N, List<N>> successorsNodes = new HashMap<>();
private Map<N, List<A>> successorsEdges = new HashMap<>();
public DepthFirstSearch(final IPathSearchInput<N, A> problem) {
super(problem);
this.goalTester = problem.getGoalTester();
}
@Override
public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
try {
this.checkAndConductTermination();
this.registerActiveThread();
this.logger.debug("Conducting step. Current path length is {}", this.currentPath != null ? this.currentPath.getNumberOfNodes() : "0");
switch (this.getState()) {
case CREATED:
N root = ((ISingleRootGenerator<N>) this.getInput().getGraphGenerator().getRootGenerator()).getRoot();
this.post(new GraphInitializedEvent<>(this, root));
/* check whether a path has already been set externally */
if (this.currentPath == null) {
this.currentPath = new SearchGraphPath<>(this.getInput().getGraphGenerator().getRootGenerator().getRoots().iterator().next());
} else {
if (!this.currentPath.getRoot().equals(root)) {
throw new IllegalArgumentException("The root of the given path is not the root of the tree provided by the graph generator.");
}
/* post an event of all the nodes that have been added */
int n = this.currentPath.getNumberOfNodes();
for (int i = 0; i < n - 1; i++) {
N node = this.currentPath.getNodes().get(i);
for (N successor : this.successorsNodes.get(node)) {
this.post(new NodeAddedEvent<>(this, node, successor, "or_open"));
this.post(new NodeTypeSwitchEvent<>(this, node, "or_closed"));
}
}
N leaf = this.currentPath.getHead();
if (this.goalTester.isGoal(this.currentPath)) {
this.post(new NodeTypeSwitchEvent<>(this, this.currentPath.getHead(), "or_solution"));
this.lastNodeWasTrueLeaf = true;
} else if (this.getInput().getGraphGenerator().getSuccessorGenerator().generateSuccessors(leaf).isEmpty()) {
this.lastNodeWasTrueLeaf = true;
}
}
this.logger.info("Algorithm activated.");
return this.activate();
case ACTIVE:
/* compute the currently relevant leaf */
N leaf = this.currentPath.getHead();
if (this.lastNodeWasTrueLeaf) {
/* find the deepest antecessor of the leaf that has not been exhausted */
N formerLeaf;
int indexOfChildInSuccessorsOfParent;
do {
if (this.currentPath.getNumberOfNodes() == 1) { // if this was the last node, terminate the algorithm
return this.terminate();
}
this.successorsNodes.remove(leaf); // this is relevant if the leaf is actually now an inner node
this.currentPath.cutHead();
formerLeaf = leaf;
this.logger.trace("Last node {} was a leaf node (goal or dead-end) in the original graph. Computing new leaf node by first switching to the next sibling of parent {}.", formerLeaf, leaf);
leaf = this.currentPath.getHead();
indexOfChildInSuccessorsOfParent = this.successorsNodes.get(leaf).indexOf(formerLeaf);
assert indexOfChildInSuccessorsOfParent >= 0 : "Could not identify node " + leaf + " as a successor of " + leaf + ". Successors of parent: " + this.successorsNodes.get(leaf);
this.logger.trace("Node {} is child #{} of the parent node {}.", formerLeaf, indexOfChildInSuccessorsOfParent, leaf);
}
while (indexOfChildInSuccessorsOfParent == this.successorsNodes.get(leaf).size() - 1);
/* get next successor of the current leaf */
A successorAction = this.successorsEdges.get(leaf).get(indexOfChildInSuccessorsOfParent + 1);
leaf = this.successorsNodes.get(leaf).get(indexOfChildInSuccessorsOfParent + 1);
this.currentPath.extend(leaf, successorAction);
assert this.checkPathConsistency(this.currentPath);
}
this.logger.debug("Relevant leaf node is {}.", leaf);
if (this.goalTester.isGoal(this.currentPath)) {
this.lastNodeWasTrueLeaf = true;
IAlgorithmEvent event = new GraphSearchSolutionCandidateFoundEvent<>(this, new SearchGraphPath<>(this.currentPath));
this.post(event);
this.post(new NodeTypeSwitchEvent<>(this, leaf, "or_solution"));
this.logger.debug("The leaf node is a goal node. Returning goal path {}", this.currentPath);
return event;
} else {
this.logger.debug("The leaf node is not a goal node. Creating successors and diving into the first one.");
this.post(new NodeTypeSwitchEvent<>(this, leaf, "or_closed"));
final N expandedLeaf = leaf;
List<INewNodeDescription<N, A>> successorsOfThis = this.computeTimeoutAware(
() -> this.getInput().getGraphGenerator().getSuccessorGenerator().generateSuccessors(expandedLeaf), "DFS successor generation", true);
long lastTerminationCheck = 0;
List<N> successorNodes = new ArrayList<>();
List<A> successorEdges = new ArrayList<>();
for (INewNodeDescription<N, A> child : successorsOfThis) {
this.post(new NodeAddedEvent<>(this, expandedLeaf, child.getTo(), "or_open"));
if (System.currentTimeMillis() - lastTerminationCheck > 50) {
this.checkAndConductTermination();
lastTerminationCheck = System.currentTimeMillis();
}
successorNodes.add(child.getTo());
successorEdges.add(child.getArcLabel());
}
this.successorsNodes.put(leaf, successorNodes);
this.successorsEdges.put(leaf, successorEdges);
this.lastNodeWasTrueLeaf = successorsOfThis.isEmpty();
if (this.lastNodeWasTrueLeaf) {
this.logger.debug("Detected that {} is a dead-end (has no successors and is not a goal node).", leaf);
} else {
this.currentPath.extend(successorNodes.get(0), successorEdges.get(0));
assert this.checkPathConsistency(this.currentPath);
this.logger.debug("Computed {} successors for {}, and selected {} as the next successor. Current path is now {}.", successorsOfThis.size(), leaf, successorsOfThis.get(0), this.currentPath);
}
return new NodeExpansionCompletedEvent<>(this, leaf);
}
default:
throw new IllegalStateException("Cannot do anything in state " + this.getState());
}
} finally {
this.unregisterActiveThread();
}
}
public ILabeledPath<N, A> getCurrentPath() {
return this.currentPath.getUnmodifiableAccessor();
}
public int[] getDecisionIndicesForCurrentPath() {
int n = this.currentPath.getNumberOfNodes();
int[] decisions = new int[n - 1];
ILabeledPath<N, A> tmpPath = this.getCurrentPath();
N last = null;
for (int i = 0; i < n; i++) {
N current = tmpPath.getRoot();
if (last != null) {
decisions[i - 1] = this.successorsNodes.get(last).indexOf(current);
assert decisions[i - 1] != -1;
}
last = current;
tmpPath = tmpPath.getPathFromChildOfRoot();
}
return decisions;
}
public void setCurrentPath(final ILabeledPath<N, A> path) {
try {
/* check that the root of the path is consistent with the true root */
Object root = this.currentPath.getNumberOfNodes() == 0 ? ((ISingleRootGenerator<?>) this.getGraphGenerator().getRootGenerator()).getRoot() : this.currentPath.getNodes().get(0);
if (!root.equals(path.getRoot())) {
throw new IllegalArgumentException();
}
/* now check that all other nodes are also valid successors in the original graph */
Map<N, List<N>> tentativeSuccessors = new HashMap<>();
ISuccessorGenerator<N, A> successorGenerator = this.getGraphGenerator().getSuccessorGenerator();
int n = path.getNumberOfNodes();
for (int i = 0; i < n; i++) {
N node = path.getNodes().get(i);
if (i > 0 && !tentativeSuccessors.get(path.getNodes().get(i - 1)).contains(node)) {
throw new IllegalArgumentException("Node " + node + " is not a successor of " + path.getNodes().get(i - 1) + " in the original graph.");
}
if (i < n - 1) {
tentativeSuccessors.put(node, successorGenerator.generateSuccessors(node).stream().map(INewNodeDescription::getTo).collect(Collectors.toList()));
}
}
/* replace successor map and current path variable */
this.currentPath = new SearchGraphPath<>(path);
this.successorsNodes.clear();
this.successorsNodes.putAll(tentativeSuccessors);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public void setCurrentPath(final int... decisions) {
try {
N root = this.currentPath.getNumberOfNodes() == 0 ? ((ISingleRootGenerator<N>) this.getGraphGenerator().getRootGenerator()).getRoot() : this.currentPath.getRoot();
SearchGraphPath<N, A> tentativePath = new SearchGraphPath<>(root);
Map<N, List<N>> tentativeSuccessors = new HashMap<>();
Map<N, List<A>> tentativeSuccessorActions = new HashMap<>();
ISuccessorGenerator<N, A> successorGenerator = this.getGraphGenerator().getSuccessorGenerator();
int n = decisions.length;
for (int i = 0; i < n; i++) {
N node = tentativePath.getHead();
List<INewNodeDescription<N, A>> descriptions = successorGenerator.generateSuccessors(node);
tentativeSuccessors.put(node, descriptions.stream().map(INewNodeDescription::getTo).collect(Collectors.toList()));
tentativeSuccessorActions.put(node, descriptions.stream().map(INewNodeDescription::getArcLabel).collect(Collectors.toList()));
tentativePath.extend(tentativeSuccessors.get(node).get(decisions[i]), tentativeSuccessorActions.get(node).get(decisions[i]));
}
/* replace successor map and current path variable */
this.currentPath = tentativePath;
this.successorsNodes.clear();
this.successorsNodes.putAll(tentativeSuccessors);
this.checkPathConsistency(this.currentPath);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private boolean checkPathConsistency(final ILabeledPath<N, A> path) {
N last = null;
for (N node : path.getNodes()) {
if (last != null) {
assert this.successorsNodes.containsKey(last) : "No successor entry found for node " + last;
if (!this.successorsNodes.containsKey(last)) {
return false;
}
if (!this.successorsNodes.get(last).contains(node)) {
throw new IllegalStateException("The path has an edge from " + last + " to " + node + " that is not reflected in the successors.");
}
}
last = node;
}
return true;
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switch logger name from {} to {}", this.loggerName, name);
this.loggerName = name;
this.logger = LoggerFactory.getLogger(this.loggerName);
if (this.getGraphGenerator() instanceof ILoggingCustomizable) {
((ILoggingCustomizable) this.getGraphGenerator()).setLoggerName(name + ".graphgen");
}
this.logger.info("Switched logger name to {}", this.loggerName);
super.setLoggerName(this.loggerName + "._algorithm");
}
@Override
public String getLoggerName() {
return this.loggerName;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/dfs/DepthFirstSearchFactory.java
|
package ai.libs.jaicore.search.algorithms.standard.dfs;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import ai.libs.jaicore.search.core.interfaces.StandardORGraphSearchFactory;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
public class DepthFirstSearchFactory<N, A> extends StandardORGraphSearchFactory<IPathSearchInput<N, A>, SearchGraphPath<N, A>,N, A, Double, DepthFirstSearch<N, A>> {
private String loggerName;
public DepthFirstSearchFactory() {
super();
}
@Override
public DepthFirstSearch<N, A> getAlgorithm() {
if (this.getInput().getGraphGenerator() == null) {
throw new IllegalStateException("Cannot produce RandomSearch searches before the graph generator is set in the problem.");
}
return this.getAlgorithm(this.getInput());
}
@Override
public DepthFirstSearch<N, A> getAlgorithm(final IPathSearchInput<N, A> input) {
return new DepthFirstSearch<>(input);
}
public String getLoggerName() {
return this.loggerName;
}
public void setLoggerName(final String loggerName) {
this.loggerName = loggerName;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/dfs/TinyDepthFirstSearch.java
|
package ai.libs.jaicore.search.algorithms.standard.dfs;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchInput;
public class TinyDepthFirstSearch<N, A> {
private final List<SearchGraphPath<N, A>> solutionPaths = new LinkedList<>();
private final ISuccessorGenerator<N, A> successorGenerator;
private final INodeGoalTester<N, A> goalTester;
private final N root;
private final Deque<N> nodes = new LinkedList<>();
private final Deque<A> edges = new LinkedList<>();
public TinyDepthFirstSearch(final GraphSearchInput<N, A> problem) {
super();
this.root = ((ISingleRootGenerator<N>) problem.getGraphGenerator().getRootGenerator()).getRoot();
this.goalTester = (INodeGoalTester<N, A>) problem.getGoalTester();
this.successorGenerator = problem.getGraphGenerator().getSuccessorGenerator();
this.nodes.add(this.root);
}
public void run() throws InterruptedException {
this.dfs(this.root);
}
public void dfs(final N head) throws InterruptedException {
if (this.goalTester.isGoal(head)) {
this.solutionPaths.add(new SearchGraphPath<>(new ArrayList<>(this.nodes), new ArrayList<>(this.edges)));
}
else {
/* expand node and invoke dfs for each child in order */
List<INewNodeDescription<N,A>> successors = this.successorGenerator.generateSuccessors(head);
for (INewNodeDescription<N,A> succ : successors) {
N to = succ.getTo();
A label = succ.getArcLabel();
this.nodes.addFirst(to);
this.edges.addFirst(label);
this.dfs(to);
N removed = this.nodes.removeFirst();
this.edges.removeFirst();
assert removed == to : "Expected " + to + " but removed " + removed;
}
}
}
public List<SearchGraphPath<N, A>> getSolutionPaths() {
return this.solutionPaths;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/gbf/GeneralBestFirstEvaluationAggregation.java
|
package ai.libs.jaicore.search.algorithms.standard.gbf;
import java.util.Map;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public interface GeneralBestFirstEvaluationAggregation<T, A> {
public int aggregate(Map<BackPointerPath<T, A, Integer>, Integer> nodes);
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/gbf/GeneralBestFirstEvaluationOrSelector.java
|
package ai.libs.jaicore.search.algorithms.standard.gbf;
import java.util.List;
import java.util.Map;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public interface GeneralBestFirstEvaluationOrSelector<T, A> {
public List<BackPointerPath<T, A, Integer>> getSuccessorRanking(Map<BackPointerPath<T, A, Integer>, Integer> nodes);
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/gbf/SolutionEventBus.java
|
package ai.libs.jaicore.search.algorithms.standard.gbf;
import com.google.common.eventbus.EventBus;
public class SolutionEventBus<T> extends EventBus {
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/lds/BestFirstLimitedDiscrepancySearch.java
|
package ai.libs.jaicore.search.algorithms.standard.lds;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.events.result.ISolutionCandidateFoundEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.ILabeledPath;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import ai.libs.jaicore.basic.algorithm.ASolutionCandidateFoundEvent;
import ai.libs.jaicore.basic.algorithm.AlgorithmFinishedEvent;
import ai.libs.jaicore.basic.algorithm.AlgorithmInitializedEvent;
import ai.libs.jaicore.basic.algorithm.EAlgorithmState;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.StandardBestFirst;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.SuccessorComputationCompletedEvent;
import ai.libs.jaicore.search.core.interfaces.AOptimalPathInORGraphSearch;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNodeRecommenderInput;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
/**
* This class conducts a limited discrepancy search by running a best first algorithm with list-based node evaluations.
* Since the f-values are lists too, we do not simply extend BestFirst but rather forward all commands to it.
*
* @author fmohr
*
* @param <T>
* @param <A>
* @param <V>
*/
public class BestFirstLimitedDiscrepancySearch<I extends GraphSearchWithNodeRecommenderInput<T, A>, T, A, V extends Comparable<V>> extends AOptimalPathInORGraphSearch<I, T, A, V> {
private Logger logger = LoggerFactory.getLogger(BestFirstLimitedDiscrepancySearch.class);
private String loggerName;
private final StandardBestFirst<T, A, NodeOrderList> bestFirst;
private class OrderListNumberComputer implements IPathEvaluator<T, A, NodeOrderList> {
private final Comparator<T> heuristic;
private final Map<BackPointerPath<T, A, ?>, List<T>> childOrdering = new HashMap<>();
public OrderListNumberComputer(final Comparator<T> heuristic) {
super();
this.heuristic = heuristic;
}
@Override
public NodeOrderList evaluate(final ILabeledPath<T, A> node) {
NodeOrderList list = new NodeOrderList();
BackPointerPath<T, A, ?> parent = ((BackPointerPath<T, A, ?>)node).getParent();
if (parent == null) {
return list;
}
/* add the label sequence of the parent to this node*/
list.addAll((NodeOrderList) parent.getScore());
list.add(this.childOrdering.get(parent).indexOf(node.getHead()));
return list;
}
@Subscribe
public void receiveSuccessorsCreatedEvent(final SuccessorComputationCompletedEvent<T, A, ?> successorDescriptions) {
List<T> successors = successorDescriptions.getSuccessorDescriptions().stream().map(INewNodeDescription::getTo).sorted(this.heuristic).collect(Collectors.toList());
this.childOrdering.put(successorDescriptions.getNode(), successors);
}
}
public BestFirstLimitedDiscrepancySearch(final I problem) {
super(problem);
OrderListNumberComputer nodeEvaluator = new OrderListNumberComputer(problem.getRecommender());
this.bestFirst = new StandardBestFirst<>(new GraphSearchWithSubpathEvaluationsInput<>(problem, nodeEvaluator));
this.bestFirst.registerListener(nodeEvaluator);
}
@Override
public void cancel() {
super.cancel();
this.bestFirst.cancel();
}
@Override
public void registerListener(final Object listener) {
this.bestFirst.registerListener(listener);
}
@Override
public void setNumCPUs(final int numberOfCPUs) {
super.setNumCPUs(numberOfCPUs);
this.bestFirst.setNumCPUs(numberOfCPUs);
}
@Override
public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
this.checkAndConductTermination();
if (this.getState().equals(EAlgorithmState.CREATED)) {
this.bestFirst.setTimeout(this.getTimeout());
return this.activate();
}
IAlgorithmEvent e = this.bestFirst.nextWithException();
if (e instanceof AlgorithmInitializedEvent) {
return this.nextWithException();
} else if (e instanceof AlgorithmFinishedEvent) {
return this.terminate();
} else if (e instanceof ISolutionCandidateFoundEvent) {
@SuppressWarnings({ "unchecked", "rawtypes" })
EvaluatedSearchGraphPath<T, A, NodeOrderList> solution = (EvaluatedSearchGraphPath<T, A, NodeOrderList>) ((ISolutionCandidateFoundEvent) e).getSolutionCandidate();
EvaluatedSearchGraphPath<T, A, V> modifiedSolution = new EvaluatedSearchGraphPath<>(solution.getNodes(), solution.getArcs(), null);
return new ASolutionCandidateFoundEvent<>(this, modifiedSolution);
} else {
return e;
}
}
@Override
public String getLoggerName() {
return this.loggerName;
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switching logger from {} to {}", this.logger.getName(), name);
this.loggerName = name;
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Activated logger {} with name {}", name, this.logger.getName());
if (this.bestFirst instanceof ILoggingCustomizable) {
this.bestFirst.setLoggerName(name + ".bestfirst");
}
super.setLoggerName(this.loggerName + "._orgraphsearch");
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/lds/BestFirstLimitedDiscrepancySearchFactory.java
|
package ai.libs.jaicore.search.algorithms.standard.lds;
import ai.libs.jaicore.search.core.interfaces.StandardORGraphSearchFactory;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNodeRecommenderInput;
public class BestFirstLimitedDiscrepancySearchFactory<I extends GraphSearchWithNodeRecommenderInput<N, A>, N, A, V extends Comparable<V>>
extends StandardORGraphSearchFactory<I, EvaluatedSearchGraphPath<N, A, V>, N, A, V, BestFirstLimitedDiscrepancySearch<I, N, A, V>> {
@Override
public BestFirstLimitedDiscrepancySearch<I, N, A, V> getAlgorithm() {
if (this.getInput() == null) {
throw new IllegalArgumentException("Cannot create algorithm; problem input has not been set yet");
}
return this.getAlgorithm(this.getInput());
}
@Override
public BestFirstLimitedDiscrepancySearch<I, N, A, V> getAlgorithm(final I input) {
return new BestFirstLimitedDiscrepancySearch<>(input);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/lds/LimitedDiscrepancySearch.java
|
package ai.libs.jaicore.search.algorithms.standard.lds;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.datastructure.graph.ILabeledPath;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.algorithm.ASolutionCandidateFoundEvent;
import ai.libs.jaicore.graph.TreeNode;
import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent;
import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent;
import ai.libs.jaicore.search.core.interfaces.AOptimalPathInORGraphSearch;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNodeRecommenderInput;
/**
* Implementation of the algorithm presented in
*
* @inproceedings{harvey1995, title={Limited discrepancy search}, author={Harvey, William D and Ginsberg, Matthew L}, booktitle={IJCAI (1)}, pages={607--615}, year={1995} }
*
* @author fmohr
*
*/
public class LimitedDiscrepancySearch<I extends GraphSearchWithNodeRecommenderInput<N, A>, N, A, V extends Comparable<V>> extends AOptimalPathInORGraphSearch<I, N, A, V> {
/* logging */
private Logger logger = LoggerFactory.getLogger(LimitedDiscrepancySearch.class);
private String loggerName;
/* communication */
protected TreeNode<N> traversalTree;
protected Map<N, A> actionToNode = new HashMap<>();
protected Collection<TreeNode<N>> expanded = new HashSet<>();
protected Collection<TreeNode<N>> exhausted = new HashSet<>();
/* graph construction helpers */
protected final ISingleRootGenerator<N> rootGenerator;
protected final ISuccessorGenerator<N, A> successorGenerator;
protected final IPathGoalTester<N, A> pathGoalTester;
/* graph traversal helpers */
protected final Comparator<N> heuristic;
/* algorithm state */
private int maxK = 0;
private int currentK = 0;
public LimitedDiscrepancySearch(final I problemInput) {
super(problemInput);
this.rootGenerator = (ISingleRootGenerator<N>) this.getInput().getGraphGenerator().getRootGenerator();
this.successorGenerator = this.getInput().getGraphGenerator().getSuccessorGenerator();
this.pathGoalTester = this.getInput().getGoalTester();
this.heuristic = problemInput.getRecommender();
}
@Override
public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmTimeoutedException, AlgorithmExecutionCanceledException, AlgorithmException {
this.registerActiveThread();
try {
switch (this.getState()) {
case CREATED:
this.traversalTree = this.newNode(null, this.rootGenerator.getRoot());
this.post(new GraphInitializedEvent<>(this, this.traversalTree));
return this.activate();
case ACTIVE:
this.currentK = this.maxK;
IAlgorithmEvent event = this.ldsProbe(this.traversalTree);
if (event instanceof NoMoreNodesOnLevelEvent) {
if (this.currentK == 0) { // if all deviations have been used, increase number of maximum deviations
this.logger.info("Probe process has no more nodes to be considered, restarting with augmented k {}", this.maxK + 1);
this.maxK++;
return event;
}
else {
return this.terminate(); // otherwise, terminate (allowing for more deviations will not yield more results)
}
} else {
this.logger.info("Returning event {}", event);
this.post(event);
return event;
}
default:
throw new IllegalStateException("The algorithm cannot do anything in state " + this.getState());
}
}
finally {
this.unregisterActiveThread();
}
}
private void updateExhaustMap(final TreeNode<N> node) {
if (node == null) {
return;
}
if (this.exhausted.contains(node)) {
this.updateExhaustMap(node.getParent());
}
if (this.exhausted.containsAll(node.getChildren())) {
this.exhausted.add(node);
this.updateExhaustMap(node.getParent());
}
}
/**
* Computes a solution path that deviates k times from the heuristic (if possible)
*
* @param node
* @param k
* @return
* @throws InterruptedException
* @throws AlgorithmExecutionCanceledException
* @throws AlgorithmTimeoutedException
* @throws AlgorithmException
*/
private IAlgorithmEvent ldsProbe(final TreeNode<N> node) throws InterruptedException, AlgorithmTimeoutedException, AlgorithmExecutionCanceledException, AlgorithmException {
this.logger.debug("Probing under node {} with k = {}. Exhausted: {}", node.getValue(), this.currentK, this.exhausted.contains(node));
/* return solution event if this is a solution node */
if (this.pathGoalTester.isGoal(this.getPathForGoalCheck(node.getValue()))) {
this.updateExhaustMap(node);
List<N> path = node.getValuesOnPathFromRoot();
List<A> actions = path.stream().map(n -> this.actionToNode.get(n)).filter(Objects::nonNull).collect(Collectors.toList());
EvaluatedSearchGraphPath<N, A, V> solution = new EvaluatedSearchGraphPath<>(path, actions, null);
this.updateBestSeenSolution(solution);
this.logger.debug("Found solution {}.", node.getValue());
return new ASolutionCandidateFoundEvent<>(this, solution);
}
/* if this node has not been expanded, compute successors and the priorities among them and attach them to search graph */
if (!this.expanded.contains(node)) {
this.expanded.add(node);
this.logger.debug("Starting successor generation of {}", node.getValue());
long start = System.currentTimeMillis();
Collection<INewNodeDescription<N, A>> succ = this.computeTimeoutAware(() -> this.successorGenerator.generateSuccessors(node.getValue()), "Successor generation" , true);
if (succ == null || succ.isEmpty()) {
this.logger.debug("No successors were generated.");
return new NoMoreNodesOnLevelEvent(this);
}
this.logger.debug("Computed {} successors in {}ms. Attaching the nodes to the local model.", succ.size(), System.currentTimeMillis() - start);
List<INewNodeDescription<N, A>> prioSucc = succ.stream().sorted((d1, d2) -> this.heuristic.compare(d1.getTo(), d2.getTo())).collect(Collectors.toList());
this.checkAndConductTermination();
List<TreeNode<N>> generatedNodes = new ArrayList<>();
long lastCheck = System.currentTimeMillis();
for (INewNodeDescription<N, A> successorDescription : prioSucc) {
if (System.currentTimeMillis() - lastCheck > 10) {
this.checkAndConductTermination();
lastCheck = System.currentTimeMillis();
}
TreeNode<N> newNode = this.newNode(node, successorDescription.getTo());
this.actionToNode.put(successorDescription.getTo(), successorDescription.getArcLabel());
generatedNodes.add(newNode);
}
this.logger.debug("Local model updated.");
this.checkAndConductTermination();
} else {
this.logger.info("Not expanding node {} again.", node.getValue());
}
List<TreeNode<N>> children = node.getChildren();
if (children.isEmpty()) {
return new NoMoreNodesOnLevelEvent(this);
}
/* if no deviation is allowed, return the probe for the first child (unless that child is already exhausted) */
if (this.currentK == 0 || children.size() == 1) {
boolean onlyAdmissibleChildExhausted = this.exhausted.contains(children.get(0));
this.logger.debug("No deviation allowed or only one child node. Probing this child (if not, the reason is that it is exhausted already): {}", !onlyAdmissibleChildExhausted);
return !onlyAdmissibleChildExhausted ? this.ldsProbe(children.get(0)) : new NoMoreNodesOnLevelEvent(this);
}
/* deviate from the heuristic. If no more discrepancies are allowed, keep searching under the first child unless that child has been exhausted */
this.currentK--;
this.logger.debug("Deviating from heuristic. Decreased current k to {}", this.currentK);
if (this.exhausted.contains(children.get(1))) {
return new NoMoreNodesOnLevelEvent(this);
}
return this.ldsProbe(children.get(1));
}
protected synchronized TreeNode<N> newNode(final TreeNode<N> parent, final N newNode) {
/* attach new node to traversal tree */
TreeNode<N> newTree = parent != null ? parent.addChild(newNode) : new TreeNode<>(newNode);
/* send events for this new node */
if (parent != null) {
boolean isGoal = this.pathGoalTester.isGoal(this.getPathForGoalCheck(newNode));
this.post(new NodeAddedEvent<TreeNode<N>>(this, parent, newTree, "or_" + (isGoal ? "solution" : "created")));
}
return newTree;
}
private ILabeledPath<N, A> getPathForGoalCheck(final N node) {
return new BackPointerPath<>(null, node, null);
}
@Override
public String getLoggerName() {
return this.loggerName;
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switching logger from {} to {}", this.logger.getName(), name);
this.loggerName = name;
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Activated logger {} with name {}", name, this.logger.getName());
super.setLoggerName(this.loggerName + "._orgraphsearch");
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/lds/LimitedDiscrepancySearchFactory.java
|
package ai.libs.jaicore.search.algorithms.standard.lds;
import ai.libs.jaicore.search.core.interfaces.StandardORGraphSearchFactory;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNodeRecommenderInput;
public class LimitedDiscrepancySearchFactory<I extends GraphSearchWithNodeRecommenderInput<N, A>, N, A, V extends Comparable<V>>
extends StandardORGraphSearchFactory<I, EvaluatedSearchGraphPath<N, A, V>, N, A, V, LimitedDiscrepancySearch<I, N, A, V>> {
@Override
public LimitedDiscrepancySearch<I, N, A, V> getAlgorithm() {
if (this.getInput() == null) {
throw new IllegalArgumentException("Cannot create algorithm; problem input has not been set yet");
}
return this.getAlgorithm(this.getInput());
}
@Override
public LimitedDiscrepancySearch<I, N, A, V> getAlgorithm(final I input) {
return new LimitedDiscrepancySearch<>(input);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/lds/NoMoreNodesOnLevelEvent.java
|
package ai.libs.jaicore.search.algorithms.standard.lds;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
public class NoMoreNodesOnLevelEvent extends AAlgorithmEvent {
public NoMoreNodesOnLevelEvent(final IAlgorithm<?, ?> algorithm) {
super(algorithm);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/lds/NodeOrderList.java
|
package ai.libs.jaicore.search.algorithms.standard.lds;
import java.util.ArrayList;
@SuppressWarnings("serial")
public class NodeOrderList extends ArrayList<Integer> implements Comparable<NodeOrderList> {
@Override
public int compareTo(final NodeOrderList o) {
if (o == null) {
return 1;
}
/* first just count the number of deviations */
int thisDeviations = this.stream().mapToInt(x -> x).sum();
int otherDeviations = o.stream().mapToInt(x -> x).sum();
if (thisDeviations != otherDeviations) {
return thisDeviations - otherDeviations;
}
/* if we come here, the number of deviations for the two nodes is the same. Then take the one with the highest unique deviation */
int nThis = this.size();
for (int i = 0; i < nThis; i++) {
if (!this.get(i).equals(o.get(i))) {
return o.get(i).compareTo(this.get(i));
}
}
return 0;
}
@Override
public boolean equals(final Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/mcts/MCTSPathSearch.java
|
package ai.libs.jaicore.search.algorithms.standard.mcts;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.events.result.ISolutionCandidateFoundEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.event.IEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import ai.libs.jaicore.basic.algorithm.AlgorithmFinishedEvent;
import ai.libs.jaicore.basic.algorithm.AlgorithmInitializedEvent;
import ai.libs.jaicore.basic.algorithm.EAlgorithmState;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.search.algorithms.mdp.mcts.GraphBasedMDP;
import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS;
import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory;
import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSIterationCompletedEvent;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent;
import ai.libs.jaicore.search.core.interfaces.AOptimalPathInORGraphSearch;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.probleminputs.IMDP;
/**
*
* @author Felix Mohr
*
* @param <I>
* Problem type
* @param <N>
* Type of states (nodes)
* @param <A>
* Type of actions
*/
public class MCTSPathSearch<I extends IPathSearchWithPathEvaluationsInput<N, A, Double>, N, A> extends AOptimalPathInORGraphSearch<I, N, A, Double> {
private Logger logger = LoggerFactory.getLogger(MCTSPathSearch.class);
private final GraphBasedMDP<N, A> mdp;
private final MCTS<N, A> mcts;
private final Set<Integer> hashCodesOfReturnedPaths = new HashSet<>();
public MCTSPathSearch(final I problem, final MCTSFactory<N, A, ?> mctsFactory) {
super(problem);
this.mdp = new GraphBasedMDP<>(problem);
this.mcts = mctsFactory.getAlgorithm(this.mdp);
this.mcts.registerListener(new Object() {
@Subscribe
public void receiveMCTSEvent(final IAlgorithmEvent e) {
if (!(e instanceof AlgorithmInitializedEvent) && !(e instanceof AlgorithmFinishedEvent)) {
MCTSPathSearch.this.post(e); // forward everything
}
}
});
}
@Override
public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
switch (this.getState()) {
case CREATED:
/* initialize MCTS */
this.mdp.setLoggerName(this.getLoggerName() + ".mdp");
IEvent mctsInitEvent;
do {
mctsInitEvent = this.mcts.next();
} while (!(mctsInitEvent instanceof AlgorithmInitializedEvent));
return this.activate();
case ACTIVE:
/* if MCTS has finished, terminate */
if (this.mcts.getState() != EAlgorithmState.ACTIVE) {
return this.terminate();
}
/* keep asking for playouts until a playout is returned that is a solution path */
IAlgorithmEvent e;
while (!((e = this.mcts.nextWithException()) instanceof AlgorithmFinishedEvent)) {
/* if this is not an event that declares the completion of an iteration, ignore it */
if (!(e instanceof MCTSIterationCompletedEvent)) {
continue;
}
/* form a path object and return a respective event */
MCTSIterationCompletedEvent<N, A, Double> ce = (MCTSIterationCompletedEvent<N, A, Double>) e;
double overallScore = SetUtil.sum(ce.getScores());
this.logger.info("Registered rollout with score {}. Updating best seen solution correspondingly.", overallScore);
EvaluatedSearchGraphPath<N, A, Double> path = new EvaluatedSearchGraphPath<>(ce.getRollout(), overallScore);
/* only if the roll-out is a goal path, emit a success event */
if (this.getGoalTester().isGoal(path)) {
this.updateBestSeenSolution(path);
int hashCode = path.hashCode();
if (this.hashCodesOfReturnedPaths.contains(hashCode)) {
this.logger.info("Skipping (and supressing) previously found solution with hash code {}", hashCode);
continue;
}
this.hashCodesOfReturnedPaths.add(hashCode);
ISolutionCandidateFoundEvent<EvaluatedSearchGraphPath<N, A, Double>> event = new EvaluatedSearchSolutionCandidateFoundEvent<>(this, path);
this.post(event);
return event;
}
}
return this.terminate();
default:
throw new IllegalStateException();
}
}
@Override
public void setTimeout(final Timeout to) {
long toInSeconds = to.seconds();
if (toInSeconds < 2) {
throw new IllegalArgumentException("Cannot run MCTS with a timeout of less than 2 seconds.");
}
super.setTimeout(to);
this.mcts.setTimeout(new Timeout(to.seconds() - 1, TimeUnit.SECONDS));
}
@Override
public void cancel() {
super.cancel();
this.mcts.cancel(); // forwarding cancel
}
@Override
public void setLoggerName(final String name) {
super.setLoggerName(name + "._algorithm");
this.logger = LoggerFactory.getLogger(name);
this.mcts.setLoggerName(name + ".mcts");
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
public IMDP<N, A, Double> getMdp() {
return this.mdp;
}
public MCTS<N, A> getMcts() {
return this.mcts;
}
public int getNumberOfNodesInMemory() {
return this.mcts.getNumberOfNodesInMemory();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/mcts/MCTSPathSearchFactory.java
|
package ai.libs.jaicore.search.algorithms.standard.mcts;
import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearchFactory;
import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput;
import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
/**
*
* @author Felix Mohr
*
* @param <N> Type of states (nodes)
* @param <A> Type of actions
*/
public class MCTSPathSearchFactory<N, A>
implements IOptimalPathInORGraphSearchFactory<IPathSearchWithPathEvaluationsInput<N, A, Double>, EvaluatedSearchGraphPath<N, A, Double>, N, A, Double, MCTSPathSearch<IPathSearchWithPathEvaluationsInput<N, A, Double>, N, A>> {
private IPathSearchWithPathEvaluationsInput<N, A, Double> problem;
private MCTSFactory<N, A, ?> mctsFactory;
@Override
public MCTSPathSearch<IPathSearchWithPathEvaluationsInput<N, A, Double>, N, A> getAlgorithm() {
if (this.problem == null) {
throw new IllegalStateException("No problem has been defined.");
}
return this.getAlgorithm(this.problem);
}
@Override
public MCTSPathSearch<IPathSearchWithPathEvaluationsInput<N, A, Double>, N, A> getAlgorithm(final IPathSearchWithPathEvaluationsInput<N, A, Double> input) {
if (this.mctsFactory == null) {
throw new IllegalStateException("No MCTS factory has been set. Please set a factory prior to building the MCTS path search.");
}
return new MCTSPathSearch<>(input, this.mctsFactory);
}
public IPathSearchWithPathEvaluationsInput<N, A, Double> getProblem() {
return this.problem;
}
public MCTSPathSearchFactory<N, A> withProblem(final IPathSearchWithPathEvaluationsInput<N, A, Double> problem) {
this.problem = problem;
return this;
}
public MCTSFactory<N, A, ?> getMctsFactory() {
return this.mctsFactory;
}
public MCTSPathSearchFactory<N, A> withMCTSFactory(final MCTSFactory<N, A, ?> mctsFactory) {
this.mctsFactory = mctsFactory;
return this;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/opencollections/EnforcedExplorationOpenSelection.java
|
package ai.libs.jaicore.search.algorithms.standard.opencollections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.PriorityQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
/**
* This OPEN selection allows to enforce that the search is restricted to be searched under a given node
*
* @author fmohr
*
* @param <N>
* @param <V>
* @param <W>
*/
public class EnforcedExplorationOpenSelection<N, A, V extends Comparable<V>> extends PriorityQueue<BackPointerPath<N, A, V>> {
private static final Logger logger = LoggerFactory.getLogger(EnforcedExplorationOpenSelection.class);
private final Collection<BackPointerPath<N, A, V>> suspended = new ArrayList<>();
private BackPointerPath<N, A, V> temporaryRoot; // this is the node that is currently used as a root
/**
* Set the temporary root under which the search should explore.
* This means to decide for each node on OPEN or SUSPENDED again whether they are under the new temporary root
*
* @param temporaryRoot
*/
public void setTemporaryRoot(final BackPointerPath<N, A, V> temporaryRoot) {
int numItemsBefore = this.size() + this.suspended.size();
this.temporaryRoot = temporaryRoot;
Collection<BackPointerPath<N, A, V>> openAndSuspendedNodes = SetUtil.union(this.suspended, this);
this.suspended.clear();
this.clear();
for (BackPointerPath<N, A, V> n : openAndSuspendedNodes) {
BackPointerPath<N, A, V> current = n;
boolean isSuspsended = true;
while (current != null) {
if (current.equals(temporaryRoot)) {
isSuspsended = false;
break;
}
current = current.getParent();
}
if (isSuspsended) {
this.suspended.add(n);
} else {
this.add(n);
}
}
int numItemsAfter = this.size() + this.suspended.size();
assert numItemsAfter == numItemsBefore : "The total number of elements in OPEN/SUSPENDED has changed from " + numItemsBefore + " to " + numItemsAfter + " by setting the temporary root!";
}
public BackPointerPath<N, A, V> getTemporaryRoot() {
return this.temporaryRoot;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/random/RandomSearch.java
|
package ai.libs.jaicore.search.algorithms.standard.random;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.ILabeledPath;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.graph.Graph;
import ai.libs.jaicore.graph.LabeledGraph;
import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent;
import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent;
import ai.libs.jaicore.graphvisualizer.events.graph.NodeTypeSwitchEvent;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.GraphSearchSolutionCandidateFoundEvent;
import ai.libs.jaicore.search.algorithms.standard.random.exception.IllegalArgumentForPathExtensionException;
import ai.libs.jaicore.search.core.interfaces.AAnyPathInORGraphSearch;
import ai.libs.jaicore.search.model.ILazyRandomizableSuccessorGenerator;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
import ai.libs.jaicore.timing.TimedComputation;
/**
* This search randomly draws paths from the root. At every node, each successor is chosen with the same probability except if a priority predicate is defined. A priority predicate says whether or not a node lies on a path that has
* priority. A node only has priority until all successors that have priority are exhausted.
*
* @author fmohr
*
* @param <N>
* @param <A>
*/
public class RandomSearch<N, A> extends AAnyPathInORGraphSearch<IPathSearchInput<N, A>, SearchGraphPath<N, A>, N, A> implements ILoggingCustomizable {
/* logging */
private String loggerName;
private Logger logger = LoggerFactory.getLogger(RandomSearch.class);
private final ILabeledPath<N, A> root;
private final ISuccessorGenerator<N, A> gen;
private final boolean isRandomizableSingleNodeSuccessorGenerator;
private final IPathGoalTester<N, A> goalTester;
private final LabeledGraph<N, A> exploredGraph = new LabeledGraph<>();
private final Set<N> closed = new HashSet<>();
private final Predicate<N> priorityPredicate;
private final Set<N> prioritizedNodes = new HashSet<>();
private final Set<N> exhausted = new HashSet<>(); // the set of nodes of which all solution paths have been computed
private final Random random;
private final Map<N, Iterator<INewNodeDescription<N, A>>> successorGenerators = new HashMap<>();
private int iterations = 0;
public RandomSearch(final IPathSearchInput<N, A> problem) {
this(problem, 0);
}
public RandomSearch(final IPathSearchInput<N, A> problem, final int seed) {
this(problem, new Random(seed));
}
public RandomSearch(final IPathSearchInput<N, A> problem, final Random random) {
this(problem, null, random);
}
public RandomSearch(final IPathSearchInput<N, A> problem, final Predicate<N> priorityPredicate, final Random random) {
super(problem);
N rootNode = ((ISingleRootGenerator<N>) problem.getGraphGenerator().getRootGenerator()).getRoot();
this.gen = problem.getGraphGenerator().getSuccessorGenerator();
this.isRandomizableSingleNodeSuccessorGenerator = this.gen instanceof ILazyRandomizableSuccessorGenerator;
this.goalTester = problem.getGoalTester();
this.exploredGraph.addItem(rootNode);
this.root = new SearchGraphPath<>(rootNode);
this.random = random;
this.priorityPredicate = priorityPredicate;
}
/**
* This expansion either generates all successors of a node (if the successor generator function is not able to provide single successor) or only one new successor.
*
* The node is put on CLOSED once all successors have been generated.
*
* Note that the fact that a new successor is generated does not mean that the algorithm will choose the newly generated successor to be appended to the paths.
*
* @param node
* @throws InterruptedException
* @throws AlgorithmExecutionCanceledException
* @throws AlgorithmTimeoutedException
*/
private void expandPath(final ILabeledPath<N, A> path) throws InterruptedException, AlgorithmTimeoutedException, AlgorithmExecutionCanceledException {
synchronized (this.exploredGraph) {
assert this.exploredGraph.isGraphSane();
assert !this.goalTester.isGoal(path) : "Goal nodes cannot be expanded!";
N node = path.getHead();
assert this.exploredGraph.hasItem(node) : "Node that shall be expanded is not part of the graph: " + node;
assert !this.closed.contains(node);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Expanding next node with hash code {}", node.hashCode());
}
boolean closeNodeAfterwards = false;
if (this.isRandomizableSingleNodeSuccessorGenerator) {
/* generate the next successor */
this.logger.debug("Graph generator is lazy. Get iterator for node.");
Iterator<INewNodeDescription<N, A>> iterator = this.successorGenerators.computeIfAbsent(node, n -> ((ILazyRandomizableSuccessorGenerator<N, A>) this.gen).getIterativeGenerator(n, this.random));
if (!iterator.hasNext()) {
throw new IllegalArgumentForPathExtensionException(
"The path cannot be expanded since the head has no successors. However, it is also not marked as a goal node. Output of goal check is: " + this.goalTester.isGoal(path) + ".", path);
}
INewNodeDescription<N, A> successor = iterator.next();
assert this.exploredGraph.isGraphSane();
Objects.requireNonNull(successor, "Received null object as a successor");
assert this.exploredGraph.hasItem(node) : "Parent node of successor is not part of the explored graph.";
if (this.exploredGraph.getSuccessors(node).contains(successor.getTo())) {
throw new IllegalStateException("Single node generator has generated a known successor. Generating another candidate.");
}
assert !this.exploredGraph.hasItem(successor.getTo()) : "Successor " + successor.getTo() + " has been reached before. Predecessors of that node are: " + this.exploredGraph.getPredecessors(successor.getTo());
this.addNodeToLocalModel(path, successor.getTo(), successor.getArcLabel());
/* if this was the last successor, set the close node flag to 1 */
closeNodeAfterwards = !iterator.hasNext();
if (closeNodeAfterwards) {
this.successorGenerators.remove(node);
}
}
/* if the successor generator cannot produce random sequences of successors, generate all successors and draw randomly from them */
else {
Timeout toForSuccessorComputation = new Timeout(this.getRemainingTimeToDeadline().milliseconds() - this.getTimeoutPrecautionOffset(), TimeUnit.MILLISECONDS);
this.logger.debug("Graph generator is not lazy or cannot cope with randomness. Computing all successors of node. Timeout is {}ms", toForSuccessorComputation.milliseconds());
long start = System.currentTimeMillis();
List<INewNodeDescription<N, A>> successors;
try {
successors = TimedComputation.compute(() -> this.gen.generateSuccessors(node), toForSuccessorComputation, "Successor computation in RandomSearch");
} catch (ExecutionException e) {
throw new RuntimeException(e);
} // could have been interrupted here
this.logger.debug("Identified {} successor(s) in {}ms, which are now appended.", successors.size(), System.currentTimeMillis() - start);
Collection<N> knownSuccessors = this.exploredGraph.getSuccessors(node);
long lastTerminationCheck = 0;
int addedSuccessors = 0;
for (INewNodeDescription<N, A> successor : successors) {
if (System.currentTimeMillis() - lastTerminationCheck > 100) {
this.checkAndConductTermination();
lastTerminationCheck = System.currentTimeMillis();
}
if (knownSuccessors.contains(successor.getTo())) {
this.logger.debug("Skipping successor {}, which is already part of the model.", successor.getTo());
} else {
this.addNodeToLocalModel(path, successor.getTo(), successor.getArcLabel());
addedSuccessors++;
}
}
this.logger.debug("{} nodes have been added to the local model. Now checking prioritization.", addedSuccessors);
/* if the node has successors but none of them is prioritized, remove the node from the priority list */
if (this.prioritizedNodes.contains(node) && SetUtil.intersection(this.exploredGraph.getSuccessors(node), this.prioritizedNodes).isEmpty()) {
this.prioritizedNodes.remove(node);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Removed node with code {} from set of prioritized nodes.", node.hashCode());
}
this.updateExhaustedAndPrioritizedState(node);
}
closeNodeAfterwards = true;
}
if (closeNodeAfterwards) {
/* if the node was not prioritized, change its state */
if (!this.prioritizedNodes.contains(node)) {
this.post(new NodeTypeSwitchEvent<N>(this, node, "or_closed"));
}
this.closed.add(node);
}
this.logger.debug("Finished node expansion. Sizes of explored graph and CLOSED are {} and {} respectively.", this.exploredGraph.getItems().size(), this.closed.size());
}
}
private SearchGraphPath<N, A> addNodeToLocalModel(final ILabeledPath<N, A> path, final N to, final A label) {
assert this.exploredGraph.isGraphSane();
N from = path.getHead();
assert from != null;
assert to != null;
if (this.exploredGraph.hasItem(to)) {
throw new IllegalArgumentException("Cannot add node " + to + " to local model, because it is already contained in it.\n\tThe most probable explanation for this exception is that the underlying graph is not a tree!");
}
assert this.exploredGraph.hasItem(from) : "The head " + from + " of the path with " + path.getNumberOfNodes() + " nodes is not part of the explored graph! Here is the path: \n\t"
+ path.getNodes().stream().map(Object::toString).collect(Collectors.joining("\n\t"));
this.exploredGraph.addItem(to);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Added node with hash code {} to graph.", to.hashCode());
}
assert this.exploredGraph.hasItem(to);
assert this.exploredGraph.isGraphSane();
boolean isPrioritized = this.priorityPredicate != null && this.priorityPredicate.test(to);
if (isPrioritized) {
this.prioritizedNodes.add(to);
}
this.exploredGraph.addEdge(from, to, label);
SearchGraphPath<N, A> extendedPath = new SearchGraphPath<>(path, to, label);
boolean isGoalNode = this.goalTester.isGoal(extendedPath);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Added node {} as a successor of {} with edge label {} to the model. Contained in prioritized: {}", to.hashCode(), from.hashCode(), label, this.prioritizedNodes.contains(to));
}
this.post(new NodeAddedEvent<>(this, from, to, isGoalNode ? "or_solution" : (isPrioritized ? "or_prioritized" : "or_open")));
return extendedPath;
}
@Override
public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
try {
this.registerActiveThread();
this.logger.debug("Starting next algorithm step.");
assert this.exploredGraph.isGraphSane();
switch (this.getState()) {
case CREATED:
this.post(new GraphInitializedEvent<>(this, this.root));
this.logger.info("Starting random search ...");
assert this.exploredGraph.isGraphSane();
return this.activate();
case ACTIVE:
/* if the root is exhausted, cancel */
this.iterations++;
SearchGraphPath<N, A> drawnPath = null;
drawnPath = this.nextSolutionUnderSubPath(this.root);
if (drawnPath == null) {
this.logger.info("Drew NULL path, terminating");
return this.terminate();
}
assert !drawnPath.getNodes().isEmpty() && this.goalTester.isGoal(drawnPath) : "The drawn path is empty or its leaf node is not a goal!";
this.logger.info("Drew path of length {}. Posting this event. For more details on the path, enable TRACE", drawnPath.getNodes().size());
this.logger.trace("The drawn path is {}", drawnPath);
IAlgorithmEvent event = new GraphSearchSolutionCandidateFoundEvent<>(this, drawnPath);
this.logger.info("Identified new solution. Event is {}", event);
this.post(event);
assert this.exploredGraph.isGraphSane();
return event;
default:
throw new IllegalStateException("Cannot do anything in state " + this.getState());
}
} catch (InterruptedException e) {
if (this.hasThreadBeenInterruptedDuringShutdown(Thread.currentThread())) {
this.checkTermination(false);
assert false : "The thread has been interrupted due to shutdown but apparently no stopping criterion is satisfied!";
throw new AlgorithmException("This part should never be reached!");
} else {
throw e;
}
} finally {
this.unregisterActiveThread();
}
}
public boolean knowsNode(final N node) {
synchronized (this.exploredGraph) {
return this.exploredGraph.getItems().contains(node);
}
}
public void appendPathToNode(final ILabeledPath<N, A> path) {
ILabeledPath<N, A> cPath = new SearchGraphPath<>(path.getRoot());
for (N node : path.getNodes()) {
if (!this.exploredGraph.getItems().contains(node)) {
cPath = this.addNodeToLocalModel(cPath, node, path.getInArc(node));
}
}
}
/**
* Returns a completion of the given path so that the whole path is a goal path. The given path is then a prefix of the returned path.
*
* @param path
* @return
* @throws InterruptedException
* @throws AlgorithmExecutionCanceledException
* @throws AlgorithmTimeoutedException
*/
public SearchGraphPath<N, A> nextSolutionUnderSubPath(final ILabeledPath<N, A> path) throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
if (this.logger.isInfoEnabled()) {
this.logger.info("Looking for next solution under node with hash code {}. Remaining time is {}. Enable TRACE for concrete node description.", path.getHead().hashCode(), this.getRemainingTimeToDeadline());
this.logger.trace("Description of node under which we search: {}", path.getHead());
}
this.checkAndConductTermination();
assert this.exploredGraph.isGraphSane();
/* if the root is exhausted, cancel */
if (this.exhausted.contains(path)) {
return null;
}
/* maintain two variables for prioritized search */
boolean hasCheckedWhetherPrioritizedPathExists = false;
boolean chasePrioritizedPath = false;
/* conduct a random walk from the root to a goal */
SearchGraphPath<N, A> cPath = new SearchGraphPath<>(path);
int origLength = cPath.getNumberOfNodes();
N head = cPath.getHead();
int triedStepbacks = 0;
synchronized (this.exploredGraph) {
while (!this.goalTester.isGoal(cPath)) {
this.checkAndConductTermination();
assert RandomSearchUtil.checkValidityOfPathCompletion(path, cPath) : "Completion has become invalid!";
assert this.checkThatNodeExistsInExploredGraph(head);
assert this.exploredGraph.isGraphSane();
/* expand node if this has not happened yet. */
if (!this.closed.contains(head)) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Current head {} has not been expanded yet, expanding it now.", head.hashCode());
}
this.expandPath(cPath);
}
/* get unexhausted successors */
List<N> successors = this.exploredGraph.getSuccessors(head).stream().filter(n -> !this.exhausted.contains(n)).collect(Collectors.toList());
assert this.exploredGraph.getSuccessors(head).stream().filter(n -> !this.exploredGraph.hasItem(n)).collect(Collectors.toList()).isEmpty() : "Corrupt exploration graph: Some successors cannot be found again in the graph: "
+ this.exploredGraph.getSuccessors(head).stream().filter(n -> !this.exploredGraph.hasItem(n)).collect(Collectors.toList());
/* if we are in a dead end, mark the node as exhausted and remove the head again */
if (successors.isEmpty()) {
this.logger.debug("Detected a dead-end in {}.", head);
this.exhausted.add(head);
this.prioritizedNodes.remove(head); // remove prioritized node from list if it is in
if (this.isExhausted()) {
this.logger.debug("The graph has been exhausted.");
return null;
}
if (head == path.getHead()) { // do not go above the given path
return null;
}
cPath = cPath.getPathToParentOfHead();
assert RandomSearchUtil.checkValidityOfPathCompletion(path, cPath) : "Completion has become invalid!";
head = cPath.getHead();
this.logger.debug("Reset head due to dead-end to parent. New head: {}.", head);
continue;
}
/* if at least one of the successors is prioritized, choose one of those; otherwise choose one at random */
assert SetUtil.intersection(this.exhausted, this.prioritizedNodes).isEmpty() : "There are nodes that are both exhausted and prioritized, which must not be the case:"
+ SetUtil.intersection(this.exhausted, this.prioritizedNodes).stream().map(n -> "\n\t" + n).collect(Collectors.joining());
Collection<N> prioritizedSuccessors = SetUtil.intersection(successors, this.prioritizedNodes);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Number of prioritized successors of node {} is {}", head.hashCode(), prioritizedSuccessors.size());
}
N lastHead = head;
if (!prioritizedSuccessors.isEmpty()) {
head = prioritizedSuccessors.iterator().next();
this.logger.debug("Following arc {} to prioritized node {}", this.exploredGraph.getEdgeLabel(lastHead, head), head);
/* we now know that there exist prioritizes paths. That means that we also want to chase them as long as possible */
if (!hasCheckedWhetherPrioritizedPathExists) {
hasCheckedWhetherPrioritizedPathExists = true;
chasePrioritizedPath = true;
}
}
/* otherwise, if there is no prioritized successors but there ARE prioritized nodes under this path, step back */
else if (chasePrioritizedPath) {
if (cPath.getNumberOfNodes() > origLength) {
this.logger.debug("The current head is not prioritized, but we know that there are prioritized nodes we could follow. Stepping back! Current head: {}", head);
cPath = cPath.getPathToParentOfHead();
head = cPath.getHead();
triedStepbacks++;
if (triedStepbacks > 50) {
chasePrioritizedPath = false;
}
continue;
} else {
this.logger.debug(
"The current head is not prioritized, and we throught that there should be more prioritized nodes. But we have reached the root and hence know that there are none. Hence, we change the flag and now follow unprioritized nodes!");
chasePrioritizedPath = false;
continue; // this will make the RandomSearch try the same node again (now not chasing prioritized nodes anymore)
}
}
else {
int n = successors.size();
assert n != 0 : "Ended up in a situation where only exhausted nodes can be chosen.";
int k = this.random.nextInt(n);
head = successors.get(k);
final N tmpHead = head; // needed for stream in assertion
assert !cPath.containsNode(head) : "Going in circles ... " + cPath.getNodes().stream().map(pn -> "\n\t[" + (pn.equals(tmpHead) ? "*" : " ") + "]" + pn.toString()).collect(Collectors.joining()) + "\n\t[*]" + head;
this.logger.trace("Selected {} as new head.", head);
assert this.checkThatNodeExistsInExploredGraph(head);
}
cPath.extend(head, this.exploredGraph.getEdgeLabel(lastHead, head));
}
}
assert RandomSearchUtil.checkValidityOfPathCompletion(path, cPath);
/* propagate exhausted state */
this.logger.trace("Head node {} has been exhausted.", head);
this.exhausted.add(head);
this.prioritizedNodes.remove(head);
this.updateExhaustedAndPrioritizedState(head);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Returning next solution path. Hash code is {}", cPath.hashCode());
}
if (cPath.getRoot() != path.getRoot()) {
throw new IllegalStateException("Root got lost over the path!");
}
return head == this.root ? null : cPath;
}
private boolean checkThatNodeExistsInExploredGraph(final N node) {
assert this.exploredGraph.hasItem(node) : "Head node of random path is not in explored graph: " + node;
return true;
}
/**
* This method goes from the given node up to the root and checks, for each node on this path, whether all of its children have been exhausted.
*
* @param node
*/
private void updateExhaustedAndPrioritizedState(final N node) {
synchronized (this.exploredGraph) {
N current = node;
Collection<N> predecessors;
while (!(predecessors = this.exploredGraph.getPredecessors(current)).isEmpty()) {
assert predecessors.size() == 1;
current = predecessors.iterator().next();
/* if the currently considered node is not even fully expanded, it is certainly not exhausted */
boolean currentIsCompletelyExpanded = !this.isRandomizableSingleNodeSuccessorGenerator || !this.successorGenerators.containsKey(current) || !this.successorGenerators.get(current).hasNext();
if (!currentIsCompletelyExpanded) {
this.logger.trace("Leaving update routine at node {}, which has not been expanded completely.", current);
return;
}
boolean currentIsPrioritized = this.prioritizedNodes.contains(current);
boolean allChildrenExhausted = true;
boolean allPrioritizedChildrenExhausted = true;
for (N successor : this.exploredGraph.getSuccessors(current)) {
if (!this.exhausted.contains(successor)) {
allChildrenExhausted = false;
if (currentIsPrioritized && this.prioritizedNodes.contains(successor)) {
allPrioritizedChildrenExhausted = false;
break;
} else if (!currentIsPrioritized) {
break;
}
}
}
if (allChildrenExhausted) {
this.logger.trace("Update state of {} as being exhausted since all its children have been exhausted.", current);
this.exhausted.add(current);
}
if (currentIsPrioritized && allPrioritizedChildrenExhausted) {
int sizeBefore = this.prioritizedNodes.size();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Removing node {} from set of prioritized nodes.", current.hashCode());
}
this.prioritizedNodes.remove(current);
this.post(new NodeTypeSwitchEvent<N>(this, current, "or_closed"));
int sizeAfter = this.prioritizedNodes.size();
assert sizeAfter == sizeBefore - 1;
}
}
}
}
public boolean isExhausted() {
return this.exhausted.contains(this.root.getHead());
}
public Graph<N> getExploredGraph() {
return this.exploredGraph;
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switch logger name from {} to {}", this.loggerName, name);
this.loggerName = name;
this.logger = LoggerFactory.getLogger(this.loggerName);
if (this.getGraphGenerator() instanceof ILoggingCustomizable) {
((ILoggingCustomizable) this.getGraphGenerator()).setLoggerName(name + ".graphgen");
}
this.logger.info("Switched logger name to {}", this.loggerName);
super.setLoggerName(this.loggerName + "._algorithm");
}
@Override
public String getLoggerName() {
return this.loggerName;
}
public Random getRandom() {
return this.random;
}
public int getIterations() {
return this.iterations;
}
public void setIterations(final int iterations) {
this.iterations = iterations;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/random/RandomSearchFactory.java
|
package ai.libs.jaicore.search.algorithms.standard.random;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import ai.libs.jaicore.search.core.interfaces.StandardORGraphSearchFactory;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
public class RandomSearchFactory<N, A> extends StandardORGraphSearchFactory<IPathSearchInput<N, A>, SearchGraphPath<N, A>,N, A, Double, RandomSearch<N, A>> {
private String loggerName;
private int seed;
public RandomSearchFactory() {
super();
}
@Override
public RandomSearch<N, A> getAlgorithm() {
if (this.getInput().getGraphGenerator() == null) {
throw new IllegalStateException("Cannot produce RandomSearch searches before the graph generator is set in the problem.");
}
return this.getAlgorithm(this.getInput());
}
@Override
public RandomSearch<N, A> getAlgorithm(final IPathSearchInput<N, A> input) {
return new RandomSearch<>(input, this.seed);
}
public int getSeed() {
return this.seed;
}
public void setSeed(final int seed) {
this.seed = seed;
}
public String getLoggerName() {
return this.loggerName;
}
public void setLoggerName(final String loggerName) {
this.loggerName = loggerName;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/random/RandomSearchUtil.java
|
package ai.libs.jaicore.search.algorithms.standard.random;
import java.util.List;
import org.api4.java.datastructure.graph.ILabeledPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RandomSearchUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(RandomSearchUtil.class);
private RandomSearchUtil() {
/* prevent instantiation */
}
public static <N, A> boolean checkValidityOfPathCompletion(final ILabeledPath<N, A> prefix, final ILabeledPath<N, A> completion) throws InterruptedException {
List<N> prefixNodes = prefix.getNodes();
List<A> prefixArcs = prefix.getArcs();
List<N> completionNodes = completion.getNodes();
List<A> completionArcs = completion.getArcs();
if (completionArcs.size() != completionNodes.size() - 1) {
LOGGER.error("Incorrect number of arcs!");
return false;
}
if (prefixArcs.size() != prefixNodes.size() - 1) {
LOGGER.error("Incorrect number of arcs!");
return false;
}
if (prefixNodes.size() > completionNodes.size()) {
LOGGER.error("Completion is shorter than prefix!");
return false;
}
int l = prefixNodes.size();
for (int i = 0; i < l; i++) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
if (prefixNodes.get(i) != completionNodes.get(i)) {
LOGGER.error("The {}-th node on the path does not match the respective node in the prefix:\n\tPath:\t{}\n\tPrefix:\t{}", i, completionNodes.get(i), prefixNodes.get(i));
return false;
}
if (i < l-1 && prefixArcs.get(i) != completionArcs.get(i)) {
LOGGER.error("The {}-th arc on the path does not match the respective arc in the prefix:\n\tPath:\t{}\n\tPrefix:\t{}", i, completionArcs.get(i), prefixArcs.get(i));
return false;
}
}
int n = completionNodes.size();
for (int i = l; i < n; i++) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
if (prefixNodes.contains(completionNodes.get(i))) {
LOGGER.error("A node contained in the completion (without prefix) must not also be contained in the prefix already. The following node is contained twice:\n\t{}", completionNodes.get(i));
return false;
}
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/random
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/random/exception/IllegalArgumentForPathExtensionException.java
|
package ai.libs.jaicore.search.algorithms.standard.random.exception;
import org.api4.java.datastructure.graph.ILabeledPath;
public class IllegalArgumentForPathExtensionException extends IllegalArgumentException {
private static final long serialVersionUID = -7700158497338421978L;
private final transient ILabeledPath<?, ?> path;
public IllegalArgumentForPathExtensionException(final String message, final ILabeledPath<?, ?> path) {
super(message);
this.path = path;
}
public ILabeledPath<?, ?> getPath() {
return this.path;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/rdfs/RandomizedDepthFirstSearch.java
|
package ai.libs.jaicore.search.algorithms.standard.rdfs;
import java.util.Random;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.StandardBestFirst;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation.RandomizedDepthFirstNodeEvaluator;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
public class RandomizedDepthFirstSearch<T, A> extends StandardBestFirst<T, A, Double> {
private Logger logger = LoggerFactory.getLogger(RandomizedDepthFirstSearch.class);
private String loggerName;
public RandomizedDepthFirstSearch(final IPathSearchInput<T, A> problem, final Random random) {
super(new GraphSearchWithSubpathEvaluationsInput<>(problem, new RandomizedDepthFirstNodeEvaluator<>(random)));
}
@Override
public String getLoggerName() {
return this.loggerName;
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switching logger from {} to {}", this.logger.getName(), name);
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Activated logger {} with name {}", name, this.logger.getName());
super.setLoggerName(this.loggerName + "._bestfirst");
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/rstar/GammaNode.java
|
package ai.libs.jaicore.search.algorithms.standard.rstar;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
/**
* Node wrapper for usage in R*.
*
* Every node is equipped with path to its backpointer i.e. parent, the g-value and
* the AVOID label.
*
* @author fischor, fmohr, mwever
*
* @param <T> problem state type
* @param <V> internal label type (in R* its RStarK)
*/
public class GammaNode<T, A> extends BackPointerPath<T, A, RStarK> {
private double g = Double.MAX_VALUE;
private boolean avoid = false;
/**
* List of all predecessors for this node.
* Initialized here and then filled throughout R* processes.
*/
private Collection<GammaNode<T, A>> predecessors = new ArrayList<>();
/**
* Maps from each successor s_ to the lowest cost for path(this, s_).
* This is either a heuristic estimate or the actual known lowest cost.
*/
protected HashMap<GammaNode<T, A>, Double> cLow = new HashMap<>();
/**
* Constructor.
* Ignores parent node because we use the backpointer attribute.
*
* @param point
*/
public GammaNode(final T point) {
super(null, point, null);
}
@Override
public GammaNode<T, A> getParent() {
return (GammaNode<T, A>) super.getParent();
}
/**
* Add a predecessor to this node.
* @param n The predecessor to be added.
* @return Returns true iff the predecessor could be added successfully.
*/
public boolean addPredecessor(final GammaNode<T, A> n) {
return this.predecessors.add(n);
}
/**
* @return The collection of all predecessors of this node.
*/
public Collection<GammaNode<T, A>> getPredecessors() {
return this.predecessors;
}
/**
* @return The value of g.
*/
public double getG() {
return this.g;
}
/**
* @param g The new value of g.
*/
public void setG(final double g) {
this.g = g;
}
/**
* @return The value of the avoid flag of this node.
*/
public boolean getAvoid() {
return this.avoid;
}
/**
* @param avoid The new value of the avoid flag of this node.
*/
public void setAvoid(final boolean avoid) {
this.avoid = avoid;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/rstar/GraphBasedDistantSuccessorGenerator.java
|
package ai.libs.jaicore.search.algorithms.standard.rstar;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.common.math.IMetric;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic.DistantSuccessorGenerator;
public class GraphBasedDistantSuccessorGenerator<N, A> implements DistantSuccessorGenerator<N>, ILoggingCustomizable {
private static final int MAX_ATTEMPTS = 10;
private final ISuccessorGenerator<N, A> succesorGenerator;
private final INodeGoalTester<N, A> goalTester;
private final Random random;
private Logger logger = LoggerFactory.getLogger(GraphBasedDistantSuccessorGenerator.class);
public GraphBasedDistantSuccessorGenerator(final IPathSearchInput<N, A> graphSearchInput, final int seed) {
super();
this.succesorGenerator = graphSearchInput.getGraphGenerator().getSuccessorGenerator();
this.goalTester = (INodeGoalTester<N, A>)graphSearchInput.getGoalTester();
this.random = new Random(seed);
}
@Override
public List<N> getDistantSuccessors(final N n, final int k, final IMetric<N> metricOverStates, final double delta) throws InterruptedException {
List<N> successorsInOriginalGraph = new ArrayList<>();
if (this.goalTester.isGoal(n)) {
return successorsInOriginalGraph;
}
for (int i = 0; i < MAX_ATTEMPTS && successorsInOriginalGraph.size() < k; i++) {
this.logger.debug("Drawing next distant successor for {}. {}/{} have already been drawn. This is the {}-th attempt.", n, successorsInOriginalGraph.size(), k, i + 1);
N candidatePoint = n;
/* detect potential dead end */
boolean deadEnd = false;
while (!this.goalTester.isGoal(candidatePoint) && metricOverStates.getDistance(n, candidatePoint) <= delta) {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Successor generation has been interrupted.");
}
assert !this.goalTester.isGoal(candidatePoint) : "Node must not be a goal node!";
List<INewNodeDescription<N, A>> localSuccessors = this.succesorGenerator.generateSuccessors(candidatePoint);
if (localSuccessors.isEmpty()) {
this.logger.warn("List of local successors is empty for node {}! This may be due to a dead-end in the search graph.", candidatePoint);
deadEnd = true;
break;
}
candidatePoint = localSuccessors.size() > 1 ? localSuccessors.get(this.random.nextInt(localSuccessors.size() - 1)).getTo() : localSuccessors.get(0).getTo();
this.logger.trace("Next node on path to distant successor is {}", candidatePoint);
}
if (deadEnd) {
this.logger.debug("Skipping this candidate, because it is a dead-end.");
continue;
}
/* check that we really have a node different from the one we expand here */
if (candidatePoint == n) {
if (this.goalTester.isGoal(candidatePoint)) {
throw new IllegalStateException("The last point is the point we want to extend. The reason is that this point is already a goal node.");
}
else if (metricOverStates.getDistance(n, candidatePoint) > delta) {
throw new IllegalStateException("The last point is the point we want to extend. The reason is that the chosen node had a two high delta " + metricOverStates.getDistance(n, candidatePoint) + ".");
}
else {
throw new IllegalStateException("The last point is the point we want to extend. The reason is unclear at this point.");
}
}
/* add the node if we don't have it yet */
if (!successorsInOriginalGraph.contains(candidatePoint)) {
successorsInOriginalGraph.add(candidatePoint);
}
}
this.logger.info("Returning {} successors.", successorsInOriginalGraph.size());
return successorsInOriginalGraph;
}
@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-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/rstar/RStar.java
|
package ai.libs.jaicore.search.algorithms.standard.rstar;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.events.result.ISolutionCandidateFoundEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.common.math.IMetric;
import org.api4.java.datastructure.graph.implicit.IRootGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.algorithm.AlgorithmInitializedEvent;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.search.algorithms.standard.astar.AStar;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.NodeExpansionCompletedEvent;
import ai.libs.jaicore.search.core.interfaces.AOptimalPathInORGraphSearch;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchInput;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNumberBasedAdditivePathEvaluation;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic.DistantSuccessorGenerator;
/**
* Implementation of the R* algorithm.
*
* @author fischor, fmohr, mwever
*
* @param <T> a nodes external label i.e. a state of a problem
* @param <A> action (action space of problem)
*/
public class RStar<I extends GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic<T, A>, T, A> extends AOptimalPathInORGraphSearch<I, T, A, Double> {
/* Open list. */
protected PriorityQueue<GammaNode<T, A>> open = new PriorityQueue<>((n1, n2) -> (n1.getScore().compareTo(n2.getScore())));
/* Closed list of already expanded states. */
protected ArrayList<GammaNode<T, A>> closed = new ArrayList<>();
private final IPathEvaluator<T, A, Double> h;
private final GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic.PathCostEstimator<T, A> hPath;
/* For actual search problem */
private final int k;
protected final double w;
private final double delta;
private final IMetric<T> metricOverStates;
private GammaNode<T, A> bestSeenGoalNode;
private final Map<Pair<GammaNode<T, A>, GammaNode<T, A>>, SearchGraphPath<T, A>> externalPathsBetweenGammaNodes = new HashMap<>(); // the pairs should always be in a parent-child relation
private List<ISolutionCandidateFoundEvent<EvaluatedSearchGraphPath<T, A, Double>>> unreturnedSolutionEvents = new LinkedList<>();
private Collection<AStar<T, A>> activeAStarSubroutines = new ArrayList<>();
private Logger logger = LoggerFactory.getLogger(RStar.class);
/**
*
* @param gammaGraphGenerator
* @param w
* @param k
* @param delta
*/
public RStar(final I problem, final double w, final int k, final double delta) {
super(problem);
this.h = ((GraphSearchWithNumberBasedAdditivePathEvaluation.FComputer<T, A>) this.getInput().getPathEvaluator()).getH();
this.hPath = ((GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic.SubPathEvaluationBasedFComputer<T, A>) this.getInput().getPathEvaluator()).gethPath();
this.w = w;
this.k = k;
this.metricOverStates = this.getInput().getMetricOverStates();
this.delta = delta;
}
/**
* Updates a state i.e. node n in the open list. Lines 1 - 5 in the paper.
*
* @param n
* @throws InterruptedException
* @throws PathEvaluationException
*/
private void updateState(final GammaNode<T, A> n) throws PathEvaluationException, InterruptedException {
if ((n.getG() > this.w * this.h.evaluate(n)) || ((n.getParent() == null || !this.isPathRealizationKnownForAbstractEdgeToNode(n)) && n.getAvoid())) {
n.setScore(new RStarK(true, n.getG() + this.w * this.h.evaluate(n)));
} else {
n.setScore(new RStarK(false, n.getG() + this.w * this.h.evaluate(n)));
}
}
/**
* Tries to compute the local path
* Lines 6 - 12 in the paper.
*
* @param n
* @throws InterruptedException
* @throws AlgorithmException
* @throws TimeoutException
* @throws AlgorithmExecutionCanceledException
*/
private void reevaluateState(final GammaNode<T, A> n) throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
/* Line 7: Try to compute the local path from bp(n) to n. (we use AStar for this) */
this.logger.debug("Reevaluating node {}", n);
if (n.getParent() == null) {
throw new IllegalArgumentException("Can only re-evaluate nodes that have a parent!");
}
IPathSearchInput<T, A> subProblem = new GraphSearchInput<>(new SubPathGraphGenerator<>(this.getInput().getGraphGenerator(), n.getParent().getHead()), c -> c.equals(n.getHead()));
AStar<T, A> astar = new AStar<>(new GraphSearchWithNumberBasedAdditivePathEvaluation<>(subProblem, (GraphSearchWithNumberBasedAdditivePathEvaluation.FComputer<T, A>) this.getInput().getPathEvaluator()));
astar.setLoggerName(this.getLoggerName() + ".astar");
astar.setTimeout(new Timeout(this.getRemainingTimeToDeadline().milliseconds(), TimeUnit.MILLISECONDS));
this.logger.trace("Invoking AStar with root {} and only goal node {}", n.getParent().getHead(), n.getHead());
this.activeAStarSubroutines.add(astar);
EvaluatedSearchGraphPath<T, A, Double> optimalPath = astar.call();
this.checkAndConductTermination();
this.activeAStarSubroutines.remove(astar);
this.externalPathsBetweenGammaNodes.put(new Pair<>(n.getParent(), n), optimalPath);
double bestKnownValueFromParentToNode = optimalPath != null ? optimalPath.getScore() : Double.MAX_VALUE;
n.getParent().cLow.put(n, bestKnownValueFromParentToNode);
/**
* If no path bp(n)->n could be computed or
* the g = "cost from n_start to bp(n)" + the cost of the found path is greater than w*h(n_start, n)
* the state n should be avoided.
*/
// Line 8
if (!n.isGoal() && (optimalPath == null || (n.getParent().getG() + bestKnownValueFromParentToNode > this.w * this.hPath.h(n.getParent(), n)))) {
n.setParent(this.argminCostToStateOverPredecessors(n));
n.setAvoid(true);
}
n.setG(n.getParent().getG() + n.getParent().cLow.get(n));
if (!n.isGoal()) {
try {
this.updateState(n);
} catch (PathEvaluationException e) {
throw new AlgorithmException("Failed due to path evaluation failure.", e);
}
}
}
@Override
public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
try {
this.registerActiveThread();
this.logger.debug("Performing next step. Current state is {}", this.getState());
this.checkAndConductTermination();
switch (this.getState()) {
case CREATED:
AlgorithmInitializedEvent initializationEvent = this.activate();
/* Lines 14 to 17 */
IRootGenerator<T> rootGenerator = this.getInput().getGraphGenerator().getRootGenerator();
for (T root : rootGenerator.getRoots()) {
GammaNode<T, A> internalRoot = new GammaNode<>(root);
internalRoot.setScore(new RStarK(false, this.w * this.h.evaluate(internalRoot)));
internalRoot.setG(0);
this.open.add(internalRoot);
}
assert !this.open.isEmpty() : "OPEN must not be empty after initialization!";
return initializationEvent;
case ACTIVE:
/* return unreturned solutions if such exist */
if (!this.unreturnedSolutionEvents.isEmpty()) {
this.logger.info("Returning known solution from solution cache!");
return this.unreturnedSolutionEvents.remove(0);
}
/**
* Run while the open list is not empty and there exists a node in the open list
* with higher priority i.e. less k than k_n_goal (if the highest priority is a
* goal node, then we return in th next lines).
*/
// Lines 18 & 19
GammaNode<T, A> n = this.open.poll();
this.logger.debug("Selected {} for expansion.", n);
if (n == null || (this.bestSeenGoalNode != null && n.getScore().compareTo(this.bestSeenGoalNode.getScore()) > 0)) {
this.logger.info("Terminating RStar.");
return this.terminate();
}
// Lines 20 & 21
if (n.getParent() != null && !this.isPathRealizationKnownForAbstractEdgeToNode(n)) {
/*
* The path that corresponds to the edge bp(s)->s has not been computed yet. Try
* to compute it using reevaluateState.
*/
this.reevaluateState(n);
/* put the node on OPEN again */
this.logger.debug("Putting node {} on OPEN again", n);
this.open.add(n);
} else { // The path from bp(s)->s has already been computed.
// Line 23.
this.closed.add(n);
/* Line 24 to 27: Compute successors */
this.logger.debug("Starting generation of successors of {}", n);
Collection<GammaNode<T, A>> successors = this.generateGammaSuccessors(n);
this.logger.debug("Generated {} successors.", successors.size());
for (GammaNode<T, A> n_ : successors) { // Line 28
/*
* Line 29: Initialize successors by setting the path from s to s_ to null, and
* by estimating the lowest cost from s to s_ with the heuristic h(s, s_).
*/
n.cLow.put(n_, this.hPath.h(n, n_));
/*
* Lines 30 and 31 of the algorithm can be omitted here. They contain further
* initialization of the successors, but This is done implicitly in the
* generation process of the Gamma successors.
*/
/*
* If the generated successor n_ i.e. s_ has never been visited yet
* (n_.getParent() == null) or the actual cost to s (n.g) plus the (estimated)
* cost from s to s_ (c_low(s, s_)) is better than the actual known cost (n_.g)
* to s_, then we have to update these values for s_ (because with s we found a
* better predecessor for s_).
*/
// Line 32
boolean isNewNode = n_.getParent() == null;
if (isNewNode || (n.getG() + n.cLow.get(n_) < n_.getG())) {
n_.setG(n.getG() + n.cLow.get(n_));
n_.setParent(n);
this.updateState(n_); // updates priority of n_ in open list.
if (isNewNode) {
this.logger.debug("Adding new node {} to OPEN.", n_);
this.open.add(n_);
}
}
}
}
return new NodeExpansionCompletedEvent<>(this, n.getHead());
default:
throw new IllegalStateException("Cannot do anything in state " + this.getState());
}
} catch (PathEvaluationException e) {
throw new AlgorithmException("Failed due to path evaluation failure.", e);
} finally {
this.unregisterActiveThread();
}
}
private boolean isPathRealizationKnownForAbstractEdgeToNode(final GammaNode<T, A> node) {
return this.externalPathsBetweenGammaNodes.containsKey(new Pair<>(node.getParent(), node));
}
/**
* Calculates the path in the original graph that corresponds to the reduced
* gamma graph using the established path witnesses.
*
* @param n
* @return
*/
private EvaluatedSearchGraphPath<T, A, Double> getFullExternalPath(final GammaNode<T, A> n) {
List<T> nodes = new ArrayList<>();
List<A> edges = new ArrayList<>();
GammaNode<T, A> current = n;
nodes.add(n.getHead());
while (current.getParent() != null) {
Pair<GammaNode<T, A>, GammaNode<T, A>> pair = new Pair<>(current.getParent(), current);
assert this.externalPathsBetweenGammaNodes.containsKey(pair);
SearchGraphPath<T, A> externalPath = this.externalPathsBetweenGammaNodes.get(pair);
nodes.addAll(0, externalPath.getNodes());
List<A> concreteEdges = externalPath.getArcs();
if (concreteEdges == null) {
concreteEdges = new ArrayList<>();
int m = externalPath.getNodes().size();
for (int i = 0; i < m; i++) {
concreteEdges.add(null);
}
}
edges.addAll(0, concreteEdges);
current = current.getParent();
}
return new EvaluatedSearchGraphPath<>(nodes, edges, n.getG());
}
/**
*
* @param n
* @return
*/
private GammaNode<T, A> argminCostToStateOverPredecessors(final GammaNode<T, A> n) {
GammaNode<T, A> argmin = null;
for (GammaNode<T, A> p : n.getPredecessors()) {
if ((argmin == null) || (p.getG() + p.cLow.get(n) < argmin.getG() + argmin.cLow.get(n))) {
argmin = p;
}
}
return argmin;
}
/**
* @throws AlgorithmExecutionCanceledException @throws
* AlgorithmException @throws AlgorithmTimeoutedException Generates this.RStarK
* Gamma graph successors for a state s within distance this.delta. Queries the
* this.gammaSuccessorGenerator and checks if a generate state has been visited
* i.e. generated in Gamma before. If yes, it takes the old reference from the
* this.alreadyGeneratedStates list. Also maintains the predecessor set of
* nodes.
*
* @param n Gamma node to generate successors for. @return List of Gamma
* nodes. @throws InterruptedException @throws
*/
private Collection<GammaNode<T, A>> generateGammaSuccessors(final GammaNode<T, A> n) throws InterruptedException, AlgorithmTimeoutedException, AlgorithmException, AlgorithmExecutionCanceledException {
/*
* first create a list of k nodes that are in reach of delta of the current node
*/
this.logger.trace("Invoking distant successor generator timeout-aware.");
List<T> randomDistantSuccessors = this.computeTimeoutAware(() -> this.getInput().getDistantSuccessorGenerator().getDistantSuccessors(n.getHead(), this.k, this.metricOverStates, this.delta), "Computing distant successors", true);
assert randomDistantSuccessors.size() == new HashSet<>(randomDistantSuccessors).size() : "Distant successor generator has created the same successor ar least twice: \n\t "
+ SetUtil.getMultiplyContainedItems(randomDistantSuccessors).stream().map(T::toString).collect(Collectors.joining("\n\t"));
this.logger.trace("Distant successor generator generated {}/{} successors.", randomDistantSuccessors.size(), this.k);
/*
* remove nodes for which a node is already on CLOSED (no reopening in this
* algorithm)
*/
randomDistantSuccessors.removeIf(childNode -> this.closed.stream().anyMatch(closedNode -> closedNode.getHead().equals(childNode)));
this.logger.trace("{} successors are still considered after having removed nodes that already are on CLOSED, which holds {} item(s).", randomDistantSuccessors.size(), this.closed.size());
/* now transform these node into (possibly existing) GammaNode objects */
ArrayList<GammaNode<T, A>> succWithoutClosed = new ArrayList<>();
for (T childNode : randomDistantSuccessors) {
Optional<GammaNode<T, A>> representantOnOpen = this.open.stream().filter(closedNode -> closedNode.getHead().equals(childNode)).findFirst();
GammaNode<T, A> gammaNodeForThisChild;
if (representantOnOpen.isPresent()) {
gammaNodeForThisChild = representantOnOpen.get();
} else {
gammaNodeForThisChild = new GammaNode<>(childNode);
gammaNodeForThisChild.setGoal(((INodeGoalTester<T, A>) this.getInput().getGoalTester()).isGoal(childNode));
}
/* if this is a solution, add it as a new solution */
if (gammaNodeForThisChild.isGoal()) {
this.logger.info("Found new solution. Adding it to the solution set.");
if (this.bestSeenGoalNode == null || this.bestSeenGoalNode.getG() > n.getG()) {
this.bestSeenGoalNode = n;
this.updateBestSeenSolution(this.getFullExternalPath(n));
}
EvaluatedSearchSolutionCandidateFoundEvent<T, A, Double> solutionEvent = new EvaluatedSearchSolutionCandidateFoundEvent<>(this, this.getFullExternalPath(gammaNodeForThisChild));
this.post(solutionEvent);
this.unreturnedSolutionEvents.add(solutionEvent);
}
gammaNodeForThisChild.addPredecessor(n);
succWithoutClosed.add(gammaNodeForThisChild);
}
return succWithoutClosed;
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
super.setLoggerName(name + "._orgraphsearch");
/* set logger name of the graph generator */
if (this.getGraphGenerator() instanceof ILoggingCustomizable) {
((ILoggingCustomizable) this.getGraphGenerator()).setLoggerName(name + ".graphgenerator");
}
/* set logger name of the distant graph generator */
DistantSuccessorGenerator<T> distantSuccessorGenerator = this.getInput().getDistantSuccessorGenerator();
if (distantSuccessorGenerator instanceof ILoggingCustomizable) {
((ILoggingCustomizable) distantSuccessorGenerator).setLoggerName(name + ".distantsuccessorgenerator");
}
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void cancel() {
this.logger.info("RStar received cancel. Now invoking shutdown routing and cancel the AStar subroutines.");
super.cancel();
this.activeAStarSubroutines.forEach(IAlgorithm::cancel);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/rstar/RStarFactory.java
|
package ai.libs.jaicore.search.algorithms.standard.rstar;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import ai.libs.jaicore.search.core.interfaces.StandardORGraphSearchFactory;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic;
public class RStarFactory<I extends GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic<T, A>, T, A> extends StandardORGraphSearchFactory<I, EvaluatedSearchGraphPath<T, A, Double>, T, A, Double, RStar<I, T, A>> {
private int timeoutForFInMS;
private IPathEvaluator<T, A, Double> timeoutEvaluator;
private String loggerName;
private double w = 1.0;
private int k = 3;
private double delta = 0.0;
public RStarFactory() {
super();
}
public RStarFactory(final int timeoutForFInMS) {
this();
if (timeoutForFInMS > 0) {
this.timeoutForFInMS = timeoutForFInMS;
}
}
public double getW() {
return this.w;
}
public void setW(final double w) {
this.w = w;
}
public int getK() {
return this.k;
}
public void setK(final int k) {
this.k = k;
}
public double getDelta() {
return this.delta;
}
public void setDelta(final double delta) {
this.delta = delta;
}
@Override
public RStar<I, T, A> getAlgorithm() {
return this.getAlgorithm(this.getInput());
}
@Override
public RStar<I, T, A> getAlgorithm(final I input) {
RStar<I, T, A> search = new RStar<>(input, this.w, this.k, this.delta);
if (this.loggerName != null && this.loggerName.length() > 0) {
search.setLoggerName(this.loggerName);
}
return search;
}
public void setTimeoutForFComputation(final int timeoutInMS, final IPathEvaluator<T, A, Double> timeoutEvaluator) {
this.timeoutForFInMS = timeoutInMS;
this.timeoutEvaluator = timeoutEvaluator;
}
public int getTimeoutForFInMS() {
return this.timeoutForFInMS;
}
public IPathEvaluator<T, A, Double> getTimeoutEvaluator() {
return this.timeoutEvaluator;
}
public String getLoggerName() {
return this.loggerName;
}
public void setLoggerName(final String loggerName) {
this.loggerName = loggerName;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/rstar/RStarK.java
|
package ai.libs.jaicore.search.algorithms.standard.rstar;
/**
* k-Values (Priorities used for expansion from open.)
*/
public class RStarK implements Comparable<RStarK>{
private boolean avoid;
private double f;
RStarK(final boolean avoid, final double f) {
this.avoid = avoid;
this.f = f;
}
@Override
/**
* Compare to k-values i.e. provide a natural ordering for them.
* E.g.: [false, 0.9] < [false, 2.2] < [true, 0.1] < [true, 2.0]
*
* @return -1 if this < o, 0 iff this == o, +1 iff this > 0
*/
public int compareTo(final RStarK o) {
// Compare first AVOID flag.
if (!this.avoid && o.avoid) {
return -1;
}
if (this.avoid && !o.avoid) {
return +1;
}
// Then compare f-values.
return Double.compare(this.f, o.f);
}
@Override
public String toString() {
return String.format("[%b, %g]", this.avoid, this.f);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/rstar/SubPathGraphGenerator.java
|
package ai.libs.jaicore.search.algorithms.standard.rstar;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.api4.java.datastructure.graph.implicit.IRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
public class SubPathGraphGenerator<N, A> implements IGraphGenerator<N, A> {
private final IGraphGenerator<N, A> gg;
private final N from;
public SubPathGraphGenerator(final IGraphGenerator<N, A> gg, final N from) {
super();
this.gg = gg;
this.from = from;
}
@Override
public IRootGenerator<N> getRootGenerator() {
return (ISingleRootGenerator<N>)(() -> this.from);
}
@Override
public ISuccessorGenerator<N, A> getSuccessorGenerator() {
return this.gg.getSuccessorGenerator();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/BasicUncertaintySource.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty;
import java.util.List;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IEvaluatedPath;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IUncertaintySource;
import org.api4.java.datastructure.graph.ILabeledPath;
public class BasicUncertaintySource<T, A, V extends Comparable<V>> implements IUncertaintySource<T, A,V> {
@Override
public double calculateUncertainty(final IEvaluatedPath<T, A, V> n, final List<ILabeledPath<T, A>> simulationPaths, final List<V> simulationEvaluations) {
double uncertainty = 1.0d;
if (simulationPaths != null && !simulationPaths.isEmpty()) {
T t = n.getHead();
double meanDepth = 0.0d;
for (ILabeledPath<T, A> path : simulationPaths) {
if (path.getNodes().contains(t) && !path.isPoint()) {
double post = 0.0d;
boolean startsCounting = false;
for (T pe : path.getNodes()) {
if (startsCounting) {
post++;
}
if (pe.equals(t)) {
startsCounting = true;
}
}
meanDepth += post / path.getNumberOfNodes();
}
}
if (meanDepth != 0.0d) {
uncertainty = meanDepth / (simulationPaths.size());
}
}
if (simulationEvaluations != null && simulationEvaluations.size() > 1
&& simulationEvaluations.get(0) instanceof Double) {
double mean = 0.0d;
double sampleVariance = 0.0d;
for (V f : simulationEvaluations) {
mean += (Double) f;
}
mean /= simulationEvaluations.size();
for (V f : simulationEvaluations) {
sampleVariance += ((Double) f - mean) * ((Double) f - mean);
}
sampleVariance = Math.sqrt(sampleVariance / (simulationEvaluations.size() - 1));
if (mean != 0.0d) {
double coefficientOfVariation = sampleVariance / mean;
coefficientOfVariation = Math.max(Math.abs(coefficientOfVariation), 1.0d);
uncertainty *= coefficientOfVariation;
}
}
return uncertainty;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/ISolutionDistanceMetric.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty;
import java.util.List;
import org.api4.java.common.math.IMetric;
@FunctionalInterface
public interface ISolutionDistanceMetric <T> extends IMetric<List<T>> {
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/OversearchAvoidanceConfig.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty;
import java.util.Comparator;
import ai.libs.jaicore.search.algorithms.standard.uncertainty.paretosearch.FirstInFirstOutComparator;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public class OversearchAvoidanceConfig<N, A, V extends Comparable<V>> {
public enum OversearchAvoidanceMode {
PARETO_FRONT_SELECTION, TWO_PHASE_SELECTION, NONE
}
private OversearchAvoidanceMode oversearchAvoidanceMode;
private long seed;
private boolean adjustPhaseLengthsDynamically = false;
private long timeout;
private int interval = 50;
private double exploitationScoreThreshold = 0.1d;
private double explorationUncertaintyThreshold = 0.1d;
private double minimumSolutionDistanceForExploration = 0.0d;
private ISolutionDistanceMetric<N> solutionDistanceMetric = (s1, s2) -> 1.0d;
private Comparator<BackPointerPath<N, A, V>> paretoComparator = new FirstInFirstOutComparator<>();
public OversearchAvoidanceConfig(final OversearchAvoidanceMode mode, final long seed) {
this.oversearchAvoidanceMode = mode;
this.seed = seed;
}
public OversearchAvoidanceMode getOversearchAvoidanceMode() {
return this.oversearchAvoidanceMode;
}
public ISolutionDistanceMetric<N> getSolutionDistanceMetric() {
return this.solutionDistanceMetric;
}
public OversearchAvoidanceConfig<N, A, V> setSolutionDistanceMetric(final ISolutionDistanceMetric<N> solutionDistanceMetric) {
this.solutionDistanceMetric = solutionDistanceMetric;
return this;
}
public boolean getAdjustPhaseLengthsDynamically() {
return this.adjustPhaseLengthsDynamically;
}
public void activateDynamicPhaseLengthsAdjustment(final long timeout) {
this.adjustPhaseLengthsDynamically = true;
this.timeout = timeout;
}
public long getTimeout() {
return this.timeout;
}
public int getInterval() {
return this.interval;
}
public void setInterval(final int interval) {
this.interval = interval;
}
public double getExploitationScoreThreshold() {
return this.exploitationScoreThreshold;
}
public void setExploitationScoreThreshold(final double exploitationScoreThreshold) {
this.exploitationScoreThreshold = exploitationScoreThreshold;
}
public double getExplorationUncertaintyThreshold() {
return this.explorationUncertaintyThreshold;
}
public void setExplorationUncertaintyThreshold(final double explorationUncertaintyThreshold) {
this.explorationUncertaintyThreshold = explorationUncertaintyThreshold;
}
public double getMinimumSolutionDistanceForExploration() {
return this.minimumSolutionDistanceForExploration;
}
public void setMinimumSolutionDistanceForExploration(final double minimumSolutionDistanceForExploration) {
this.minimumSolutionDistanceForExploration = minimumSolutionDistanceForExploration;
}
public long getSeed() {
return this.seed;
}
public void setParetoComparator(final Comparator<BackPointerPath<N, A, V>> paretoComparator) {
this.paretoComparator = paretoComparator;
}
public Comparator<BackPointerPath<N, A, V>> getParetoComperator() {
return this.paretoComparator;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/UncertaintyORGraphSearchFactory.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty;
import java.util.PriorityQueue;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallyUncertaintyAnnotatingPathEvaluator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.BestFirst;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.BestFirstFactory;
import ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch.BasicClockModelPhaseLengthAdjuster;
import ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch.BasicExplorationCandidateSelector;
import ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch.IPhaseLengthAdjuster;
import ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch.UncertaintyExplorationOpenSelection;
import ai.libs.jaicore.search.algorithms.standard.uncertainty.paretosearch.ParetoSelection;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithUncertaintyBasedSubpathEvaluationInput;
public class UncertaintyORGraphSearchFactory<N, A, V extends Comparable<V>>
extends BestFirstFactory<GraphSearchWithUncertaintyBasedSubpathEvaluationInput<N, A, V>, N, A, V> {
private static final Logger logger = LoggerFactory.getLogger(UncertaintyORGraphSearchFactory.class);
private OversearchAvoidanceConfig<N, A,V> oversearchAvoidanceConfig;
@Override
public BestFirst<GraphSearchWithUncertaintyBasedSubpathEvaluationInput<N, A, V>, N, A, V> getAlgorithm() {
if (this.oversearchAvoidanceConfig == null) {
throw new IllegalStateException("Uncertainty Config has not been set yet.");
}
/*
* let the best first factory configure general aspects of the best first search
*/
BestFirst<GraphSearchWithUncertaintyBasedSubpathEvaluationInput<N, A, V>, N, A, V> search = super.getAlgorithm();
/* check that node evaluator supports uncertainty */
if (!(search.getNodeEvaluator() instanceof IPotentiallyUncertaintyAnnotatingPathEvaluator)) {
throw new UnsupportedOperationException("Cannot create uncertainty based search with node evaluator " + search.getNodeEvaluator().getClass().getName() + ", which does not implement " + IPotentiallyUncertaintyAnnotatingPathEvaluator.class.getName());
}
if (!((IPotentiallyUncertaintyAnnotatingPathEvaluator<?,?,?>)search.getNodeEvaluator()).annotatesUncertainty()) {
throw new UnsupportedOperationException("The given node evaluator supports uncertainty annotation, but it declares that it will not annotate uncertainty. Maybe no uncertainty source has been defined.");
}
/* now set uncertainty-specific behavior */
switch (this.oversearchAvoidanceConfig.getOversearchAvoidanceMode()) {
case NONE:
logger.warn("Usage of OversearchAvoidanceMode.NONE is deprecated! Use StandardBestFirst search instead.");
break;
case TWO_PHASE_SELECTION:
if (this.oversearchAvoidanceConfig.getAdjustPhaseLengthsDynamically()) {
search.setOpen(new UncertaintyExplorationOpenSelection<N, A, V>(
this.oversearchAvoidanceConfig.getTimeout(),
this.oversearchAvoidanceConfig.getInterval(),
this.oversearchAvoidanceConfig.getExploitationScoreThreshold(),
this.oversearchAvoidanceConfig.getExplorationUncertaintyThreshold(),
new BasicClockModelPhaseLengthAdjuster(),
this.oversearchAvoidanceConfig.getSolutionDistanceMetric(),
new BasicExplorationCandidateSelector<N, A, V>(this.oversearchAvoidanceConfig.getMinimumSolutionDistanceForExploration())
));
} else {
search.setOpen(new UncertaintyExplorationOpenSelection<N, A,V>(
this.oversearchAvoidanceConfig.getTimeout(),
this.oversearchAvoidanceConfig.getInterval(),
this.oversearchAvoidanceConfig.getExploitationScoreThreshold(),
this.oversearchAvoidanceConfig.getExplorationUncertaintyThreshold(),
new IPhaseLengthAdjuster() {
@Override
public int[] getInitialPhaseLengths(final int interval) {
return new int[] {interval / 2, interval - (interval / 2)};
}
@Override
public int[] adjustPhaseLength(final int currentExplorationLength, final int currentExploitationLength, final long passedTime,
final long timeout) {
return new int[] {currentExplorationLength, currentExploitationLength};
}
},
this.oversearchAvoidanceConfig.getSolutionDistanceMetric(),
new BasicExplorationCandidateSelector<N, A,V>(this.oversearchAvoidanceConfig.getMinimumSolutionDistanceForExploration())
));
}
break;
case PARETO_FRONT_SELECTION:
PriorityQueue<BackPointerPath<N,A, V>> pareto = new PriorityQueue<>(this.oversearchAvoidanceConfig.getParetoComperator());
search.setOpen(new ParetoSelection<>(pareto));
break;
default:
throw new UnsupportedOperationException("Mode " + this.oversearchAvoidanceConfig.getOversearchAvoidanceMode() + " is currently not supported.");
}
return search;
}
public OversearchAvoidanceConfig<N, A,V> getConfig() {
return this.oversearchAvoidanceConfig;
}
public void setConfig(final OversearchAvoidanceConfig<N,A, V> config) {
this.oversearchAvoidanceConfig = config;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/explorationexploitationsearch/BasicClockModelPhaseLengthAdjuster.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch;
public class BasicClockModelPhaseLengthAdjuster implements IPhaseLengthAdjuster {
private int interval;
@Override
public int[] getInitialPhaseLengths(int interval) {
this.interval = interval;
return new int[]{this.interval - 1, 1};
}
@Override
public int[] adjustPhaseLength(int currentExplorationLength, int currentExploitationLength, long passedTime, long timeout) {
double alpha = ((double) Math.min(passedTime, timeout))/((double) timeout) * 0.5 * Math.PI;
int exploration = (int)(Math.cos(alpha) * (double)interval);
int exploitation = this.interval - exploration;
return new int[]{Math.max(exploration, 1), Math.max(exploitation, 1)};
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/explorationexploitationsearch/BasicExplorationCandidateSelector.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import ai.libs.jaicore.search.algorithms.standard.uncertainty.ISolutionDistanceMetric;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public class BasicExplorationCandidateSelector<T, A, V extends Comparable<V>> implements IExplorationCandidateSelector<T, A, V> {
private double minimumSolutionDistanceForExploration;
public BasicExplorationCandidateSelector(final double minimumSolutionDistanceForExploration) {
this.minimumSolutionDistanceForExploration = minimumSolutionDistanceForExploration;
}
@Override
public List<BackPointerPath<T, A, V>> selectExplorationCandidates(final Queue<BackPointerPath<T, A, V>> allCandidates, final BackPointerPath<T, A, V> bestCandidate, final ISolutionDistanceMetric<T> solutionDistanceMetric) {
return allCandidates.stream().filter(n -> {
if (bestCandidate == n) {
return false;
}
double solutionDistance = solutionDistanceMetric.getDistance(n.getNodes(), bestCandidate.getNodes());
return solutionDistance >= this.minimumSolutionDistanceForExploration;
}).collect(Collectors.toList());
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/explorationexploitationsearch/IExplorationCandidateSelector.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch;
import java.util.List;
import java.util.Queue;
import ai.libs.jaicore.search.algorithms.standard.uncertainty.ISolutionDistanceMetric;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
@FunctionalInterface
public interface IExplorationCandidateSelector<T, A, V extends Comparable<V>> {
public List<BackPointerPath<T, A, V>> selectExplorationCandidates(Queue<BackPointerPath<T, A, V>> allCandidates, BackPointerPath<T, A, V> bestCandidate, ISolutionDistanceMetric<T> solutionDistanceMetric);
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/explorationexploitationsearch/IPhaseLengthAdjuster.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch;
public interface IPhaseLengthAdjuster {
/**
* Called before the search to set the phase lengths initially.
* @param interval Overall length of both phases combined.
* @return An array with two elements [newExplorationPhaseLength, newExploitationPhaseLength] to adjust the phase lengths.
*/
public int[] getInitialPhaseLengths(int interval);
/**
* Called on every complete iteration of an exploration and an exploitation phase to determine how to change the phase lengths.
* @param currentExplorationLength Current length of the exploration phase.
* @param currentExploitationLength Current length of the exploitation phase.
* @param passedTime Passed time of the search.
* @param timout Timeout for the search.
* @return An array with two elements [newExplorationPhaseLength, newExploitationPhaseLength] to adjust the phase lengths.
*/
public int[] adjustPhaseLength (int currentExplorationLength, int currentExploitationLength, long passedTime, long timeout);
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/explorationexploitationsearch/UncertaintyExplorationOpenSelection.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.ENodeAnnotation;
import ai.libs.jaicore.search.algorithms.standard.uncertainty.ISolutionDistanceMetric;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
import ai.libs.jaicore.search.model.travesaltree.DefaultNodeComparator;
public class UncertaintyExplorationOpenSelection<T, A, V extends Comparable<V>> implements Queue<BackPointerPath<T, A, V>> {
private static final Logger logger = LoggerFactory.getLogger(UncertaintyExplorationOpenSelection.class);
private final Queue<BackPointerPath<T, A, V>> exploitationOpen = new PriorityQueue<>(new DefaultNodeComparator<>());
private final PriorityQueue<BackPointerPath<T, A, V>> explorationOpen = new PriorityQueue<>(new DefaultNodeComparator<>());
private final ISolutionDistanceMetric<T> solutionDistanceMetric;
private final IPhaseLengthAdjuster phaseLengthAdjuster;
private final IExplorationCandidateSelector<T,A, V> candidateSelector;
private int explorationPhaseLength;
private int exploitationPhaseLength;
private double exploitationScoreThreshold;
private double explorationUncertaintyThreshold;
private int selectedNodes = 0;
private int exploredNodes = 0;
private long timeout;
private long startTime;
private boolean exploring = true;
public UncertaintyExplorationOpenSelection(final long timeout, final int phaseInterval, final double exploitationScoreThreshold, final double explorationUncertaintyThreshold, final IPhaseLengthAdjuster phaseLengthAdjuster,
final ISolutionDistanceMetric<T> solutionDistanceMetric, final IExplorationCandidateSelector<T, A,V> candidateSelector) {
super();
this.timeout = timeout;
this.startTime = System.currentTimeMillis();
int[] phaseLenghts = phaseLengthAdjuster.getInitialPhaseLengths(phaseInterval);
assert phaseLenghts.length == 2;
this.explorationPhaseLength = phaseLenghts[0];
this.exploitationPhaseLength = phaseLenghts[1];
this.exploitationScoreThreshold = exploitationScoreThreshold;
this.explorationUncertaintyThreshold = explorationUncertaintyThreshold;
this.phaseLengthAdjuster = phaseLengthAdjuster;
this.solutionDistanceMetric = solutionDistanceMetric;
this.candidateSelector = candidateSelector;
}
@Override
public BackPointerPath<T, A, V> peek() {
return this.selectCandidate(this.exploring);
}
private synchronized BackPointerPath<T, A, V> selectCandidate(final boolean isExploring) {
Comparator<BackPointerPath<T, A, V>> comparator = (n1, n2) -> {
try {
Double u1 = (Double) n1.getAnnotation(ENodeAnnotation.F_UNCERTAINTY.name());
Double u2 = (Double) n2.getAnnotation(ENodeAnnotation.F_UNCERTAINTY.name());
V v1 = n1.getScore();
V v2 = n2.getScore();
if (isExploring) {
if (Math.abs(u1 - u2) <= this.explorationUncertaintyThreshold) {
return -1 * v1.compareTo(v2);
} else {
return Double.compare(u1, u2);
}
} else {
if (v1 instanceof Double && v2 instanceof Double) {
Double s1 = (Double) v1;
Double s2 = (Double) v2;
if (Math.abs(s1 - s2) <= this.exploitationScoreThreshold) {
return Double.compare(u1, u2);
} else {
return Double.compare(s1, s2);
}
} else {
if (v1 instanceof Double && v2 instanceof Double) {
Double s1 = (Double) v1;
Double s2 = (Double) v2;
if (Math.abs(s1 - s2) <= this.exploitationScoreThreshold) {
return Double.compare(u1, u2);
} else {
return v1.compareTo(v2);
}
} else {
return v1.compareTo(v2);
}
}
}
} catch (Exception e) {
logger.error(e.getMessage());
return 0;
}
};
if (isExploring) {
return this.explorationOpen.stream().max(comparator).orElse(this.explorationOpen.peek());
} else {
return this.exploitationOpen.stream().min(comparator).orElse(this.exploitationOpen.peek());
}
}
private void adjustPhaseLengths(final long passedTime) {
int[] newPhaseLengths = this.phaseLengthAdjuster.adjustPhaseLength(this.explorationPhaseLength, this.exploitationPhaseLength, passedTime, this.timeout);
assert newPhaseLengths.length == 2;
this.explorationPhaseLength = newPhaseLengths[0];
this.exploitationPhaseLength = newPhaseLengths[1];
}
@Override
public synchronized boolean add(final BackPointerPath<T, A, V> node) {
if (node == null) {
throw new IllegalArgumentException("Cannot add node NULL to OPEN");
}
assert !this.contains(node) : "Node " + node + " is already there!";
if (this.exploring) {
return this.explorationOpen.add(node);
} else {
return this.exploitationOpen.add(node);
}
}
@Override
public synchronized boolean remove(final Object node) {
if (this.exploitationOpen.contains(node) && this.explorationOpen.contains(node)) {
throw new IllegalStateException("A node (" + node + ") that is to be removed is in BOTH open lists!");
}
if (this.exploring) {
return this.explorationOpen.remove(node) || this.exploitationOpen.remove(node);
} else {
return this.exploitationOpen.remove(node) || this.explorationOpen.remove(node);
}
}
@Override
public synchronized boolean addAll(final Collection<? extends BackPointerPath<T, A, V>> arg0) {
assert this.exploitationOpen != null : "Primary OPEN is NULL!";
if (arg0 == null) {
throw new IllegalArgumentException("Cannot add NULL collection");
}
if (this.exploring) {
return this.explorationOpen.addAll(arg0);
} else {
return this.exploitationOpen.addAll(arg0);
}
}
@Override
public synchronized void clear() {
this.exploitationOpen.clear();
this.explorationOpen.clear();
}
@Override
public synchronized boolean contains(final Object arg0) {
return this.exploitationOpen.contains(arg0) || this.explorationOpen.contains(arg0);
}
@Override
public boolean containsAll(final Collection<?> arg0) {
for (Object o : arg0) {
if (!this.contains(o)) {
return false;
}
}
return true;
}
@Override
public synchronized boolean isEmpty() {
return this.exploitationOpen.isEmpty() && this.explorationOpen.isEmpty();
}
@Override
public Iterator<BackPointerPath<T, A, V>> iterator() {
return this.exploring ? this.explorationOpen.iterator() : this.exploitationOpen.iterator();
}
@Override
public synchronized boolean removeAll(final Collection<?> arg0) {
return this.exploitationOpen.removeAll(arg0) && this.explorationOpen.removeAll(arg0);
}
@Override
public synchronized boolean retainAll(final Collection<?> arg0) {
return this.exploitationOpen.retainAll(arg0) && this.explorationOpen.retainAll(arg0);
}
@Override
public synchronized int size() {
return this.exploitationOpen.size() + this.explorationOpen.size();
}
@Override
public Object[] toArray() {
return this.exploitationOpen.toArray();
}
@SuppressWarnings("unchecked")
@Override
public <X> X[] toArray(final X[] arg0) {
return (X[]) this.exploitationOpen.toArray();
}
@Override
public BackPointerPath<T, A, V> element() {
return this.peek();
}
@Override
public boolean offer(final BackPointerPath<T, A, V> e) {
return this.add(e);
}
@Override
public BackPointerPath<T, A, V> poll() {
return this.remove();
}
@Override
public synchronized BackPointerPath<T, A, V> remove() {
/* determine element to be returned and remove it from the respective list */
BackPointerPath<T, A, V> peek = this.peek();
this.remove(peek);
/* update internal state */
if (!this.exploring) {
this.selectedNodes++;
if (this.selectedNodes % this.exploitationPhaseLength == 0) {
List<BackPointerPath<T, A, V>> explorationCandidates = this.candidateSelector.selectExplorationCandidates(this.exploitationOpen, this.exploitationOpen.peek(), this.solutionDistanceMetric);
/* enable exploration with the node selected by the explorer evaluator */
try {
logger.info("Entering exploration phase under {}", explorationCandidates);
} catch (Exception e) {
logger.error(e.getMessage());
}
this.exploring = true;
this.exploredNodes = 0;
this.exploitationOpen.removeAll(explorationCandidates);
this.explorationOpen.clear();
this.explorationOpen.addAll(explorationCandidates);
}
} else {
this.exploredNodes++;
if (this.exploredNodes > this.explorationPhaseLength || this.explorationOpen.isEmpty()) {
this.adjustPhaseLengths(System.currentTimeMillis() - this.startTime);
this.exploring = false;
this.exploitationOpen.addAll(this.explorationOpen);
this.explorationOpen.clear();
logger.info("Entering exploitation phase");
}
}
/* return the peeked element */
return peek;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/paretosearch/CosinusDistanceComparator.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.paretosearch;
import java.util.Comparator;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.ENodeAnnotation;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public class CosinusDistanceComparator<T, A, V extends Comparable<V>> implements Comparator<BackPointerPath<T, A, V>> {
public final double x1;
public final double x2;
public CosinusDistanceComparator(final double x1, final double x2) {
this.x1 = x1;
this.x2 = x2;
}
/**
* Compares the cosine distance of two nodes to x.
*
* @param first
* @param second
* @return negative iff first < second, 0 iff first == second, positive iff first > second
*/
@Override
public int compare(final BackPointerPath<T, A, V> first, final BackPointerPath<T, A, V> second) {
Double firstF = (Double) first.getAnnotation(ENodeAnnotation.F_SCORE.name());
Double firstU = (Double) first.getAnnotation(ENodeAnnotation.F_UNCERTAINTY.name());
Double secondF = (Double) second.getAnnotation(ENodeAnnotation.F_SCORE.name());
Double secondU = (Double) second.getAnnotation(ENodeAnnotation.F_UNCERTAINTY.name());
double cosDistanceFirst = 1 - this.cosineSimilarity(firstF, firstU);
double cosDistanceSecond = 1 - this.cosineSimilarity(secondF, secondU);
return (int) ((cosDistanceFirst - cosDistanceSecond) * 10000);
}
/**
* Cosine similarity to x.
*
* @param f
* @param u
* @return
*/
public double cosineSimilarity(final double f, final double u) {
return (this.x1 * f + this.x2 * u) / (Math.sqrt(f * f + u * u) * Math.sqrt(this.x1 * this.x1 + this.x2 * this.x2));
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/paretosearch/FirstInFirstOutComparator.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.paretosearch;
import java.util.Comparator;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public class FirstInFirstOutComparator<T, A, V extends Comparable<V>> implements Comparator<BackPointerPath<T, A, V>> {
/**
* Compares two Pareto nodes on time of insertion (n). FIFO behaviour.
*
* @param first
* @param second
* @return negative iff first.n < second.n, 0 iff fist.n == second.n, positive iff first.n > second.n
*/
@Override
public int compare(final BackPointerPath<T, A, V> first, final BackPointerPath<T, A, V> second) {
return (int) first.getAnnotation("n") - (int) second.getAnnotation("n");
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/paretosearch/ParetoFrontVisualizer.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.paretosearch;
import java.util.ArrayList;
import java.util.List;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.XYChart;
import org.knowm.xchart.XYChartBuilder;
import org.knowm.xchart.XYSeries.XYSeriesRenderStyle;
import org.knowm.xchart.style.Styler.ChartTheme;
import org.knowm.xchart.style.Styler.LegendPosition;
public class ParetoFrontVisualizer {
private final XYChart chart;
private final SwingWrapper<XYChart> vis;
private final List<Double> fValues;
private final List<Double> uncertainties;
public ParetoFrontVisualizer() {
this.chart = new XYChartBuilder().width(600).height(500).title("Paretofront Visualizer").theme(ChartTheme.Matlab).xAxisTitle("Uncertainty").yAxisTitle("F Value").build();
this.chart.getStyler().setYAxisMin(0.0d);
this.chart.getStyler().setXAxisMin(0.0d);
this.chart.getStyler().setYAxisMax(1.0d);
this.chart.getStyler().setXAxisMax(1.0d);
this.chart.getStyler().setDefaultSeriesRenderStyle(XYSeriesRenderStyle.Scatter);
this.chart.getStyler().setLegendPosition(LegendPosition.OutsideS);
this.chart.getStyler().setMarkerSize(4);
this.chart.addSeries("Paretofront Candidates", new double[] { 1 }, new double[] { 1 });
this.vis = new SwingWrapper<>(this.chart);
this.fValues = new ArrayList<>();
this.uncertainties = new ArrayList<>();
}
public void show() {
this.vis.displayChart();
}
public void update(final double fValue, final double uncertainty) {
this.fValues.add(fValue);
this.uncertainties.add(uncertainty);
if (this.fValues.size() == this.uncertainties.size()) {
double[] f = new double[this.fValues.size()];
double[] u = new double[this.uncertainties.size()];
for (int i = 0; i < this.fValues.size(); i++) {
f[i] = this.fValues.get(i);
u[i] = this.uncertainties.get(i);
}
javax.swing.SwingUtilities.invokeLater(() -> {
this.chart.updateXYSeries("Paretofront Candidates", u, f, null);
this.vis.repaintChart();
});
} else {
throw new IllegalStateException("Unqueal value amounts");
}
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/paretosearch/ParetoNode.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.paretosearch;
import java.util.HashSet;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
/**
* Internal representation of nodes to maintain pareto front.
*/
public class ParetoNode<T, A, V extends Comparable<V>> {
private final BackPointerPath<T, A, V> node;
/* Number of creation of this pareto node. */
private final HashSet<ParetoNode<T, A, V>> dominates;
private final HashSet<ParetoNode<T, A, V>> dominatedBy;
public ParetoNode(final BackPointerPath<T, A, V> node) {
this.node = node;
this.dominates = new HashSet<>();
this.dominatedBy = new HashSet<>();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{" + this.node.getHead() + "] dominated by {");
for (ParetoNode<T, A, V> p : this.dominatedBy) {
sb.append(p.node.getHead() + ",");
}
sb.append("} dominates { ");
for (ParetoNode<T, A, V> p : this.dominates) {
sb.append(p.node.getHead() + ",");
}
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
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;
}
ParetoNode other = (ParetoNode) obj;
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-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/paretosearch/ParetoSelection.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.paretosearch;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.ENodeAnnotation;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
/**
* Open collection pareto front implementation.
*
* @param <T>
* internal label of node
* @param <V>
* external label of node
*/
public class ParetoSelection<T, A, V extends Comparable<V>> implements Queue<BackPointerPath<T, A, V>> {
private static final String UNCERTAINTY = ENodeAnnotation.F_UNCERTAINTY.name();
private static final String DOMINATES = "dominates";
private static final String DOMINATED_BY = "dominatedBy";
/* Contains all open nodes. */
private final LinkedList<BackPointerPath<T, A, V>> open;
/* Contains all maximal open nodes. */
private final Queue<BackPointerPath<T, A, V>> pareto;
/* Node counter. */
private int n = 0;
/**
* Constructor.
*
* @param pareto
* Pareto set implementation.
*/
public ParetoSelection(final Queue<BackPointerPath<T, A, V>> pareto) {
this.open = new LinkedList<>();
this.pareto = pareto;
}
/**
* Tests if p dominates q.
*
* @param p
* @param q
* @return true if p dominates q. False, otherwise.
*/
@SuppressWarnings("unchecked")
private boolean dominates(final BackPointerPath<T, A, V> p, final BackPointerPath<T, A, V> q) {
if (!p.getAnnotations().containsKey(UNCERTAINTY)) {
throw new IllegalArgumentException("Node " + p + " has no uncertainty information.");
}
if (!q.getAnnotations().containsKey(UNCERTAINTY)) {
throw new IllegalArgumentException("Node " + q + " has no uncertainty information.");
}
// Get f and u values of nodes
V p_f = (V) p.getAnnotation("f");
double p_u = (double) p.getAnnotation(UNCERTAINTY);
V q_f = (V) q.getAnnotation("f");
double q_u = (double) q.getAnnotation(UNCERTAINTY);
// p dominates q <=> (q.f < p.f AND q.u <= p.u) OR (q.f <= p.f AND q.u < p.u)
return ((p_f.compareTo(q_f) < 0) && (p_u <= q_u)) || ((p_f.compareTo(q_f) <= 0) && (p_u < q_u));
}
/**
* Tests if p is maximal.
*
* @param n
* @return
*/
@SuppressWarnings("unchecked")
private boolean isMaximal(final BackPointerPath<T, A, V> n) {
return ((HashSet<BackPointerPath<T, A, V>>) n.getAnnotation(DOMINATED_BY)).size() == 0;
}
/**
* Adds a node to the open list and, if its not dominated by any other point
* also to the pareto front.
*
* @param n
* @return
*/
@Override
public boolean add(final BackPointerPath<T, A, V> n) {
if (n.getScore() == null) {
throw new IllegalArgumentException("Cannot add nodes with value NULL to OPEN!");
}
// Initialize annotations necessary for pareto queue.
n.setAnnotation("n", this.n++);
n.setAnnotation(DOMINATES, new HashSet<BackPointerPath<T, A, V>>());
n.setAnnotation(DOMINATED_BY, new HashSet<BackPointerPath<T, A, V>>());
for (BackPointerPath<T, A, V> q : this.open) {
// n dominates q
if (this.dominates(n, q)) {
((HashSet<BackPointerPath<T, A, V>>) n.getAnnotation(DOMINATES)).add(q);
((HashSet<BackPointerPath<T, A, V>>) q.getAnnotation(DOMINATED_BY)).add(n);
// Remove q from pareto front if its now dominated i.e. not maximal anymore.
if (!this.isMaximal(q)) {
this.pareto.remove(q);
}
}
// n dominated by q
if (this.dominates(q, n)) {
((HashSet<BackPointerPath<T, A, V>>) n.getAnnotation(DOMINATES)).add(q);
((HashSet<BackPointerPath<T, A, V>>) q.getAnnotation(DOMINATED_BY)).add(n);
}
}
// If n is not dominated by any other point, add it to pareto front.
if (this.isMaximal(n)) {
this.pareto.add(n);
}
return this.open.add(n);
}
@Override
public boolean addAll(final Collection<? extends BackPointerPath<T, A, V>> c) {
boolean changed = false;
for (BackPointerPath<T, A, V> p : c) {
changed |= this.add(p);
}
return changed;
}
@Override
public void clear() {
this.open.clear();
}
@Override
public boolean contains(final Object o) {
return this.open.contains(o);
}
@Override
public boolean containsAll(final Collection<?> c) {
return this.open.containsAll(c);
}
@Override
public boolean isEmpty() {
return this.open.isEmpty();
}
@Override
public Iterator<BackPointerPath<T, A, V>> iterator() {
return this.pareto.iterator();
}
@Override
public boolean removeAll(final Collection<?> c) {
return this.open.removeAll(c);
}
@Override
public boolean retainAll(final Collection<?> c) {
return this.open.retainAll(c);
}
@Override
public int size() {
return this.open.size();
}
@Override
public Object[] toArray() {
return this.open.toArray();
}
@Override
public <X> X[] toArray(final X[] a) {
return this.open.toArray(a);
}
/**
* Return a node from pareto front.
*/
@Override
public BackPointerPath<T, A, V> peek() {
return this.pareto.isEmpty() ? null : this.pareto.peek();
}
/**
* Removes an Node from
*
* @param o
* @return
*/
@Override
public boolean remove(final Object o) {
if (o instanceof BackPointerPath) {
BackPointerPath<T, A, V> node = (BackPointerPath<T, A, V>) o;
// Remove all associations of n.
for (BackPointerPath<T, A, V> q : (HashSet<BackPointerPath<T, A, V>>) node.getAnnotation(DOMINATES)) {
((HashSet<BackPointerPath<T, A, V>>) q.getAnnotation(DOMINATED_BY)).remove(node);
// Add q to pareto if its now no longer dominated by any other point.
if (this.isMaximal(q)) {
this.pareto.add(q);
}
}
for (BackPointerPath<T, A, V> q : (HashSet<BackPointerPath<T, A, V>>) node.getAnnotation(DOMINATED_BY)) {
((HashSet<BackPointerPath<T, A, V>>) q.getAnnotation(DOMINATES)).remove(node); // TODO: Is this even necessary?
}
// Remove n from Pareto set and Open list.
this.pareto.remove(node);
return this.open.remove(node);
} else {
return false;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("OPEN LIST: \n");
for (BackPointerPath p : this.open) {
sb.append(p.toString());
sb.append("\n");
}
sb.append("PARETO = [");
for (BackPointerPath<T, A, V> p : this.pareto) {
sb.append(p.getHead());
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
@Override
public BackPointerPath<T, A, V> element() {
return this.peek();
}
@Override
public boolean offer(final BackPointerPath<T, A, V> arg0) {
return this.add(arg0);
}
@Override
public BackPointerPath<T, A, V> poll() {
BackPointerPath<T, A, V> node = this.peek();
this.remove(node);
return node;
}
@Override
public BackPointerPath<T, A, V> remove() {
return this.poll();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/uncertainty/paretosearch/RandomComparator.java
|
package ai.libs.jaicore.search.algorithms.standard.uncertainty.paretosearch;
import java.util.Comparator;
import java.util.Random;
import ai.libs.jaicore.search.model.travesaltree.BackPointerPath;
public class RandomComparator<T, A, V extends Comparable<V>> implements Comparator<BackPointerPath<T, A, V>> {
private final Random random = new Random(System.currentTimeMillis());
/**
* Randomly outputs a negative or positive integer. (Never zero).
*
* @param first
* @param second
* @return negative iff first.n < second.n, 0 iff first.n == second.n, positive iff first.n > second.n
*/
@Override
public int compare(final BackPointerPath<T, A, V> first, final BackPointerPath<T, A, V> second) {
int r = this.random.nextInt(2); // This is either 0 or 1.
if (r == 0) {
return -1;
} else {
return 1;
}
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core/interfaces/AAnyPathInORGraphSearch.java
|
package ai.libs.jaicore.search.core.interfaces;
import org.api4.java.ai.graphsearch.problem.IPathInORGraphSearch;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig;
import ai.libs.jaicore.basic.algorithm.AAlgorithm;
import ai.libs.jaicore.basic.algorithm.ASolutionCandidateIterator;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.GraphSearchSolutionCandidateFoundEvent;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
/**
* This is a template for algorithms that aim at finding paths from a root to
* goal nodes in a graph. This template does not assume paths to have a score.
*
* The output type of this algorithm is fixed to EvaluatedSearchGraphPath<NSrc, ASrc, V>
*
* @author fmohr
*
* @param <I>
* @param <N>
* @param <A>
* @param <V>
* @param <NSearch>
* @param <Asearch>
*/
public abstract class AAnyPathInORGraphSearch<I extends IPathSearchInput<N, A>, O extends SearchGraphPath<N, A>, N, A> extends ASolutionCandidateIterator<I, O>
implements IPathInORGraphSearch<I, O, N, A> {
/* Logger variables */
private Logger logger = LoggerFactory.getLogger(AAlgorithm.class);
private String loggerName;
public AAnyPathInORGraphSearch(final I problem) {
super(problem);
}
protected AAnyPathInORGraphSearch(final IOwnerBasedAlgorithmConfig config,final I problem) {
super(config,problem);
}
protected GraphSearchSolutionCandidateFoundEvent<N, A, O> registerSolution(final O path) {
GraphSearchSolutionCandidateFoundEvent<N, A, O> event = new GraphSearchSolutionCandidateFoundEvent<>(this, path);
this.post(event);
return event;
}
@Override
public IGraphGenerator<N, A> getGraphGenerator() {
return this.getInput().getGraphGenerator();
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switching logger to {}", name);
this.loggerName = name;
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Switched to logger {}", name);
super.setLoggerName(this.loggerName + "._algorithm");
}
@Override
public String getLoggerName() {
return this.loggerName;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core/interfaces/AOptimalPathInORGraphSearch.java
|
package ai.libs.jaicore.search.core.interfaces;
import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearch;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig;
import ai.libs.jaicore.basic.algorithm.AAlgorithm;
import ai.libs.jaicore.basic.algorithm.AOptimizer;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
/**
* This is a template for algorithms that aim at finding paths from a root to
* goal nodes in a graph. This template does not assume paths to have a score.
*
* The output type of this algorithm is fixed to EvaluatedSearchGraphPath<NSrc, ASrc, V>
*
* @author fmohr
*
* @param <I>
* @param <N>
* @param <A>
* @param <V>
* @param <NSearch>
* @param <Asearch>
*/
public abstract class AOptimalPathInORGraphSearch<I extends IPathSearchInput<N, A>, N, A, V extends Comparable<V>> extends AOptimizer<I, EvaluatedSearchGraphPath<N, A, V>, V>
implements IOptimalPathInORGraphSearch<I, EvaluatedSearchGraphPath<N, A, V>, N, A, V> {
/* Logger variables */
private Logger logger = LoggerFactory.getLogger(AAlgorithm.class);
private String loggerName;
public AOptimalPathInORGraphSearch(final I problem) {
super(problem);
}
protected AOptimalPathInORGraphSearch(final IOwnerBasedAlgorithmConfig config,final I problem) {
super(config,problem);
}
@SuppressWarnings("unchecked")
@Override
public EvaluatedSearchSolutionCandidateFoundEvent<N, A, V> nextSolutionCandidateEvent() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
return (EvaluatedSearchSolutionCandidateFoundEvent<N, A, V>) super.nextSolutionCandidateEvent();
}
protected EvaluatedSearchSolutionCandidateFoundEvent<N, A, V> registerSolution(final EvaluatedSearchGraphPath<N, A, V> path) {
this.updateBestSeenSolution(path);
EvaluatedSearchSolutionCandidateFoundEvent<N, A, V> event = new EvaluatedSearchSolutionCandidateFoundEvent<>(this, path);
this.logger.info("Identified solution with score {}. Now posting the solution event {} to {} listeners. Enable DEBUG to see the concrete nodes, actions and listeners.", path.getScore(), event, this.getListeners().size());
this.logger.debug("{} nodes (enable TRACE to see exact definitions). Actions: {}. Listeners: {}", path.getNumberOfNodes(), path.getArcs(), this.getListeners());
this.logger.trace("Nodes: {}", path.getNodes());
this.post(event);
this.logger.debug("Event transmitted successfully.");
return event;
}
@Override
public IGraphGenerator<N, A> getGraphGenerator() {
return this.getInput().getGraphGenerator();
}
public IPathGoalTester<N, A> getGoalTester() {
return this.getInput().getGoalTester();
}
@Override
public void setLoggerName(final String name) {
this.logger.info("Switching logger to {}", name);
this.loggerName = name;
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Switched to logger {}", name);
super.setLoggerName(this.loggerName + "._algorithm");
}
@Override
public String getLoggerName() {
return this.loggerName;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core/interfaces/EdgeCountingSolutionEvaluator.java
|
package ai.libs.jaicore.search.core.interfaces;
import org.api4.java.common.attributedobjects.IObjectEvaluator;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
/**
* Uses Double to be compliant with algorithms that MUST work with double instead of Integer (such as AStar)
*
* @author fmohr
*
* @param <N>
*/
public class EdgeCountingSolutionEvaluator<N, A> implements IObjectEvaluator<SearchGraphPath<N, A>, Double> {
@Override
public Double evaluate(final SearchGraphPath<N, A> solutionPath) {
return solutionPath.getNodes().size() * 1.0;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core/interfaces/ISuccessorGenerationRelevantRemovalNode.java
|
package ai.libs.jaicore.search.core.interfaces;
public interface ISuccessorGenerationRelevantRemovalNode {
public boolean allowsGeneErasure();
public void eraseGenes();
public void recoverGenes();
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/core/interfaces/StandardORGraphSearchFactory.java
|
package ai.libs.jaicore.search.core.interfaces;
import org.api4.java.ai.graphsearch.problem.IPathSearch;
import org.api4.java.ai.graphsearch.problem.IPathSearchFactory;
import org.api4.java.ai.graphsearch.problem.IPathSearchInput;
import ai.libs.jaicore.basic.algorithm.AAlgorithmFactory;
public abstract class StandardORGraphSearchFactory<I extends IPathSearchInput<N, A>, O, N, A, V extends Comparable<V>, A2 extends IPathSearch<I, O, N, A>> extends AAlgorithmFactory<I, O, A2> implements IPathSearchFactory<I, O, N, A, A2> {
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/canadiantravelerproblem/CTPMDP.java
|
package ai.libs.jaicore.search.exampleproblems.canadiantravelerproblem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.graph.LabeledGraph;
import ai.libs.jaicore.search.exampleproblems.lake.ECTPEdgeKnowledge;
import ai.libs.jaicore.search.probleminputs.AMDP;
import it.unimi.dsi.fastutil.shorts.ShortArrayList;
import it.unimi.dsi.fastutil.shorts.ShortList;
public class CTPMDP extends AMDP<CTPState, Short, Double> {
private final LabeledGraph<Short, Double> network;
public CTPMDP(final LabeledGraph<Short, Double> network) {
super(new CTPState(new ShortArrayList(Arrays.asList((short)0)), new HashMap<>()));
this.network = network;
/* now set all edges in the MDP for reachable initial neighbors to known (either free or blocked) */
for (short succ : network.getSuccessors((short)0)) {
this.getInitState().getEdgeKnowledge().put(new Pair<>((short)0, succ), Math.random() < .5 ? ECTPEdgeKnowledge.KNOWN_BLOCKED : ECTPEdgeKnowledge.KNOWN_FREE);
}
}
@Override
public Collection<Short> getApplicableActions(final CTPState state) {
Collection<Short> applicable = new ArrayList<>();
for (short nextPos : this.network.getConnected(state.getPosition())) {
if (state.getCurrentTour().contains(nextPos) && (nextPos != 0 || state.getCurrentTour().size() != this.network.getItems().size())) { // avoid that a visited position is visited again (except the start 0)
continue;
}
short first = (short)Math.min(state.getPosition(), nextPos);
short second = (short)Math.max(state.getPosition(), nextPos);
ECTPEdgeKnowledge edgeKnowledge = state.getEdgeKnowledge().get(new Pair<>(first, second));
if (edgeKnowledge == null || edgeKnowledge == ECTPEdgeKnowledge.UNKNOWN) {
throw new IllegalStateException("Being at one end of an edge, we should know wheter or not it is blocked. However, knowledge is: " + edgeKnowledge);
}
if (edgeKnowledge == ECTPEdgeKnowledge.KNOWN_FREE) {
applicable.add(nextPos);
}
}
return applicable;
}
@Override
/**
* being now in "action" as the new state, check for each of the places reachable from there whether the roads are blocked */
public Map<CTPState, Double> getProb(final CTPState state, final Short action) throws InterruptedException {
/* there will be one possible successor state for each combination of cases of edges to locations we have NOT VISITED so far */
List<Pair<Short, Short>> unknownEdges = new ArrayList<>();
for (short nextPos : this.network.getConnected(action)) {
if (state.getCurrentTour().contains(nextPos)) { // edges to places already visited are irrelevant
continue;
}
short first = (short)Math.min(action, nextPos);
short second = (short)Math.max(action, nextPos);
Pair<Short, Short> edge = new Pair<>(first, second);
if (!state.getEdgeKnowledge().containsKey(edge)) {
unknownEdges.add(edge);
}
}
/* insert one successor for each possible knowledge acquisition and assuming uniform probabilities */
if (unknownEdges.isEmpty()) { // this happens when we move the last point, because we know whether there is snow from the origin to that point
Map<CTPState, Double> out = new HashMap<>();
Map<Pair<Short, Short>, ECTPEdgeKnowledge> curKnowledge = state.getEdgeKnowledge();
ShortList newTour = new ShortArrayList(state.getCurrentTour());
newTour.add((short)action);
CTPState succ = new CTPState(newTour, new HashMap<>(curKnowledge));
out.put(succ, 1.0); // we can then be sure to reach this state
return out;
}
else {
Collection<List<ECTPEdgeKnowledge>> combos = SetUtil.cartesianProduct(Arrays.asList(ECTPEdgeKnowledge.KNOWN_FREE, ECTPEdgeKnowledge.KNOWN_BLOCKED), unknownEdges.size());
Map<CTPState, Double> out = new HashMap<>();
double prob = 1.0 / combos.size();
ShortList newTour = new ShortArrayList(state.getCurrentTour());
Map<Pair<Short, Short>, ECTPEdgeKnowledge> curKnowledge = state.getEdgeKnowledge();
newTour.add((short)action);
for (List<ECTPEdgeKnowledge> combo : combos) {
Map<Pair<Short, Short>, ECTPEdgeKnowledge> newKnowledge = new HashMap<>(curKnowledge);
for (int i = 0; i < unknownEdges.size(); i++) {
newKnowledge.put(unknownEdges.get(i), combo.get(i));
}
CTPState succ = new CTPState(newTour, newKnowledge);
out.put(succ, prob);
}
return out;
}
}
@Override
public Double getScore(final CTPState state, final Short action, final CTPState successor) {
short first = (short)Math.min(state.getPosition(), action);
short second = (short)Math.max(state.getPosition(), action);
if (this.getApplicableActions(successor).isEmpty()) {
return Double.MAX_VALUE;
}
return this.network.getEdgeLabel(first, second).doubleValue();
}
@Override
public boolean isMaximizing() {
return false;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/canadiantravelerproblem/CTPState.java
|
package ai.libs.jaicore.search.exampleproblems.canadiantravelerproblem;
import java.util.Map;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.search.exampleproblems.lake.ECTPEdgeKnowledge;
import it.unimi.dsi.fastutil.shorts.ShortList;
public class CTPState {
private final ShortList currentTour;
private final Map<Pair<Short, Short>, ECTPEdgeKnowledge> edgeKnowledge;
public CTPState(final ShortList currentTour, final Map<Pair<Short, Short>, ECTPEdgeKnowledge> edgeKnowledge) {
super();
this.currentTour = currentTour;
this.edgeKnowledge = edgeKnowledge;
}
public ShortList getCurrentTour() {
return this.currentTour;
}
public Map<Pair<Short, Short>, ECTPEdgeKnowledge> getEdgeKnowledge() {
return this.edgeKnowledge;
}
public short getPosition() {
return this.currentTour.getShort(this.currentTour.size() - 1);
}
@Override
public String toString() {
return this.currentTour.toString() + " - " + this.edgeKnowledge;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.currentTour == null) ? 0 : this.currentTour.hashCode());
result = prime * result + ((this.edgeKnowledge == null) ? 0 : this.edgeKnowledge.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;
}
CTPState other = (CTPState) obj;
if (this.currentTour == null) {
if (other.currentTour != null) {
return false;
}
} else if (!this.currentTour.equals(other.currentTour)) {
return false;
}
if (this.edgeKnowledge == null) {
if (other.edgeKnowledge != null) {
return false;
}
} else if (!this.edgeKnowledge.equals(other.edgeKnowledge)) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/cannibals/CannibalGraphGenerator.java
|
package ai.libs.jaicore.search.exampleproblems.cannibals;
import java.util.ArrayList;
import java.util.List;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.IRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import ai.libs.jaicore.problems.cannibals.CannibalProblem;
import ai.libs.jaicore.search.model.NodeExpansionDescription;
public class CannibalGraphGenerator implements IGraphGenerator<CannibalProblem, String> {
private final CannibalProblem initState;
public CannibalGraphGenerator(final CannibalProblem initState) {
super();
this.initState = initState;
}
@Override
public IRootGenerator<CannibalProblem> getRootGenerator() {
return new ISingleRootGenerator<CannibalProblem>() {
@Override
public CannibalProblem getRoot() {
return CannibalGraphGenerator.this.initState;
}
};
}
@Override
public ISuccessorGenerator<CannibalProblem, String> getSuccessorGenerator() {
return new ISuccessorGenerator<CannibalProblem, String>() {
@Override
public List<INewNodeDescription<CannibalProblem, String>> generateSuccessors(final CannibalProblem node) throws InterruptedException {
List<INewNodeDescription<CannibalProblem, String>> successors = new ArrayList<>();
int ml = node.getMissionariesOnLeft();
int mr = node.getMissionariesOnRight();
int cl = node.getCannibalsOnLeft();
int cr = node.getCannibalsOnRight();
/* first consider the case that the boat is on the left */
if (node.isBoatOnLeft()) {
if (ml >= 2) {
CannibalProblem candidate = new CannibalProblem(false, ml - 2, cl, mr + 2, cr);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "2m->"));
}
}
if (ml >= 1) {
CannibalProblem candidate = new CannibalProblem(false, ml - 1, cl, mr + 1, cr);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "1m->"));
}
}
if (cl >= 1) {
CannibalProblem candidate = new CannibalProblem(false, ml, cl - 1, mr, cr + 1);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "1c->"));
}
}
if (ml >= 1 && cl >= 1) {
CannibalProblem candidate = new CannibalProblem(false, ml - 1, cl - 1, mr + 1, cr + 1);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "1m1c->"));
}
}
if (cl >= 2) {
CannibalProblem candidate = new CannibalProblem(false, ml, cl - 2, mr, cr + 2);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "2c->"));
}
}
}
/* now consider the cases that the boat is on the right */
else {
if (mr >= 2) {
CannibalProblem candidate = new CannibalProblem(true, ml + 2, cl, mr - 2, cr);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "2m<-"));
}
}
if (mr >= 1) {
CannibalProblem candidate = new CannibalProblem(true, ml + 1, cl, mr - 1, cr);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "1m<-"));
}
}
if (cr >= 1) {
CannibalProblem candidate = new CannibalProblem(true, ml, cl + 1, mr, cr - 1);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "1c<-"));
}
}
if (mr >= 1 && cr >= 1) {
CannibalProblem candidate = new CannibalProblem(true, ml + 1, cl + 1, mr - 1, cr - 1);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "1m1c<-"));
}
}
if (cr >= 2) {
CannibalProblem candidate = new CannibalProblem(true, ml, cl + 2, mr, cr - 2);
CannibalGraphGenerator.this.checkThatNumberOfPeopleHasNotChanged(node, candidate);
if (!candidate.isLost()) {
successors.add(new NodeExpansionDescription<>(candidate, "2c<-"));
}
}
}
return successors;
}
};
}
private void checkThatNumberOfPeopleHasNotChanged(final CannibalProblem a, final CannibalProblem b) {
if (a.getTotalNumberOfPeople() != b.getTotalNumberOfPeople()) {
throw new IllegalStateException("Number of people has changed from " + a.getTotalNumberOfPeople() + " to " + b.getTotalNumberOfPeople());
}
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/cannibals/CannibalNodeGoalPredicate.java
|
package ai.libs.jaicore.search.exampleproblems.cannibals;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester;
import ai.libs.jaicore.problems.cannibals.CannibalProblem;
public class CannibalNodeGoalPredicate implements INodeGoalTester<CannibalProblem, String> {
@Override
public boolean isGoal(final CannibalProblem n) {
return n.isWon();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/cannibals/CannibalProblemToGraphSearchReducer.java
|
package ai.libs.jaicore.search.exampleproblems.cannibals;
import java.util.List;
import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction;
import ai.libs.jaicore.problems.cannibals.CannibalProblem;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithPathEvaluationsInput;
public class CannibalProblemToGraphSearchReducer implements AlgorithmicProblemReduction<CannibalProblem, List<String>, GraphSearchWithPathEvaluationsInput<CannibalProblem, String, Integer>, SearchGraphPath<CannibalProblem, String>> {
@Override
public GraphSearchWithPathEvaluationsInput<CannibalProblem, String, Integer> encodeProblem(final CannibalProblem problem) {
return new GraphSearchWithPathEvaluationsInput<>(new CannibalGraphGenerator(problem), new CannibalNodeGoalPredicate(), p -> p.getArcs().size());
}
@Override
public List<String> decodeSolution(final SearchGraphPath<CannibalProblem, String> solution) {
return solution.getArcs();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/EnhancedTTSPGraphSearchToAdditiveGraphSearchReducer.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp;
import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSPState;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithNumberBasedAdditivePathEvaluation;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
public class EnhancedTTSPGraphSearchToAdditiveGraphSearchReducer implements AlgorithmicProblemReduction<GraphSearchWithSubpathEvaluationsInput<EnhancedTTSPState, String, Double>, EvaluatedSearchGraphPath<EnhancedTTSPState, String, Double>, GraphSearchWithNumberBasedAdditivePathEvaluation<EnhancedTTSPState, String>, EvaluatedSearchGraphPath<EnhancedTTSPState, String, Double>> {
@Override
public GraphSearchWithNumberBasedAdditivePathEvaluation<EnhancedTTSPState, String> encodeProblem(final GraphSearchWithSubpathEvaluationsInput<EnhancedTTSPState, String, Double> problem) {
return new GraphSearchWithNumberBasedAdditivePathEvaluation<>(problem, (from, to) -> to.getHead().getTime() - from.getHead().getTime(), node -> 0.0);
}
@Override
public EvaluatedSearchGraphPath<EnhancedTTSPState, String, Double> decodeSolution(final EvaluatedSearchGraphPath<EnhancedTTSPState, String, Double> solution) {
return solution;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/EnhancedTTSPGraphSearchToUncertaintyBasedGraphSearchReducer.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp;
import java.util.Random;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallyUncertaintyAnnotatingPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IUncertaintySource;
import org.api4.java.common.attributedobjects.IObjectEvaluator;
import org.api4.java.datastructure.graph.ILabeledPath;
import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSPState;
import ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation.RandomCompletionBasedNodeEvaluator;
import ai.libs.jaicore.search.model.other.AgnosticPathEvaluator;
import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithUncertaintyBasedSubpathEvaluationInput;
public class EnhancedTTSPGraphSearchToUncertaintyBasedGraphSearchReducer implements AlgorithmicProblemReduction<GraphSearchWithSubpathEvaluationsInput<EnhancedTTSPState, String, Double>, EvaluatedSearchGraphPath<EnhancedTTSPState, String, Double>, GraphSearchWithUncertaintyBasedSubpathEvaluationInput<EnhancedTTSPState, String, Double>, EvaluatedSearchGraphPath<EnhancedTTSPState, String, Double>> {
private Random random = new Random(0);
private int samples = 3;
private IObjectEvaluator<ILabeledPath<EnhancedTTSPState, String>, Double> solutionEvaluator = new AgnosticPathEvaluator<>();
private IUncertaintySource<EnhancedTTSPState, String, Double> uncertaintySource = (n, simulationPaths, simulationEvaluations) -> 0.5;
@Override
public GraphSearchWithUncertaintyBasedSubpathEvaluationInput<EnhancedTTSPState, String, Double> encodeProblem(final GraphSearchWithSubpathEvaluationsInput<EnhancedTTSPState, String, Double> problem) {
IPotentiallyUncertaintyAnnotatingPathEvaluator<EnhancedTTSPState, String, Double> nodeEvaluator = new RandomCompletionBasedNodeEvaluator<>(this.random, this.samples, this.solutionEvaluator);
nodeEvaluator.setUncertaintySource(this.uncertaintySource);
return new GraphSearchWithUncertaintyBasedSubpathEvaluationInput<>(problem, nodeEvaluator);
}
@Override
public EvaluatedSearchGraphPath<EnhancedTTSPState, String, Double> decodeSolution(final EvaluatedSearchGraphPath<EnhancedTTSPState, String, Double> solution) {
return solution;
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/EnhancedTTSPSimpleGraphGenerator.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.api4.java.datastructure.graph.implicit.ILazySuccessorGenerator;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.MappingIterator;
import ai.libs.jaicore.interrupt.UndeclaredInterruptedException;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSP;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSPState;
import ai.libs.jaicore.search.model.NodeExpansionDescription;
import it.unimi.dsi.fastutil.shorts.ShortList;
public class EnhancedTTSPSimpleGraphGenerator implements IGraphGenerator<EnhancedTTSPState, String>, ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(EnhancedTTSPSimpleGraphGenerator.class);
private final EnhancedTTSP problem;
public EnhancedTTSPSimpleGraphGenerator(final EnhancedTTSP problem) {
super();
this.problem = problem;
}
@Override
public ISingleRootGenerator<EnhancedTTSPState> getRootGenerator() {
return this.problem::getInitalState;
}
@Override
public ISuccessorGenerator<EnhancedTTSPState, String> getSuccessorGenerator() {
return new ILazySuccessorGenerator<EnhancedTTSPState, String>() {
@Override
public List<INewNodeDescription<EnhancedTTSPState, String>> generateSuccessors(final EnhancedTTSPState node) throws InterruptedException {
List<INewNodeDescription<EnhancedTTSPState, String>> l = new ArrayList<>();
if (node.getCurTour().size() >= EnhancedTTSPSimpleGraphGenerator.this.problem.getPossibleDestinations().size()) {
EnhancedTTSPSimpleGraphGenerator.this.logger.warn("Cannot generate successors of a node in which we are in pos {} and in which have already visited everything!", node.getCurLocation());
return l;
}
ShortList possibleUntriedDestinations = EnhancedTTSPSimpleGraphGenerator.this.problem.getPossibleRemainingDestinationsInState(node);
if (possibleUntriedDestinations.contains(node.getCurLocation())) {
throw new IllegalStateException("The list of possible destinations must not contain the current position " + node.getCurLocation() + ".");
}
int n = possibleUntriedDestinations.size();
for (int i = 0; i < n; i++) {
if (Thread.interrupted()) {
throw new InterruptedException("Successor generation has been interrupted.");
}
l.add(this.generateSuccessor(node, possibleUntriedDestinations.getShort(i)));
}
return l;
}
public INewNodeDescription<EnhancedTTSPState, String> generateSuccessor(final EnhancedTTSPState n, final short destination) throws InterruptedException {
return new NodeExpansionDescription<>(EnhancedTTSPSimpleGraphGenerator.this.problem.computeSuccessorState(n, destination), n.getCurLocation() + " -> " + destination);
}
@Override
public Iterator<INewNodeDescription<EnhancedTTSPState, String>> getIterativeGenerator(final EnhancedTTSPState node) {
ShortList availableDestinations = EnhancedTTSPSimpleGraphGenerator.this.problem.getPossibleRemainingDestinationsInState(node);
return new MappingIterator<>(availableDestinations.iterator(), s -> {
try {
return this.generateSuccessor(node, s);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new UndeclaredInterruptedException(e);
}
});
}
};
}
@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-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/EnhancedTTSPSimpleSolutionPredicate.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSP;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSPState;
public class EnhancedTTSPSimpleSolutionPredicate implements INodeGoalTester<EnhancedTTSPState, String> {
private EnhancedTTSP problem;
public EnhancedTTSPSimpleSolutionPredicate(final EnhancedTTSP problem) {
super();
this.problem = problem;
}
@Override
public boolean isGoal(final EnhancedTTSPState n) {
return n.getCurTour().size() >= this.problem.getPossibleDestinations().size() && n.getCurLocation() == this.problem.getStartLocation();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/EnhancedTTSPSolutionPredicate.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSP;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSPState;
public class EnhancedTTSPSolutionPredicate implements INodeGoalTester<EnhancedTTSPState, String> {
private EnhancedTTSP problem;
public EnhancedTTSPSolutionPredicate(final EnhancedTTSP problem) {
super();
this.problem = problem;
}
@Override
public boolean isGoal(final EnhancedTTSPState n) {
return n.getCurTour().size() >= this.problem.getPossibleDestinations().size() && n.getCurLocation() == this.problem.getStartLocation();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/EnhancedTTSPSuccessorGenerator.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.implicit.ILazySuccessorGenerator;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.MappingIterator;
import ai.libs.jaicore.basic.sets.EmptyIterator;
import ai.libs.jaicore.interrupt.UndeclaredInterruptedException;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSP;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSPState;
import ai.libs.jaicore.search.model.NodeExpansionDescription;
import it.unimi.dsi.fastutil.shorts.ShortArrayList;
import it.unimi.dsi.fastutil.shorts.ShortList;
public class EnhancedTTSPSuccessorGenerator implements ILazySuccessorGenerator<EnhancedTTSPState, String>, ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(EnhancedTTSPSuccessorGenerator.class);
private final EnhancedTTSP problem;
public EnhancedTTSPSuccessorGenerator(final EnhancedTTSP problem) {
super();
this.problem = problem;
}
private ShortList getPossibleDestinationsThatHaveNotBeenGeneratedYet(final EnhancedTTSPState n) {
short curLoc = n.getCurLocation();
ShortList possibleDestinationsToGoFromhere = new ShortArrayList();
ShortList seenPlaces = n.getCurTour();
int k = 0;
boolean openPlaces = seenPlaces.size() < this.problem.getPossibleDestinations().size() - 1;
assert n.getCurTour().size() < this.problem.getPossibleDestinations().size() : "We have already visited everything!";
assert openPlaces || curLoc != 0 : "There are no open places (out of the " + this.problem.getPossibleDestinations().size() + ", " + seenPlaces.size()
+ " of which have already been seen) but we are still in the initial position. This smells like a strange TSP.";
if (openPlaces) {
for (short l : this.problem.getPossibleDestinations()) {
if (k++ == 0) {
continue;
}
if (l != curLoc && !seenPlaces.contains(l)) {
possibleDestinationsToGoFromhere.add(l);
}
}
} else {
possibleDestinationsToGoFromhere.add((short) 0);
}
return possibleDestinationsToGoFromhere;
}
@Override
public List<INewNodeDescription<EnhancedTTSPState, String>> generateSuccessors(final EnhancedTTSPState node) throws InterruptedException {
this.logger.info("Generating all successors of node {}.", node);
List<INewNodeDescription<EnhancedTTSPState, String>> l = new ArrayList<>();
if (node.getCurTour().size() >= this.problem.getPossibleDestinations().size()) {
this.logger.warn("Cannot generate successors of a node in which we are in pos {} and in which have already visited everything!", node.getCurLocation());
return l;
}
ShortList possibleUntriedDestinations = this.getPossibleDestinationsThatHaveNotBeenGeneratedYet(node);
if (possibleUntriedDestinations.contains(node.getCurLocation())) {
throw new IllegalStateException("The list of possible destinations must not contain the current position " + node.getCurLocation() + ".");
}
int n = possibleUntriedDestinations.size();
for (int i = 0; i < n; i++) {
if (Thread.interrupted()) {
throw new InterruptedException("Successor generation has been interrupted.");
}
l.add(this.generateSuccessor(node, possibleUntriedDestinations.getShort(i)));
}
this.logger.info("Generated {} successors.", l.size());
return l;
}
public NodeExpansionDescription<EnhancedTTSPState, String> generateSuccessor(final EnhancedTTSPState n, final short destination) throws InterruptedException {
return new NodeExpansionDescription<>(this.problem.computeSuccessorState(n, destination), n.getCurLocation() + " -> " + destination);
}
@Override
public Iterator<INewNodeDescription<EnhancedTTSPState, String>> getIterativeGenerator(final EnhancedTTSPState node) {
this.logger.info("Creating iterative generator.");
if (node.getCurTour().size() == this.problem.getLocations().size()) {
return new EmptyIterator<>();
}
ShortList availableDestinations = this.getPossibleDestinationsThatHaveNotBeenGeneratedYet(node);
return new MappingIterator<>(availableDestinations.iterator(), s -> {
try {
return this.generateSuccessor(node, s);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new UndeclaredInterruptedException(e);
}
});
}
@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-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/EnhancedTTSPTelescopeGraphGenerator.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.util.FastMath;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSP;
import ai.libs.jaicore.problems.enhancedttsp.AEnhancedTTSPBinaryTelescopeNode;
import ai.libs.jaicore.problems.enhancedttsp.AEnhancedTTSPBinaryTelescopeNode.EnhancedTTSPBinaryTelescopeDestinationDecisionNode;
import ai.libs.jaicore.problems.enhancedttsp.AEnhancedTTSPBinaryTelescopeNode.EnhancedTTSPBinaryTelescopeDeterminedDestinationNode;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSPState;
import ai.libs.jaicore.search.model.NodeExpansionDescription;
import it.unimi.dsi.fastutil.shorts.ShortList;
public class EnhancedTTSPTelescopeGraphGenerator implements IGraphGenerator<AEnhancedTTSPBinaryTelescopeNode, String>, ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(EnhancedTTSPTelescopeGraphGenerator.class);
private final EnhancedTTSP problem;
public EnhancedTTSPTelescopeGraphGenerator(final EnhancedTTSP problem) {
super();
this.problem = problem;
this.logMode();
}
private void logMode() {
this.logger.info("Initialized {} with {} locations: {}", this.getClass().getSimpleName(), this.problem.getPossibleDestinations().size(), this.problem.getPossibleDestinations());
}
@Override
public ISingleRootGenerator<AEnhancedTTSPBinaryTelescopeNode> getRootGenerator() {
return () -> new EnhancedTTSPBinaryTelescopeDeterminedDestinationNode(null, this.problem.getInitalState());
}
@Override
public ISuccessorGenerator<AEnhancedTTSPBinaryTelescopeNode, String> getSuccessorGenerator() {
return new ISuccessorGenerator<AEnhancedTTSPBinaryTelescopeNode, String>() {
@Override
public List<INewNodeDescription<AEnhancedTTSPBinaryTelescopeNode, String>> generateSuccessors(final AEnhancedTTSPBinaryTelescopeNode node) throws InterruptedException {
long start = System.currentTimeMillis();
EnhancedTTSPTelescopeGraphGenerator.this.logger.info("Computing successors of node {}", node);
List<INewNodeDescription<AEnhancedTTSPBinaryTelescopeNode, String>> l = new ArrayList<>();
if (node.getCurTour().size() >= EnhancedTTSPTelescopeGraphGenerator.this.problem.getPossibleDestinations().size()) {
EnhancedTTSPTelescopeGraphGenerator.this.logger.info("Cannot generate successors of a node in which we are in pos {} and in which have already visited everything!", node.getCurLocation());
return l;
}
ShortList remainingTargets = EnhancedTTSPTelescopeGraphGenerator.this.problem.getPossibleRemainingDestinationsInState(node.getState());
EnhancedTTSPTelescopeGraphGenerator.this.logger.debug("Remaining targets: {}", remainingTargets);
short numberOfRemainingTargets = (short)(remainingTargets.size());
short minDepth = (short)Math.floor(FastMath.log(2, numberOfRemainingTargets));
int numberOfNodesOnMinDepthPlus1 = (numberOfRemainingTargets - (int)Math.pow(2, minDepth)) * 2;
/* get bit sets for child nodes */
List<Boolean> bitSetForLeftChild;
List<Boolean> bitSetForRightChild;
if (node instanceof EnhancedTTSPBinaryTelescopeDestinationDecisionNode) {
EnhancedTTSPBinaryTelescopeDestinationDecisionNode cNode = (EnhancedTTSPBinaryTelescopeDestinationDecisionNode)node;
bitSetForLeftChild = new ArrayList<>(cNode.getField());
bitSetForRightChild = new ArrayList<>(cNode.getField());
EnhancedTTSPTelescopeGraphGenerator.this.logger.debug("Cloning current BitVector {} into left and right.", bitSetForLeftChild);
}
else {
EnhancedTTSPTelescopeGraphGenerator.this.logger.debug("Creating new BitVector in this state node.");
bitSetForLeftChild = new ArrayList<>();
bitSetForRightChild = new ArrayList<>();
}
bitSetForLeftChild.add(false);
bitSetForRightChild.add(true);
/* determine whether the children are leaf nodes */
boolean leftChildIsLeaf = false;
boolean rightChildIsLeaf = false;
if (bitSetForLeftChild.size() >= minDepth) {
if (numberOfRemainingTargets == 2 || bitSetForLeftChild.size() == minDepth + 1) {
leftChildIsLeaf = true;
rightChildIsLeaf = true;
}
else { // here, the left child has depth minDepth
List<Boolean> leftChildOfLeftChild = new ArrayList<>(bitSetForLeftChild);
leftChildOfLeftChild.add(false);
long indexOfThatChild = convert(leftChildOfLeftChild);
leftChildIsLeaf = indexOfThatChild >= numberOfNodesOnMinDepthPlus1;
rightChildIsLeaf = leftChildIsLeaf || (indexOfThatChild + 2) >= numberOfNodesOnMinDepthPlus1;
}
}
if (Thread.interrupted()) {
throw new InterruptedException("Successor generation has been interrupted.");
}
EnhancedTTSPTelescopeGraphGenerator.this.logger.debug("Children bit-vectors are {}/{}. Leaf predicates are {}/{}", bitSetForLeftChild, bitSetForRightChild, leftChildIsLeaf, rightChildIsLeaf);
/* compute left child */
AEnhancedTTSPBinaryTelescopeNode leftChild;
if (leftChildIsLeaf) {
short firstNextDestination = EnhancedTTSPTelescopeGraphGenerator.this.getDestinationBasedOnBitVectorAndAvailableDestinations(remainingTargets, bitSetForLeftChild);
EnhancedTTSPTelescopeGraphGenerator.this.logger.debug("Determined next location {} (index {}) from bitvector {} for left child.", firstNextDestination, convert(bitSetForLeftChild), bitSetForLeftChild);
EnhancedTTSPState successorStateForLeftChild = EnhancedTTSPTelescopeGraphGenerator.this.problem.computeSuccessorState(node.getState(), firstNextDestination);
if (numberOfRemainingTargets == 2) { // if after this decision nothing can be decided anymore, enforce another state change
short other = remainingTargets.stream().filter(s -> s != firstNextDestination).findAny().get();
successorStateForLeftChild = EnhancedTTSPTelescopeGraphGenerator.this.problem.computeSuccessorState(successorStateForLeftChild, other);
successorStateForLeftChild = EnhancedTTSPTelescopeGraphGenerator.this.problem.computeSuccessorState(successorStateForLeftChild, EnhancedTTSPTelescopeGraphGenerator.this.problem.getStartLocation());
}
leftChild = new EnhancedTTSPBinaryTelescopeDeterminedDestinationNode(node, successorStateForLeftChild);
}
else {
leftChild = new EnhancedTTSPBinaryTelescopeDestinationDecisionNode(node, false);
}
/* compute right child */
AEnhancedTTSPBinaryTelescopeNode rightChild;
if (rightChildIsLeaf) {
short firstNextDestination = EnhancedTTSPTelescopeGraphGenerator.this.getDestinationBasedOnBitVectorAndAvailableDestinations(remainingTargets, bitSetForRightChild);
EnhancedTTSPTelescopeGraphGenerator.this.logger.debug("Determined next location {} (index {}) from bitvector {} for right child.", firstNextDestination, convert(bitSetForRightChild), bitSetForRightChild);
EnhancedTTSPState successorStateForRightChild = EnhancedTTSPTelescopeGraphGenerator.this.problem.computeSuccessorState(node.getState(), firstNextDestination);
if (numberOfRemainingTargets == 2) {
short other = remainingTargets.stream().filter(s -> s != firstNextDestination).findAny().get();
successorStateForRightChild = EnhancedTTSPTelescopeGraphGenerator.this.problem.computeSuccessorState(successorStateForRightChild, other);
successorStateForRightChild = EnhancedTTSPTelescopeGraphGenerator.this.problem.computeSuccessorState(successorStateForRightChild, EnhancedTTSPTelescopeGraphGenerator.this.problem.getStartLocation());
}
rightChild = new EnhancedTTSPBinaryTelescopeDeterminedDestinationNode(node, successorStateForRightChild);
}
else {
rightChild = new EnhancedTTSPBinaryTelescopeDestinationDecisionNode(node, true);
}
l.add(new NodeExpansionDescription<>(leftChild, "l"));
l.add(new NodeExpansionDescription<>(rightChild, "r"));
long walltime = System.currentTimeMillis() - start;
if (walltime > 10) {
EnhancedTTSPTelescopeGraphGenerator.this.logger.warn("Successor generation took {}ms", walltime);
}
return l;
}
};
}
public short getDestinationBasedOnBitVectorAndAvailableDestinations(final ShortList destinations, final List<Boolean> vector) {
short pathIndex = (short)convert(vector);
short numberOfRemainingTargets = (short)(destinations.size());
short minDepth = (short)Math.floor(FastMath.log(2, numberOfRemainingTargets));
int numberOfNodesAddedOnLastLayer = (numberOfRemainingTargets - (int)Math.pow(2, minDepth));
short correctedPathIndex = vector.size() == (minDepth + 1) ? pathIndex : (short)(pathIndex + numberOfNodesAddedOnLastLayer);
return destinations.getShort(correctedPathIndex);
}
public static long convert(final List<Boolean> bits) {
long value = 0L;
for (int i = 0; i < bits.size(); ++i) {
value += bits.get(i).booleanValue() ? (1L << (bits.size() - i - 1)) : 0L;
}
return value;
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
this.logMode();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/EnhancedTTSPToBinaryTelescopeGraphSearchReducer.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp;
import java.util.function.ToDoubleFunction;
import org.api4.java.datastructure.graph.ILabeledPath;
import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSP;
import ai.libs.jaicore.problems.enhancedttsp.AEnhancedTTSPBinaryTelescopeNode;
import ai.libs.jaicore.search.exampleproblems.enhancedttsp.binarytelescope.EnhancedTTSPBinaryTelescopeSolutionPredicate;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
import it.unimi.dsi.fastutil.shorts.ShortList;
public class EnhancedTTSPToBinaryTelescopeGraphSearchReducer
implements AlgorithmicProblemReduction<EnhancedTTSP, ShortList, GraphSearchWithSubpathEvaluationsInput<AEnhancedTTSPBinaryTelescopeNode, String, Double>, ILabeledPath<AEnhancedTTSPBinaryTelescopeNode, String>> {
private final ToDoubleFunction<Number> linkFunction;
public EnhancedTTSPToBinaryTelescopeGraphSearchReducer() {
this(x -> (double)x);
}
public EnhancedTTSPToBinaryTelescopeGraphSearchReducer(final ToDoubleFunction<Number> linkFunction) {
this.linkFunction = linkFunction;
}
@Override
public GraphSearchWithSubpathEvaluationsInput<AEnhancedTTSPBinaryTelescopeNode, String, Double> encodeProblem(final EnhancedTTSP problem) {
return new GraphSearchWithSubpathEvaluationsInput<>(new EnhancedTTSPTelescopeGraphGenerator(problem), new EnhancedTTSPBinaryTelescopeSolutionPredicate(problem), path -> {
ShortList tour = this.decodeSolution(path);
double score = problem.getSolutionEvaluator().evaluate(tour);
double linkedScore = this.linkFunction.applyAsDouble(score);
return linkedScore;
});
}
@Override
public ShortList decodeSolution(final ILabeledPath<AEnhancedTTSPBinaryTelescopeNode, String> solution) {
return solution.getHead().getCurTour();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/EnhancedTTSPToSimpleGraphSearchReducer.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp;
import java.util.function.ToDoubleFunction;
import org.api4.java.datastructure.graph.ILabeledPath;
import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSP;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSPState;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
import it.unimi.dsi.fastutil.shorts.ShortList;
public class EnhancedTTSPToSimpleGraphSearchReducer
implements AlgorithmicProblemReduction<EnhancedTTSP, ShortList, GraphSearchWithSubpathEvaluationsInput<EnhancedTTSPState, String, Double>, ILabeledPath<EnhancedTTSPState, String>> {
private final ToDoubleFunction<Number> linkFunction;
public EnhancedTTSPToSimpleGraphSearchReducer() {
this(x -> (double)x);
}
public EnhancedTTSPToSimpleGraphSearchReducer(final ToDoubleFunction<Number> linkFunction) {
this.linkFunction = linkFunction;
}
@Override
public GraphSearchWithSubpathEvaluationsInput<EnhancedTTSPState, String, Double> encodeProblem(final EnhancedTTSP problem) {
return new GraphSearchWithSubpathEvaluationsInput<>(new EnhancedTTSPSimpleGraphGenerator(problem), new EnhancedTTSPSimpleSolutionPredicate(problem), node -> this.linkFunction.applyAsDouble(problem.getSolutionEvaluator().evaluate(node.getHead().getCurTour())));
}
@Override
public ShortList decodeSolution(final ILabeledPath<EnhancedTTSPState, String> solution) {
ShortList tour = solution.getHead().getCurTour();
return tour.subList(0, tour.size() - 1); // remove trailing 0
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/enhancedttsp/binarytelescope/EnhancedTTSPBinaryTelescopeSolutionPredicate.java
|
package ai.libs.jaicore.search.exampleproblems.enhancedttsp.binarytelescope;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester;
import ai.libs.jaicore.problems.enhancedttsp.EnhancedTTSP;
import ai.libs.jaicore.problems.enhancedttsp.AEnhancedTTSPBinaryTelescopeNode;
public class EnhancedTTSPBinaryTelescopeSolutionPredicate implements INodeGoalTester<AEnhancedTTSPBinaryTelescopeNode, String> {
private EnhancedTTSP problem;
public EnhancedTTSPBinaryTelescopeSolutionPredicate(final EnhancedTTSP problem) {
super();
this.problem = problem;
}
@Override
public boolean isGoal(final AEnhancedTTSPBinaryTelescopeNode n) {
return n.getCurTour().size() >= this.problem.getPossibleDestinations().size() && n.getCurLocation() == this.problem.getStartLocation();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/gridworld/GridWorldBasicGraphGenerator.java
|
package ai.libs.jaicore.search.exampleproblems.gridworld;
import java.util.ArrayList;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.IRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import ai.libs.jaicore.problems.gridworld.GridWorldNode;
import ai.libs.jaicore.problems.gridworld.GridWorldProblem;
import ai.libs.jaicore.search.model.NodeExpansionDescription;
public class GridWorldBasicGraphGenerator implements IGraphGenerator<GridWorldNode, String> {
private final GridWorldProblem problem;
public GridWorldBasicGraphGenerator(final GridWorldProblem problem) {
super();
this.problem = problem;
}
@Override
public IRootGenerator<GridWorldNode> getRootGenerator() {
return new ISingleRootGenerator<GridWorldNode>() {
@Override
public GridWorldNode getRoot() {
return new GridWorldNode(GridWorldBasicGraphGenerator.this.problem, GridWorldBasicGraphGenerator.this.problem.getStartX(), GridWorldBasicGraphGenerator.this.problem.getStartY());
}
};
}
@Override
public ISuccessorGenerator<GridWorldNode, String> getSuccessorGenerator() {
return node -> {
ArrayList<INewNodeDescription<GridWorldNode, String>> succ = new ArrayList<>();
for (int a = 4; a <= 9; a++) {
// x direction movement
int dx = 1;
if (a == 2 || a == 7) {
dx = 0;
}
if (a == 1 || a == 4 || a == 6) {
dx = -1;
}
// y direction movement
int dy = 1;
if (a == 4 || a == 5) {
dy = 0;
}
if (a == 1 || a == 2 || a == 3) {
dy = -1;
}
int newPosX = node.getX() + dx;
int newPosY = node.getY() + dy;
if (newPosX < GridWorldBasicGraphGenerator.this.problem.getGrid().length && newPosY < GridWorldBasicGraphGenerator.this.problem.getGrid()[0].length) {
succ.add(new NodeExpansionDescription<>(new GridWorldNode(GridWorldBasicGraphGenerator.this.problem, newPosX, newPosY), Integer.toString(a)));
}
}
return succ;
};
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/gridworld/GridWorldHeuristic.java
|
package ai.libs.jaicore.search.exampleproblems.gridworld;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.datastructure.graph.ILabeledPath;
import ai.libs.jaicore.problems.gridworld.GridWorldNode;
public class GridWorldHeuristic implements IPathEvaluator<GridWorldNode, Object, Double> {
private final int targetX;
private final int targetY;
public GridWorldHeuristic(final int targetX, final int targetY) {
super();
this.targetX = targetX;
this.targetY = targetY;
}
@Override
public Double evaluate(final ILabeledPath<GridWorldNode, Object> node) {
double x = Math.abs(this.targetX - node.getHead().getX());
double y = Math.abs(this.targetY - node.getHead().getY());
return Double.valueOf(x + y);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/knapsack/KnapsackProblemGraphGenerator.java
|
package ai.libs.jaicore.search.exampleproblems.knapsack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.IntStream;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.graph.implicit.IGraphGenerator;
import org.api4.java.datastructure.graph.implicit.ILazySuccessorGenerator;
import org.api4.java.datastructure.graph.implicit.INewNodeDescription;
import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator;
import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.MappingIterator;
import ai.libs.jaicore.problems.knapsack.KnapsackConfiguration;
import ai.libs.jaicore.problems.knapsack.KnapsackProblem;
import ai.libs.jaicore.search.model.NodeExpansionDescription;
public class KnapsackProblemGraphGenerator implements IGraphGenerator<KnapsackConfiguration, String>, ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(KnapsackProblemGraphGenerator.class);
private final KnapsackProblem problem;
public KnapsackProblemGraphGenerator(final KnapsackProblem problem) {
super();
this.problem = problem;
}
@Override
public ISingleRootGenerator<KnapsackConfiguration> getRootGenerator() {
return () -> new KnapsackConfiguration(new HashSet<>(), this.problem.getObjects(), 0.0);
}
class KnapsackSuccessorGenerator implements ILazySuccessorGenerator<KnapsackConfiguration, String> {
private Map<KnapsackConfiguration, Set<Integer>> expandedChildren = new HashMap<>();
private List<String> getPossiblePackingObjects(final KnapsackConfiguration n) {
List<String> possibleObjects = new ArrayList<>();
Optional<String> objectWithHighestName = n.getPackedObjects().stream().max((o1, o2) -> o1.compareTo(o2));
for (String object : n.getRemainingObjects()) {
if ((!objectWithHighestName.isPresent() || objectWithHighestName.get().compareTo(object) <= 0)
&& n.getUsedCapacity() + KnapsackProblemGraphGenerator.this.problem.getWeights().get(object) <= KnapsackProblemGraphGenerator.this.problem.getKnapsackCapacity()) {
possibleObjects.add(object);
}
}
return possibleObjects;
}
@Override
public List<INewNodeDescription<KnapsackConfiguration, String>> generateSuccessors(final KnapsackConfiguration node) throws InterruptedException {
List<INewNodeDescription<KnapsackConfiguration, String>> l = new ArrayList<>();
List<String> possibleDestinations = this.getPossiblePackingObjects(node);
int n = possibleDestinations.size();
Thread.sleep(1);
long lastSleep = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
if (System.currentTimeMillis() - lastSleep > 10) {
if (Thread.interrupted()) { // reset interrupted flag prior to throwing the exception (Java convention)
KnapsackProblemGraphGenerator.this.logger.info("Successor generation has been interrupted.");
throw new InterruptedException("Successor generation interrupted");
}
Thread.sleep(1);
lastSleep = System.currentTimeMillis();
KnapsackProblemGraphGenerator.this.logger.info("Sleeping");
}
l.add(this.generateSuccessor(node, possibleDestinations, i));
}
return l;
}
public INewNodeDescription<KnapsackConfiguration, String> generateSuccessor(final KnapsackConfiguration node, final List<String> objetcs, final int i) {
KnapsackProblemGraphGenerator.this.logger.debug("Generating successor #{} of {}", i, node);
if (!this.expandedChildren.containsKey(node)) {
this.expandedChildren.put(node, new HashSet<>());
}
int n = objetcs.size();
if (n == 0) {
KnapsackProblemGraphGenerator.this.logger.debug("No objects left, quitting.");
return null;
}
int j = i % n;
this.expandedChildren.get(node).add(j);
String object = objetcs.get(j);
KnapsackProblemGraphGenerator.this.logger.trace("Creating set of remaining objects when choosing {}.", object);
Set<String> packedObjects = new HashSet<>();
Set<String> remainingObjects = new HashSet<>();
boolean foundRemoved = false;
for (String item : node.getRemainingObjects()) {
if (!foundRemoved && item.equals(object)) {
foundRemoved = true;
packedObjects.add(item);
}
else {
remainingObjects.add(item);
}
}
packedObjects.addAll(node.getPackedObjects());
KnapsackProblemGraphGenerator.this.logger.trace("Ready.");
double usedCapacity = node.getUsedCapacity() + KnapsackProblemGraphGenerator.this.problem.getWeights().get(object);
KnapsackConfiguration newNode = new KnapsackConfiguration(packedObjects, remainingObjects, usedCapacity);
return new NodeExpansionDescription<>(newNode, "(" + node.getPackedObjects() + ", " + object + ")");
}
@Override
public Iterator<INewNodeDescription<KnapsackConfiguration, String>> getIterativeGenerator(final KnapsackConfiguration node) {
List<String> possibleObjects = this.getPossiblePackingObjects(node);
return new MappingIterator<>(IntStream.range(0, possibleObjects.size()).iterator(), i -> this.generateSuccessor(node, possibleObjects, i));
}
}
@Override
public ISuccessorGenerator<KnapsackConfiguration, String> getSuccessorGenerator() {
return new KnapsackSuccessorGenerator();
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Switched logger name to {}", name);
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/knapsack/KnapsackToGraphSearchReducer.java
|
package ai.libs.jaicore.search.exampleproblems.knapsack;
import java.util.Set;
import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator;
import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException;
import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException;
import org.api4.java.datastructure.graph.ILabeledPath;
import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction;
import ai.libs.jaicore.problems.knapsack.KnapsackConfiguration;
import ai.libs.jaicore.problems.knapsack.KnapsackProblem;
import ai.libs.jaicore.search.model.other.SearchGraphPath;
import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput;
public class KnapsackToGraphSearchReducer implements AlgorithmicProblemReduction<KnapsackProblem, Set<String>, GraphSearchWithSubpathEvaluationsInput<KnapsackConfiguration, String, Double>, SearchGraphPath<KnapsackConfiguration, String>> {
@Override
public GraphSearchWithSubpathEvaluationsInput<KnapsackConfiguration, String, Double> encodeProblem(final KnapsackProblem problem) {
return new GraphSearchWithSubpathEvaluationsInput<>(new KnapsackProblemGraphGenerator(problem), new INodeGoalTester<KnapsackConfiguration, String>() {
@Override
public boolean isGoal(final KnapsackConfiguration n) {
for (String object : n.getRemainingObjects()) {
if (n.getUsedCapacity() + problem.getWeights().get(object) <= problem.getKnapsackCapacity()) {
return false;
}
}
return true;
}
}, new IPathEvaluator<KnapsackConfiguration, String, Double>() {
@Override
public Double evaluate(final ILabeledPath<KnapsackConfiguration, String> path) throws PathEvaluationException, InterruptedException {
try {
return problem.getSolutionEvaluator().evaluate(path.getHead());
}
catch (ObjectEvaluationFailedException e) {
throw new PathEvaluationException("Could not evaluate node due to an algorithm exception: " + e.getMessage(), e);
}
}
});
}
@Override
public Set<String> decodeSolution(final SearchGraphPath<KnapsackConfiguration, String> solution) {
return solution.getNodes().get(solution.getNodes().size() - 1).getPackedObjects();
}
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/lake/ECTPEdgeKnowledge.java
|
package ai.libs.jaicore.search.exampleproblems.lake;
public enum ECTPEdgeKnowledge {
UNKNOWN, KNOWN_BLOCKED, KNOWN_FREE
}
|
0
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems
|
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/lake/ELakeActions.java
|
package ai.libs.jaicore.search.exampleproblems.lake;
public enum ELakeActions {
UP, RIGHT, DOWN, LEFT
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.