index
int64
repo_id
string
file_path
string
content
string
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/FelixLakeMDP.java
package ai.libs.jaicore.search.exampleproblems.lake; public class FelixLakeMDP extends LakeMDP { public static boolean[][] getPits(final int height) { boolean[][] pits = new boolean[height][5]; for (int i = 2; i < height - 1; i++) { pits[i][2] = true; } return pits; } public FelixLakeMDP(final int height, final int timeout) { super(new LakeLayout(height, 5, getPits(height)), height - 1, 0, height - 1, 4, timeout); } }
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/JasminLakeMDP.java
package ai.libs.jaicore.search.exampleproblems.lake; public class JasminLakeMDP extends LakeMDP { private static boolean[][] pits = new boolean[][] { {false, false, false, false}, {false, true, false, true}, {false, false, false, true}, {true, false, false, false} }; public JasminLakeMDP() { this(0); } public JasminLakeMDP(final int timeout) { super(new LakeLayout(4, 4, pits), 0, 0, 3, 3, timeout); } }
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/LakeLayout.java
package ai.libs.jaicore.search.exampleproblems.lake; import java.util.Arrays; public class LakeLayout { private final int rows; private final int cols; private final boolean[][] pits; public LakeLayout(final int rows, final int cols, final boolean[][] pits) { super(); this.rows = rows; this.cols = cols; this.pits = pits; } public int getRows() { return this.rows; } public int getCols() { return this.cols; } public boolean[][] getPits() { return this.pits; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.cols; result = prime * result + Arrays.hashCode(this.pits); result = prime * result + this.rows; 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; } LakeLayout other = (LakeLayout) obj; if (this.cols != other.cols) { return false; } if (!Arrays.equals(this.pits, other.pits)) { return false; } return (this.rows == other.rows); } }
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/LakeMDP.java
package ai.libs.jaicore.search.exampleproblems.lake; 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.search.algorithms.mdp.mcts.ActionPredictionFailedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.probleminputs.AMDP; public class LakeMDP extends AMDP<TimedLakeState, ELakeActions, Double> { private static final Collection<ELakeActions> POSSIBLE_ACTIONS = Arrays.asList(ELakeActions.values()); private final LakeLayout layout; private final int goalRow; private final int goalCol; private final int timeout; private final boolean timed; private boolean infinite; private double rewardGoal = 1; private double rewardPit = 0; private double rewardOrdinary = 0; public LakeMDP(final LakeLayout layout, final int startRow, final int startCol, final int goalRow, final int goalCol, final int timeout) { super(new TimedLakeState(layout, startRow, startCol, 0)); this.layout = layout; this.goalRow = goalRow; this.goalCol = goalCol; this.timeout = timeout; this.timed = timeout > 0; } @Override public Collection<ELakeActions> getApplicableActions(final TimedLakeState state) { if (!this.infinite && (this.timed && state.getTime() >= this.timeout) || state.isInPit() || this.isGoalState(state)) { return Arrays.asList(); } return POSSIBLE_ACTIONS; } @Override public Map<TimedLakeState, Double> getProb(final TimedLakeState state, final ELakeActions action) { Map<TimedLakeState, Double> dist = new HashMap<>(); List<TimedLakeState> possibleOutcomes = new ArrayList<>(3); switch (action) { case UP: possibleOutcomes.add(this.left(state)); possibleOutcomes.add(this.up(state)); possibleOutcomes.add(this.right(state)); break; case RIGHT: possibleOutcomes.add(this.up(state)); possibleOutcomes.add(this.right(state)); possibleOutcomes.add(this.down(state)); break; case DOWN: possibleOutcomes.add(this.left(state)); possibleOutcomes.add(this.down(state)); possibleOutcomes.add(this.right(state)); break; case LEFT: possibleOutcomes.add(this.left(state)); possibleOutcomes.add(this.up(state)); possibleOutcomes.add(this.down(state)); break; default: throw new IllegalArgumentException("Unknown action " + action); } /* compute frequencies for the different outcomes */ for (TimedLakeState succ : possibleOutcomes) { dist.put(succ, dist.computeIfAbsent(succ, s -> 0.0) + 1.0 / 3); } return dist; } public boolean isGoalState(final LakeState s) { return (s.getRow() == this.goalRow && s.getCol() == this.goalCol); } public TimedLakeState up(final TimedLakeState s) { return new TimedLakeState(s.getLayout(), Math.max(0, s.getRow() - 1), s.getCol(), this.timed ? s.getTime() + 1 : s.getTime()); } public TimedLakeState down(final TimedLakeState s) { return new TimedLakeState(s.getLayout(), Math.min(this.layout.getRows() - 1, s.getRow() + 1), s.getCol(), this.timed ? s.getTime() + 1 : s.getTime()); } public TimedLakeState left(final TimedLakeState s) { return new TimedLakeState(s.getLayout(), s.getRow(), Math.max(0, s.getCol() - 1), this.timed ? s.getTime() + 1 : s.getTime()); } public TimedLakeState right(final TimedLakeState s) { return new TimedLakeState(s.getLayout(), s.getRow(), Math.min(this.layout.getCols() - 1, s.getCol() + 1), this.timed ? s.getTime() + 1 : s.getTime()); } @Override public Double getScore(final TimedLakeState state, final ELakeActions action, final TimedLakeState successor) { if (this.timed) { return successor.isInPit() ? (1 - state.getTime() * 1.0 / this.timeout) : 1.0 / this.timeout; // every move gets more expensive than the previous one } else { if (this.isGoalState(successor)) { return this.rewardGoal; } else { return successor.isInPit() ? this.rewardPit : this.rewardOrdinary; } } } public double getRewardGoal() { return this.rewardGoal; } public void setRewardGoal(final double rewardGoal) { this.rewardGoal = rewardGoal; } public double getRewardPit() { return this.rewardPit; } public void setRewardPit(final double rewardPit) { this.rewardPit = rewardPit; } public double getRewardOrdinary() { return this.rewardOrdinary; } public void setRewardOrdinary(final double rewardOrdinary) { this.rewardOrdinary = rewardOrdinary; } @Override public boolean isMaximizing() { return !this.timed; // when timed, we try to get to the other side as quick as possible } public boolean isInfinite() { return this.infinite; } public void setInfinite(final boolean infinite) { this.infinite = infinite; } public String getStringVisualizationOfPolicy(final IPolicy<TimedLakeState, ELakeActions> policy) { StringBuilder sb = new StringBuilder(); int cols = this.layout.getCols(); int rows = this.layout.getRows(); for (int r = 0; r < rows; r++) { /* print grid above row */ for (int c = 0; c < cols; c++) { sb.append("+-"); } sb.append("+\n"); /* print content of row */ for (int c = 0; c < cols; c++) { sb.append("|"); TimedLakeState state = new TimedLakeState(this.layout, r, c, 0); try { ELakeActions action = policy.getAction(state, this.getApplicableActions(state)); sb.append(action != null ? action.toString().substring(0, 1) : "/"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // re-interrupt break; } catch (ActionPredictionFailedException e) { sb.append("EXCEPTION"); } } sb.append("+\n"); } return sb.toString(); } }
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/LakeState.java
package ai.libs.jaicore.search.exampleproblems.lake; public class LakeState { private final LakeLayout layout; private final int row; private final int col; public LakeState(final LakeLayout layout, final int row, final int col) { super(); this.layout = layout; this.row = row; this.col = col; } public LakeLayout getLayout() { return this.layout; } public int getRow() { return this.row; } public int getCol() { return this.col; } public boolean isInPit() { return this.layout.getPits()[this.row][this.col]; } public String getStringVisualization() { StringBuilder sb = new StringBuilder(); int cols = this.layout.getCols(); int rows = this.layout.getRows(); for (int r = 0; r < rows; r++) { /* print grid above row */ for (int c = 0; c < cols; c ++) { sb.append("+-"); } sb.append("+\n"); /* print content of row */ for (int c = 0; c < cols; c ++) { sb.append("|"); if (c == this.col && r == this.row) { sb.append("x"); } else if (this.layout.getPits()[r][c]) { sb.append("*"); } else { sb.append(" "); } } sb.append("+\n"); } return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.col; result = prime * result + ((this.layout == null) ? 0 : this.layout.hashCode()); result = prime * result + this.row; 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; } LakeState other = (LakeState) obj; if (this.col != other.col) { return false; } if (this.layout == null) { if (other.layout != null) { return false; } } else if (!this.layout.equals(other.layout)) { return false; } return this.row == other.row; } @Override public String toString() { return this.row + "/" + this.col; } }
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/TimedLakeState.java
package ai.libs.jaicore.search.exampleproblems.lake; public class TimedLakeState extends LakeState { private final int time; public TimedLakeState(final LakeLayout layout, final int row, final int col, final int time) { super(layout, row, col); this.time = time; } public int getTime() { return this.time; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + this.time; return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } TimedLakeState other = (TimedLakeState) obj; return this.time == other.time; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle/parentdiscarding/PDPuzzleGenerator.java
package ai.libs.jaicore.search.exampleproblems.npuzzle.parentdiscarding; import java.util.ArrayList; import java.util.Arrays; 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.ISingleRootGenerator; import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator; import ai.libs.jaicore.search.model.NodeExpansionDescription; public class PDPuzzleGenerator implements IGraphGenerator<PDPuzzleNode, String> { protected int dimension; private PDPuzzleNode root; public PDPuzzleGenerator(final int[][] board, final int emptyX, final int emptyY) { this.dimension = board.length; this.root = new PDPuzzleNode(board, emptyX, emptyY); } @Override public ISingleRootGenerator<PDPuzzleNode> getRootGenerator() { return () -> this.root; } @Override public ISuccessorGenerator<PDPuzzleNode, String> getSuccessorGenerator() { return n -> { List<INewNodeDescription<PDPuzzleNode, String>> successors = new ArrayList<>(); // Possible successors if (n.getEmptyX() > 0) { successors.add(new NodeExpansionDescription<>(this.move(n, "l"), "l")); } if (n.getEmptyX() < this.dimension - 1) { successors.add(new NodeExpansionDescription<>(this.move(n, "r"), "r")); } if (n.getEmptyY() > 0) { successors.add(new NodeExpansionDescription<>(this.move(n, "u"), "u")); } if (n.getEmptyY() < this.dimension - 1) { successors.add(new NodeExpansionDescription<>(this.move(n, "d"), "d")); } return successors; }; } /** * Moves the empty tile to another location. * The possible parameters to move the empty tiles are: * <code>l</code> for moving the empty space to the left. * <code>right</code> for moving the empty space to the right. * <code>u</code> for moving the empty space upwards. * <code>d</down> for moving the empty space downwards. * * @param n * The PDPuzzleNode which contains the boardconfiguration. * * @param m * The character which indicates the specific moves. Possible characters are given above. * */ public PDPuzzleNode move(final PDPuzzleNode n, final String move) { switch (move) { case "l": return this.move(n, 0, -1); case "r": return this.move(n, 0, 1); case "d": return this.move(n, 1, 0); case "u": return this.move(n, -1, 0); default: throw new IllegalArgumentException(move + " is not a valid move. Valid moves: {l, r, d, u}"); } } /** * The actual move of the empty tile. * * @param n * The node which contains the boardconfiguration. * @param y * The movement on the y-axis. This value should be -1 if going upwards, 1 if going downwards. * Otherwise it should be 0. * @param x * The movement on the y-axis. This value should be -1 if going left, 1 if going right. * Otherwise it should be 0. */ public PDPuzzleNode move(final PDPuzzleNode n, final int y, final int x) { // cloning the board for the new node if (x == y || Math.abs(x) > 1 || Math.abs(y) > 1) { return null; } int[][] b = new int[this.dimension][this.dimension]; int[][] board = n.getBoard(); for (int i = 0; i < this.dimension; i++) { b[i] = Arrays.copyOf(board[i], board[i].length); } int eX = n.getEmptyX(); int eY = n.getEmptyY(); b[eY][eX] = b[eY + y][eX + x]; b[eY + y][eX + x] = 0; return new PDPuzzleNode(b, eX + x, eY + y); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle/parentdiscarding/PDPuzzleNode.java
package ai.libs.jaicore.search.exampleproblems.npuzzle.parentdiscarding; import java.util.Arrays; import ai.libs.jaicore.problems.npuzzle.NPuzzleState; public class PDPuzzleNode extends NPuzzleState { public PDPuzzleNode(final int[][] board, final int emptyX, final int emptyY) { super(board, emptyX, emptyY); } /* (non-Javadoc) * @see jaicore.search.algorithms.standard.npuzzle.NPuzzleNode#getDistance() */ @Override public double getDistance() { return (double) Math.abs((this.board.length - 1) - this.emptyX) + Math.abs((this.board.length - 1) - this.emptyY); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.deepHashCode(this.board); result = prime * result + this.emptyX; result = prime * result + this.emptyY; return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } NPuzzleState other = (NPuzzleState) obj; if (this.emptyX != other.getEmptyX()) { return false; } return this.emptyY == other.getEmptyY(); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle/standard/NPuzzleGoalPredicate.java
package ai.libs.jaicore.search.exampleproblems.npuzzle.standard; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester; import ai.libs.jaicore.problems.npuzzle.NPuzzleState; public class NPuzzleGoalPredicate implements INodeGoalTester<NPuzzleState, String> { private final int dimension; public NPuzzleGoalPredicate(final int dimension) { super(); this.dimension = dimension; } @Override public boolean isGoal(final NPuzzleState n) { int[][] board = n.getBoard(); if (board[this.dimension - 1][this.dimension - 1] != 0) { return false; } else { int sol = 1; for (int i = 0; i < this.dimension; i++) { for (int j = 0; j < this.dimension; j++) { if (i != this.dimension - 1 && j != this.dimension - 1 && board[i][j] != sol) { return false; } sol++; } } return true; } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle/standard/NPuzzleGraphGenerator.java
package ai.libs.jaicore.search.exampleproblems.npuzzle.standard; import java.util.ArrayList; import java.util.Arrays; 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.ISingleRootGenerator; import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator; import ai.libs.jaicore.problems.npuzzle.NPuzzleState; import ai.libs.jaicore.search.model.NodeExpansionDescription; /** * A simple generator for the normal NPuzzleProblem. * * @author jkoepe * */ public class NPuzzleGraphGenerator implements IGraphGenerator<NPuzzleState, String> { protected int dimension; private NPuzzleState root; public NPuzzleGraphGenerator(final int[][] board) { this.dimension = board.length; int emptyX = 0; int emptyY = 0; for (int x = 0; x < board.length; x++) { for (int y = 0; y < board[x].length; y++) { if (board[x][y] == 0) { emptyX = x; emptyY = y; break; } } } this.root = new NPuzzleState(board, emptyX, emptyY); } @Override public ISingleRootGenerator<NPuzzleState> getRootGenerator() { return () -> this.root; } @Override public ISuccessorGenerator<NPuzzleState, String> getSuccessorGenerator() { return n -> { List<INewNodeDescription<NPuzzleState, String>> successors = new ArrayList<>(); // Possible successors if (n.getEmptyX() > 0) { successors.add(new NodeExpansionDescription<>(this.move(n, "l"), "l")); } if (n.getEmptyX() < this.dimension - 1) { successors.add(new NodeExpansionDescription<>(this.move(n, "r"), "r")); } if (n.getEmptyY() > 0) { successors.add(new NodeExpansionDescription<>(this.move(n, "u"), "u")); } if (n.getEmptyY() < this.dimension - 1) { successors.add(new NodeExpansionDescription<>(this.move(n, "d"), "d")); } return successors; }; } /** * Moves the empty tile to another location. * The possible parameters to move the empty tiles are: * <code>l</code> for moving the empty space to the left. * <code>right</code> for moving the empty space to the right. * <code>u</code> for moving the empty space upwards. * <code>d</down> for moving the empty space downwards. * * @param n * The NPuzzleNode which contains the boardconfiguration. * * @param m * The character which indicates the specific moves. Possible characters are given above. * */ public NPuzzleState move(final NPuzzleState n, final String move) { switch (move) { case "l": return this.move(n, 0, -1); case "r": return this.move(n, 0, 1); case "d": return this.move(n, 1, 0); case "u": return this.move(n, -1, 0); default: throw new IllegalArgumentException(move + " is not a valid move. Valid moves: {l, r, d, u}"); } } /** * The actual move of the empty tile. * * @param n * The node which contains the boardconfiguration. * @param y * The movement on the y-axis. This value should be -1 if going upwards, 1 if going downwards. * Otherwise it should be 0. * @param x * The movement on the y-axis. This value should be -1 if going left, 1 if going right. * Otherwise it should be 0. */ public NPuzzleState move(final NPuzzleState n, final int y, final int x) { // cloning the board for the new node if (x == y || Math.abs(x) > 1 || Math.abs(y) > 1) { return null; } int[][] b = new int[this.dimension][this.dimension]; int[][] board = n.getBoard(); for (int i = 0; i < this.dimension; i++) { b[i] = Arrays.copyOf(board[i], board[i].length); } int eX = n.getEmptyX(); int eY = n.getEmptyY(); b[eY][eX] = b[eY + y][eX + x]; b[eY + y][eX + x] = 0; return new NPuzzleState(b, eX + x, eY + y); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/exampleproblems/npuzzle/standard/NPuzzleToGraphSearchReducer.java
package ai.libs.jaicore.search.exampleproblems.npuzzle.standard; import java.util.Arrays; import java.util.List; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import ai.libs.jaicore.basic.StringUtil; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.problems.npuzzle.NPuzzleProblem; import ai.libs.jaicore.problems.npuzzle.NPuzzleState; import ai.libs.jaicore.search.core.interfaces.EdgeCountingSolutionEvaluator; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.model.other.SearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; public class NPuzzleToGraphSearchReducer implements AlgorithmicProblemReduction<NPuzzleProblem, List<String>, GraphSearchWithSubpathEvaluationsInput<NPuzzleState, String, Integer>, EvaluatedSearchGraphPath<NPuzzleState, String, Integer>> { @Override public GraphSearchWithSubpathEvaluationsInput<NPuzzleState, String, Integer> encodeProblem(final NPuzzleProblem problem) { IPathEvaluator<NPuzzleState, String, Integer> pathEvaluator = p -> new EdgeCountingSolutionEvaluator<NPuzzleState, String>() .evaluate(new SearchGraphPath<>(p.getNodes(), Arrays.asList(StringUtil.getArrayWithValues(p.getNodes().size() - 1, "")))).intValue(); return new GraphSearchWithSubpathEvaluationsInput<>(new NPuzzleGraphGenerator(problem.getBoard()), new NPuzzleGoalPredicate(problem.getDim()), pathEvaluator); } @Override public List<String> decodeSolution(final EvaluatedSearchGraphPath<NPuzzleState, String, Integer> 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/nqueens/NQueensGoalPredicate.java
package ai.libs.jaicore.search.exampleproblems.nqueens; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester; public class NQueensGoalPredicate implements INodeGoalTester<QueenNode, String> { private final int dimension; public NQueensGoalPredicate(final int dimension) { super(); this.dimension = dimension; } @Override public boolean isGoal(final QueenNode n) { return n.getNumberOfQueens() == this.dimension; } }
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/nqueens/NQueensGraphGenerator.java
package ai.libs.jaicore.search.exampleproblems.nqueens; 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.ISingleRootGenerator; import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator; import ai.libs.jaicore.search.model.NodeExpansionDescription; @SuppressWarnings("serial") public class NQueensGraphGenerator implements IGraphGenerator<QueenNode, String> { private final int dimension; private int countSinceLastSleep = 0; public NQueensGraphGenerator(final int dimension) { this.dimension = dimension; } @Override public ISingleRootGenerator<QueenNode> getRootGenerator() { return () -> new QueenNode(this.dimension); } @Override public ISuccessorGenerator<QueenNode, String> getSuccessorGenerator() { return n -> { List<INewNodeDescription<QueenNode, String>> l = new ArrayList<>(); int currentRow = n.getPositions().size(); for (int i = 0; i < this.dimension; i++, this.countSinceLastSleep ++) { if (this.countSinceLastSleep % 100 == 0) { Thread.sleep(5); } if (Thread.interrupted()) { throw new InterruptedException("Successor generation has been interrupted."); } if (!n.attack(currentRow, i)) { l.add(new NodeExpansionDescription<>(new QueenNode(n, i), "" + i)); } } return l; }; } }
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/nqueens/NQueensGraphSearchToGraphSearchWithSubPathEvaluationReducer.java
package ai.libs.jaicore.search.exampleproblems.nqueens; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.search.model.other.SearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; public class NQueensGraphSearchToGraphSearchWithSubPathEvaluationReducer implements AlgorithmicProblemReduction<GraphSearchInput<QueenNode, String>, SearchGraphPath<QueenNode, String>, GraphSearchWithSubpathEvaluationsInput<QueenNode, String, Double>, SearchGraphPath<QueenNode, String>> { @Override public GraphSearchWithSubpathEvaluationsInput<QueenNode, String, Double> encodeProblem(final GraphSearchInput<QueenNode, String> problem) { IPathEvaluator<QueenNode, String, Double> nodeEvaluator = node -> (double) node.getHead().getNumberOfAttackedCells(); return new GraphSearchWithSubpathEvaluationsInput<>(problem, nodeEvaluator); } @Override public SearchGraphPath<QueenNode, String> decodeSolution(final SearchGraphPath<QueenNode, String> 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/nqueens/NQueensGraphSearchToNodeRecommendedTreeReducer.java
package ai.libs.jaicore.search.exampleproblems.nqueens; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.search.model.other.SearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; import ai.libs.jaicore.search.probleminputs.GraphSearchWithNodeRecommenderInput; public class NQueensGraphSearchToNodeRecommendedTreeReducer implements AlgorithmicProblemReduction<GraphSearchInput<QueenNode, String>, SearchGraphPath<QueenNode, String>, GraphSearchWithNodeRecommenderInput<QueenNode, String>, SearchGraphPath<QueenNode, String>> { @Override public GraphSearchWithNodeRecommenderInput<QueenNode, String> encodeProblem(final GraphSearchInput<QueenNode, String> problem) { return new GraphSearchWithNodeRecommenderInput<>(problem, (n1, n2) -> Integer.valueOf(n1.getNumberOfAttackedCells()).compareTo(n2.getNumberOfAttackedCells())); } @Override public SearchGraphPath<QueenNode, String> decodeSolution(final SearchGraphPath<QueenNode, String> 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/nqueens/NQueensToGraphSearchReducer.java
package ai.libs.jaicore.search.exampleproblems.nqueens; import java.util.List; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.problems.nqueens.NQueensProblem; import ai.libs.jaicore.search.model.other.AgnosticPathEvaluator; import ai.libs.jaicore.search.model.other.SearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; import ai.libs.jaicore.search.probleminputs.GraphSearchWithPathEvaluationsInput; public class NQueensToGraphSearchReducer implements AlgorithmicProblemReduction<NQueensProblem, List<Integer>, GraphSearchInput<QueenNode, String>, SearchGraphPath<QueenNode, String>> { @Override public GraphSearchInput<QueenNode, String> encodeProblem(final NQueensProblem problem) { IGraphGenerator<QueenNode, String> graphGenerator = new NQueensGraphGenerator(problem.getN()); return new GraphSearchWithPathEvaluationsInput<>(graphGenerator, new NQueensGoalPredicate(problem.getN()), new AgnosticPathEvaluator<>()); } @Override public List<Integer> decodeSolution(final SearchGraphPath<QueenNode, String> solution) { return solution.getHead().getPositions(); } }
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/nqueens/QueenNode.java
package ai.libs.jaicore.search.exampleproblems.nqueens; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @SuppressWarnings("serial") public class QueenNode implements Serializable { private final int dimension; private final List<Integer> positions; /** * Creates a QueenNode with a empty board * * @param dimension * The dimension of the board. */ public QueenNode(final int dimension) { this.positions = new ArrayList<>(); this.dimension = dimension; } /** * Creates a QueenNode with one Queen on it * * @param x * The row position of the queen. * @param y * The column position of the queen. * @param dimension * The dimension of the board. */ public QueenNode(final int x, final int y, final int dimension) { this.positions = new ArrayList<>(); this.positions.add(x, y); this.dimension = dimension; } /** * Creates a QueenNode with exiting positions of other queens * * @param pos * The positions of the other queens. * @param y * The column position of the newly placed queen. * @param dimension * The dimension of the board. */ public QueenNode(final List<Integer> pos, final int y, final int dimension) { this.positions = new ArrayList<>(pos); this.positions.add(this.positions.size(), y); this.dimension = dimension; } /** * Creates a QueenNode with exiting positions of other queens * * @param pos * The positions of the other queens. * @param x * The row position of the newly placed queen. * @param y * The column position of the newly placed queen. * @param dimension * The dimension of the board. */ public QueenNode(final List<Integer> pos, final int x, final int y, final int dimension) { this.positions = new ArrayList<>(pos); for (Integer p : pos) { this.positions.add(p); } this.positions.add(x, y); this.dimension = dimension; } /** * Creates a new QueenNode out of another QueenNode to add a new queen. * * @param n * The old QueenNode. * @param y * The column position of the new queen. */ public QueenNode(final QueenNode n, final int y) { this.positions = new ArrayList<>(n.getPositions().size()); for (Integer p : n.getPositions()) { this.positions.add(p); } this.positions.add(y); this.dimension = n.getDimension(); } public List<Integer> getPositions() { return this.positions; } public int getDimension() { return this.dimension; } @Override public String toString() { return this.positions.toString(); } public String boardVisualizationAsString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < this.dimension; i++) { sb.append("----"); } sb.append("\n|"); for (int i = 0; i < this.dimension; i++) { for (int j = 0; j < this.dimension; j++) { if (this.positions.size() > i && this.positions.get(i) == j) { sb.append(" Q |"); } else { sb.append(" |"); } } sb.append("\n"); for (int j = 0; j < this.dimension; j++) { sb.append("----"); } if (i < this.dimension - 1) { sb.append("\n|"); } } return sb.toString(); } /** * Checks if a cell is attacked by the queens on the board * * @param i * The row of the cell to be checked. * @param j * The collumn of the cell to be checked. * @return * <code>true</code> if the cell is attacked, <code>false</code> otherwise. */ public boolean attack(final int i, final int j) { for (Integer p : this.positions) { if (j == p) { return true; } int x = Math.abs(i - this.positions.indexOf(p)); if (j == p + x || p - x == j) { return true; } } return false; } public String toStringAttack() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < this.dimension; i++) { sb.append("----"); } sb.append("\n|"); for (int i = 0; i < this.dimension; i++) { for (int j = 0; j < this.dimension; j++) { if (this.positions.get(i) == j) { sb.append(" Q |"); } else { boolean attack = this.attack(i, j); if (attack) { sb.append(" O |"); } else { sb.append(" |"); } } } sb.append("\n"); for (int j = 0; j < this.dimension; j++) { sb.append("----"); } if (i < this.dimension - 1) { sb.append("\n|"); } } return sb.toString(); } public int getNumberOfQueens() { return this.positions.size(); } /** * Returns the number of attacked cells of the current boardconfiguration * * @return * The number of attacked cells. */ public int getNumberOfAttackedCells() { int attackedCells = this.positions.size() * this.dimension; for (int i = this.positions.size(); i < this.dimension; i++) { for (int j = 0; j < this.dimension; j++) { if (this.attack(i, j)) { attackedCells++; } } } return attackedCells; } /** * Returns the number of attacked cells in the next free row from top down. * * @return * The number of attacked cells in the next row. * @throws InterruptedException */ public int getNumberOfAttackedCellsInNextRow() throws InterruptedException { int attackedCells = 0; for (int i = 0; i < this.dimension; i++) { if (Thread.interrupted()) { throw new InterruptedException(); } if (this.attack(this.dimension - 1, i)) { attackedCells++; } } return attackedCells; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.dimension; result = prime * result + ((this.positions == null) ? 0 : this.positions.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } QueenNode other = (QueenNode) obj; if (this.dimension != other.dimension) { return false; } if (this.positions == null) { if (other.positions != null) { return false; } } else if (!this.positions.equals(other.positions)) { return false; } return true; } public int getNumberOfNotAttackedCells() { return (this.dimension * this.dimension) - this.getNumberOfAttackedCells(); } }
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/openshop/OpenShopGoalPredicate.java
package ai.libs.jaicore.search.exampleproblems.openshop; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester; public class OpenShopGoalPredicate implements INodeGoalTester<OpenShopState, String> { @Override public boolean isGoal(final OpenShopState node) { return (node instanceof OpenShopOperationSelectionState) && ((OpenShopOperationSelectionState)node).getUnselectedOperations().isEmpty(); } }
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/openshop/OpenShopGraphGenerator.java
package ai.libs.jaicore.search.exampleproblems.openshop; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; 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 ai.libs.jaicore.problems.scheduling.JobSchedulingProblemInput; import ai.libs.jaicore.problems.scheduling.Machine; import ai.libs.jaicore.problems.scheduling.Operation; import ai.libs.jaicore.search.model.NodeExpansionDescription; public class OpenShopGraphGenerator implements IGraphGenerator<OpenShopState, String> { private final JobSchedulingProblemInput problem; private final boolean pruneInactiveNodes; public OpenShopGraphGenerator(final JobSchedulingProblemInput problem) { this(problem, false); } public OpenShopGraphGenerator(final JobSchedulingProblemInput problem, final boolean pruneInactiveNodes) { super(); this.problem = problem; this.pruneInactiveNodes = pruneInactiveNodes; } @Override public ISingleRootGenerator<OpenShopState> getRootGenerator() { return () -> new OpenShopOperationSelectionState(this.problem, null, null, this.problem.getOperations().stream().map(Operation::getName).collect(Collectors.toList())); } @Override public ISuccessorGenerator<OpenShopState, String> getSuccessorGenerator() { return n -> { List<INewNodeDescription<OpenShopState, String>> succ = new ArrayList<>(); /* for actives schedules, continue as usual */ if (n instanceof OpenShopOperationSelectionState) { for (String opName : ((OpenShopOperationSelectionState) n).getUnselectedOperations()) { OpenShopMachineSelectionState successor = new OpenShopMachineSelectionState(this.problem, (OpenShopOperationSelectionState)n, this.problem.getOperation(opName)); /* add successor only if the solution can still be active! */ if (!this.pruneInactiveNodes || successor.getSchedule().isActive()) { succ.add(new NodeExpansionDescription<>(successor, opName)); } } } else if (n instanceof OpenShopMachineSelectionState) { /* identify assignable machines */ Collection<Machine> possibleMachines = ((OpenShopMachineSelectionState) n).getOperationSelectedInParent().getWorkcenter().getMachines(); for (Machine m : possibleMachines) { List<String> possibleOps = new ArrayList<>(((OpenShopMachineSelectionState) n).getParent().getUnselectedOperations()); String removeOp = ((OpenShopMachineSelectionState) n).getOperationSelectedInParent().getName(); boolean removed = possibleOps.remove(removeOp); if (!removed) { throw new IllegalStateException("Agenda has not been reduced. Operation that was supposed to be removed: " + removeOp); } OpenShopOperationSelectionState successor = new OpenShopOperationSelectionState(this.problem, (OpenShopMachineSelectionState)n, m, possibleOps); /* add successor only if the solution can still be active! */ if (!this.pruneInactiveNodes || successor.getSchedule().isActive()) { succ.add(new NodeExpansionDescription<>(successor, m.getMachineID())); } } } else { throw new IllegalArgumentException("Unsupported type " + n); } 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/openshop/OpenShopGraphSearchProblem.java
package ai.libs.jaicore.search.exampleproblems.openshop; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import ai.libs.jaicore.problems.scheduling.JobSchedulingProblemInput; import ai.libs.jaicore.problems.scheduling.Operation; import ai.libs.jaicore.problems.scheduling.Schedule; public class OpenShopGraphSearchProblem implements IPathSearchWithPathEvaluationsInput<OpenShopState, String, Double> { private final JobSchedulingProblemInput problem; private final OpenShopGraphGenerator gg; private final OpenShopGoalPredicate gp = new OpenShopGoalPredicate(); public OpenShopGraphSearchProblem(final JobSchedulingProblemInput problem) { super(); this.problem = problem; this.gg = new OpenShopGraphGenerator(problem); } @Override public IGraphGenerator<OpenShopState, String> getGraphGenerator() { return this.gg; } @Override public IPathGoalTester<OpenShopState, String> getGoalTester() { return this.gp; } @Override public IPathEvaluator<OpenShopState, String, Double> getPathEvaluator() { return p -> { Schedule s = p.getHead().getSchedule(); double baseScore = this.problem.getScoreOfSchedule(s); /* penalize inactive operations */ int inActive = 0; for (Operation o : this.problem.getOperations()) { if (s.canOperationBeScheduledEarlierWithoutAnyOtherEffect(o)) { inActive ++; } } return baseScore + 1000 * inActive; }; } public JobSchedulingProblemInput getProblem() { return this.problem; } }
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/openshop/OpenShopMachineSelectionState.java
package ai.libs.jaicore.search.exampleproblems.openshop; import java.util.List; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.problems.scheduling.Machine; import ai.libs.jaicore.problems.scheduling.JobSchedulingProblemInput; import ai.libs.jaicore.problems.scheduling.Operation; public class OpenShopMachineSelectionState extends OpenShopState { private final OpenShopOperationSelectionState parent; private final Operation operationSelectedInParent; public OpenShopMachineSelectionState(final JobSchedulingProblemInput problem, final OpenShopOperationSelectionState parent, final Operation operationSelectedInParent) { super(problem); this.parent = parent; this.operationSelectedInParent = operationSelectedInParent; } public OpenShopOperationSelectionState getParent() { return this.parent; } public Operation getOperationSelectedInParent() { return this.operationSelectedInParent; } @Override public List<Pair<Operation, Machine>> getPartialAssignment() { return this.parent.getPartialAssignment(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.operationSelectedInParent == null) ? 0 : this.operationSelectedInParent.hashCode()); result = prime * result + ((this.parent == null) ? 0 : this.parent.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; } OpenShopMachineSelectionState other = (OpenShopMachineSelectionState) obj; if (this.operationSelectedInParent == null) { if (other.operationSelectedInParent != null) { return false; } } else if (!this.operationSelectedInParent.equals(other.operationSelectedInParent)) { return false; } if (this.parent == null) { if (other.parent != null) { return false; } } else if (!this.parent.equals(other.parent)) { return false; } return true; } @Override public String toString() { return "OpenShopMachineSelectionState [parent=" + this.parent + ", operationSelectedInParent=" + this.operationSelectedInParent + "]"; } }
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/openshop/OpenShopOperationSelectionState.java
package ai.libs.jaicore.search.exampleproblems.openshop; import java.util.ArrayList; import java.util.Collection; import java.util.List; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.problems.scheduling.Machine; import ai.libs.jaicore.problems.scheduling.JobSchedulingProblemInput; import ai.libs.jaicore.problems.scheduling.Operation; public class OpenShopOperationSelectionState extends OpenShopState { private final OpenShopMachineSelectionState parent; private final Machine machineSelectedInParent; private final Collection<String> unselectedOperations; public OpenShopOperationSelectionState(final JobSchedulingProblemInput problem, final OpenShopMachineSelectionState parent, final Machine machineSelectedInParent, final Collection<String> unselectedOperations) { super(problem); this.parent = parent; this.machineSelectedInParent = machineSelectedInParent; this.unselectedOperations = unselectedOperations; } public OpenShopMachineSelectionState getParent() { return this.parent; } public Machine getMachineSelectedInParent() { return this.machineSelectedInParent; } public Collection<String> getUnselectedOperations() { return this.unselectedOperations; } @Override public List<Pair<Operation, Machine>> getPartialAssignment() { if (this.parent == null) { return new ArrayList<>(); } List<Pair<Operation, Machine>> assignmentAtLastNode = this.parent.getParent().getPartialAssignment(); Pair<Operation, Machine> nextAssignment = new Pair<>(this.parent.getOperationSelectedInParent(), this.machineSelectedInParent); assignmentAtLastNode.add(nextAssignment); return assignmentAtLastNode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.machineSelectedInParent == null) ? 0 : this.machineSelectedInParent.hashCode()); result = prime * result + ((this.parent == null) ? 0 : this.parent.hashCode()); result = prime * result + ((this.unselectedOperations == null) ? 0 : this.unselectedOperations.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; } OpenShopOperationSelectionState other = (OpenShopOperationSelectionState) obj; if (this.machineSelectedInParent == null) { if (other.machineSelectedInParent != null) { return false; } } else if (!this.machineSelectedInParent.equals(other.machineSelectedInParent)) { return false; } if (this.parent == null) { if (other.parent != null) { return false; } } else if (!this.parent.equals(other.parent)) { return false; } if (this.unselectedOperations == null) { if (other.unselectedOperations != null) { return false; } } else if (!this.unselectedOperations.equals(other.unselectedOperations)) { 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/openshop/OpenShopState.java
package ai.libs.jaicore.search.exampleproblems.openshop; import java.util.List; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.problems.scheduling.Machine; import ai.libs.jaicore.problems.scheduling.JobSchedulingProblemInput; import ai.libs.jaicore.problems.scheduling.Operation; import ai.libs.jaicore.problems.scheduling.Schedule; import ai.libs.jaicore.problems.scheduling.ScheduleBuilder; public abstract class OpenShopState { private final JobSchedulingProblemInput problem; public OpenShopState(final JobSchedulingProblemInput problem) { super(); this.problem = problem; } public abstract List<Pair<Operation, Machine>> getPartialAssignment(); public Schedule getSchedule() { ScheduleBuilder sb = new ScheduleBuilder(this.problem); for (Pair<Operation, Machine> p : this.getPartialAssignment()) { sb.assign(p.getX(), p.getY()); } return sb.build(); } }
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/racetrack/RacetrackAction.java
package ai.libs.jaicore.search.exampleproblems.racetrack; public class RacetrackAction { private final int hAcceleration; private final int vAcceleration; public RacetrackAction(final int hAcceleration, final int vAcceleration) { super(); this.hAcceleration = hAcceleration; this.vAcceleration = vAcceleration; } public int gethAcceleration() { return this.hAcceleration; } public int getvAcceleration() { return this.vAcceleration; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.hAcceleration; result = prime * result + this.vAcceleration; 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; } RacetrackAction other = (RacetrackAction) obj; if (this.hAcceleration != other.hAcceleration) { return false; } return this.vAcceleration == other.vAcceleration; } @Override public String toString() { return "acceleration(" + this.hAcceleration + ", vAcceleration=" + this.vAcceleration + ")"; } }
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/racetrack/RacetrackMDP.java
package ai.libs.jaicore.search.exampleproblems.racetrack; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import ai.libs.jaicore.search.probleminputs.AMDP; public class RacetrackMDP extends AMDP<RacetrackState, RacetrackAction, Double> { private final boolean[][] track; // true for accessible fields and false for others private final boolean[][] goal; // true for goal fields and false for others private final double successRate; private static final List<RacetrackAction> POSSIBLE_ACTIONS; private final boolean stopOnCrash; static { POSSIBLE_ACTIONS = new ArrayList<>(); for (int vAcc = -1; vAcc < 2; vAcc ++) { for (int hAcc = -1; hAcc < 2; hAcc ++) { POSSIBLE_ACTIONS.add(new RacetrackAction(hAcc, vAcc)); } } } private static List<RacetrackState> getPossibleInitStates(final boolean[][] start) { List<RacetrackState> validStartStates= new ArrayList<>(); for (int i = 0; i < start.length; i++) { for (int j = 0; j < start[i].length; j++) { if (start[i][j]) { validStartStates.add(new RacetrackState(i, j, 0, 0, false, false, false)); } } } return validStartStates; } private static RacetrackState drawInitState(final boolean[][] start, final Random random) { List<RacetrackState> validStartStates = getPossibleInitStates(start); Collections.shuffle(validStartStates); return validStartStates.get(random.nextInt(validStartStates.size())); } private final List<RacetrackState> possibleInitStates; public RacetrackMDP(final boolean[][] track, final boolean[][] start, final boolean[][] goal, final double successRate, final Random random, final boolean stopOnCrash) { super(drawInitState(start, random)); this.track = track; this.goal = goal; this.successRate = successRate; this.possibleInitStates = getPossibleInitStates(start); this.stopOnCrash = stopOnCrash; } @Override public boolean isMaximizing() { return false; // get to the goal as fast as possible } @Override public Collection<RacetrackAction> getApplicableActions(final RacetrackState state) { if (this.stopOnCrash && state.isCrashed()) { return new ArrayList<>(); } return POSSIBLE_ACTIONS; } private boolean hasMatchOnLine(final boolean[][] boolmap, final int xStart, final int yStart, final int xEnd, final int yEnd) { if (xEnd == xStart) { for (int i = Math.min(yStart, yEnd); i <= Math.max(yStart, yEnd); i++) { if (boolmap[xStart][i]) { return true; } } return false; } if (yEnd == yStart) { for (int i = Math.min(xStart, xEnd); i <= Math.max(xStart, xEnd); i++) { if (boolmap[i][yStart]) { return true; } } return false; } double slope = (yEnd - yStart) * 1.0 / (xEnd - xStart); int xCur = xStart; int yCur = yStart; int xMoves = 0; int yMoves = 0; int xFactor = xEnd > xStart ? 1 : -1; int yFactor = yEnd > yStart ? 1 : -1; while (xCur != xEnd) { xMoves ++; xCur += xFactor; int expectedYMoves = Math.abs((int)Math.round(xMoves * slope)); if (expectedYMoves > yMoves) { while (expectedYMoves > yMoves) { yMoves ++; yCur += yFactor; if (boolmap[xCur][yCur]) { return true; } } } else { if (boolmap[xCur][yCur]) { return true; } } } return false; } @Override /** * in fact we just teleport (no check of fields in between) * */ public Map<RacetrackState, Double> getProb(final RacetrackState state, final RacetrackAction action) { Map<RacetrackState, Double> out = new HashMap<>(); /* first determine the possible new coordinates */ int xCur = state.getX(); int yCur = state.getY(); int xLazy = xCur + state.gethSpeed(); int yLazy = yCur + state.getvSpeed(); int xAcc = xLazy += action.gethAcceleration(); int yAcc = yLazy += action.getvAcceleration(); /* first consider the case that speed change failed */ if (xLazy >= 0 && xLazy < this.track.length && yLazy >= 0 && yLazy < this.track[xLazy].length && this.track[xLazy][yLazy]) { boolean finished = this.hasMatchOnLine(this.goal, xCur, yCur, xLazy, yLazy); RacetrackState succ = new RacetrackState(xLazy, yLazy, state.gethSpeed(), state.getvSpeed(), false, finished, false); out.put(succ, 1 - this.successRate); } else { double prob = (1 - this.successRate) * 1.0 / this.possibleInitStates.size(); for (RacetrackState initState : this.possibleInitStates) { RacetrackState crashState = new RacetrackState(initState.getX(), initState.getY(), 0, 0, false, false, true); out.put(crashState, prob); } } /* now consider the case that the speed change succeeded */ if (xAcc >= 0 && xAcc < this.track.length && yAcc >= 0 && yAcc < this.track[xAcc].length && this.track[xAcc][yAcc]) { boolean finished = this.hasMatchOnLine(this.goal, xCur, yCur, xAcc, yAcc); RacetrackState succ = new RacetrackState(xAcc, yAcc, state.gethSpeed() + action.gethAcceleration(), state.getvSpeed() + action.getvAcceleration(), true, finished, false); if (out.containsKey(succ)) { out.put(succ, out.get(succ) + this.successRate); } else { out.put(succ, this.successRate); } } else { double prob = this.successRate / this.possibleInitStates.size(); for (RacetrackState initState : this.possibleInitStates) { RacetrackState crashState = new RacetrackState(initState.getX(), initState.getY(), 0, 0, true, false, true); out.put(crashState, out.get(crashState) + prob); } } return out; } @Override public Double getScore(final RacetrackState state, final RacetrackAction action, final RacetrackState successor) { double rawScore = successor.isCrashed() ? 100.0 : 1.0; // every move costs one time unit if it is admissible and 10 if the car is set back to an init state return rawScore / 100; // make it inside [0,1] } }
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/racetrack/RacetrackReader.java
package ai.libs.jaicore.search.exampleproblems.racetrack; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Random; import ai.libs.jaicore.basic.FileUtil; public class RacetrackReader { public RacetrackMDP read(final File file, final double successRate, final Random random, final boolean stopOnCrash) throws IOException { List<String> lines = FileUtil.readFileAsList(file); String[] dimensions = lines.remove(0).trim().split(","); int height = Integer.parseInt(dimensions[0]); int width = Integer.parseInt(dimensions[1]); if (height != lines.size()) { throw new IllegalArgumentException("The file specifies a height of " + height + " but defines a course of " + lines.size() + " lines."); } boolean[][] track = new boolean[width][height]; boolean[][] start = new boolean[width][height]; boolean[][] goal = new boolean[width][height]; for (int y = 0; y < height; y++) { String line = lines.get(height - 1 - y); for (int x = 0; x < width; x++) { char c = line.charAt(x); if (c == '.') { track[x][y] = true; } if (c == 'S') { track[x][y] = true; start[x][y] = true; } if (c == 'F') { track[x][y] = true; goal[x][y] = true; } } } return new RacetrackMDP(track, start, goal, successRate, random, stopOnCrash); } }
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/racetrack/RacetrackState.java
package ai.libs.jaicore.search.exampleproblems.racetrack; public class RacetrackState { private final int x; private final int y; private final int hSpeed; private final int vSpeed; private final boolean finished; private final boolean lastSuccess; private final boolean crashed; public RacetrackState(final int x, final int y, final int hSpeed, final int vSpeed, final boolean lastSuccess, final boolean finished, final boolean crashed) { super(); this.x = x; this.y = y; this.hSpeed = hSpeed; this.vSpeed = vSpeed; this.lastSuccess = lastSuccess; this.finished = finished; this.crashed = crashed; } public int getX() { return this.x; } public int getY() { return this.y; } public int getvSpeed() { return this.vSpeed; } public int gethSpeed() { return this.hSpeed; } public boolean isFinished() { return this.finished; } public boolean isLastSuccess() { return this.lastSuccess; } public boolean isCrashed() { return this.crashed; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.hSpeed; result = prime * result + this.vSpeed; result = prime * result + this.x; result = prime * result + this.y; return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } RacetrackState other = (RacetrackState) obj; if (this.hSpeed != other.hSpeed) { return false; } if (this.vSpeed != other.vSpeed) { return false; } if (this.x != other.x) { return false; } return this.y == other.y; } @Override public String toString() { return this.x + "/" + this.y + " (" + this.hSpeed + "/" + this.vSpeed + ")[" + this.lastSuccess + "]"; } }
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/randomtrees/RandomTreeGoalTester.java
package ai.libs.jaicore.search.exampleproblems.randomtrees; import java.util.List; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester; public class RandomTreeGoalTester implements INodeGoalTester<List<Integer>, Integer> { private final int d; public RandomTreeGoalTester(final int d) { super(); this.d = d; } @Override public boolean isGoal(final List<Integer> node) { return node.size() == this.d; } }
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/randomtrees/RandomTreeGraphGenerator.java
package ai.libs.jaicore.search.exampleproblems.randomtrees; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; 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 ai.libs.jaicore.search.model.NodeExpansionDescription; public class RandomTreeGraphGenerator implements IGraphGenerator<List<Integer>, Integer> { private final int b; private final int d; private final long seed; private final int maxPerDepth; public RandomTreeGraphGenerator(final int b, final int d, final long seed, final int maxPerDepth) { super(); this.b = b; this.d = d; this.seed = seed; this.maxPerDepth = maxPerDepth; } @Override public ISingleRootGenerator<List<Integer>> getRootGenerator() { return Arrays::asList; } @Override public ISuccessorGenerator<List<Integer>, Integer> getSuccessorGenerator() { return n -> { List<INewNodeDescription<List<Integer>, Integer>> l = new ArrayList<>(); if (n.size() == this.d) { return l; } for (int i = 0; i < this.b; i++) { List<Integer> nP = new ArrayList<>(n); nP.add((int)(i * 1.0 * this.maxPerDepth + new Random(this.seed + (i * n.hashCode()) + this.b).nextInt(this.maxPerDepth)) / this.b); l.add(new NodeExpansionDescription<>(nP, i)); } return l; }; } }
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/randomtrees/RandomTreeSearchProblem.java
package ai.libs.jaicore.search.exampleproblems.randomtrees; import java.util.List; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; public class RandomTreeSearchProblem implements IPathSearchWithPathEvaluationsInput<List<Integer>, Integer, Double> { private final int b; private final int d; private final long seed; private final IGraphGenerator<List<Integer>, Integer> gg; private final IPathGoalTester<List<Integer>, Integer> gt; private final IPathEvaluator<List<Integer>, Integer, Double> se; private final boolean scoresPerEdge; public RandomTreeSearchProblem(final int b, final int d, final long seed, final int maxPerDepth, final boolean scoresPerEdge) { super(); this.b = b; this.d = d; this.seed = seed; this.gg = new RandomTreeGraphGenerator(b, d, seed, maxPerDepth); this.gt = new RandomTreeGoalTester(d); this.scoresPerEdge = scoresPerEdge; this.se = n -> scoresPerEdge ? ((double)n.getHead().stream().reduce((current, added) -> current + added).get()) / (d * maxPerDepth) : n.getHead().get(n.getHead().size() - 1); } @Override public IGraphGenerator<List<Integer>, Integer> getGraphGenerator() { return this.gg; } @Override public IPathGoalTester<List<Integer>, Integer> getGoalTester() { return this.gt; } @Override public IPathEvaluator<List<Integer>, Integer, Double> getPathEvaluator() { return this.se; } public int getB() { return this.b; } public int getD() { return this.d; } public IGraphGenerator<List<Integer>, Integer> getGg() { return this.gg; } public IPathGoalTester<List<Integer>, Integer> getGt() { return this.gt; } public IPathEvaluator<List<Integer>, Integer, Double> getSe() { return this.se; } public boolean isScoresPerEdge() { return this.scoresPerEdge; } public long getSeed() { return this.seed; } }
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/sailing/SailingLayout.java
package ai.libs.jaicore.search.exampleproblems.sailing; public class SailingLayout { private final int numRows; private final int numCols; public SailingLayout(final int numRows, final int numCols) { super(); this.numRows = numRows; this.numCols = numCols; } public int getNumRows() { return this.numRows; } public int getNumCols() { return this.numCols; } }
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/sailing/SailingMDP.java
package ai.libs.jaicore.search.exampleproblems.sailing; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import ai.libs.jaicore.search.probleminputs.AMDP; public class SailingMDP extends AMDP<SailingState, SailingMove, Double> { private final int rows; private final int cols; private final int goalRow; private final int goalCol; private final int movesToNormalizeOver; public SailingMDP(final int rows, final int cols, final int initRow, final int initCol, final int goalRow, final int goalCol, final SailingMove initWind, final int movesToNormalizeOver) { super(new SailingState(initRow, initCol, initWind)); this.rows = rows; this.cols = cols; this.goalRow = goalRow; this.goalCol = goalCol; if (movesToNormalizeOver < 0) { throw new IllegalArgumentException("Number of moves to normalize over must not be negative!"); } this.movesToNormalizeOver = 4 * movesToNormalizeOver > 0 ? movesToNormalizeOver : movesToNormalizeOver / 4; } @Override public Collection<SailingMove> getApplicableActions(final SailingState state) { if (state.getRow() == this.goalRow && state.getCol() == this.goalCol) { return Arrays.asList(); } Set<SailingMove> possibleMoves = Arrays.stream(SailingMove.values()).collect(Collectors.toSet()); possibleMoves.remove(state.getWind()); if (state.getRow() == 0) { possibleMoves.remove(SailingMove.N); possibleMoves.remove(SailingMove.NE); possibleMoves.remove(SailingMove.NW); } if (state.getCol() == 0) { possibleMoves.remove(SailingMove.W); possibleMoves.remove(SailingMove.NW); possibleMoves.remove(SailingMove.SW); } if (state.getRow() == this.rows - 1) { possibleMoves.remove(SailingMove.S); possibleMoves.remove(SailingMove.SE); possibleMoves.remove(SailingMove.SW); } if (state.getCol() == this.cols - 1) { possibleMoves.remove(SailingMove.E); possibleMoves.remove(SailingMove.NE); possibleMoves.remove(SailingMove.SE); } return possibleMoves; } @Override public Map<SailingState, Double> getProb(final SailingState state, final SailingMove action) { if (!this.getApplicableActions(state).contains(action)) { throw new IllegalArgumentException("Action " + action + " is not applicable in state " + state); } int newRow = state.getRow(); int newCol = state.getCol(); switch (action) { case NW: case NE: case N: newRow -= 1; break; case SW: case SE: case S: newRow += 1; break; default: // do nothing in this case break; } switch (action) { case NW: case W: case SW: newCol -= 1; break; case NE: case E: case SE: newCol += 1; break; default: // do nothing in this case break; } List<SailingMove> windDirections = null; switch (state.getWind()) { case N: windDirections = Arrays.asList(SailingMove.NW, SailingMove.N, SailingMove.NE); break; case NE: windDirections = Arrays.asList(SailingMove.N, SailingMove.NE, SailingMove.E); break; case E: windDirections = Arrays.asList(SailingMove.NE, SailingMove.E, SailingMove.SE); break; case SE: windDirections = Arrays.asList(SailingMove.E, SailingMove.SE, SailingMove.S); break; case S: windDirections = Arrays.asList(SailingMove.SE, SailingMove.S, SailingMove.SW); break; case SW: windDirections = Arrays.asList(SailingMove.S, SailingMove.SW, SailingMove.W); break; case W: windDirections = Arrays.asList(SailingMove.SW, SailingMove.W, SailingMove.NW); break; case NW: windDirections = Arrays.asList(SailingMove.W, SailingMove.NW, SailingMove.N); break; default: throw new IllegalStateException("Wind direction has an unknown value " + state.getWind() + "!"); } Map<SailingState, Double> map = new HashMap<>(); for (SailingMove wind : windDirections) { map.put(new SailingState(newRow, newCol, wind), 1.0 / windDirections.size()); } return map; } @Override public Double getScore(final SailingState state, final SailingMove action, final SailingState successor) { double unnormalizedScore = this.getUnnormalizedScore(state, action); return this.movesToNormalizeOver > 0 ? unnormalizedScore / (4 * this.movesToNormalizeOver) : unnormalizedScore; } public double getUnnormalizedScore(final SailingState state, final SailingMove action) { SailingMove wind = state.getWind(); switch (wind) { case N: switch (action) { case NW: case NE: return 4.0; case W: case E: return 3.0; case SW: case SE: return 2.0; case S: return 1.0; default: throw new IllegalArgumentException(); } case NE: switch (action) { case N: case E: return 4.0; case NW: case SE: return 3.0; case W: case S: return 2.0; case SW: return 1.0; default: throw new IllegalArgumentException(); } case E: switch (action) { case NE: case SE: return 4.0; case N: case S: return 3.0; case NW: case SW: return 2.0; case W: return 1.0; default: throw new IllegalArgumentException(); } case SE: switch (action) { case E: case S: return 4.0; case NE: case SW: return 3.0; case N: case W: return 2.0; case NW: return 1.0; default: throw new IllegalArgumentException(); } case S: switch (action) { case SE: case SW: return 4.0; case E: case W: return 3.0; case NE: case NW: return 2.0; case N: return 1.0; default: throw new IllegalArgumentException(); } case SW: switch (action) { case S: case W: return 4.0; case SE: case NW: return 3.0; case E: case N: return 2.0; case NE: return 1.0; default: throw new IllegalArgumentException(); } case W: switch (action) { case SW: case NW: return 4.0; case S: case N: return 3.0; case SE: case NE: return 2.0; case E: return 1.0; default: throw new IllegalArgumentException(); } case NW: switch (action) { case W: case N: return 4.0; case SW: case NE: return 3.0; case S: case E: return 2.0; case SE: return 1.0; default: throw new IllegalArgumentException(); } default: throw new IllegalStateException(); } } public int getRows() { return this.rows; } public int getCols() { return this.cols; } public int getGoalRow() { return this.goalRow; } public int getGoalCol() { return this.goalCol; } @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/sailing/SailingMove.java
package ai.libs.jaicore.search.exampleproblems.sailing; public enum SailingMove { N, NE, E, SE, S, SW, W, NW }
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/sailing/SailingState.java
package ai.libs.jaicore.search.exampleproblems.sailing; public class SailingState { private final int row; private final int col; private final SailingMove wind; // indicates from where one perceives the wind public SailingState(final int row, final int col, final SailingMove wind) { super(); this.row = row; this.col = col; this.wind = wind; } public int getRow() { return this.row; } public int getCol() { return this.col; } public SailingMove getWind() { return this.wind; } @Override public String toString() { return this.row + "/" + this.col + "/" + this.wind; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.col; result = prime * result + this.row; result = prime * result + ((this.wind == null) ? 0 : this.wind.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; } SailingState other = (SailingState) obj; if (this.col != other.col) { return false; } if (this.row != other.row) { return false; } return this.wind == other.wind; } }
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/samegame/SameGameGoalPredicate.java
package ai.libs.jaicore.search.exampleproblems.samegame; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.INodeGoalTester; import ai.libs.jaicore.problems.samegame.SameGameCell; public class SameGameGoalPredicate implements INodeGoalTester<SameGameNode, SameGameCell> { @Override public boolean isGoal(final SameGameNode node) { return node.isGoalState(); } }
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/samegame/SameGameGraphGenerator.java
package ai.libs.jaicore.search.exampleproblems.samegame; 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.ISingleRootGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.problems.samegame.SameGameCell; import ai.libs.jaicore.problems.samegame.SameGameState; public class SameGameGraphGenerator implements IGraphGenerator<SameGameNode, SameGameCell>, ILoggingCustomizable { private final SameGameState initState; private final SameGameNode rootNode; private Logger logger = LoggerFactory.getLogger(SameGameGraphGenerator.class); public SameGameGraphGenerator(final SameGameState initState) { super(); this.initState = initState; this.rootNode = new SameGameNode(this.initState); } @Override public ISingleRootGenerator<SameGameNode> getRootGenerator() { return () -> this.rootNode; } @Override public ILazySuccessorGenerator<SameGameNode, SameGameCell> getSuccessorGenerator() { return new SameGameLazySuccessorGenerator(); } @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/samegame/SameGameGraphSearchProblem.java
package ai.libs.jaicore.search.exampleproblems.samegame; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import ai.libs.jaicore.problems.samegame.SameGameCell; import ai.libs.jaicore.problems.samegame.SameGameState; public class SameGameGraphSearchProblem implements IPathSearchWithPathEvaluationsInput<SameGameNode, SameGameCell, Double> { private static final SameGameGoalPredicate GP = new SameGameGoalPredicate(); private final SameGameGraphGenerator gg; private final SameGamePathEvaluator pe; public SameGameGraphSearchProblem(final SameGameState initState) { this(initState, true); } public SameGameGraphSearchProblem(final SameGameState initState, final boolean maximize) { this(initState, maximize, false); } public SameGameGraphSearchProblem(final SameGameState initState, final boolean maximize, final boolean relativeScores) { this.gg = new SameGameGraphGenerator(initState); this.pe = new SameGamePathEvaluator(initState, maximize, relativeScores); } @Override public SameGameGraphGenerator getGraphGenerator() { return this.gg; } @Override public IPathGoalTester<SameGameNode, SameGameCell> getGoalTester() { return GP; } @Override public IPathEvaluator<SameGameNode, SameGameCell, Double> getPathEvaluator() { return this.pe; } public int getMaxScore() { return this.pe.getMaxScore(); } }
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/samegame/SameGameLazySuccessorGenerator.java
package ai.libs.jaicore.search.exampleproblems.samegame; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Random; import java.util.stream.Collectors; import org.api4.java.datastructure.graph.implicit.INewNodeDescription; import ai.libs.jaicore.problems.samegame.SameGameCell; import ai.libs.jaicore.search.model.ILazyRandomizableSuccessorGenerator; import ai.libs.jaicore.search.model.NodeExpansionDescription; public class SameGameLazySuccessorGenerator implements ILazyRandomizableSuccessorGenerator<SameGameNode, SameGameCell>{ private Random random = new Random(0); @Override public List<INewNodeDescription<SameGameNode, SameGameCell>> generateSuccessors(final SameGameNode node) throws InterruptedException { Objects.requireNonNull(node, "The given node must not be null."); List<INewNodeDescription<SameGameNode, SameGameCell>> succ = new ArrayList<>(); Iterator<INewNodeDescription<SameGameNode, SameGameCell>> it = this.getIterativeGenerator(node); while (it.hasNext()) { succ.add(it.next()); } assert !(node.getState() != null && node.getState().isMovePossible()) || !succ.isEmpty() : "No successors have been generated, but there is a move possible!"; return succ; } @Override public Iterator<INewNodeDescription<SameGameNode, SameGameCell>> getIterativeGenerator(final SameGameNode n) { return this.getIterativeGenerator(n, this.random); } @Override public Iterator<INewNodeDescription<SameGameNode, SameGameCell>> getIterativeGenerator(final SameGameNode n, final Random random) { return new Iterator<INewNodeDescription<SameGameNode, SameGameCell>>() { private final List<SameGameCell> unselectedCells; { if (n.getState() == null) { n.recoverGenes(); } this.unselectedCells = n.getState().getBlocksOfPieces().stream().filter(b -> b.size() > 1).map(b -> b.iterator().next()).collect(Collectors.toList()); if (this.unselectedCells.isEmpty() && n.getState().isMovePossible()) { throw new IllegalStateException("Moves possible, but no block can be selected. Here is the board: " + n.getState().getBoardAsString() + "\nand are the blocks of pieces: " + n.getState().getBlocksOfPieces().stream().map(b -> "\n\t" + b.toString()).collect(Collectors.joining())); } Collections.shuffle(this.unselectedCells, random); if (n.allowsGeneErasure()) { n.eraseGenes(); } } @Override public boolean hasNext() { return !this.unselectedCells.isEmpty(); } @Override public NodeExpansionDescription<SameGameNode, SameGameCell> next() { if (this.unselectedCells.isEmpty()) { throw new NoSuchElementException("Set of unselected cells is empty!"); } SameGameCell nextCell = this.unselectedCells.remove(0); if (!n.isKeepInMemory()) { n.recoverGenes(); } SameGameNode node = new SameGameNode(n, nextCell); if (!n.isKeepInMemory()) { n.eraseGenes(); } return new NodeExpansionDescription<>(node, nextCell); } }; } }
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/samegame/SameGameNode.java
package ai.libs.jaicore.search.exampleproblems.samegame; import java.util.ArrayList; import java.util.List; import ai.libs.jaicore.problems.samegame.SameGameCell; import ai.libs.jaicore.problems.samegame.SameGameState; import ai.libs.jaicore.search.core.interfaces.ISuccessorGenerationRelevantRemovalNode; public class SameGameNode implements ISuccessorGenerationRelevantRemovalNode { private final SameGameNode parent; private SameGameState state; private final SameGameCell selectedCell; private final short score; private final boolean isGoalState; private final boolean keepInMemory; private final int hashOfPathToRoot; public SameGameNode(final SameGameState state) { super(); this.state = state; this.parent = null; this.isGoalState = !this.state.isMovePossible(); this.score = state.getScore(); this.selectedCell = null; this.keepInMemory = true; this.hashOfPathToRoot = this.getDecisionPathToRoot().hashCode(); } public SameGameNode(final SameGameNode parent, final SameGameCell selectedCell) { this.selectedCell = selectedCell; this.parent = parent; SameGameState stateAfterMove= parent.getState().getStateAfterMove(selectedCell.getRow(), selectedCell.getCol()); this.isGoalState = !stateAfterMove.isMovePossible(); this.score = stateAfterMove.getScore(); List<SameGameCell> pathToRoot = this.getDecisionPathToRoot(); this.keepInMemory = parent.getDecisionPathToRoot().size() % 2 == 0; if (this.keepInMemory) { this.state = stateAfterMove; } this.hashOfPathToRoot = pathToRoot.hashCode(); } @Override public void eraseGenes() { if (this.keepInMemory) { throw new IllegalStateException("Cannot erase genes of node that is configured to keep its genes!"); } this.state = null; } @Override public void recoverGenes() { if (this.parent == null) { return; } boolean eraseGenesInParentAfterwards = false; if (this.parent.state == null) { this.parent.recoverGenes(); eraseGenesInParentAfterwards = true; } SameGameState parentState = this.parent.getState(); if (eraseGenesInParentAfterwards) { this.parent.eraseGenes(); } this.state = parentState.getStateAfterMove(this.selectedCell.getRow(), this.selectedCell.getCol()); } public boolean isGoalState() { return this.isGoalState; } public SameGameState getState() { return this.state; } public int getScore() { return this.score; } public List<SameGameNode> getPath() { if (this.parent == null) { List<SameGameNode> rootList = new ArrayList<>(); rootList.add(this); return rootList; } List<SameGameNode> path = this.parent.getPath(); path.add(this); return path; } public List<SameGameCell> getDecisionPathToRoot() { if (this.parent == null) { return new ArrayList<>(); } List<SameGameCell> path = this.parent.getDecisionPathToRoot(); path.add(this.selectedCell); return path; } @Override public int hashCode() { return this.hashOfPathToRoot; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } SameGameNode other = (SameGameNode) obj; return this.getDecisionPathToRoot().equals(other.getDecisionPathToRoot()); } public boolean isKeepInMemory() { return this.keepInMemory; } @Override public boolean allowsGeneErasure() { return !this.keepInMemory; } public SameGameCell getSelectedCell() { return this.selectedCell; } @Override public String toString() { return "SameGameNode [selectedCell=" + this.selectedCell + ", score=" + this.score + "]"; } }
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/samegame/SameGamePathEvaluator.java
package ai.libs.jaicore.search.exampleproblems.samegame; 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; import ai.libs.jaicore.problems.samegame.SameGameCell; import ai.libs.jaicore.problems.samegame.SameGameState; public class SameGamePathEvaluator implements IPathEvaluator<SameGameNode, SameGameCell, Double> { private final boolean maximize; private final int minScore; private final int maxScore; private final boolean relativeScores; public SameGamePathEvaluator(final SameGameState initState, final boolean maximize, final boolean relativeScores) { this.minScore = -10000; this.maxScore = (int) Math.pow(initState.getNumberOfPiecesPerColor().values().stream().max(Integer::compare).get() - 2.0, 2); this.relativeScores = relativeScores; this.maximize = maximize; } @Override public Double evaluate(final ILabeledPath<SameGameNode, SameGameCell> path) throws PathEvaluationException, InterruptedException { double unitVal = ((double) path.getHead().getScore() - this.minScore) / (this.relativeScores ? (this.maxScore - this.minScore) : 1); return this.maximize ? unitVal : (1 - unitVal); } public double getOriginalScoreFromRelativeScore(final double relativeScore) { double relOriginalScore = this.maximize ? relativeScore : (1-relativeScore); return relOriginalScore * (this.maxScore - this.minScore) + this.minScore; } public boolean isMaximize() { return this.maximize; } public int getMinScore() { return this.minScore; } public int getMaxScore() { return this.maxScore; } public boolean isRelativeScores() { return this.relativeScores; } }
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/taxi/ETaxiAction.java
package ai.libs.jaicore.search.exampleproblems.taxi; public enum ETaxiAction { N, E, S, W, PICKUP, PUTDOWN }
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/taxi/TaxiMDP.java
package ai.libs.jaicore.search.exampleproblems.taxi; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import ai.libs.jaicore.basic.sets.IntCoordinates; import ai.libs.jaicore.search.probleminputs.AMDP; public class TaxiMDP extends AMDP<TaxiState, ETaxiAction, Double> { private final boolean[][][] possibleTransitions; // this is the street map: width x height. Third dimension is 0=N,1=E,2=S,3=W private final int width; private final int height; private final double successRate; private final List<IntCoordinates> pickupLocations; private final IntCoordinates pickupLocation; private final IntCoordinates targetLocation; private static TaxiState drawInitState(final int width, final int height, final List<IntCoordinates> pickupLocations, final Random random) { int x; int y; IntCoordinates coords; do { x = random.nextInt(width); y = random.nextInt(height); coords = new IntCoordinates(x, y); } while (pickupLocations.contains(coords)); return new TaxiState(coords, false, false); } public TaxiMDP(final boolean[][][] possibleTransitions, final double successRate, final List<IntCoordinates> pickupLocations, final Random random) { super (drawInitState(possibleTransitions.length, possibleTransitions[0].length, pickupLocations, random)); this.width = possibleTransitions.length; this.height = possibleTransitions[0].length; this.possibleTransitions = possibleTransitions; this.successRate = successRate; this.pickupLocations = pickupLocations; this.pickupLocation = pickupLocations.get(0); this.targetLocation = pickupLocations.get(1); } public boolean[][][] getPossibleTransitions() { return this.possibleTransitions; } public double getSuccessRate() { return this.successRate; } public List<IntCoordinates> getPickupLocations() { return this.pickupLocations; } @Override public boolean isMaximizing() { return true; } @Override public Collection<ETaxiAction> getApplicableActions(final TaxiState state) { Collection<ETaxiAction> possibleActions = new ArrayList<>(); if (state.isPassengerDelivered()) { return possibleActions; } if (state.getPosition().equals(this.pickupLocation) && !state.isPassengerOnBoard()) { possibleActions.add(ETaxiAction.PICKUP); return possibleActions; } if (state.getPosition().equals(this.targetLocation) && state.isPassengerOnBoard()) { possibleActions.add(ETaxiAction.PUTDOWN); return possibleActions; } for (ETaxiAction a : ETaxiAction.values()) { if (a != ETaxiAction.PICKUP && a != ETaxiAction.PUTDOWN && this.isDirectionPossible(state, a)) { possibleActions.add(a); } } return possibleActions; } private boolean isDirectionPossible(final TaxiState state, final ETaxiAction action) { int x = state.getPosition().getX(); int y = state.getPosition().getY(); switch (action) { case W: return x > 0 && this.possibleTransitions[x][y][3]; case E: return x < this.width - 1 && this.possibleTransitions[x][y][1]; case S: return y > 0 && this.possibleTransitions[x][y][2]; case N: return y < this.height - 1 && this.possibleTransitions[x][y][0]; default: throw new IllegalStateException("Invalid direction " + action); } } @Override public Map<TaxiState, Double> getProb(final TaxiState state, final ETaxiAction action) { Map<TaxiState, Double> dist = new HashMap<>(); if (action == ETaxiAction.PICKUP) { TaxiState succ = new TaxiState(state.getPosition(), true, false); dist.put(succ, 1.0); return dist; } if (action == ETaxiAction.PUTDOWN) { TaxiState succ = new TaxiState(state.getPosition(), false, true); dist.put(succ, 1.0); return dist; } IntCoordinates pos = state.getPosition(); boolean lPossible = this.isDirectionPossible(state, ETaxiAction.W); boolean rPossible = this.isDirectionPossible(state, ETaxiAction.E); boolean tPossible = this.isDirectionPossible(state, ETaxiAction.N); boolean bPossible = this.isDirectionPossible(state, ETaxiAction.S); boolean isOnBoard = state.isPassengerOnBoard(); boolean isDelivered = state.isPassengerDelivered(); if (action == ETaxiAction.N) { dist.put(new TaxiState(pos.getUp(), isOnBoard, isDelivered), this.successRate); double prob = (lPossible && rPossible) ? (1 - this.successRate) / 2 : (1 - this.successRate); if (lPossible) { dist.put(new TaxiState(pos.getLeft(), isOnBoard, isDelivered), prob); } if (rPossible) { dist.put(new TaxiState(pos.getRight(), isOnBoard, isDelivered), prob); } } else if (action == ETaxiAction.E) { dist.put(new TaxiState(pos.getRight(), isOnBoard, isDelivered), this.successRate); double prob = (tPossible && bPossible) ? (1 - this.successRate) / 2 : (1 - this.successRate); if (tPossible) { dist.put(new TaxiState(pos.getUp(), isOnBoard, isDelivered), prob); } if (bPossible) { dist.put(new TaxiState(pos.getDown(), isOnBoard, isDelivered), prob); } } else if (action == ETaxiAction.S) { dist.put(new TaxiState(pos.getDown(), isOnBoard, isDelivered), this.successRate); double prob = (lPossible && rPossible) ? (1 - this.successRate) / 2 : (1 - this.successRate); if (lPossible) { dist.put(new TaxiState(pos.getLeft(), isOnBoard, isDelivered), prob); } if (rPossible) { dist.put(new TaxiState(pos.getRight(), isOnBoard, isDelivered), prob); } } else if (action == ETaxiAction.W) { dist.put(new TaxiState(pos.getLeft(), isOnBoard, isDelivered), this.successRate); double prob = (tPossible && bPossible) ? (1 - this.successRate) / 2 : (1 - this.successRate); if (tPossible) { dist.put(new TaxiState(pos.getUp(), isOnBoard, isDelivered), prob); } if (bPossible) { dist.put(new TaxiState(pos.getDown(), isOnBoard, isDelivered), prob); } } else { throw new IllegalArgumentException("Do not know how to process action " + action + " in state " + state); } return dist; } @Override public Double getScore(final TaxiState state, final ETaxiAction action, final TaxiState successor) { if (successor.isPassengerDelivered() && action == ETaxiAction.PUTDOWN) { return (20.0 - 1) / 100; } return -1.0 / 100; } @Override public String toString() { StringBuilder sb = new StringBuilder(); int cols = this.width; int rows = this.height; int startCol = this.getInitState().getPosition().getX(); int startRow = this.getInitState().getPosition().getY(); int pickupCol = this.pickupLocation.getX(); int pickupRow = this.pickupLocation.getY(); int targetCol = this.targetLocation.getX(); int targetRow = this.targetLocation.getY(); for (int r = rows - 1; r >= 0; r --) { /* print grid above row */ for (int c = 0; c < cols; c ++) { sb.append("+-"); } sb.append("+\n"); /* print content of row */ for (int c = 0; c < cols; c ++) { sb.append("|"); if (c == startCol && r == startRow) { sb.append("x"); } else if (targetCol == c && targetRow == r) { sb.append("*"); } else if (pickupCol == c && pickupRow == r) { sb.append("o"); } else { sb.append(" "); } } sb.append("+\n"); } return sb.toString(); } }
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/taxi/TaxiState.java
package ai.libs.jaicore.search.exampleproblems.taxi; import ai.libs.jaicore.basic.sets.IntCoordinates; public class TaxiState { private final IntCoordinates position; private final boolean passengerOnBoard; private final boolean passengerDelivered; public TaxiState(final IntCoordinates position, final boolean passengerOnBoard, final boolean passengerDelivered) { super(); this.position = position; this.passengerOnBoard = passengerOnBoard; this.passengerDelivered = passengerDelivered; } public IntCoordinates getPosition() { return this.position; } public boolean isPassengerOnBoard() { return this.passengerOnBoard; } public boolean isPassengerDelivered() { return this.passengerDelivered; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.passengerDelivered ? 1231 : 1237); result = prime * result + (this.passengerOnBoard ? 1231 : 1237); result = prime * result + ((this.position == null) ? 0 : this.position.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; } TaxiState other = (TaxiState) obj; if (this.passengerDelivered != other.passengerDelivered) { return false; } if (this.passengerOnBoard != other.passengerOnBoard) { return false; } if (this.position == null) { if (other.position != null) { return false; } } else if (!this.position.equals(other.position)) { return false; } return true; } @Override public String toString() { return this.position.getX() + "/" + this.position.getY() + "[" + this.passengerOnBoard + ", " + this.passengerDelivered + "]"; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/experiments/ASearchExperimentDecoder.java
package ai.libs.jaicore.search.experiments; import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearch; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IEvaluatedPath; import ai.libs.jaicore.experiments.AExperimentDecoder; import ai.libs.jaicore.experiments.IExperimentSetConfig; public abstract class ASearchExperimentDecoder<N, A, I extends IPathSearchWithPathEvaluationsInput<N, A, Double>, O extends IEvaluatedPath<N, A, Double>, P extends IOptimalPathInORGraphSearch<? extends I, ? extends O, N, A, Double>> extends AExperimentDecoder<I, P> implements ISearchExperimentDecoder<N, A, I, O, P> { public ASearchExperimentDecoder(final IExperimentSetConfig config) { super(config); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/experiments/ISearchExperimentDecoder.java
package ai.libs.jaicore.search.experiments; import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearch; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IEvaluatedPath; import ai.libs.jaicore.experiments.IExperimentDecoder; public interface ISearchExperimentDecoder<N, A, I extends IPathSearchWithPathEvaluationsInput<N, A, Double>, O extends IEvaluatedPath<N, A, Double>, P extends IOptimalPathInORGraphSearch<? extends I, ? extends O, N, A, Double>> extends IExperimentDecoder<I, P> { }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/experiments/SearchExperimentDomain.java
package ai.libs.jaicore.search.experiments; import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearch; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IEvaluatedPath; import ai.libs.jaicore.experiments.AExperimentDomain; import ai.libs.jaicore.experiments.IExperimentBuilder; import ai.libs.jaicore.experiments.IExperimentSetConfig; public abstract class SearchExperimentDomain<B extends IExperimentBuilder, I extends IPathSearchWithPathEvaluationsInput<N, A, Double>, N, A> extends AExperimentDomain<B, I, IOptimalPathInORGraphSearch<? extends I, ? extends IEvaluatedPath<N, A, Double>, N, A, Double>> { public SearchExperimentDomain(final IExperimentSetConfig config, final ISearchExperimentDecoder<N, A, I, IEvaluatedPath<N, A, Double>, IOptimalPathInORGraphSearch<? extends I, ? extends IEvaluatedPath<N, A, Double>, N, A, Double>> decoder) { super(config, decoder); } @Override public ISearchExperimentDecoder<N, A, I, IEvaluatedPath<N, A, Double>, IOptimalPathInORGraphSearch<? extends I, ? extends IEvaluatedPath<N, A, Double>, N, A, Double>> getDecoder() { return (ISearchExperimentDecoder<N, A, I, IEvaluatedPath<N, A, Double>, IOptimalPathInORGraphSearch<? extends I, ? extends IEvaluatedPath<N, A, Double>, N, A, Double>>)super.getDecoder(); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/experiments/SearchExperimentsProfiler.java
package ai.libs.jaicore.search.experiments; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearch; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IEvaluatedPath; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException; import ai.libs.jaicore.experiments.Experiment; import ai.libs.jaicore.experiments.exceptions.ExperimentDecodingException; import ai.libs.jaicore.search.landscapeanalysis.GenericLandscapeAnalyzer; import ai.libs.jaicore.search.landscapeanalysis.LandscapeAnalysisCompletionTechnique; public class SearchExperimentsProfiler { private static final String FOLDER_LANDSCAPES = "landscapes"; private class Toolbox<I extends IPathSearchWithPathEvaluationsInput<N, A, Double>, N, A> { private final ISearchExperimentDecoder<N, A, I, IEvaluatedPath<N, A, Double>, IOptimalPathInORGraphSearch<? extends I, ? extends IEvaluatedPath<N, A, Double>, N, A, Double>> decoder; public Toolbox(final ISearchExperimentDecoder<N, A, I, IEvaluatedPath<N, A, Double>, IOptimalPathInORGraphSearch<? extends I, ? extends IEvaluatedPath<N, A, Double>, N, A, Double>> decoder) { super(); this.decoder = decoder; } public GenericLandscapeAnalyzer<N, A> getLandscapeAnalyzer(final Experiment experiment) { try { return new GenericLandscapeAnalyzer<>(this.decoder.getProblem(experiment)); } catch (ExperimentDecodingException e) { throw new IllegalStateException(e); } } } private final Toolbox<?, ?, ?> toolbox; private File workingDirectory; public <I extends IPathSearchWithPathEvaluationsInput<N, A, Double>, N, A> SearchExperimentsProfiler( final ISearchExperimentDecoder<N, A, I, IEvaluatedPath<N, A, Double>, IOptimalPathInORGraphSearch<? extends I, ? extends IEvaluatedPath<N, A, Double>, N, A, Double>> decoder, final File workingDirectory) { this.toolbox = new Toolbox<>(decoder); this.workingDirectory = workingDirectory; } private File getLandscapeFolder(final Experiment experiment) { File folder = new File(this.workingDirectory + File.separator + FOLDER_LANDSCAPES + File.separator + experiment.hashCode()); folder.mkdirs(); return folder; } public void plainLandscapeAnalysis(final Experiment experiment, final Number probeSize) throws IOException, PathEvaluationException, InterruptedException { try (FileWriter fw = new FileWriter(new File(this.getLandscapeFolder(experiment) + File.separator + probeSize.intValue() + ".plainlandscape"))) { for (double d : this.toolbox.getLandscapeAnalyzer(experiment).getValues(probeSize, LandscapeAnalysisCompletionTechnique.RANDOM)) { fw.write(d + "\n"); } } } public void iterativeLandscapeAnalysis(final Experiment experiment, final Number probeSize) throws IOException, PathEvaluationException, InterruptedException { List<List<double[]>> iterativeAnalysisResults = this.toolbox.getLandscapeAnalyzer(experiment).getIterativeProbeValuesAlongRandomPath(probeSize); int m = iterativeAnalysisResults.size(); for (int depth = 0; depth < m; depth++) { List<double[]> probesInDepth = iterativeAnalysisResults.get(depth); int n = probesInDepth.size(); for (int branch = 0; branch < n; branch++) { try (FileWriter fw = new FileWriter(new File(this.getLandscapeFolder(experiment) + File.separator + depth + "-" + branch + ".iterativelandscape"))) { for (double d : probesInDepth.get(branch)) { fw.write(d + "\n"); } } } } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/experiments/StandardExperimentSearchAlgorithmFactory.java
package ai.libs.jaicore.search.experiments; import java.util.Arrays; import java.util.Random; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearch; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IEvaluatedPath; import ai.libs.jaicore.basic.IOwnerBasedRandomConfig; import ai.libs.jaicore.experiments.Experiment; import ai.libs.jaicore.experiments.configurations.IAlgorithmNameConfig; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.brue.BRUEFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.FixedCommitmentMCTSFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.PlackettLuceMCTSFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.preferencekernel.bootstrapping.BootstrappingPreferenceKernel; import ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.preferencekernel.bootstrapping.DefaultBootsrapConfigurator; import ai.libs.jaicore.search.algorithms.mdp.mcts.ensemble.EnsembleMCTSFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.spuct.SPUCTFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.tag.TAGMCTSFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.thompson.DNGMCTSFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.thompson.DNGPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.uct.UCBPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.uct.UCTFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.uuct.UUCTFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.uuct.utility.VaR; import ai.libs.jaicore.search.algorithms.standard.auxilliary.iteratingoptimizer.IteratingGraphSearchOptimizer; import ai.libs.jaicore.search.algorithms.standard.auxilliary.iteratingoptimizer.IteratingGraphSearchOptimizerFactory; import ai.libs.jaicore.search.algorithms.standard.bestfirst.BestFirst; import ai.libs.jaicore.search.algorithms.standard.dfs.DepthFirstSearchFactory; import ai.libs.jaicore.search.algorithms.standard.mcts.MCTSPathSearch; import ai.libs.jaicore.search.algorithms.standard.random.RandomSearchFactory; import ai.libs.jaicore.search.problemtransformers.GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformerViaRDFS; import ai.libs.jaicore.search.problemtransformers.GraphSearchWithPathEvaluationsInputToGraphSearchWithSubpathEvaluationViaUninformedness; public class StandardExperimentSearchAlgorithmFactory<N, A, I extends IPathSearchWithPathEvaluationsInput<N, A, Double>> { private MCTSPathSearch<I, N, A> getMCTS(final I input, final MCTSFactory<N, A, ?> factory, final int maxiter, final int seed) { factory.withRandom(new Random(seed)); factory.withMaxIterations(maxiter); return new MCTSPathSearch<>(input, factory); } @SuppressWarnings("unchecked") public IOptimalPathInORGraphSearch<I, ? extends IEvaluatedPath<N, A, Double>, N, A, Double> getAlgorithm(final Experiment experiment, final IPathSearchWithPathEvaluationsInput<N, A, Double> input) { final int seed = Integer.parseInt(experiment.getValuesOfKeyFields().get(IOwnerBasedRandomConfig.K_SEED)); final String algorithm = experiment.getValuesOfKeyFields().get(IAlgorithmNameConfig.K_ALGORITHM_NAME); final int maxiter = Integer.MAX_VALUE; if (algorithm.startsWith("uuct-")) { String[] parts = algorithm.split("-"); double alpha = Double.parseDouble(parts[1]); double b = Double.parseDouble(parts[2]); UUCTFactory<N, A> uuctFactory = new UUCTFactory<>(); uuctFactory.setUtility(new VaR(alpha, b)); return this.getMCTS((I)input, uuctFactory, maxiter, seed); } switch (algorithm) { case "random": IteratingGraphSearchOptimizerFactory<I, N, A, Double> factory = new IteratingGraphSearchOptimizerFactory<>(); RandomSearchFactory<N, A> rsf = new RandomSearchFactory<>(); rsf.setSeed(seed); factory.setBaseAlgorithmFactory(rsf); IteratingGraphSearchOptimizer<I, N, A, Double> optimizer = factory.getAlgorithm((I)input); return optimizer; case "bf-uninformed": GraphSearchWithPathEvaluationsInputToGraphSearchWithSubpathEvaluationViaUninformedness<N, A> reducer = new GraphSearchWithPathEvaluationsInputToGraphSearchWithSubpathEvaluationViaUninformedness<>(); IPathSearchWithPathEvaluationsInput<N, A, Double> reducedProblem = reducer.encodeProblem(input); return new BestFirst<>((I)reducedProblem); case "bf-informed": GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformerViaRDFS<N, A, Double> reducer2 = new GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformerViaRDFS<>(n -> null, n -> false, new Random(seed), 3, 30 * 1000, 60 * 1000); // THIS IS AN ARBITRARY CONFIG USED FOR THE AUTOML SCENARIO (1h total timeout)!! return new BestFirst<>((I)reducer2.encodeProblem(input)); case "uct": return this.getMCTS((I)input, new UCTFactory<>(), maxiter, seed); case "ensemble": DNGMCTSFactory<N, A> dngFactory = new DNGMCTSFactory<>(); dngFactory.setInitLambda(0.01); DNGPolicy<N, A> dng001 = (DNGPolicy<N, A>)this.getMCTS((I)input, dngFactory, maxiter, seed).getMcts().getTreePolicy(); dngFactory.setInitLambda(0.1); DNGPolicy<N, A> dng01 = (DNGPolicy<N, A>)this.getMCTS((I)input, dngFactory, maxiter, seed).getMcts().getTreePolicy(); dngFactory.setInitLambda(1); DNGPolicy<N, A> dng1 = (DNGPolicy<N, A>)this.getMCTS((I)input, dngFactory, maxiter, seed).getMcts().getTreePolicy(); dngFactory.setInitLambda(10); DNGPolicy<N, A> dng10 = (DNGPolicy<N, A>)this.getMCTS((I)input, dngFactory, maxiter, seed).getMcts().getTreePolicy(); dngFactory.setInitLambda(100); DNGPolicy<N, A> dng100 = (DNGPolicy<N, A>)this.getMCTS((I)input, dngFactory, maxiter, seed).getMcts().getTreePolicy(); EnsembleMCTSFactory<N, A> eFactory = new EnsembleMCTSFactory<>(); eFactory.setTreePolicies(Arrays.asList(new UCBPolicy<>(1.0, true), dng001, dng01, dng1, dng01, dng10, dng100)); return this.getMCTS((I)input, eFactory, maxiter, seed); case "sp-uct": SPUCTFactory<N, A> spucbFactory = new SPUCTFactory<>(); spucbFactory.setBigD(10000); return this.getMCTS((I)input, spucbFactory, maxiter, seed); case "pl-mcts-mean": return this.getMCTS((I)input, new PlackettLuceMCTSFactory<N, A>().withPreferenceKernel(new BootstrappingPreferenceKernel<>(DescriptiveStatistics::getMean, new DefaultBootsrapConfigurator(), 1)), maxiter, seed); case "pl-mcts-mean+std": return this.getMCTS((I)input, new PlackettLuceMCTSFactory<N, A>().withPreferenceKernel(new BootstrappingPreferenceKernel<>(d -> d.getMean() + d.getStandardDeviation(), new DefaultBootsrapConfigurator(), 1)), maxiter, seed); case "pl-mcts-mean-std": return this.getMCTS((I)input, new PlackettLuceMCTSFactory<N, A>().withPreferenceKernel(new BootstrappingPreferenceKernel<>(d -> d.getMean() - d.getStandardDeviation(), new DefaultBootsrapConfigurator(), 1)), maxiter, seed); case "pl-mcts-min": return this.getMCTS((I)input, new PlackettLuceMCTSFactory<N, A>().withPreferenceKernel(new BootstrappingPreferenceKernel<>(DescriptiveStatistics::getMin, new DefaultBootsrapConfigurator(), 1)), maxiter, seed); case "mcts-kfix-100-mean": FixedCommitmentMCTSFactory<N, A> fcFactory1 = new FixedCommitmentMCTSFactory<>(); fcFactory1.setK(100); fcFactory1.setMetric(DescriptiveStatistics::getMean); return this.getMCTS((I)input, fcFactory1, maxiter, seed); case "mcts-kfix-200-mean": FixedCommitmentMCTSFactory<N, A> fcFactory2 = new FixedCommitmentMCTSFactory<>(); fcFactory2.setK(200); fcFactory2.setMetric(DescriptiveStatistics::getMean); return this.getMCTS((I)input, fcFactory2, maxiter, seed); case "dng": return this.getMCTS((I)input, new DNGMCTSFactory<>(), maxiter, seed); case "tag": return this.getMCTS((I)input, new TAGMCTSFactory<>(), maxiter, seed); case "brue": return this.getMCTS((I)input, new BRUEFactory<>(), maxiter, seed); case "dfs": IteratingGraphSearchOptimizerFactory<I, N, A, Double> dfsFactory = new IteratingGraphSearchOptimizerFactory<>(); dfsFactory.setBaseAlgorithmFactory(new DepthFirstSearchFactory<>()); return dfsFactory.getAlgorithm((I)input); default: throw new IllegalArgumentException("Unsupported algorithm " + algorithm); } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/experiments
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/experiments/terminationcriteria/MaxRolloutExperimentTerminationCriterion.java
package ai.libs.jaicore.search.experiments.terminationcriteria; import ai.libs.jaicore.experiments.MaxNumberOfEventsTerminationCriterion; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RolloutEvent; public class MaxRolloutExperimentTerminationCriterion extends MaxNumberOfEventsTerminationCriterion { public MaxRolloutExperimentTerminationCriterion(final int maxNumberOfRollouts) { super(maxNumberOfRollouts, RolloutEvent.class); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/experiments
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/experiments/terminationcriteria/MaxSolutionExperimentTerminationCriterion.java
package ai.libs.jaicore.search.experiments.terminationcriteria; import org.api4.java.algorithm.events.result.ISolutionCandidateFoundEvent; import ai.libs.jaicore.experiments.MaxNumberOfEventsTerminationCriterion; public class MaxSolutionExperimentTerminationCriterion extends MaxNumberOfEventsTerminationCriterion { public MaxSolutionExperimentTerminationCriterion(final int maxNumberOfSolutions) { super(maxNumberOfSolutions, ISolutionCandidateFoundEvent.class); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/bradleyterry/BradleyTerryEventPropertyComputer.java
package ai.libs.jaicore.search.gui.plugins.mcts.bradleyterry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.api4.java.algorithm.events.IAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyComputationFailedException; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoAlgorithmEventPropertyComputer; import ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.ObservationsUpdatedEvent; public class BradleyTerryEventPropertyComputer implements AlgorithmEventPropertyComputer { public static final String UPDATE_PROPERTY_NAME = "bt_update"; private NodeInfoAlgorithmEventPropertyComputer nodeInfoAlgorithmEventPropertyComputer; public BradleyTerryEventPropertyComputer(final NodeInfoAlgorithmEventPropertyComputer nodeInfoAlgorithmEventPropertyComputer) { this.nodeInfoAlgorithmEventPropertyComputer = nodeInfoAlgorithmEventPropertyComputer; } @Override public Object computeAlgorithmEventProperty(final IAlgorithmEvent algorithmEvent) throws PropertyComputationFailedException { if (algorithmEvent instanceof ObservationsUpdatedEvent) { ObservationsUpdatedEvent<?> btEvent = (ObservationsUpdatedEvent<?>) algorithmEvent; return new BradleyTerryUpdate(this.nodeInfoAlgorithmEventPropertyComputer.getIdOfNodeIfExistent(btEvent.getNode()), btEvent.getVisits(), btEvent.getWinsLeft(), btEvent.getWinsRight(), new ArrayList<>(btEvent.getScoresLeft()), new ArrayList<>(btEvent.getScoresRight()), btEvent.getpLeft(), btEvent.getpRight(), btEvent.getpLeftScaled(), btEvent.getpRightScaled()); } return null; } @Override public String getPropertyName() { return UPDATE_PROPERTY_NAME; } @Override public List<AlgorithmEventPropertyComputer> getRequiredPropertyComputers() { return Arrays.asList(this.nodeInfoAlgorithmEventPropertyComputer); } @Override public void overwriteRequiredPropertyComputer(final AlgorithmEventPropertyComputer computer) { this.nodeInfoAlgorithmEventPropertyComputer = (NodeInfoAlgorithmEventPropertyComputer)computer; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/bradleyterry/BradleyTerryPlugin.java
package ai.libs.jaicore.search.gui.plugins.mcts.bradleyterry; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoAlgorithmEventPropertyComputer; import ai.libs.jaicore.search.gui.plugins.rollouthistograms.RolloutInfoAlgorithmEventPropertyComputer; public class BradleyTerryPlugin extends ASimpleMVCPlugin<BradleyTerryPluginModel, BradleyTerryPluginView, BradleyTerryPluginController> { public BradleyTerryPlugin() { this("Bradley Terry Plugin"); } public BradleyTerryPlugin(final String title) { super(title); } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(new RolloutInfoAlgorithmEventPropertyComputer(), new BradleyTerryEventPropertyComputer(new NodeInfoAlgorithmEventPropertyComputer())); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/bradleyterry/BradleyTerryPluginController.java
package ai.libs.jaicore.search.gui.plugins.mcts.bradleyterry; import java.util.ArrayList; import java.util.List; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.graphview.NodeClickedEvent; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; import ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.ObservationsUpdatedEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RolloutEvent; import ai.libs.jaicore.search.gui.plugins.rollouthistograms.RolloutInfo; import ai.libs.jaicore.search.gui.plugins.rollouthistograms.RolloutInfoAlgorithmEventPropertyComputer; public class BradleyTerryPluginController extends ASimpleMVCPluginController<BradleyTerryPluginModel, BradleyTerryPluginView> { public BradleyTerryPluginController(final BradleyTerryPluginModel model, final BradleyTerryPluginView view) { super(model, view); } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent || guiEvent instanceof GoToTimeStepEvent) { this.getModel().clear(); } else if (guiEvent instanceof NodeClickedEvent) { this.getModel().setCurrentlySelectedNode(((NodeClickedEvent) guiEvent).getSearchGraphNode()); this.getView().update(); } } @Override public void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) { if (algorithmEvent.correspondsToEventOfClass(RolloutEvent.class)) { RolloutInfo rolloutInfo = (RolloutInfo) algorithmEvent.getProperty(RolloutInfoAlgorithmEventPropertyComputer.ROLLOUT_SCORE_PROPERTY_NAME); String lastNode = null; for (String n : rolloutInfo.getPath()) { if (lastNode != null) { List<String> successors = this.getModel().getListsOfKnownSuccessors().computeIfAbsent(lastNode, k -> new ArrayList<>()); if (!successors.contains(n)) { successors.add(n); } this.getModel().getParents().put(n, lastNode); } lastNode = n; } } else if (algorithmEvent.correspondsToEventOfClass(ObservationsUpdatedEvent.class)) { BradleyTerryUpdate updateInfo = (BradleyTerryUpdate) algorithmEvent.getProperty(BradleyTerryEventPropertyComputer.UPDATE_PROPERTY_NAME); this.getModel().setNodeStats(updateInfo); } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/bradleyterry/BradleyTerryPluginModel.java
package ai.libs.jaicore.search.gui.plugins.mcts.bradleyterry; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; /** * * @author fmohr * * @param <BalancedTreeNode> * The node type class. */ public class BradleyTerryPluginModel extends ASimpleMVCPluginModel<BradleyTerryPluginView, BradleyTerryPluginController> { private String currentlySelectedNode = "0"; private final Map<String, String> parents = new HashMap<>(); private final Map<String, List<String>> listsOfKnownSuccessors = new HashMap<>(); private final Map<String, BradleyTerryUpdate> btUpdates = new HashMap<>(); @Override public void clear() { this.getView().clear(); } public void setCurrentlySelectedNode(final String currentlySelectedNode) { this.currentlySelectedNode = currentlySelectedNode; this.getView().clear(); this.getView().update(); } public String getCurrentlySelectedNode() { return this.currentlySelectedNode; } public void setNodeStats(final BradleyTerryUpdate update) { if (update == null) { throw new IllegalArgumentException("Cannot process NULL update"); } String node = update.getNode(); if (!this.listsOfKnownSuccessors.containsKey(node)) { throw new IllegalArgumentException("Cannot receive update for an unknown node. Make sure that Rollout events are processed!"); } this.btUpdates.put(node, update); if (node.equals(this.getCurrentlySelectedNode())) { this.getView().update(); } } public Map<String, BradleyTerryUpdate> getBtUpdates() { return this.btUpdates; } public BradleyTerryUpdate getUpdateOfSelectedNode() { return this.btUpdates.get(this.getCurrentlySelectedNode()); } public Map<String, List<String>> getListsOfKnownSuccessors() { return this.listsOfKnownSuccessors; } public List<String> getListOfKnownSuccessorsOfCurrentlySelectedNode() { return this.listsOfKnownSuccessors.get(this.getCurrentlySelectedNode()); } public Map<String, String> getParents() { return this.parents; } public String getParentOfCurrentNode() { return this.parents.get(this.getCurrentlySelectedNode()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/bradleyterry/BradleyTerryPluginView.java
package ai.libs.jaicore.search.gui.plugins.mcts.bradleyterry; import java.util.Map; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import ai.libs.jaicore.graphvisualizer.plugin.graphview.NodeClickedEvent; import javafx.application.Platform; import javafx.scene.control.Button; import javafx.scene.layout.FlowPane; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; /** * * @author fmohr * * @param <BalancedTreeNode> * The node class */ public class BradleyTerryPluginView extends ASimpleMVCPluginView<BradleyTerryPluginModel, BradleyTerryPluginController, FlowPane> { private final Button left = new Button("left"); private final Button right = new Button("right"); private final Button parent = new Button("parent"); private WebEngine engine; private static final String HTML_TD_OPEN = "<td>"; private static final String HTML_TD_CLOSE = "</td>"; private static final String HTML_TR_OPEN = "<tr>"; private static final String HTML_TR_CLOSE = "</tr>"; public BradleyTerryPluginView(final BradleyTerryPluginModel model) { super(model, new FlowPane()); Platform.runLater(() -> { WebView view = new WebView(); FlowPane node = this.getNode(); node.getChildren().add(this.left); node.getChildren().add(this.right); node.getChildren().add(this.parent); this.left.setOnMouseClicked(e -> { DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(null, this.getLeftChild(model.getCurrentlySelectedNode()))); this.parent.setDisable(false); }); this.right.setOnMouseClicked(e -> { DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(null, this.getRightChild(model.getCurrentlySelectedNode()))); this.parent.setDisable(false); }); this.parent.setOnMouseClicked(e -> { String parentOfCurrent = this.getModel().getParentOfCurrentNode(); DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(null, parentOfCurrent)); if (!this.getModel().getParents().containsKey(parentOfCurrent)) { this.parent.setDisable(true); } }); node.getChildren().add(view); this.engine = view.getEngine(); this.engine.loadContent("Nothing there yet."); }); } private String getLeftChild(final String node) { return this.getModel().getListsOfKnownSuccessors().get(node).get(0); } private String getRightChild(final String node) { return this.getModel().getListsOfKnownSuccessors().get(node).size() > 1 ? this.getModel().getListsOfKnownSuccessors().get(node).get(1) : null; } @Override public void update() { StringBuilder sb = new StringBuilder(); sb.append("<h2>Analysis of node "); String currentNode = this.getModel().getCurrentlySelectedNode(); sb.append(currentNode); sb.append(" (depth "); Map<String, String> parents = this.getModel().getParents(); int depth = 0; while (parents.containsKey(currentNode)) { currentNode = parents.get(currentNode); depth++; } sb.append(depth); sb.append(")</h2>"); BradleyTerryUpdate update = this.getModel().getUpdateOfSelectedNode(); if (update != null) { sb.append("<p>Number of visits: "); sb.append(update.getVisits()); sb.append("</p>"); sb.append("<h2>Stats of children</h2><table><tr>"); /* first row contains number of visits */ BradleyTerryUpdate modelOfLeftChild = this.getModel().getBtUpdates().get(this.getLeftChild(update.getNode())); BradleyTerryUpdate modelOfRightChild = this.getModel().getBtUpdates().get(this.getRightChild(update.getNode())); sb.append(HTML_TD_OPEN); sb.append(modelOfLeftChild != null ? modelOfLeftChild.getVisits() : 0); sb.append(HTML_TD_CLOSE); sb.append(HTML_TD_OPEN); sb.append(modelOfRightChild != null ? modelOfRightChild.getVisits() : 0); sb.append(HTML_TD_CLOSE); /* second row contains wins */ sb.append(HTML_TR_CLOSE); sb.append(HTML_TR_OPEN); sb.append(HTML_TD_OPEN); sb.append(update.getWinsLeft()); sb.append(HTML_TD_CLOSE); sb.append(HTML_TD_OPEN); sb.append(update.getWinsRight()); sb.append(HTML_TD_CLOSE); /* third row contains probabilities */ sb.append(HTML_TR_CLOSE); sb.append(HTML_TR_OPEN); sb.append(HTML_TD_OPEN); sb.append(update.getpLeftScaled()); sb.append(" ("); sb.append(update.getpLeft()); sb.append(")</td>"); sb.append(HTML_TD_OPEN); sb.append(update.getpRightScaled()); sb.append(" ("); sb.append(update.getpRight()); sb.append(")</td>"); /* fourth row contains stats summary */ sb.append(HTML_TR_CLOSE); sb.append(HTML_TR_OPEN); DescriptiveStatistics leftStats = new DescriptiveStatistics(); update.getScoresLeft().forEach(leftStats::addValue); DescriptiveStatistics rightStats = new DescriptiveStatistics(); update.getScoresRight().forEach(rightStats::addValue); sb.append(HTML_TD_OPEN); sb.append(leftStats.toString().replace("\n", "<br />")); sb.append(HTML_TD_CLOSE); sb.append(HTML_TD_OPEN); sb.append(rightStats.toString().replace("\n", "<br />")); sb.append(HTML_TD_CLOSE); /* third row contains lists of considers observations */ sb.append("</tr><tr>"); sb.append("<td style=\"vertical-align: top;\"><ul>"); update.getScoresLeft().forEach(d -> sb.append("<li>" + d + "</li>")); sb.append("</ul></td>"); sb.append("<td style=\"vertical-align: top;\"><ul>"); update.getScoresRight().forEach(d -> sb.append("<li>" + d + "</li>")); sb.append("</ul></td>"); sb.append("</tr></table>"); } Platform.runLater(() -> this.engine.loadContent(sb.toString())); } @Override public void clear() { /* don't do anything */ } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/bradleyterry/BradleyTerryUpdate.java
package ai.libs.jaicore.search.gui.plugins.mcts.bradleyterry; import java.util.Collection; public class BradleyTerryUpdate { private final String node; private final int visits; private final int winsLeft; private final int winsRight; private final Collection<Double> scoresLeft; private final Collection<Double> scoresRight; private final double pLeft; private final double pRight; private final double pLeftScaled; private final double pRightScaled; public BradleyTerryUpdate(final String node, final int visits, final int winsLeft, final int winsRight, final Collection<Double> scoresLeft, final Collection<Double> scoresRight, final double pLeft, final double pRight, final double pLeftScaled, final double pRightScaled) { super(); this.node = node; this.visits = visits; this.winsLeft = winsLeft; this.winsRight = winsRight; this.scoresLeft = scoresLeft; this.scoresRight = scoresRight; this.pLeft = pLeft; this.pRight = pRight; this.pLeftScaled = pLeftScaled; this.pRightScaled = pRightScaled; } public String getNode() { return this.node; } public int getVisits() { return this.visits; } public int getWinsLeft() { return this.winsLeft; } public int getWinsRight() { return this.winsRight; } public Collection<Double> getScoresLeft() { return this.scoresLeft; } public double getpLeft() { return this.pLeft; } public double getpRight() { return this.pRight; } public Collection<Double> getScoresRight() { return this.scoresRight; } public double getpLeftScaled() { return this.pLeftScaled; } public double getpRightScaled() { return this.pRightScaled; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/dng/DNGBeliefUpdate.java
package ai.libs.jaicore.search.gui.plugins.mcts.dng; public class DNGBeliefUpdate { private final String node; private final double mu; private final double alpha; private final double beta; private final double lambda; public DNGBeliefUpdate(final String node, final double mu, final double alpha, final double beta, final double lambda) { super(); this.node = node; this.mu = mu; this.alpha = alpha; this.beta = beta; this.lambda = lambda; } public String getNode() { return this.node; } public double getMu() { return this.mu; } public double getAlpha() { return this.alpha; } public double getBeta() { return this.beta; } public double getLambda() { return this.lambda; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/dng/DNGEventPropertyComputer.java
package ai.libs.jaicore.search.gui.plugins.mcts.dng; import java.util.Arrays; import java.util.List; import org.api4.java.algorithm.events.IAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyComputationFailedException; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoAlgorithmEventPropertyComputer; import ai.libs.jaicore.search.algorithms.mdp.mcts.thompson.DNGBeliefUpdateEvent; import ai.libs.jaicore.search.algorithms.mdp.mcts.thompson.DNGQSampleEvent; public class DNGEventPropertyComputer implements AlgorithmEventPropertyComputer { public static final String UPDATE_PROPERTY_NAME = "dng_update"; private NodeInfoAlgorithmEventPropertyComputer nodeInfoAlgorithmEventPropertyComputer; public DNGEventPropertyComputer(final NodeInfoAlgorithmEventPropertyComputer nodeInfoAlgorithmEventPropertyComputer) { this.nodeInfoAlgorithmEventPropertyComputer = nodeInfoAlgorithmEventPropertyComputer; } @Override public Object computeAlgorithmEventProperty(final IAlgorithmEvent algorithmEvent) throws PropertyComputationFailedException { if (algorithmEvent instanceof DNGQSampleEvent) { DNGQSampleEvent<?,?> dngEvent = (DNGQSampleEvent<?,?>) algorithmEvent; String idOfNode = this.nodeInfoAlgorithmEventPropertyComputer.getIdOfNodeIfExistent(dngEvent.getNode()); return new DNGQSample(idOfNode, dngEvent.getAction().toString(), dngEvent.getScore()); } if (algorithmEvent instanceof DNGBeliefUpdateEvent) { DNGBeliefUpdateEvent<?> dngEvent = (DNGBeliefUpdateEvent<?>) algorithmEvent; String idOfNode = this.nodeInfoAlgorithmEventPropertyComputer.getIdOfNodeIfExistent(dngEvent.getNode()); return new DNGBeliefUpdate(idOfNode, dngEvent.getMu(), dngEvent.getAlpha(), dngEvent.getBeta(), dngEvent.getLambda()); } return null; } @Override public String getPropertyName() { return UPDATE_PROPERTY_NAME; } @Override public List<AlgorithmEventPropertyComputer> getRequiredPropertyComputers() { return Arrays.asList(this.nodeInfoAlgorithmEventPropertyComputer); } @Override public void overwriteRequiredPropertyComputer(final AlgorithmEventPropertyComputer computer) { this.nodeInfoAlgorithmEventPropertyComputer = (NodeInfoAlgorithmEventPropertyComputer)computer; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/dng/DNGMCTSPlugin.java
package ai.libs.jaicore.search.gui.plugins.mcts.dng; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoAlgorithmEventPropertyComputer; import ai.libs.jaicore.search.gui.plugins.rollouthistograms.RolloutInfoAlgorithmEventPropertyComputer; public class DNGMCTSPlugin extends ASimpleMVCPlugin<DNGMCTSPluginModel, DNGMCTSPluginView, DNGMCTSPluginController> { public DNGMCTSPlugin() { this("DNG MCTS Plugin"); } public DNGMCTSPlugin(final String title) { super(title); } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(new RolloutInfoAlgorithmEventPropertyComputer(), new DNGEventPropertyComputer(new NodeInfoAlgorithmEventPropertyComputer())); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/dng/DNGMCTSPluginController.java
package ai.libs.jaicore.search.gui.plugins.mcts.dng; import java.util.ArrayList; import java.util.List; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.graphview.NodeClickedEvent; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; import ai.libs.jaicore.search.algorithms.mdp.mcts.thompson.DNGBeliefUpdateEvent; import ai.libs.jaicore.search.algorithms.mdp.mcts.thompson.DNGQSampleEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RolloutEvent; import ai.libs.jaicore.search.gui.plugins.rollouthistograms.RolloutInfo; import ai.libs.jaicore.search.gui.plugins.rollouthistograms.RolloutInfoAlgorithmEventPropertyComputer; public class DNGMCTSPluginController extends ASimpleMVCPluginController<DNGMCTSPluginModel, DNGMCTSPluginView> { public DNGMCTSPluginController(final DNGMCTSPluginModel model, final DNGMCTSPluginView view) { super(model, view); } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent || guiEvent instanceof GoToTimeStepEvent) { this.getModel().clear(); } else if (guiEvent instanceof NodeClickedEvent) { this.getModel().setCurrentlySelectedNode(((NodeClickedEvent) guiEvent).getSearchGraphNode()); this.getView().update(); } } @Override public void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) { if (algorithmEvent.correspondsToEventOfClass(RolloutEvent.class)) { RolloutInfo rolloutInfo = (RolloutInfo) algorithmEvent.getProperty(RolloutInfoAlgorithmEventPropertyComputer.ROLLOUT_SCORE_PROPERTY_NAME); String lastNode = null; for (String n : rolloutInfo.getPath()) { if (lastNode != null) { List<String> successors = this.getModel().getListsOfKnownSuccessors().computeIfAbsent(lastNode, k -> new ArrayList<>()); if (!successors.contains(n)) { successors.add(n); } this.getModel().getParents().put(n, lastNode); } this.getModel().addObservation(n, (double)rolloutInfo.getScore()); lastNode = n; } } else if (algorithmEvent.correspondsToEventOfClass(DNGQSampleEvent.class)) { DNGQSample updateInfo = (DNGQSample) algorithmEvent.getProperty(DNGEventPropertyComputer.UPDATE_PROPERTY_NAME); this.getModel().setNodeStats(updateInfo); } else if (algorithmEvent.correspondsToEventOfClass(DNGBeliefUpdateEvent.class)) { DNGBeliefUpdate updateInfo = (DNGBeliefUpdate) algorithmEvent.getProperty(DNGEventPropertyComputer.UPDATE_PROPERTY_NAME); this.getModel().setNodeStats(updateInfo); } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/dng/DNGMCTSPluginModel.java
package ai.libs.jaicore.search.gui.plugins.mcts.dng; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; /** * * @author fmohr * * @param <BalancedTreeNode> * The node type class. */ public class DNGMCTSPluginModel extends ASimpleMVCPluginModel<DNGMCTSPluginView, DNGMCTSPluginController> { private String currentlySelectedNode = "0"; private final Map<String, String> parents = new HashMap<>(); private final Map<String, List<String>> listsOfKnownSuccessors = new HashMap<>(); private final Map<String, List<Double>> listOfObersvationsPerNode = new HashMap<>(); private final Map<String, Map<String, List<Double>>> observedQValues = new HashMap<>(); private final Map<String, List<DNGBeliefUpdate>> observedUpdates = new HashMap<>(); @Override public void clear() { this.getView().clear(); } public void setCurrentlySelectedNode(final String currentlySelectedNode) { this.currentlySelectedNode = currentlySelectedNode; this.getView().clear(); this.getView().update(); } public String getCurrentlySelectedNode() { return this.currentlySelectedNode; } public void addObservation(final String node, final double score) { this.listOfObersvationsPerNode.computeIfAbsent(node, n -> new ArrayList<>()).add(score); } public void setNodeStats(final DNGQSample update) { if (update == null) { throw new IllegalArgumentException("Cannot process NULL update"); } String node = update.getNode(); if (!this.listsOfKnownSuccessors.containsKey(node)) { throw new IllegalArgumentException("Cannot receive update for an unknown node. Make sure that Rollout events are processed!"); } this.observedQValues.computeIfAbsent(node, n -> new HashMap<>()).computeIfAbsent(update.getSuccessor(), n2 -> new ArrayList<>()).add(update.getScore()); if (node.equals(this.getCurrentlySelectedNode())) { this.getView().update(); } } public void setNodeStats(final DNGBeliefUpdate update) { if (update == null) { throw new IllegalArgumentException("Cannot process NULL update"); } String node = update.getNode(); this.observedUpdates.computeIfAbsent(node, n -> new ArrayList<>()).add(update); if (node.equals(this.getCurrentlySelectedNode())) { this.getView().update(); } } public Map<String, List<Double>> getQValuesOfNode(final String node) { return this.observedQValues.get(node); } public Map<String, List<Double>> getQValuesOfSelectedNode() { return this.observedQValues.get(this.getCurrentlySelectedNode()); } public Map<String, List<String>> getListsOfKnownSuccessors() { return this.listsOfKnownSuccessors; } public List<String> getListOfKnownSuccessorsOfCurrentlySelectedNode() { return this.listsOfKnownSuccessors.get(this.getCurrentlySelectedNode()); } public Map<String, String> getParents() { return this.parents; } public String getParentOfCurrentNode() { return this.parents.get(this.getCurrentlySelectedNode()); } public Map<String, List<DNGBeliefUpdate>> getObservedMuValues() { return this.observedUpdates; } public List<DNGBeliefUpdate> getObservedMuValuesOfCurrentlySelectedNode() { return this.observedUpdates.get(this.getCurrentlySelectedNode()); } public Map<String, List<Double>> getListOfObersvationsPerNode() { return this.listOfObersvationsPerNode; } public DescriptiveStatistics getObservationStatisticsOfNode(final String node) { DescriptiveStatistics stats = new DescriptiveStatistics(); for (double val : this.listOfObersvationsPerNode.get(node)) { stats.addValue(val); } return stats; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/dng/DNGMCTSPluginView.java
package ai.libs.jaicore.search.gui.plugins.mcts.dng; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import ai.libs.jaicore.basic.MathExt; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import ai.libs.jaicore.graphvisualizer.plugin.graphview.NodeClickedEvent; import javafx.application.Platform; import javafx.scene.control.Button; import javafx.scene.layout.FlowPane; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; /** * * @author fmohr * * @param <BalancedTreeNode> * The node class */ public class DNGMCTSPluginView extends ASimpleMVCPluginView<DNGMCTSPluginModel, DNGMCTSPluginController, FlowPane> { private final Button left = new Button("left"); private final Button right = new Button("right"); private final Button parent = new Button("parent"); private WebEngine engine; private static final String HTML_BR = "<br />"; private static final String HTML_H4_OPEN = "<h4>"; private static final String HTML_H4_CLOSE = "</h4>"; public DNGMCTSPluginView(final DNGMCTSPluginModel model) { super(model, new FlowPane()); Platform.runLater(() -> { WebView view = new WebView(); FlowPane node = this.getNode(); node.getChildren().add(this.left); node.getChildren().add(this.right); node.getChildren().add(this.parent); this.left.setOnMouseClicked(e -> { DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(null, this.getLeftChild(model.getCurrentlySelectedNode()))); this.parent.setDisable(false); }); this.right.setOnMouseClicked(e -> { DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(null, this.getRightChild(model.getCurrentlySelectedNode()))); this.parent.setDisable(false); }); this.parent.setOnMouseClicked(e -> { String parentOfCurrent = this.getModel().getParentOfCurrentNode(); DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(null, parentOfCurrent)); if (!this.getModel().getParents().containsKey(parentOfCurrent)) { this.parent.setDisable(true); } }); node.getChildren().add(view); this.engine = view.getEngine(); this.engine.loadContent("Nothing there yet."); }); } private String getLeftChild(final String node) { return this.getModel().getListsOfKnownSuccessors().get(node).get(0); } private String getRightChild(final String node) { return this.getModel().getListsOfKnownSuccessors().get(node).size() > 1 ? this.getModel().getListsOfKnownSuccessors().get(node).get(1) : null; } @Override public void update() { StringBuilder sb = new StringBuilder(); sb.append("<h2>Analysis of node "); String currentNode = this.getModel().getCurrentlySelectedNode(); sb.append(currentNode); sb.append(" (depth "); Map<String, String> parents = this.getModel().getParents(); int depth = 0; while (parents.containsKey(currentNode)) { currentNode = parents.get(currentNode); depth++; } sb.append(depth); sb.append(")</h2>"); sb.append("<h3>Mu-Estimates of Children</h3>"); String currentlySelectedNode = this.getModel().getCurrentlySelectedNode(); String leftChild = this.getLeftChild(currentlySelectedNode); String rightChild = this.getRightChild(currentlySelectedNode); List<DNGBeliefUpdate> muValuesOfLeft = this.getModel().getObservedMuValues().get(leftChild); sb.append(HTML_H4_OPEN + leftChild + " (" + (muValuesOfLeft != null ? muValuesOfLeft.size() : "-1") + ")"); sb.append(HTML_H4_CLOSE); if (muValuesOfLeft != null) { DNGBeliefUpdate latestUpdate = muValuesOfLeft.get(muValuesOfLeft.size() - 1); DescriptiveStatistics statsOfLeft = this.getModel().getObservationStatisticsOfNode(leftChild); sb.append("Mu: " + latestUpdate.getMu() + HTML_BR); sb.append("Mu - sampleMean: " + (latestUpdate.getMu() - statsOfLeft.getMean()) + HTML_BR); sb.append("Alpha: " + latestUpdate.getAlpha() + HTML_BR); sb.append("Beta: " + latestUpdate.getBeta() + HTML_BR); sb.append("Lambda: " + latestUpdate.getLambda()); } if (rightChild != null) { List<DNGBeliefUpdate> muValuesOfRight = this.getModel().getObservedMuValues().get(rightChild); DescriptiveStatistics statsOfRight = this.getModel().getObservationStatisticsOfNode(rightChild); sb.append(HTML_H4_OPEN + rightChild + " (" + (muValuesOfRight != null ? muValuesOfRight.size() : "-1") + ")"); sb.append(HTML_H4_CLOSE); if (muValuesOfRight != null) { DNGBeliefUpdate latestUpdate = muValuesOfRight.get(muValuesOfRight.size() - 1); sb.append("Mu: " + latestUpdate.getMu() + HTML_BR); sb.append("Mu - sampleMean: " + (latestUpdate.getMu() - statsOfRight.getMean()) + HTML_BR); sb.append("Alpha: " + latestUpdate.getAlpha() + HTML_BR); sb.append("Beta: " + latestUpdate.getBeta() + HTML_BR); sb.append("Lambda: " + latestUpdate.getLambda()); } } sb.append("<h3>Q-Values of Children</h3>"); Map<String, List<Double>> qValues = this.getModel().getQValuesOfSelectedNode(); if (qValues != null) { List<Double> scoresOfLeft = qValues.get(leftChild); sb.append(HTML_H4_OPEN); sb.append(leftChild + " (" + scoresOfLeft.size() + ")"); sb.append(HTML_H4_CLOSE); sb.append(scoresOfLeft.subList(Math.max(0, scoresOfLeft.size() - 5), scoresOfLeft.size()).stream().map(v -> MathExt.round(v, 4)).collect(Collectors.toList())); List<Double> scoresOfRight = qValues.get(rightChild); if (scoresOfRight != null) { sb.append(HTML_H4_OPEN); sb.append(rightChild + " (" + scoresOfRight.size() + ")"); sb.append(HTML_H4_CLOSE); sb.append(scoresOfRight.subList(Math.max(0, scoresOfRight.size() - 5), scoresOfRight.size()).stream().map(v -> MathExt.round(v, 4)).collect(Collectors.toList())); } } Platform.runLater(() -> this.engine.loadContent(sb.toString())); } @Override public void clear() { /* do nothing */ } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/mcts/dng/DNGQSample.java
package ai.libs.jaicore.search.gui.plugins.mcts.dng; public class DNGQSample { private final String node; private final String action; private final double score; public DNGQSample(final String node, final String action, final double score) { super(); this.node = node; this.action = action; this.score = score; } public String getNode() { return this.node; } public String getSuccessor() { return this.action; } public double getScore() { return this.score; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rolloutboxplots/SearchRolloutBoxplotPlugin.java
package ai.libs.jaicore.search.gui.plugins.rolloutboxplots; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; import ai.libs.jaicore.search.gui.plugins.rollouthistograms.RolloutInfoAlgorithmEventPropertyComputer; public class SearchRolloutBoxplotPlugin extends ASimpleMVCPlugin<SearchRolloutBoxplotPluginModel, SearchRolloutBoxplotPluginView, SearchRolloutBoxplotPluginController> { public SearchRolloutBoxplotPlugin() { this("boxplot"); } public SearchRolloutBoxplotPlugin(final String title) { super(title); } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(new RolloutInfoAlgorithmEventPropertyComputer()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rolloutboxplots/SearchRolloutBoxplotPluginController.java
package ai.libs.jaicore.search.gui.plugins.rolloutboxplots; import java.util.ArrayList; import java.util.List; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.graphview.NodeClickedEvent; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RolloutEvent; import ai.libs.jaicore.search.gui.plugins.rollouthistograms.RolloutInfo; import ai.libs.jaicore.search.gui.plugins.rollouthistograms.RolloutInfoAlgorithmEventPropertyComputer; public class SearchRolloutBoxplotPluginController extends ASimpleMVCPluginController<SearchRolloutBoxplotPluginModel, SearchRolloutBoxplotPluginView> { public SearchRolloutBoxplotPluginController(final SearchRolloutBoxplotPluginModel model, final SearchRolloutBoxplotPluginView view) { super(model, view); } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent || guiEvent instanceof GoToTimeStepEvent) { this.getModel().clear(); } else if (guiEvent instanceof NodeClickedEvent) { synchronized (this.getView()) { this.getModel().setCurrentlySelectedNode(((NodeClickedEvent) guiEvent).getSearchGraphNode()); this.getView().clear(); this.getView().update(); } } } @Override public void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) { if (algorithmEvent.correspondsToEventOfClass(RolloutEvent.class)) { RolloutInfo rolloutInfo = (RolloutInfo) algorithmEvent.getProperty(RolloutInfoAlgorithmEventPropertyComputer.ROLLOUT_SCORE_PROPERTY_NAME); String lastNode = null; for (String n : rolloutInfo.getPath()) { if (lastNode != null) { List<String> successors = this.getModel().getListsOfKnownSuccessors().computeIfAbsent(lastNode, k -> new ArrayList<>()); if (!successors.contains(n)) { successors.add(n); } this.getModel().getParents().put(n, lastNode); } this.getModel().addEntry(n, (double) rolloutInfo.getScore()); lastNode = n; } } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rolloutboxplots/SearchRolloutBoxplotPluginModel.java
package ai.libs.jaicore.search.gui.plugins.rolloutboxplots; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; /** * * @author fmohr * * @param <BalancedTreeNode> * The node type class. */ public class SearchRolloutBoxplotPluginModel extends ASimpleMVCPluginModel<SearchRolloutBoxplotPluginView, SearchRolloutBoxplotPluginController> { private String currentlySelectedNode = "0"; private final Map<String, String> parents = new HashMap<>(); private final Map<String, List<String>> listsOfKnownSuccessors = new HashMap<>(); private final Map<String, DescriptiveStatistics> observedPerformances = new HashMap<>(); public final void addEntry(final String node, final double score) { this.observedPerformances.computeIfAbsent(node, n -> new DescriptiveStatistics()).addValue(score); this.getView().update(); } public Map<String, DescriptiveStatistics> getObservedPerformances() { return this.observedPerformances; } public DescriptiveStatistics getObservedPerformancesUnderSelectedNode() { return this.observedPerformances.get(this.currentlySelectedNode); } @Override public void clear() { this.observedPerformances.clear(); this.getView().clear(); } public void setCurrentlySelectedNode(final String currentlySelectedNode) { this.currentlySelectedNode = currentlySelectedNode; this.getView().clear(); this.getView().update(); } public String getCurrentlySelectedNode() { return this.currentlySelectedNode; } public Map<String, List<String>> getListsOfKnownSuccessors() { return this.listsOfKnownSuccessors; } public List<String> getListOfKnownSuccessorsOfCurrentlySelectedNode() { return this.listsOfKnownSuccessors.get(this.getCurrentlySelectedNode()); } public Map<String, String> getParents() { return this.parents; } public String getParentOfCurrentNode() { return this.parents.get(this.getCurrentlySelectedNode()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rolloutboxplots/SearchRolloutBoxplotPluginView.java
package ai.libs.jaicore.search.gui.plugins.rolloutboxplots; import java.util.List; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import ai.libs.jaicore.graphvisualizer.events.gui.DefaultGUIEventBus; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import ai.libs.jaicore.graphvisualizer.plugin.graphview.NodeClickedEvent; import javafx.application.Platform; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; /** * * @author fmohr * * @param <BalancedTreeNode> * The node class */ public class SearchRolloutBoxplotPluginView extends ASimpleMVCPluginView<SearchRolloutBoxplotPluginModel, SearchRolloutBoxplotPluginController, StackPane> { private final Button left = new Button("left"); private final Button right = new Button("right"); private final Button parent = new Button("parent"); private WebEngine engine; public SearchRolloutBoxplotPluginView(final SearchRolloutBoxplotPluginModel model) { super(model, new StackPane()); Platform.runLater(() -> { WebView view = new WebView(); StackPane node = this.getNode(); node.getChildren().add(view); this.engine = view.getEngine(); this.engine.loadContent("Nothing there yet."); node.getChildren().add(this.left); node.getChildren().add(this.right); node.getChildren().add(this.parent); this.left.setOnMouseClicked(e -> { DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(null, this.getLeftChild(model.getCurrentlySelectedNode()))); this.parent.setDisable(false); }); this.right.setOnMouseClicked(e -> { DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(null, this.getRightChild(model.getCurrentlySelectedNode()))); this.parent.setDisable(false); }); this.parent.setOnMouseClicked(e -> { String parentOfCurrent = this.getModel().getParentOfCurrentNode(); DefaultGUIEventBus.getInstance().postEvent(new NodeClickedEvent(null, parentOfCurrent)); if (!this.getModel().getParents().containsKey(parentOfCurrent)) { this.parent.setDisable(true); } }); }); } private String getLeftChild(final String node) { if (!this.getModel().getListsOfKnownSuccessors().containsKey(node)) { throw new IllegalArgumentException(node + " has no children in the known model!"); } return this.getModel().getListsOfKnownSuccessors().get(node).get(0); } private String getRightChild(final String node) { return this.getModel().getListsOfKnownSuccessors().get(node).size() > 1 ? this.getModel().getListsOfKnownSuccessors().get(node).get(1) : null; } @Override public synchronized void update() { StringBuilder sb = new StringBuilder(); DescriptiveStatistics stats = this.getModel().getObservedPerformancesUnderSelectedNode(); if (stats != null) { sb.append(stats.toString().replace("\n", "<br />")); List<String> successors = this.getModel().getListOfKnownSuccessorsOfCurrentlySelectedNode(); if (successors != null) { sb.append("<table><tr>"); for (String successor : successors) { DescriptiveStatistics statsOfSuccessor = this.getModel().getObservedPerformances().get(successor); /* update table */ sb.append("<td>"); sb.append(statsOfSuccessor.toString().replace("\n", "<br />")); sb.append("</td>"); } sb.append("</tr></table>"); } Platform.runLater(() -> this.engine.loadContent(sb.toString())); } } @Override public synchronized void clear() { /* nothing to do */ } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rollouthistograms/RolloutInfo.java
package ai.libs.jaicore.search.gui.plugins.rollouthistograms; import java.util.List; public class RolloutInfo { private List<String> path; private Object score; @SuppressWarnings("unused") private RolloutInfo() { // for serialization purposes } public RolloutInfo(List<String> path, Object score) { this.path = path; this.score = score; } public List<String> getPath() { return path; } public Object getScore() { return score; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((path == null) ? 0 : path.hashCode()); result = prime * result + ((score == null) ? 0 : score.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } RolloutInfo other = (RolloutInfo) obj; if (path == null) { if (other.path != null) { return false; } } else if (!path.equals(other.path)) { return false; } if (score == null) { if (other.score != null) { return false; } } else if (!score.equals(other.score)) { return false; } return true; } @Override public String toString() { return "RolloutInfo [path=" + path + ", score=" + score + "]"; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rollouthistograms/RolloutInfoAlgorithmEventPropertyComputer.java
package ai.libs.jaicore.search.gui.plugins.rollouthistograms; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.api4.java.algorithm.events.IAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.events.recorder.property.PropertyComputationFailedException; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoAlgorithmEventPropertyComputer; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RolloutEvent; public class RolloutInfoAlgorithmEventPropertyComputer implements AlgorithmEventPropertyComputer { public static final String ROLLOUT_SCORE_PROPERTY_NAME = "rollout_info"; private NodeInfoAlgorithmEventPropertyComputer nodeInfoAlgorithmEventPropertyComputer; public RolloutInfoAlgorithmEventPropertyComputer() { this.nodeInfoAlgorithmEventPropertyComputer = new NodeInfoAlgorithmEventPropertyComputer(); } @Override public Object computeAlgorithmEventProperty(final IAlgorithmEvent algorithmEvent) throws PropertyComputationFailedException { if (algorithmEvent instanceof RolloutEvent) { RolloutEvent<?, ?> rolloutEvent = (RolloutEvent<?, ?>) algorithmEvent; List<?> rolloutPath = rolloutEvent.getPath(); return new RolloutInfo(this.convertNodeToNodeIds(rolloutPath), rolloutEvent.getScore()); } return null; } private List<String> convertNodeToNodeIds(final List<?> pathNodes) throws PropertyComputationFailedException { List<String> path = pathNodes.stream().map(n -> (Object) n).map(n -> this.nodeInfoAlgorithmEventPropertyComputer.getIdOfNodeIfExistent(n)).collect(Collectors.toList()); if (path.contains(null)) { throw new PropertyComputationFailedException("Cannot compute rollout score due to null nodes in path: " + path); } return path; } @Override public String getPropertyName() { return ROLLOUT_SCORE_PROPERTY_NAME; } @Override public List<AlgorithmEventPropertyComputer> getRequiredPropertyComputers() { return Arrays.asList(this.nodeInfoAlgorithmEventPropertyComputer); } @Override public void overwriteRequiredPropertyComputer(final AlgorithmEventPropertyComputer computer) { this.nodeInfoAlgorithmEventPropertyComputer = (NodeInfoAlgorithmEventPropertyComputer)computer; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rollouthistograms/SearchRolloutHistogramPlugin.java
package ai.libs.jaicore.search.gui.plugins.rollouthistograms; import java.util.Arrays; import java.util.Collection; import ai.libs.jaicore.graphvisualizer.events.recorder.property.AlgorithmEventPropertyComputer; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPlugin; public class SearchRolloutHistogramPlugin extends ASimpleMVCPlugin<SearchRolloutHistogramPluginModel, SearchRolloutHistogramPluginView, SearchRolloutHistogramPluginController> { public SearchRolloutHistogramPlugin() { this("Histogram"); } public SearchRolloutHistogramPlugin(final String title) { super(title); } @Override public Collection<AlgorithmEventPropertyComputer> getPropertyComputers() { return Arrays.asList(new RolloutInfoAlgorithmEventPropertyComputer()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rollouthistograms/SearchRolloutHistogramPluginController.java
package ai.libs.jaicore.search.gui.plugins.rollouthistograms; import org.api4.java.algorithm.events.serializable.IPropertyProcessedAlgorithmEvent; import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginController; import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent; import ai.libs.jaicore.graphvisualizer.plugin.graphview.NodeClickedEvent; import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RolloutEvent; public class SearchRolloutHistogramPluginController extends ASimpleMVCPluginController<SearchRolloutHistogramPluginModel, SearchRolloutHistogramPluginView> { public SearchRolloutHistogramPluginController(final SearchRolloutHistogramPluginModel model, final SearchRolloutHistogramPluginView view) { super(model, view); } @Override public void handleGUIEvent(final GUIEvent guiEvent) { if (guiEvent instanceof ResetEvent || guiEvent instanceof GoToTimeStepEvent) { this.getModel().clear(); } else if (guiEvent instanceof NodeClickedEvent) { this.getModel().setCurrentlySelectedNode(((NodeClickedEvent) guiEvent).getSearchGraphNode()); this.getView().update(); } } @Override public void handleAlgorithmEventInternally(final IPropertyProcessedAlgorithmEvent algorithmEvent) { if (algorithmEvent.correspondsToEventOfClass(RolloutEvent.class)) { RolloutInfo rolloutInfo = (RolloutInfo) algorithmEvent.getProperty(RolloutInfoAlgorithmEventPropertyComputer.ROLLOUT_SCORE_PROPERTY_NAME); rolloutInfo.getPath().forEach(n -> this.getModel().addEntry(n, (double) rolloutInfo.getScore())); } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rollouthistograms/SearchRolloutHistogramPluginModel.java
package ai.libs.jaicore.search.gui.plugins.rollouthistograms; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginModel; /** * * @author fmohr * * @param <BalancedTreeNode> * The node type class. */ public class SearchRolloutHistogramPluginModel extends ASimpleMVCPluginModel<SearchRolloutHistogramPluginView, SearchRolloutHistogramPluginController> { private String currentlySelectedNode; private final Map<String, List<Double>> observedPerformances = new HashMap<>(); public final void addEntry(String node, double score) { if (!observedPerformances.containsKey(node)) { observedPerformances.put(node, Collections.synchronizedList(new LinkedList<>())); } observedPerformances.get(node).add(score); getView().update(); } public Map<String, List<Double>> getObservedPerformances() { return observedPerformances; } public List<Double> getObservedPerformancesUnderSelectedNode() { return observedPerformances.get(currentlySelectedNode); } @Override public void clear() { observedPerformances.clear(); getView().clear(); } public void setCurrentlySelectedNode(String currentlySelectedNode) { this.currentlySelectedNode = currentlySelectedNode; getView().clear(); getView().update(); } public String getCurrentlySelectedNode() { return currentlySelectedNode; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/gui/plugins/rollouthistograms/SearchRolloutHistogramPluginView.java
package ai.libs.jaicore.search.gui.plugins.rollouthistograms; import ai.libs.jaicore.graphvisualizer.events.gui.Histogram; import ai.libs.jaicore.graphvisualizer.plugin.ASimpleMVCPluginView; import javafx.application.Platform; import javafx.scene.layout.StackPane; /** * * @author fmohr * * @param <BalancedTreeNode> * The node class */ public class SearchRolloutHistogramPluginView extends ASimpleMVCPluginView<SearchRolloutHistogramPluginModel, SearchRolloutHistogramPluginController, StackPane> { private final Histogram histogram; private final int n = 100; public SearchRolloutHistogramPluginView(final SearchRolloutHistogramPluginModel model) { super(model, new StackPane()); this.histogram = new Histogram(this.n); this.histogram.setTitle("Search Rollout Performances"); Platform.runLater(() -> { this.getNode().getChildren().add(this.histogram); }); } @Override public void update() { if (this.getModel().getCurrentlySelectedNode() != null && this.getModel().getObservedPerformancesUnderSelectedNode() != null) { Platform.runLater(() -> { this.histogram.update(this.getModel().getObservedPerformancesUnderSelectedNode()); }); } } @Override public void clear() { Platform.runLater(this.histogram::clear); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/landscapeanalysis/GenericLandscapeAnalyzer.java
package ai.libs.jaicore.search.landscapeanalysis; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException; import org.api4.java.datastructure.graph.ILabeledPath; 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.model.other.SearchGraphPath; public class GenericLandscapeAnalyzer<N, A> { private static Logger logger = LoggerFactory.getLogger("testers"); private final IPathSearchWithPathEvaluationsInput<N, A, Double> problem; private final N root; private final ISuccessorGenerator<N, A> successorGenerator; private final IPathGoalTester<N, A> goalTester; private double min = Double.MAX_VALUE; public GenericLandscapeAnalyzer(final IPathSearchWithPathEvaluationsInput<N, A, Double> problem) { super(); this.problem = problem; this.root = problem.getGraphGenerator().getRootGenerator().getRoots().iterator().next(); this.successorGenerator = problem.getGraphGenerator().getSuccessorGenerator(); this.goalTester = problem.getGoalTester(); } public double[] getValues(final Number probeSize) throws InterruptedException, PathEvaluationException { return this.getValues(probeSize, LandscapeAnalysisCompletionTechnique.RANDOM); } public double[] getValues(final Number probeSize, final LandscapeAnalysisCompletionTechnique technique) throws InterruptedException, PathEvaluationException { return this.getValues(new SearchGraphPath<>(this.root), probeSize, technique); } public double[] getValues(final List<Integer> decisions, final int probeSize, final LandscapeAnalysisCompletionTechnique technique) throws InterruptedException, PathEvaluationException { List<N> nodes = new ArrayList<>(decisions.size() + 1); List<A> arcs = new ArrayList<>(decisions.size()); N current = this.root; nodes.add(current); for (int child : decisions) { INewNodeDescription<N, A> ned = this.successorGenerator.generateSuccessors(current).get(child); current = ned.getTo(); nodes.add(current); arcs.add(ned.getArcLabel()); } ILabeledPath<N,A> path = new SearchGraphPath<>(nodes, arcs); return this.getValues(path, probeSize, technique); } public double[] getValues(final ILabeledPath<N, A> path, final Number probeSize, final LandscapeAnalysisCompletionTechnique technique) throws InterruptedException, PathEvaluationException { List<Double> values = this.probeUnderPath(path, probeSize, technique); int n = values.size(); double[] valuesAsArray = new double[n]; for (int i = 0; i < n; i++) { valuesAsArray[i] = values.get(i); } return valuesAsArray; } private List<Double> probeUnderPath(final ILabeledPath<N, A> path, final Number limit, final LandscapeAnalysisCompletionTechnique technique) throws InterruptedException, PathEvaluationException { N node = path.getHead(); int cLimit = limit.intValue(); List<Double> scoresUnderChildren = new ArrayList<>(cLimit); if (this.goalTester.isGoal(path)) { double score = this.problem.getPathEvaluator().evaluate(path); if (score < this.min) { this.min = score; } scoresUnderChildren.add(score); return scoresUnderChildren; } List<INewNodeDescription<N, A>> successors = this.successorGenerator.generateSuccessors(node); int n = successors.size(); /* if we cannot delve into all successors, order them by the defined technique */ if (n > cLimit) { switch (technique) { case FIRST: /* do nothing */ break; case LAST: Collections.reverse(successors); break; case RANDOM: Collections.shuffle(successors); break; } } int limitPerChild = (int)Math.floor(cLimit * 1.0 / n); int numberOfChildrenWithExtra = cLimit % n; for (int child = 0; child < n; child++) { int limitForThisChild = limitPerChild + (child < numberOfChildrenWithExtra ? 1 : 0); if (limitForThisChild <= 0) { return scoresUnderChildren; } ILabeledPath<N, A> newPath = new SearchGraphPath<>(path, successors.get(child).getTo(), successors.get(child).getArcLabel()); scoresUnderChildren.addAll(this.probeUnderPath(newPath, limitForThisChild, technique)); } return scoresUnderChildren; } public List<List<double[]>> getIterativeProbeValuesAlongRandomPath(final Number probSizePerLevelAndChild) throws PathEvaluationException, InterruptedException { ILabeledPath<N, A> currentPath = new SearchGraphPath<>(this.root); while (!this.goalTester.isGoal(currentPath)) { List<INewNodeDescription<N, A>> nedList = this.problem.getGraphGenerator().getSuccessorGenerator().generateSuccessors(currentPath.getHead()); Collections.shuffle(nedList); currentPath = new SearchGraphPath<>(currentPath, nedList.get(0).getTo(), nedList.get(0).getArcLabel()); } logger.info("Drew path {}: {}" , currentPath.getArcs(), currentPath.getHead()); return this.getIterativeProbeValues(currentPath, probSizePerLevelAndChild); } public List<List<double[]>> getIterativeProbeValues(final ILabeledPath<N, A> path, final Number probSizePerLevelAndChild) throws PathEvaluationException, InterruptedException { List<List<double[]>> iterativeProbes = new ArrayList<>(); for (int depth = 0; depth < path.getNumberOfNodes() - 1; depth++) { logger.info("Probing on level {}", depth); /* compute sub-path of the relevant depth */ ILabeledPath<N, A> subPath = path; while (subPath.getNumberOfNodes() > depth + 1) { subPath = subPath.getPathToParentOfHead(); } /* compute successors in that depth */ List<INewNodeDescription<N, A>> nedList = this.problem.getGraphGenerator().getSuccessorGenerator().generateSuccessors(subPath.getHead()); /* sample under each of the nodes */ List<double[]> probesOnLevel = new ArrayList<>(nedList.size()); for (INewNodeDescription<N, A> ned : nedList) { ILabeledPath<N, A> extendedPath = new SearchGraphPath<>(subPath, ned.getTo(), ned.getArcLabel()); double[] landscape = this.getValues(extendedPath, probSizePerLevelAndChild, LandscapeAnalysisCompletionTechnique.RANDOM); probesOnLevel.add(landscape); } iterativeProbes.add(probesOnLevel); } return iterativeProbes; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/landscapeanalysis/LandscapeAnalysisCompletionTechnique.java
package ai.libs.jaicore.search.landscapeanalysis; public enum LandscapeAnalysisCompletionTechnique { FIRST, LAST, RANDOM }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/ILazyRandomizableSuccessorGenerator.java
package ai.libs.jaicore.search.model; import java.util.Iterator; import java.util.Random; import org.api4.java.datastructure.graph.implicit.ILazySuccessorGenerator; import org.api4.java.datastructure.graph.implicit.INewNodeDescription; /** * This allows to ensure that the received iterator is randomized in the desired way. * * @author Felix Mohr * * @param <N> * @param <A> */ public interface ILazyRandomizableSuccessorGenerator<N, A> extends ILazySuccessorGenerator<N, A> { public Iterator<INewNodeDescription<N, A>> getIterativeGenerator(N node, Random random); }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/NodeExpansionDescription.java
package ai.libs.jaicore.search.model; import org.api4.java.datastructure.graph.implicit.INewNodeDescription; public class NodeExpansionDescription<S, A> implements INewNodeDescription<S, A> { private final S to; private final A action; public NodeExpansionDescription(final S to) { this(to, null); } public NodeExpansionDescription(final S to, final A action) { super(); this.to = to; this.action = action; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.action == null) ? 0 : this.action.hashCode()); result = prime * result + ((this.to == null) ? 0 : this.to.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; } NodeExpansionDescription other = (NodeExpansionDescription) obj; if (this.action == null) { if (other.action != null) { return false; } } else if (!this.action.equals(other.action)) { return false; } if (this.to == null) { if (other.to != null) { return false; } } else if (!this.to.equals(other.to)) { return false; } return true; } @Override public S getTo() { return this.to; } public A getAction() { return this.action; } @Override public S getFrom() { throw new UnsupportedOperationException(); } @Override public A getArcLabel() { return this.getAction(); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/other/AgnosticPathEvaluator.java
package ai.libs.jaicore.search.model.other; import org.api4.java.common.attributedobjects.IObjectEvaluator; import org.api4.java.datastructure.graph.ILabeledPath; public class AgnosticPathEvaluator<N, A> implements IObjectEvaluator<ILabeledPath<N, A>, Double> { @Override public Double evaluate(final ILabeledPath<N, A> solutionPath) { return 0.0; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/other/EvaluatedSearchGraphPath.java
package ai.libs.jaicore.search.model.other; import java.util.List; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IEvaluatedPath; import org.api4.java.datastructure.graph.ILabeledPath; public class EvaluatedSearchGraphPath<N, A, V extends Comparable<V>> extends SearchGraphPath<N, A> implements IEvaluatedPath<N, A, V> { private final V score; public EvaluatedSearchGraphPath(final ILabeledPath<N, A> path, final V score) { super(path); this.score = score; } public EvaluatedSearchGraphPath(final List<N> nodes, final List<A> edges, final V score) { super(nodes, edges); this.score = score; } @Override public V getScore() { return this.score; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.score == null) ? 0 : this.score.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } EvaluatedSearchGraphPath other = (EvaluatedSearchGraphPath) obj; if (this.score == null) { if (other.score != null) { return false; } } else if (!this.score.equals(other.score)) { return false; } return true; } @Override public String toString() { return "EvaluatedSearchGraphPath [score=" + this.score + "]"; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/other/SearchGraphPath.java
package ai.libs.jaicore.search.model.other; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.graph.ReadOnlyPathAccessor; public class SearchGraphPath<N, A> implements ILabeledPath<N, A> { private final List<N> nodes; private final List<A> edges; private final Map<String, Object> annotations; public SearchGraphPath(final ILabeledPath<N, A> path) { this (new ArrayList<>(path.getNodes()), new ArrayList<>(path.getArcs()), (path instanceof SearchGraphPath) ? new HashMap<>(((SearchGraphPath) path).annotations) : new HashMap<>()); } public SearchGraphPath(final ILabeledPath<N, A> pathA, final ILabeledPath<N, A> pathB, final A link) { this.nodes = new ArrayList<>(); this.nodes.addAll(pathA.getNodes()); this.nodes.addAll(pathB.getNodes()); this.edges = new ArrayList<>(); this.edges.addAll(pathA.getArcs()); this.edges.add(link); this.edges.addAll(pathB.getArcs()); this.annotations = new HashMap<>(); } public SearchGraphPath(final ILabeledPath<N, A> pathA, final N attachedNode, final A link) { this.nodes = new ArrayList<>(); this.nodes.addAll(pathA.getNodes()); this.nodes.add(attachedNode); this.edges = new ArrayList<>(); this.edges.addAll(pathA.getArcs()); this.edges.add(link); this.annotations = new HashMap<>(); } public SearchGraphPath(final N node) { this(new ArrayList<>(Collections.singletonList(node)), new ArrayList<>(), new HashMap<>()); } public SearchGraphPath(final List<N> nodes, final List<A> edges) { this(nodes, edges, new HashMap<>()); } public SearchGraphPath(final List<N> nodes, final List<A> edges, final Map<String, Object> annotations) { super(); if (nodes.isEmpty()) { throw new IllegalArgumentException("List of nodes of a path must not be empty!"); } if (edges == null || nodes.size() != edges.size() + 1) { throw new IllegalArgumentException("Number of edges must be exactly one less than the one of nodes! Number of nodes: " + nodes.size() + ". Edges: " + (edges != null ? edges.size() : null)); } this.nodes = nodes; this.edges = edges; this.annotations = annotations; } @Override public List<N> getNodes() { return Collections.unmodifiableList(this.nodes); } @Override public List<A> getArcs() { return this.edges != null ? Collections.unmodifiableList(this.edges) : null; } public Map<String, Object> getAnnotations() { return this.annotations; } public void setAnnotation(final String key, final Object value) { this.annotations.put(key, value); } @Override public int hashCode() { return new HashCodeBuilder().append(this.nodes).append(this.edges).append(this.annotations).toHashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } SearchGraphPath other = (SearchGraphPath) obj; return new EqualsBuilder().append(this.nodes, other.nodes).append(this.edges, other.edges).isEquals(); } @Override public String toString() { return "SearchGraphPath [nodes=" + this.nodes + ", edges=" + this.edges + ", annotations=" + this.annotations + "]"; } @Override public N getRoot() { return this.nodes.get(0); } @Override public N getHead() { return this.nodes.get(this.nodes.size() - 1); } @Override public SearchGraphPath<N, A> getPathToParentOfHead() { if (this.nodes.isEmpty()) { throw new UnsupportedOperationException("This is an empty path!"); } if (this.isPoint()) { throw new UnsupportedOperationException("Root has no head!"); } return new SearchGraphPath<>(this.nodes.subList(0, this.nodes.size() - 1), this.edges.subList(0, this.edges.size() - 1)); } @Override public boolean isPoint() { return this.nodes.size() == 1; } @Override public int getNumberOfNodes() { return this.nodes.size(); } @Override public ILabeledPath<N, A> getPathFromChildOfRoot() { return new SearchGraphPath<>(this.nodes.subList(1, this.nodes.size()), this.edges != null ? this.edges.subList(1, this.edges.size()) : null); } @Override public A getInArc(final N node) { return this.edges.get(this.nodes.indexOf(node) - 1); } @Override public A getOutArc(final N node) { return this.edges.get(this.nodes.indexOf(node)); } @Override public boolean containsNode(final N node) { return this.nodes.contains(node); } @Override public ILabeledPath<N, A> getUnmodifiableAccessor() { return new ReadOnlyPathAccessor<>(this); } @Override public N getParentOfHead() { return this.nodes.get(this.nodes.size() - 2); } @Override public void extend(final N newHead, final A arcToNewHead) { this.nodes.add(newHead); this.edges.add(arcToNewHead); } @Override public void cutHead() { if (this.isPoint()) { throw new NoSuchElementException("The path consists only of one point, which cannot be removed."); } this.nodes.remove(this.nodes.size() - 1); this.edges.remove(this.edges.size() - 1); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/travesaltree/AbstractNode.java
package ai.libs.jaicore.search.model.travesaltree; /** * abstract class for nodeobjects which only contains a simple equals method and the id * @author jkoepe * */ public abstract class AbstractNode { //the id of the node protected int id; public AbstractNode() { this.id = 0; } public AbstractNode(int id) { this.id = id; } /** * Method to set the id, if it was not set in the construction * @param id * The id the node should get. */ public void setId(int id) { if(this.id == 0) { this.id = id; } } /** * @return the id */ public int getId() { return id; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/travesaltree/BackPointerPath.java
package ai.libs.jaicore.search.model.travesaltree; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IEvaluatedPath; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.graph.ReadOnlyPathAccessor; import ai.libs.jaicore.logging.ToJSONStringUtil; import ai.libs.jaicore.search.algorithms.standard.bestfirst.ENodeAnnotation; public class BackPointerPath<N, A, V extends Comparable<V>> implements IEvaluatedPath<N, A, V> { private final N nodeLabel; private final A edgeLabelToParent; private boolean goal; protected BackPointerPath<N, A, V> parent; private final Map<String, Object> annotations = new HashMap<>(); // for nodes effectively examined public BackPointerPath(final N point) { this(null, point, null); } public BackPointerPath(final BackPointerPath<N, A, V> parent, final N point, final A edgeLabelToParent) { super(); this.parent = parent; this.nodeLabel = point; this.edgeLabelToParent = edgeLabelToParent; } public BackPointerPath<N, A, V> getParent() { return this.parent; } @Override public N getHead() { return this.nodeLabel; } @SuppressWarnings("unchecked") @Override public V getScore() { return (V) this.annotations.get(ENodeAnnotation.F_SCORE.toString()); } public void setParent(final BackPointerPath<N, A, V> newParent) { this.parent = newParent; } public void setScore(final V internalLabel) { this.setAnnotation(ENodeAnnotation.F_SCORE.toString(), internalLabel); } public void setAnnotation(final String annotationName, final Object annotationValue) { this.annotations.put(annotationName, annotationValue); } public Object getAnnotation(final String annotationName) { return this.annotations.get(annotationName); } public Map<String, Object> getAnnotations() { return this.annotations; } public boolean isGoal() { return this.goal; } public void setGoal(final boolean goal) { this.goal = goal; } public List<BackPointerPath<N, A, V>> path() { List<BackPointerPath<N, A, V>> path = new ArrayList<>(); BackPointerPath<N, A, V> current = this; while (current != null) { path.add(0, current); current = current.parent; } return path; } @Override public List<N> getNodes() { List<N> path = new ArrayList<>(); BackPointerPath<N, A, V> current = this; while (current != null) { path.add(0, current.nodeLabel); current = current.parent; } return path; } public String getString() { String s = "Node [ref="; s += this.toString(); s += ", externalLabel="; s += this.nodeLabel; s += ", goal"; s += this.goal; s += ", parentRef="; if (this.parent != null) { s += this.parent.toString(); } else { s += "null"; } s += ", annotations="; s += this.annotations; s += "]"; return s; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("externalLabel", this.nodeLabel); fields.put("goal", this.goal); fields.put(ENodeAnnotation.F_SCORE.name(), this.getScore()); fields.put(ENodeAnnotation.F_ERROR.name(), this.annotations.get(ENodeAnnotation.F_ERROR.name())); return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields); } @Override public List<A> getArcs() { if (this.parent == null) { return new LinkedList<>(); } List<A> pathToHere = this.parent.getArcs(); pathToHere.add(this.edgeLabelToParent); return pathToHere; } public A getEdgeLabelToParent() { return this.edgeLabelToParent; } @Override public N getRoot() { return this.parent == null ? this.nodeLabel : this.parent.getRoot(); } @Override public BackPointerPath<N, A, V> getPathToParentOfHead() { return this.parent; } @Override public int getNumberOfNodes() { return this.parent == null ? 1 : this.parent.getNumberOfNodes() + 1; } @Override public boolean isPoint() { return this.parent == null; } @Override public BackPointerPath<N, A, V> getPathFromChildOfRoot() { if (this.parent.getParent() == null) { return new BackPointerPath<>(this.nodeLabel); } return new BackPointerPath<>(this.parent.getPathFromChildOfRoot(), this.nodeLabel, this.edgeLabelToParent); } @Override public A getInArc(final N node) { if (this.nodeLabel.equals(node)) { return this.edgeLabelToParent; } return this.parent.getInArc(node); } @Override public A getOutArc(final N node) { if (this.parent == null) { throw new NoSuchElementException("No such node found."); } if (this.parent.nodeLabel.equals(node)) { return this.edgeLabelToParent; } return this.parent.getOutArc(node); } @Override public boolean containsNode(final N node) { return this.nodeLabel.equals(node) || (this.parent != null && this.parent.containsNode(node)); } @Override public ILabeledPath<N, A> getUnmodifiableAccessor() { return new ReadOnlyPathAccessor<>(this); } @Override public N getParentOfHead() { return this.parent.getHead(); } @Override public void extend(final N newHead, final A arcToNewHead) { throw new UnsupportedOperationException("To assure consistency, back-pointer paths do not support modifications."); } @Override public void cutHead() { throw new UnsupportedOperationException("To assure consistency, back-pointer paths do not support modifications."); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/travesaltree/DefaultNodeComparator.java
package ai.libs.jaicore.search.model.travesaltree; import java.util.Comparator; public class DefaultNodeComparator<N, A, V extends Comparable<V>> implements Comparator<BackPointerPath<N, A, V>> { @Override public int compare(final BackPointerPath<N, A, V> arg0, final BackPointerPath<N, A, V> arg1) { return arg0.getScore().compareTo(arg1.getScore()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/travesaltree/Edge.java
package ai.libs.jaicore.search.model.travesaltree; public class Edge<T, A, V extends Comparable<V>> { private final BackPointerPath<T, A, V> from, to; public Edge(final BackPointerPath<T, A, V> from, final BackPointerPath<T, A, V> to) { super(); this.from = from; this.to = to; } public BackPointerPath<T, A, V> getFrom() { return this.from; } public BackPointerPath<T, A, V> getTo() { return this.to; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.from == null) ? 0 : this.from.hashCode()); result = prime * result + ((this.to == null) ? 0 : this.to.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } @SuppressWarnings("unchecked") Edge<T, A, V> other = (Edge<T, A, V>) obj; if (this.from == null) { if (other.from != null) { return false; } } else if (!this.from.equals(other.from)) { return false; } if (this.to == null) { if (other.to != null) { return false; } } else if (!this.to.equals(other.to)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/travesaltree/GraphEventBus.java
package ai.libs.jaicore.search.model.travesaltree; import com.google.common.eventbus.EventBus; public class GraphEventBus<T> extends EventBus { }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/travesaltree/JaicoreNodeInfoGenerator.java
package ai.libs.jaicore.search.model.travesaltree; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.checkerframework.checker.units.qual.A; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoGenerator; import ai.libs.jaicore.search.algorithms.standard.bestfirst.ENodeAnnotation; public class JaicoreNodeInfoGenerator<N, V extends Comparable<V>> implements NodeInfoGenerator<BackPointerPath<N, A, V>> { private final NodeInfoGenerator<List<N>> nodeInfoGeneratorForPoints; public JaicoreNodeInfoGenerator() { this(null); } public JaicoreNodeInfoGenerator(final NodeInfoGenerator<List<N>> nodeInfoGeneratorForPoints) { super(); this.nodeInfoGeneratorForPoints = nodeInfoGeneratorForPoints; } @Override public String generateInfoForNode(final BackPointerPath<N, A, V> node) { StringBuilder sb = new StringBuilder(); Map<String, Object> annotations = node.getAnnotations(); sb.append("<h2>Annotation</h2><table><tr><th>Key</th><th>Value</th></tr>"); for (Entry<String, Object> annotationEntry : annotations.entrySet()) { if (!annotationEntry.getKey().equals(ENodeAnnotation.F_ERROR.toString())) { sb.append("<tr><td>" + annotationEntry.getKey() + "</td><td>" + annotationEntry.getValue() + "</td></tr>"); } } sb.append("</table>"); sb.append("<h2>Node Score</h2>"); sb.append(annotations.get(ENodeAnnotation.F_SCORE.toString()) + ""); if (annotations.containsKey("fRPSamples")) { sb.append(" (based on " + annotations.get("fRPSamples") + " samples)"); } if (annotations.containsKey(ENodeAnnotation.F_ERROR.toString()) && (annotations.get(ENodeAnnotation.F_ERROR.toString()) instanceof Throwable)) { sb.append("<h2>Error Details:</h2><pre style=\"color: red;\">"); Throwable e = (Throwable) annotations.get(ENodeAnnotation.F_ERROR.toString()); do { sb.append("Error Type " + e.getClass().getName() + "\nMessage: " + e.getMessage() + "\nStack Trace:\n"); for (StackTraceElement ste : e.getStackTrace()) { sb.append(" " + ste.toString() + "\n"); } e = e.getCause(); if (e != null) { sb.append("Caused By: "); } } while (e != null); sb.append("</pre>"); } if (this.nodeInfoGeneratorForPoints != null) { sb.append(this.nodeInfoGeneratorForPoints.generateInfoForNode(node.getNodes())); } return sb.toString(); } @Override public String getName() { return JaicoreNodeInfoGenerator.class.getName(); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/model/travesaltree/ReducedGraphGenerator.java
package ai.libs.jaicore.search.model.travesaltree; import java.util.ArrayList; import java.util.Arrays; 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.ISuccessorGenerator; /** * Graph generator that uses another graph generator as a basis by reducing the * graph generated by the basis generator so that it does not contain long * chains of nodes anymore, that is successors of a node are skipped while a * node only has 1 successor. Usage: Create a new ReducedGraphGenerator object * and swap all ocurrences of the graph generator it uses as a basis with the * reduced graph generator. * * @author Helena Graf * * @param <T> * @param <A> */ public class ReducedGraphGenerator<T, A> implements IGraphGenerator<T, A> { private IGraphGenerator<T, A> basis; /** * Create a new ReducedGraphGenerator that uses the given graph generator as a * basis. * * @param basis * the graph generator to use as a basis */ public ReducedGraphGenerator(final IGraphGenerator<T, A> basis) { this.basis = basis; } @Override public IRootGenerator<T> getRootGenerator() { return this.basis.getRootGenerator(); } @Override public ISuccessorGenerator<T, A> getSuccessorGenerator() { return new ISuccessorGenerator<T, A>() { private ISuccessorGenerator<T, A> generator = ReducedGraphGenerator.this.basis.getSuccessorGenerator(); /** * Expands the node recursively while it only has one successor, until the end * of the branch or a split point in the graph is reached. * * @param node * The node to expand * @return The fully refined node * @throws InterruptedException */ public INewNodeDescription<T, A> reduce(final INewNodeDescription<T, A> node) throws InterruptedException { List<INewNodeDescription<T, A>> sucessors = this.generator.generateSuccessors(node.getTo()); List<INewNodeDescription<T, A>> previous = Arrays.asList(node); while (sucessors.size() == 1) { previous = sucessors; sucessors = this.generator.generateSuccessors(sucessors.get(0).getTo()); } return previous.get(0); } @Override public List<INewNodeDescription<T, A>> generateSuccessors(final T node) throws InterruptedException { List<INewNodeDescription<T, A>> successors = this.generator.generateSuccessors(node); // Skip through nodes with 1 successor to find while (successors.size() == 1) { List<INewNodeDescription<T, A>> previous = successors; successors = this.generator.generateSuccessors(successors.get(0).getTo()); if (successors.isEmpty()) { return previous; } } List<INewNodeDescription<T, A>> reducedSuccessors = new ArrayList<>(); for (INewNodeDescription<T, A> successor : successors) { reducedSuccessors.add(this.reduce(successor)); } return reducedSuccessors; } }; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/AMDP.java
package ai.libs.jaicore.search.probleminputs; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; import ai.libs.jaicore.basic.sets.SetUtil; public abstract class AMDP<N, A, V extends Comparable<V>> implements IMDP<N, A, V> { private final N initState; protected AMDP(final N initState) { super(); this.initState = initState; } @Override public N getInitState() { return this.initState; } @Override public double getProb(final N state, final A action, final N successor) throws InterruptedException { return this.getProb(state, action, successor, false); } public double getProb(final N state, final A action, final N successor, final boolean setProbabilityOfUndefinedToZero) throws InterruptedException { Map<N, Double> dist = this.getProb(state, action); if (!dist.containsKey(successor)) { if (setProbabilityOfUndefinedToZero) { return 0.0; } else { throw new IllegalArgumentException("No probability defined for the following triplet:\n\tFrom state: " + state + "\n\tUsed action: " + action + "\n\tTo state: " + successor + ".\nDistribution is: " + dist.entrySet().stream().map(e -> "\n\t" + e.toString()).collect(Collectors.joining())); } } return dist.get(successor); } @Override public boolean isTerminalState(final N state) throws InterruptedException { return this.getApplicableActions(state).isEmpty(); } @Override public A getUniformlyRandomApplicableAction(final N state, final Random random) throws InterruptedException { return SetUtil.getRandomElement(this.getApplicableActions(state), random); } @Override public boolean isActionApplicableInState(final N state, final A action) throws InterruptedException { return this.getApplicableActions(state).contains(action); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/GraphSearchInput.java
package ai.libs.jaicore.search.probleminputs; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; /** * This input is provided to algorithms that should find a solution path in a graph without path cost. * That is, the set of solutions is exactly the set of paths from the root to a goal node. * * @author fmohr * * @param <N> * @param <A> */ public class GraphSearchInput<N, A> implements IPathSearchInput<N, A> { private final IGraphGenerator<N, A> graphGenerator; private final IPathGoalTester<N, A> goalTester; public GraphSearchInput(final IPathSearchInput<N, A> inputToClone) { this(inputToClone.getGraphGenerator(), inputToClone.getGoalTester()); } public GraphSearchInput(final IGraphGenerator<N, A> graphGenerator, final IPathGoalTester<N, A> goalTester) { super(); this.graphGenerator = graphGenerator; this.goalTester = goalTester; } @Override public IGraphGenerator<N, A> getGraphGenerator() { return this.graphGenerator; } @Override public IPathGoalTester<N, A> getGoalTester() { return this.goalTester; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/GraphSearchWithNodeRecommenderInput.java
package ai.libs.jaicore.search.probleminputs; import java.util.Comparator; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; public class GraphSearchWithNodeRecommenderInput<N, A> extends GraphSearchInput<N, A> { private final Comparator<N> recommender; public GraphSearchWithNodeRecommenderInput(final IPathSearchInput<N, A> graphSearchInput, final Comparator<N> recommender) { super(graphSearchInput); this.recommender = recommender; } public GraphSearchWithNodeRecommenderInput(final IGraphGenerator<N, A> graphGenerator, final IPathGoalTester<N, A> goalTester, final Comparator<N> recommender) { super(graphGenerator, goalTester); this.recommender = recommender; } public Comparator<N> getRecommender() { return this.recommender; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/GraphSearchWithNumberBasedAdditivePathEvaluation.java
package ai.libs.jaicore.search.probleminputs; import java.util.Iterator; import java.util.List; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; 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.PathEvaluationException; import org.api4.java.datastructure.graph.ILabeledPath; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import ai.libs.jaicore.search.model.travesaltree.BackPointerPath; public class GraphSearchWithNumberBasedAdditivePathEvaluation<N, A> extends GraphSearchWithSubpathEvaluationsInput<N, A, Double> { public interface EdgeCostComputer<N, A> { public double g(BackPointerPath<N, A, ?> from, BackPointerPath<N, A, ?> to); } public static class FComputer<N, A> implements IPathEvaluator<N, A, Double> { private final EdgeCostComputer<N, A> g; private final IPathEvaluator<N, A, Double> h; // this is to estimate the minimum cost between a node and ANY goal node public FComputer(final EdgeCostComputer<N, A> g, final IPathEvaluator<N, A, Double> h) { super(); this.g = g; this.h = h; } @Override public Double evaluate(final ILabeledPath<N, A> path) throws PathEvaluationException, InterruptedException { if (!(path instanceof BackPointerPath)) { throw new IllegalArgumentException("Can compute f-value only for back pointer paths."); } List<?> cPath = ((BackPointerPath<N, A, Double>)path).path(); int depth = cPath.size() - 1; double pathCost = 0; double heuristic = this.h.evaluate(path); if (depth > 0) { @SuppressWarnings("unchecked") Iterator<BackPointerPath<N, A, ?>> it = (Iterator<BackPointerPath<N, A, ?>>) cPath.iterator(); BackPointerPath<N, A, ?> parent = it.next(); BackPointerPath<N, A, ?> current; while (it.hasNext()) { current = it.next(); pathCost += this.g.g(parent, current); parent = current; } } return pathCost + heuristic; } public EdgeCostComputer<N, A> getG() { return this.g; } public IPathEvaluator<N, A, Double> getH() { return this.h; } } public GraphSearchWithNumberBasedAdditivePathEvaluation(final IPathSearchInput<N, A> baseProblem, final EdgeCostComputer<N, A> g, final IPathEvaluator<N, A, Double> h) { this(baseProblem.getGraphGenerator(), baseProblem.getGoalTester(), new FComputer<>(g, h)); } public GraphSearchWithNumberBasedAdditivePathEvaluation(final IGraphGenerator<N, A> graphGenerator, final IPathGoalTester<N, A> goalTester, final EdgeCostComputer<N, A> g, final IPathEvaluator<N, A, Double> h) { this(graphGenerator, goalTester, new FComputer<>(g, h)); } public GraphSearchWithNumberBasedAdditivePathEvaluation(final IPathSearchInput<N, A> baseProblem, final FComputer<N, A> fComputer) { this(baseProblem.getGraphGenerator(), baseProblem.getGoalTester(), fComputer); } /** * This constructor can be used if one wants to extend AStar by some more specific f-value computer. * See R* for an example. * * @param graphGenerator * @param fComputer */ public GraphSearchWithNumberBasedAdditivePathEvaluation(final IGraphGenerator<N, A> graphGenerator, final IPathGoalTester<N, A> goalTester, final FComputer<N, A> fComputer) { super(graphGenerator, goalTester, fComputer); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic.java
package ai.libs.jaicore.search.probleminputs; import java.util.List; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; 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.math.IMetric; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import ai.libs.jaicore.search.model.travesaltree.BackPointerPath; public class GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic<N, A> extends GraphSearchWithNumberBasedAdditivePathEvaluation<N, A> { public interface PathCostEstimator<N, A> { public double h(BackPointerPath<N, A, ?> from, BackPointerPath<N, A, ?> to); } public interface DistantSuccessorGenerator<N> { public List<N> getDistantSuccessors(N node, int k, IMetric<N> metricOverStates, double delta) throws InterruptedException; } public static class SubPathEvaluationBasedFComputer<N, A> extends GraphSearchWithNumberBasedAdditivePathEvaluation.FComputer<N, A> { private final PathCostEstimator<N, A> hPath; // this is to estimate the minimum cost between to concretely defined nodes public SubPathEvaluationBasedFComputer(final EdgeCostComputer<N, A> g, final IPathEvaluator<N, A, Double> h, final PathCostEstimator<N, A> hPath) { super(g, h); this.hPath = hPath; } public double h(final BackPointerPath<N, A, ?> from, final BackPointerPath<N, A, ?> to) { return this.hPath.h(from, to); } public PathCostEstimator<N, A> gethPath() { return this.hPath; } } private final IMetric<N> metricOverStates; private final DistantSuccessorGenerator<N> distantSuccessorGenerator; public GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic(final IPathSearchInput<N, A> graphSearchInput, final EdgeCostComputer<N, A> g, final IPathEvaluator<N, A, Double> h, final PathCostEstimator<N, A> hPath, final IMetric<N> metricOverStates, final DistantSuccessorGenerator<N> distantSuccessorGenerator) { super(graphSearchInput, new SubPathEvaluationBasedFComputer<>(g, h, hPath)); this.metricOverStates = metricOverStates; this.distantSuccessorGenerator = distantSuccessorGenerator; } public GraphSearchWithNumberBasedAdditivePathEvaluationAndSubPathHeuristic(final IGraphGenerator<N, A> graphGenerator, final IPathGoalTester<N, A> goalTester, final EdgeCostComputer<N, A> g, final IPathEvaluator<N, A, Double> h, final PathCostEstimator<N, A> hPath, final IMetric<N> metricOverStates, final DistantSuccessorGenerator<N> distantSuccessorGenerator) { super(graphGenerator, goalTester, new SubPathEvaluationBasedFComputer<>(g, h, hPath)); this.metricOverStates = metricOverStates; this.distantSuccessorGenerator = distantSuccessorGenerator; } public IMetric<N> getMetricOverStates() { return this.metricOverStates; } public DistantSuccessorGenerator<N> getDistantSuccessorGenerator() { return this.distantSuccessorGenerator; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/GraphSearchWithPathEvaluationsInput.java
package ai.libs.jaicore.search.probleminputs; import java.util.HashMap; import java.util.Map; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; 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.PathEvaluationException; import org.api4.java.common.attributedobjects.IObjectEvaluator; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; 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 ai.libs.jaicore.logging.ToJSONStringUtil; /** * In AILibs, a graph search problem always aims at identifying one or more paths from * a set of root nodes to a goal node. Usually, such paths are associated with a value * that qualifies them. * * This is the most general problem input one can have if there is no other knowledge. * * @author fmohr * * @param <N> * @param <A> * @param <V> */ public class GraphSearchWithPathEvaluationsInput<N, A, V extends Comparable<V>> extends GraphSearchInput<N, A> implements IPathSearchWithPathEvaluationsInput<N, A, V> { private final IPathEvaluator<N, A, V> pathEvaluator; public GraphSearchWithPathEvaluationsInput(final IPathSearchInput<N, A> graphSearchInput, final IPathEvaluator<N, A, V> pathEvaluator) { super(graphSearchInput); this.pathEvaluator = pathEvaluator; } @SuppressWarnings("unchecked") public GraphSearchWithPathEvaluationsInput(final IPathSearchInput<N, A> graphSearchInput, final IObjectEvaluator<ILabeledPath<N, A>, V> pathEvaluator) { this (graphSearchInput, pathEvaluator instanceof IPathEvaluator ? (IPathEvaluator<N, A, V>)pathEvaluator : new Evaluator<N, A, V>(pathEvaluator)); } public GraphSearchWithPathEvaluationsInput(final IGraphGenerator<N, A> graphGenerator, final IPathGoalTester<N, A> goalTester, final IObjectEvaluator<ILabeledPath<N, A>, V> pathEvaluator) { this(new GraphSearchInput<>(graphGenerator, goalTester), pathEvaluator); } @Override public IPathEvaluator<N, A, V> getPathEvaluator() { return this.pathEvaluator; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("pathEvaluator", this.pathEvaluator); fields.put("graphGenerator", super.getGraphGenerator()); return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields); } private static class Evaluator<N, A, V extends Comparable<V>> implements IPathEvaluator<N, A, V>, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(Evaluator.class); private final IObjectEvaluator<ILabeledPath<N, A>, V> pathEvaluator; public Evaluator(final IObjectEvaluator<ILabeledPath<N, A>, V> pathEvaluator) { super(); if (pathEvaluator instanceof IPathEvaluator) { throw new IllegalArgumentException("An object of type " + IPathEvaluator.class.getName() + " should not be wrapped here!"); } this.pathEvaluator = pathEvaluator; } @Override public V evaluate(final ILabeledPath<N, A> path) throws PathEvaluationException, InterruptedException { try { this.logger.info("Forwarding query for path of length {} to {}", path.getNumberOfNodes(), this.pathEvaluator.getClass().getName()); return this.pathEvaluator.evaluate(path); } catch (ObjectEvaluationFailedException e) { throw new PathEvaluationException(e.getMessage(), e.getCause()); } } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); if (this.pathEvaluator instanceof ILoggingCustomizable) { ((ILoggingCustomizable) this.pathEvaluator).setLoggerName(name + ".fw"); } } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/GraphSearchWithSubpathEvaluationsInput.java
package ai.libs.jaicore.search.probleminputs; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; /** * Many algorithms such as best first and A* use a traversal tree to browse the underlying * graph. Each node in this tree corresponds to a node in the original graph but has only * one predecessor, which may be updated over time. * * The underlying class Node<T,V> implicitly defines a back pointer PATH from the node to * the root. Therefore, evaluating a node of this class equals evaluating a path in the * original graph. * * @author fmohr * * @param <N> * @param <A> * @param <V> */ public class GraphSearchWithSubpathEvaluationsInput<N, A, V extends Comparable<V>> extends GraphSearchWithPathEvaluationsInput<N, A, V> { public GraphSearchWithSubpathEvaluationsInput(final IPathSearchInput<N, A> graphSearchInput, final IPathEvaluator<N, A, V> nodeEvaluator) { this(graphSearchInput.getGraphGenerator(), graphSearchInput.getGoalTester(), nodeEvaluator); } public GraphSearchWithSubpathEvaluationsInput(final IGraphGenerator<N, A> graphGenerator, final IPathGoalTester<N, A> goalTester, final IPathEvaluator<N, A, V> nodeEvaluator) { super(graphGenerator, goalTester, nodeEvaluator); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/GraphSearchWithUncertaintyBasedSubpathEvaluationInput.java
package ai.libs.jaicore.search.probleminputs; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallyUncertaintyAnnotatingPathEvaluator; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; public class GraphSearchWithUncertaintyBasedSubpathEvaluationInput<N, A, V extends Comparable<V>> extends GraphSearchWithSubpathEvaluationsInput<N, A, V> { public GraphSearchWithUncertaintyBasedSubpathEvaluationInput(final IPathSearchInput<N, A> baseProblem, final IPotentiallyUncertaintyAnnotatingPathEvaluator<N, A, V> nodeEvaluator) { super(baseProblem, nodeEvaluator); } public GraphSearchWithUncertaintyBasedSubpathEvaluationInput(final IGraphGenerator<N, A> graphGenerator, final IPathGoalTester<N, A> goalTester, final IPotentiallyUncertaintyAnnotatingPathEvaluator<N, A, V> nodeEvaluator) { super(graphGenerator, goalTester, nodeEvaluator); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/IMDP.java
package ai.libs.jaicore.search.probleminputs; import java.util.Collection; import java.util.Map; import java.util.Random; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; public interface IMDP<N, A, V extends Comparable<V>> { public N getInitState(); public boolean isMaximizing(); public Collection<A> getApplicableActions(N state) throws InterruptedException; public boolean isActionApplicableInState(N state, A action) throws InterruptedException; // important short cut to avoid computation of all action public A getUniformlyRandomApplicableAction(N state, Random random) throws InterruptedException; // this is to enable quick queries for applicable actions if we are gonna take a random one anyway public boolean isTerminalState(N state) throws InterruptedException; public Map<N, Double> getProb(N state, A action) throws InterruptedException; public double getProb(N state, A action, N successor) throws InterruptedException; public V getScore(N state, A action, N successor) throws InterruptedException, ObjectEvaluationFailedException; }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/MDPUtils.java
package ai.libs.jaicore.search.probleminputs; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.function.Predicate; import java.util.stream.Collectors; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IEvaluatedPath; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; 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.search.algorithms.mdp.mcts.ActionPredictionFailedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.model.other.SearchGraphPath; public class MDPUtils implements ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(MDPUtils.class); public static <N, A> Collection<N> getStates(final IMDP<N, A, ?> mdp) throws InterruptedException { Collection<N> states = new HashSet<>(); Deque<N> open = new ArrayDeque<>(); open.add(mdp.getInitState()); while (!open.isEmpty()) { N next = open.pop(); if (states.contains(next)) { continue; } states.add(next); for (A a : mdp.getApplicableActions(next)) { open.addAll(mdp.getProb(next, a).keySet()); } } return states; } public <N, A> N drawSuccessorState(final IMDP<N, A, ?> mdp, final N state, final A action) throws InterruptedException { return this.drawSuccessorState(mdp, state, action, new Random()); } public <N, A> N drawSuccessorState(final IMDP<N, A, ?> mdp, final N state, final A action, final Random rand) throws InterruptedException { if (!mdp.isActionApplicableInState(state, action)) { throw new IllegalArgumentException("Action " + action + " is not applicable in " + state); } Map<N, Double> dist = mdp.getProb(state, action); double p = rand.nextDouble(); double s = 0; for (Entry<N, Double> neighborWithProb : dist.entrySet()) { s += neighborWithProb.getValue(); if (s >= p) { return neighborWithProb.getKey(); } } throw new IllegalStateException("The accumulated probability of all the " + dist.size() + " successors is only " + s + " instead of 1.\n\tState: " + state + "\n\tAction: " + action + "\nConsidered successor states: " + dist.entrySet().stream().map(e -> "\n\t" + e.toString()).collect(Collectors.joining())); } public <N, A> IEvaluatedPath<N, A, Double> getRun(final IMDP<N, A, Double> mdp, final double gamma, final IPolicy<N, A> policy, final Random random, final Predicate<ILabeledPath<N, A>> stopCriterion) throws InterruptedException, ActionPredictionFailedException, ObjectEvaluationFailedException { double score = 0; ILabeledPath<N, A> path = new SearchGraphPath<>(mdp.getInitState()); N current = path.getRoot(); N nextState; Collection<A> possibleActions = mdp.getApplicableActions(current); double discount = 1; while (!possibleActions.isEmpty() && !stopCriterion.test(path)) { A action = policy.getAction(current, possibleActions); assert possibleActions.contains(action); nextState = this.drawSuccessorState(mdp, current, action, random); this.logger.debug("Choosing action {}. Next state is {} (probability is {})", action, nextState, mdp.getProb(current, action, nextState)); score += discount * mdp.getScore(current, action, nextState); discount *= gamma; current = nextState; path.extend(current, action); possibleActions = mdp.getApplicableActions(current); } return new EvaluatedSearchGraphPath<>(path, score); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } public static int getTimeHorizon(final double gamma, final double epsilon) { return gamma < 1 ? (int) Math.ceil(Math.log(epsilon) / Math.log(gamma)) : Integer.MAX_VALUE; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/builders/GraphSearchWithPathEvaluationsInputBuilder.java
package ai.libs.jaicore.search.probleminputs.builders; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import ai.libs.jaicore.search.probleminputs.GraphSearchWithPathEvaluationsInput; public class GraphSearchWithPathEvaluationsInputBuilder<N, A, V extends Comparable<V>> extends SearchProblemInputBuilder<N, A, IPathSearchWithPathEvaluationsInput<N, A, V>, GraphSearchWithPathEvaluationsInputBuilder<N, A, V>> { private IPathEvaluator<N, A, V> pathEvaluator; public GraphSearchWithPathEvaluationsInputBuilder() { } public GraphSearchWithPathEvaluationsInputBuilder(final IPathEvaluator<N, A, V> nodeEvaluator) { super(); this.pathEvaluator = nodeEvaluator; } @Override public GraphSearchWithPathEvaluationsInputBuilder<N, A, V> fromProblem(final IPathSearchInput<N, A> problem) { super.fromProblem(problem); if (problem instanceof GraphSearchWithPathEvaluationsInput) { this.withPathEvaluator(((GraphSearchWithPathEvaluationsInput<N, A, V>) problem).getPathEvaluator()); } return this; } public IPathEvaluator<N, A, V> getPathEvaluator() { return this.pathEvaluator; } public GraphSearchWithPathEvaluationsInputBuilder<N, A, V> withPathEvaluator(final IPathEvaluator<N, A, V> pathEvaluator) { this.pathEvaluator = pathEvaluator; return this; } @Override public IPathSearchWithPathEvaluationsInput<N, A, V> build() { return new GraphSearchWithPathEvaluationsInput<>(this.getGraphGenerator(), this.getGoalTester(), this.pathEvaluator); } @Override protected GraphSearchWithPathEvaluationsInputBuilder<N, A, V> self() { return this; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/builders/GraphSearchWithSubpathEvaluationsInputBuilder.java
package ai.libs.jaicore.search.probleminputs.builders; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; public class GraphSearchWithSubpathEvaluationsInputBuilder<N, A, V extends Comparable<V>> extends SearchProblemInputBuilder<N, A, GraphSearchWithSubpathEvaluationsInput<N, A, V>, GraphSearchWithSubpathEvaluationsInputBuilder<N, A, V>> { private IPathEvaluator<N, A, V> nodeEvaluator; public GraphSearchWithSubpathEvaluationsInputBuilder() { } public GraphSearchWithSubpathEvaluationsInputBuilder(final IPathEvaluator<N, A, V> nodeEvaluator) { super(); this.nodeEvaluator = nodeEvaluator; } public IPathEvaluator<N, A, V> getNodeEvaluator() { return this.nodeEvaluator; } public void setNodeEvaluator(final IPathEvaluator<N, A, V> nodeEvaluator) { this.nodeEvaluator = nodeEvaluator; } @Override public GraphSearchWithSubpathEvaluationsInput<N, A, V> build() { return new GraphSearchWithSubpathEvaluationsInput<>(this.getGraphGenerator(), this.getGoalTester(), this.nodeEvaluator); } @Override protected GraphSearchWithSubpathEvaluationsInputBuilder<N, A, V> self() { return this; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/probleminputs/builders/SearchProblemInputBuilder.java
package ai.libs.jaicore.search.probleminputs.builders; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.datastructure.graph.ILabeledPath; 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.search.model.other.SearchGraphPath; public abstract class SearchProblemInputBuilder<N, A, I extends IPathSearchInput<N, A>, B extends SearchProblemInputBuilder<N, A, I, B>> { private IRootGenerator<N> rootGenerator; private ISuccessorGenerator<N, A> successorGenerator; private IPathGoalTester<N, A> goalTester; private ILabeledPath<N, A> prefixPath; // the path from the original root public B withGraphGenerator(final IGraphGenerator<N, A> graphGenerator) { this.rootGenerator = graphGenerator.getRootGenerator(); this.successorGenerator = graphGenerator.getSuccessorGenerator(); return this.self(); } public IGraphGenerator<N, A> getGraphGenerator() { return new IGraphGenerator<N, A>() { @Override public IRootGenerator<N> getRootGenerator() { return SearchProblemInputBuilder.this.rootGenerator; } @Override public ISuccessorGenerator<N, A> getSuccessorGenerator() { return SearchProblemInputBuilder.this.successorGenerator; } }; } public B fromProblem(final IPathSearchInput<N, A> problem) { this.withGraphGenerator(problem.getGraphGenerator()); this.withGoalTester(problem.getGoalTester()); return this.self(); } public B withRoot(final N root) { this.rootGenerator = () -> Arrays.asList(root); return this.self(); } public void withSuccessorGenerator(final ISuccessorGenerator<N, A> successorGenerator) { this.successorGenerator = successorGenerator; } /** * Replaces the current root by a new one based on the successor generator * @throws InterruptedException **/ public B withOffsetRoot(final List<Integer> indicesOfSuccessorsFromCurrentRoot) throws InterruptedException { if (this.rootGenerator == null) { throw new IllegalStateException("Cannot offset root when currently no root is set."); } if (this.successorGenerator == null) { throw new IllegalStateException("Cannot offset root when currently no successor generator is set."); } Collection<N> roots = this.rootGenerator.getRoots(); if (roots.size() > 1) { throw new IllegalStateException("Root offset is a function that is only reasonably defined for problems with one root!"); } List<N> prefixNodes = new ArrayList<>(); List<A> prefixArcs = new ArrayList<>(); N current = roots.iterator().next(); prefixNodes.add(current); for (int child : indicesOfSuccessorsFromCurrentRoot) { INewNodeDescription<N, A> ned = this.successorGenerator.generateSuccessors(current).get(child); current = ned.getTo(); prefixArcs.add(ned.getArcLabel()); prefixNodes.add(current); } this.prefixPath = new SearchGraphPath<>(prefixNodes, prefixArcs); this.rootGenerator = new ISingleRootGenerator<N>() { @Override public N getRoot() { return SearchProblemInputBuilder.this.prefixPath.getHead(); } }; return this.self(); } public ILabeledPath<N, A> getPrefixPath() { return this.prefixPath; } public B withGoalTester(final IPathGoalTester<N, A> goalTester) { this.goalTester = goalTester; return this.self(); } public IPathGoalTester<N, A> getGoalTester() { return this.goalTester; } public abstract I build(); protected abstract B self(); }