protected Solution makeHeuristicMove( Deadline deadline, Solution s, Random random, HeuristicStats heuristicStats) { Heuristic heuristic = heuristicStats.getHeuristic(); long costBefore = s.getCost(); long startTime = System.currentTimeMillis(); s = heuristic.move( s, Deadline.min(new Deadline(heuristicMaxTimes[heuristicStats.getId()]), deadline), random); long timeDiff = System.currentTimeMillis() - startTime; long costDiff = costBefore - s.getCost(); heuristicStats.saveUsage(timeDiff, costDiff); logger.info( String.format( "Heuristic # %d has improved the solution by %d (%f %%) in %d ms; its last performance = %f", heuristicStats.getId(), costDiff, (double) costDiff * 100 / costBefore, timeDiff, heuristicStats.getLastPerformance())); return s; }
public void writeToFile(String fileName) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"); writer.write(separators.length + "\n"); for (int[] i : separators) { writer.write(i.length + "\n"); for (int j : i) { writer.write(j + "\n"); } } for (short i : rulesId) { writer.write(i + "\n"); } writer.write(rules.length + "\n"); for (Heuristic[] heuristics : rules) { writer.write(heuristics.length + "\n"); for (Heuristic heuristic : heuristics) { writer.write(heuristic.toString() + "\n"); } } writer.write(grammarInfo.length + "\n"); for (String s : grammarInfo) { writer.write(s + "\n"); } writer.close(); }
public List<String> getMorphInfo(String s) { ArrayList<String> result = new ArrayList<String>(); int[] ints = decoderEncoder.encodeToArray(revertWord(s)); int ruleId = findRuleId(ints); for (Heuristic h : rules[rulesId[ruleId]]) { result.add( h.transformWord(s).append("|").append(grammarInfo[h.getFormMorphInfo()]).toString()); } return result; }
/** * Makes this player's moves until the referee says the game is over or one of the players has * won. */ public static void makeMoves() { Move move; while (true) { if (currentGameState.getTurn() == Player.MAX) { move = MinMax.getInstance() .getNextBestMove(currentGameState, timelimit, Heuristic.getInstance()); Communicator.getInstance().sendCmd(Main.getMoveAsCommand(move)); logger.log(Level.INFO, "Player " + playerNumber + " move: " + move.toString()); } else { String command = Communicator.getInstance().getCmd(); if (Main.gameIsOver(command)) { break; } String args[] = command.split(" "); int col = Integer.parseInt(args[0]); int moveType = Integer.parseInt(args[1]); move = new Move((moveType == 0) ? MoveType.POP : MoveType.DROP, col); } currentGameState.move(move); } }
public List<String> getNormalForms(String s) { ArrayList<String> result = new ArrayList<String>(); int[] ints = decoderEncoder.encodeToArray(revertWord(s)); int ruleId = findRuleId(ints); boolean notSeenEmptyString = true; for (Heuristic h : rules[rulesId[ruleId]]) { String e = h.transformWord(s).toString(); if (e.length() > 0) { result.add(e); } else if (notSeenEmptyString) { result.add(s); notSeenEmptyString = false; } } return result; }
/** * Sets up the heuristic weighting functions for the min max heuristic. * * @param args The command line arguments. */ private static void setUpHeuristics(String args[]) { String heuristicOption = "const"; if (args.length > 0 && heuristicFunctions.containsKey(args[0])) { heuristicOption = args[0]; } Heuristic.getInstance().setWeightFunction(heuristicFunctions.get(heuristicOption)); }
private Solution processHeuristicMove( Deadline deadline, Solution s, Random random, HeuristicStats heuristicStats) { Heuristic heuristic = heuristicStats.getHeuristic(); double costBefore = s.getCost(); s = makeHeuristicMove(deadline, s, random, heuristicStats); double costDiff = costBefore - s.getCost(); if (costDiff > 0) { queue.add(heuristicStats); for (HeuristicStats stats : exploitedHeuristics) { queue.add(stats); } exploitedHeuristics.clear(); } else if (heuristic.isDeterministic()) { exploitedHeuristics.add(heuristicStats); } else { queue.add(heuristicStats); } return s; }
/* * Creates a tree of moves to take with their evaluated scores */ public void createSearchSpace(int level, State state, Board board, boolean myTurn) { int[] openColumns = board.getOpenColumns(); state.nextMoves = new State[openColumns.length]; for (int i = 0; i < openColumns.length; i++) { int move = openColumns[i]; board.handleMove(myTurn, move); int score = heuristic.getScore(board); state.nextMoves[i] = new State(move, board, score); if (level != depth && board.hasWinner() == false) createSearchSpace(level + 1, state.nextMoves[i], board, !myTurn); board.undoMove(move); board.setHasWinner(false); } }
// returns the single move to make given a board, depth, piecelist, heuristic // whill choose the best terminal board at the max depth, // or if none exists, the best board with no children (inevitable death) public Board.Direction nextMove(Board start, List<Integer> nextPiece) { int maxDepth = Math.min(exploreDepth, nextPiece.size()); double bestLiveScore = -1; Board.Direction bestLiveDirection = null; // cus why not? // add the first round seperately so we know which move to return for (Board.Direction d : Board.Direction.values()) { Board next = start.move(d, nextPiece.get(0)); if (next != null) { PriorityQueue<Double> pq = new PriorityQueue<Double>(); Deque<StackItem> stack = new ArrayDeque<StackItem>(); stack.push(new StackItem(next, 1, d)); // DFS while (!stack.isEmpty()) { StackItem cur = stack.pop(); // add more moves if not beyond max depth if (cur.d < maxDepth) { for (Board.Direction d2 : Board.Direction.values()) { Board next2 = cur.b.move(d2, nextPiece.get(cur.d)); if (next2 != null) { stack.push(new StackItem(next2, cur.d + 1, cur.move)); } } } // update live only at the bottom of the tree if (cur.d == maxDepth) { pq.add(heuristic.useHeuristic(cur.b)); if (pq.size() > 10) pq.poll(); } } double sum = 0; int count = 0; count = pq.size(); while (!pq.isEmpty()) sum += pq.poll(); if (count > 0 && sum / count > bestLiveScore) { bestLiveScore = sum / count; bestLiveDirection = d; } } } return bestLiveDirection; }
public int astar(Vertex start, Vertex goal, Heuristic h) { int count; Collection<Vertex> vertices_; Comparator<Vertex> comp; PriorityQueue<Vertex> fringe; count = 0; vertices_ = vertices.values(); comp = new Comparator<Vertex>() { public int compare(Vertex i, Vertex j) { return (i.cost + i.estimate - j.cost - j.estimate); } }; // use estimates fringe = new PriorityQueue<Vertex>(20, comp); for (Vertex v : vertices_) { v.visited = false; v.cost = 999999; } start.cost = 0; start.parent = null; fringe.add(start); while (!fringe.isEmpty()) { Vertex v = fringe.remove(); // lowest-cost count++; // count nodes if (v.equals(goal)) { // if the goal is found, quit break; } if (!v.visited) { v.visited = true; for (Edge e : v.edges) { int newcost = v.cost + e.cost; if (newcost < e.target.cost) { e.target.cost = newcost; e.target.parent = v; e.target.estimate = h.fn(e.target, goal); // use heuristic fringe.add(e.target); } } } } return count; }
private double maxscore(MachineState state, int maxDepth, int currentDepth) throws MoveDefinitionException, GoalDefinitionException, TransitionDefinitionException { if (playerResult.containsMemoizedState(state)) { return playerResult.getMemoizedState(state); } if (currentDepth == maxDepth || stateMachine.isTerminal(state)) { return Heuristic.getPlayerMobility(stateMachine, state, role); } List<Move> moves = stateMachine.getLegalMoves(state, role); double score = Double.MIN_VALUE; Collections.shuffle(moves); for (Move move : moves) { double result = minscore(move, state, maxDepth, currentDepth + 1); if (result > score) { score = result; } } playerResult.putMemoizedState(state, score); return score; }
private Heuristic[] modeifyHeuristic(Heuristic[] heuristics) { ArrayList<Heuristic> result = new ArrayList<Heuristic>(); for (Heuristic heuristic : heuristics) { boolean isAdded = true; for (Heuristic ch : result) { isAdded = isAdded && !(ch.getActualNormalSuffix().equals(heuristic.getActualNormalSuffix()) && (ch.getActualSuffixLengh() == heuristic.getActualSuffixLengh())); } if (isAdded) { result.add(heuristic); } } return result.toArray(new Heuristic[result.size()]); }
public static void faultlocalization( String diff, List<String> changed, int failednum, int passnum, HashMap<String, HashSet<String>> test_affchgs, HashMap<String, HashSet<String>> changeMap, String rank, List<String> sel) throws IOException { if (test_affchgs == null) return; // System.out.println("failed number: " + failednum+" pass number: "+passnum); HashMap<String, Double> change_vals = new HashMap<String, Double>(); for (String change : changeMap.keySet()) { double susval = 0.0; double all_fail_num = failednum; double all_pass_num = passnum; double exe_fail_num = 0; double exe_pass_num = 0; if (all_fail_num == 0 || all_pass_num == 0) susval = 0; else { for (String test : sel) { HashSet<String> set = test_affchgs.get(test); if (set != null && set.contains(change)) { if (changed.contains(test)) exe_fail_num++; else exe_pass_num++; } } susval = (exe_fail_num / all_fail_num) / ((exe_fail_num / all_fail_num) + (exe_pass_num / all_pass_num)); } change_vals.put(change, susval); } Heuristic heu = new Heuristic(diff); BufferedWriter writer = new BufferedWriter(new FileWriter(rank)); for (String s : test_affchgs.keySet()) { if (!changed.contains(s)) continue; HashSet<String> chgs = test_affchgs.get(s); writer.write("<TEST>" + s + " -" + chgs.size() + "\n"); int num = chgs.size(); String[] names = new String[num]; double[] values = new double[num]; int[] heuValues = new int[num]; int i = 0; for (String chg : chgs) { names[i] = chg; values[i] = change_vals.get(chg); heuValues[i] = heu.getHeuristicValue(chg); i++; } sort(names, values, heuValues, 0, num - 1); for (i = 0; i < num; i++) { writer.write(names[i] + ": " + values[i] + " - " + heuValues[i] + "\n"); } } writer.flush(); writer.close(); }