repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
Ludii
Ludii-master/Core/src/other/uf/UnionFindD.java
package other.uf; import java.io.Serializable; /** * Main file: Union-find-delete() * * @author tahmina */ public class UnionFindD implements Serializable { private static final long serialVersionUID = 1L; // // //------------------------------------------------------------------------- // // /** // * Constructor // */ // private UnionFindD() // { // // Do nothing // } // // //------------------------------------------------------------------------- // // /** // * @param context The current Context of the game board. // * @param activeIsLoop loop information is required or not?. // * @param siteId The last move, which we want to add in the union tree // * @param dirnChoice The direction. // * @return True if loop detected // */ // public static boolean eval // ( // final Context context, // final boolean activeIsLoop, // final int siteId, // final AbsoluteDirection dirnChoice // ) // { // final SiteType type = getSiteType(context);//Define the type of graph elements // final ContainerState state = context.state().containerStates()[0]; // final int whoSiteId = state.who(siteId, type);//it needs to change // final int numPlayers = context.game().players().count(); // final int whoSiteIdNext = context.state().next(); // final TIntArrayList nList = new TIntArrayList(); // final List<? extends TopologyElement> elements = context.game().graphPlayElements(); // final Topology topology = context.topology(); // // if (whoSiteId == 0) // { // if (state.what(siteId, type) != 0) // Why GT in this case???? // evalUFGT(context, siteId); // // return false; // } // // if (whoSiteId < 1 || whoSiteId > numPlayers) // { // //System.out.println("** Bad who in UFD.eval(): " + whoSiteId); // return false; // } // // if (siteId < 0 || siteId >= elements.size()) // { // //System.out.println("** Bad id in UFD.eval(): "); // return false; // } // // boolean ringFlag = false; // // if (state.unionInfo(dirnChoice)[whoSiteIdNext].getParent(siteId) != Constants.UNUSED) // evalD(context, siteId, true, dirnChoice); // If the same location exist any opponent player remove it // // final List<game.util.graph.Step> steps = topology.trajectories().steps(type, siteId, type, dirnChoice); // for (final game.util.graph.Step step : steps) // nList.add(step.to().id()); // // if (activeIsLoop) // ringFlag = new IsLoopAux(dirnChoice).eval(context, siteId); // // context.setRingFlagCalled(ringFlag); // // // preprocessing need to set the orthogonal neighbour items in UFD and to reduce the valid position, which contains the friendly pieces // final TIntArrayList neighbourList = preProcessingLiberties(type, state, siteId, numPlayers, nList, state.unionInfo(dirnChoice)[whoSiteId], whoSiteId); // // // Union for the current player or the current stone color // union(siteId, neighbourList, true, state.unionInfo(dirnChoice)[whoSiteId], whoSiteId); // // // preprocessing need to set the orthogonal neighbour items in UFD and to reduce the valid position, which contains the friendly pieces // final TIntArrayList neighbourListCommon = preProcessingLiberties(type, state, siteId, numPlayers, nList, state.unionInfo(dirnChoice)[numPlayers + 1], numPlayers + 1); // // // Union for the common player // union(siteId, neighbourListCommon, true, state.unionInfo(dirnChoice)[numPlayers + 1], numPlayers + 1); // // return ringFlag; // } // // //------------------------------------------------------------------------- // // /** // * "determineUnionTree" Delete works for capturing movement in Local state. // * // * @param context The current Context of the game board. // * @param deleteId deleteId, which we want to delete from the union tree. // * @param dirnChoice The direction. // */ // public static void determineUnionTree // ( // final Context context, // final int deleteId, // final AbsoluteDirection dirnChoice // ) // { // final SiteType type = getSiteType(context); // final int cid = context.containerId()[0]; // final ContainerState state = context.state().containerStates()[cid]; // final int deletePlayer = state.who(deleteId, type); //it needs to change // //If the position is empty then delete opponent union tree's // if (deletePlayer == 0) // { // if (context.game().isGraphGame()) // { // evalDeleteGT(context, deleteId); // return; // } // } // else if (state.unionInfo(dirnChoice)[deletePlayer].getParent(deleteId) == Constants.UNUSED) // { // evalD(context, deleteId, true, dirnChoice); //General for the capturing games // } // else // { //pieces movement/swapping games // evalNoLibertyFriendlyD(context, deleteId, dirnChoice); // } // } // // //------------------------------------------------------------------------- // // /** // * "evalD" Delete works for deleting game stones. // * // * @param context The current Context of the game board. // * @param deleteId deleteId, which we want to delete from the union tree. // * @param enemy True if this is enemy connection. // * @param dirnChoice The direction. // */ // public static void evalD // ( // final Context context, // final int deleteId, // final boolean enemy, // final AbsoluteDirection dirnChoice // ) // { // final SiteType type = getSiteType(context); // //final int cid = context.containerId()[deleteId];//just change it // final ContainerState state = context.state().containerStates()[0]; // int deletePlayer = state.who(deleteId, type);//it needs to change // final int numPlayers = context.game().players().count(); // //System.out.println(" deletePlayer site type 8:"+ state.what(8, SiteType.Edge)); // //System.out.println(" deletePlayer site type:"+ state.what(deleteId, SiteType.Edge)); // if (context.game().isGraphGame() && deletePlayer == 0) // { // evalDeleteGT(context, deleteId); // return; // } // // if (enemy) // deletePlayer = context.state().next(); // if we need to deleted enemy, then whoSiteId change, so if group of enemy then it will be a list // // // Deletion from specific union tree // deletion(type, context, deleteId, dirnChoice, true, false, state.unionInfo(dirnChoice)[deletePlayer], deletePlayer); // // // Deletion from common stones union tree // deletion(type, context, deleteId, dirnChoice, true, false, state.unionInfo(dirnChoice)[numPlayers + 1], numPlayers + 1); // } // // //----------------------------------------------------------------- // // /** // * @param type The specific graph element type. // * @param context The current Context of the game board. // * @param deleteLoc The location to delete game stone from any the union tree. // * @param dirnChoice Direction // * @param libertyFlag Because all the games need not to compute liberty. // * @param blockingFlag For the blocking game, there are some union tree of the free spaces. // * @param uf The UFD object // * @param whoSiteId The type of union tree. // * // * Remarks: This function is used to the general deletion in UFD frameworks. // * // */ // private static void deletion // ( // final SiteType type, // final Context context, // final int deleteLoc, // final AbsoluteDirection dirnChoice, // final boolean libertyFlag, // final boolean blockingFlag, // final UnionInfoD uf, // final int whoSiteId // ) // { // final int cid = context.containerId()[deleteLoc]; // final ContainerState state = context.state().containerStates()[cid]; // final int numPlayers = context.game().players().count(); // final int root = find(deleteLoc, uf); //determine the union tree // final BitSet bitsetsDeletePlayer = (BitSet) uf.getItemsList(root).clone(); //get all the items from the selected union tree // //save the list into bitsetsDeletePlayer // final Topology topology = context.topology(); // // for (int i = bitsetsDeletePlayer.nextSetBit(0); i >= 0; i = bitsetsDeletePlayer.nextSetBit(i + 1)) // { // uf.clearParent(i); // this loop uses to clear all // uf.clearItemsList(i); // the existing items // // if (libertyFlag) // uf.clearAllitemWithOrthoNeighbors(i); // } // // bitsetsDeletePlayer.clear(deleteLoc); // from the saved list disable the deleteId, as it no need to reconstruct // // for (int i = bitsetsDeletePlayer.nextSetBit(0); i >= 0; i = bitsetsDeletePlayer.nextSetBit(i + 1)) // { // final List<game.util.graph.Step> steps = topology.trajectories().steps(type, i, type, dirnChoice); // final TIntArrayList nList = new TIntArrayList(steps.size()); // // for (final game.util.graph.Step step : steps) // nList.add(step.to().id()); // // if (!blockingFlag) // { // final int nListSz = nList.size(); // final TIntArrayList neighbourList = new TIntArrayList(nListSz); // // for (int j = 0; j < nListSz; j++) // { // final int ni = nList.getQuick(j);//non-blocking game, create a list of neighbour for reconstruct // final int who = state.who(ni, type); // // if // ( // ((who == whoSiteId) && (whoSiteId != numPlayers + 1)) // || // ((who != whoSiteId) && (whoSiteId == numPlayers + 1)) // ) // { // neighbourList.add(ni); // } // } // // union(i, neighbourList, false, uf, whoSiteId); // } // else // { // For blocking game, no need to create a neighbour list as it contains the empty location // union(i, nList, libertyFlag, uf, whoSiteId); // } // } // } // // /** // * @param context The current Context of the game board. // * @param siteId The last move, which we want to add in the union tree // * @param role The roleType. // * @param dir Direction for connectivity // */ // public static void evalSetGT // ( // final Context context, // final int siteId, // final RoleType role, // final AbsoluteDirection dir // ) // { // final SiteType type = getSiteType(context);//Define the type of graph elements // final ContainerState state = context.state().containerStates()[0]; // final int whoSiteId = state.who(siteId, type);//it needs to change // // //System.out.println("------------------>>>UFD role:"+ role); // if (whoSiteId == 0) // { // //System.out.println("state.what(siteId, SiteType.Edge) :"+ state.what(siteId, SiteType.Edge)); // unionSetGT(context, siteId, dir); // } // } // // //----------------------------------------------------------------- // // /** // * @param context The current Context of the game board. // * @param siteId The last move, which we want to add in a union tree // * @param dir Direction for connectivity // */ // private static void unionSetGT // ( // final Context context, // final int siteId, // final AbsoluteDirection dir // ) // { // final Topology graph = context.topology(); // final ContainerState state = context.state().containerStates()[0]; // //System.out.println("here unionSet"); // //final SiteType type = SiteType.Edge; // final int numplayers = context.game().players().count(); // final Edge kEdge = graph.edges().get(siteId); // // final int vA = kEdge.vA().index(); // final int vB = kEdge.vB().index(); // for (int i = 1; i<= numplayers + 1; i++) // { // final int player = i; // final int rootP = find(vA, state.unionInfo(dir)[player]); // final int rootQ = find(vB, state.unionInfo(dir)[player]); // // if (rootP == rootQ) // return; // // if (state.unionInfo(dir)[player].getGroupSize(rootP) == 0) // { // state.unionInfo(dir)[player].setParent(vA, vA); // state.unionInfo(dir)[player].setItem(vA, vA); // } // // if (state.unionInfo(dir)[player].getGroupSize(rootQ) == 0) // { // state.unionInfo(dir)[player].setParent(vB, vB); // state.unionInfo(dir)[player].setItem(vB, vB); // } // // if (state.unionInfo(dir)[player].getGroupSize(rootP) < state.unionInfo(dir)[player].getGroupSize(rootQ)) // { // state.unionInfo(dir)[player].setParent (rootP, rootQ); // state.unionInfo(dir)[player].mergeItemsLists(rootQ, rootP); // } // else // { // state.unionInfo(dir)[player].setParent(rootQ, rootP); // state.unionInfo(dir)[player].mergeItemsLists(rootP, rootQ); // } // } // } // // //----------------------------------------------------------------- // // /** // * @param context The current Context of the game board. // * @param siteId The last move, which we want to add in a union tree // * // */ // private static void evalUFGT // ( // final Context context, // final int siteId // ) // { // final ContainerState state = context.state().containerStates()[0]; // final int numplayers = context.game().players().count(); // //StringRoutines.stackTrace(); // // if (! (context.game().isGraphGame())) // return; // // final SiteType type = SiteType.Edge; // final int player = state.who(siteId, type); // //System.out.println(" here UnionGT 425 player "+player); // if (player < 1 || player > numplayers + 1) // { // //System.out.println(" return fron UFGT"); // return; // } // //System.out.println(" here UnionGT 425 id "+siteId); // if ((player >= 1) && (player <= numplayers)) // { // unionGT(context, siteId, player); // unionGT(context, siteId, numplayers + 1); // } // else // { // for(int i = 1; i<= numplayers + 1; i++) // { // //System.out.println("set at all players: "+ i); // unionGT(context, siteId, i); // } // } // // } // // //----------------------------------------------------------------- // // private static void unionGT // ( // final Context context, // final int siteId, // final int player // ) // { // final Topology graph = context.topology(); // final ContainerState state = context.state().containerStates()[0]; // final Edge kEdge = graph.edges().get(siteId); // final int vA = kEdge.vA().index(); // final int vB = kEdge.vB().index(); // // final int rootP = find(vA, state.unionInfo(AbsoluteDirection.Adjacent)[player]); // final int rootQ = find(vB, state.unionInfo(AbsoluteDirection.Adjacent)[player]); // // if (rootP == rootQ) // return; // // if (state.unionInfo(AbsoluteDirection.Adjacent)[player].getGroupSize(rootP) == 0) // { // state.unionInfo(AbsoluteDirection.Adjacent)[player].setParent(vA, vA); // state.unionInfo(AbsoluteDirection.Adjacent)[player].setItem(vA, vA); // } // // if (state.unionInfo(AbsoluteDirection.Adjacent)[player].getGroupSize(rootQ) == 0) // { // state.unionInfo(AbsoluteDirection.Adjacent)[player].setParent(vB, vB); // state.unionInfo(AbsoluteDirection.Adjacent)[player].setItem(vB, vB); // } // // if (state.unionInfo(AbsoluteDirection.Adjacent)[player].getGroupSize(rootP) < state.unionInfo(AbsoluteDirection.Adjacent)[player].getGroupSize(rootQ)) // { // state.unionInfo(AbsoluteDirection.Adjacent)[player].setParent (rootP, rootQ); // state.unionInfo(AbsoluteDirection.Adjacent)[player].mergeItemsLists(rootQ, rootP); // } // else // { // state.unionInfo(AbsoluteDirection.Adjacent)[player].setParent(rootQ, rootP); // state.unionInfo(AbsoluteDirection.Adjacent)[player].mergeItemsLists(rootP, rootQ); // } // } // // //----------------------------------------------------------------- // // /** // * @param context The current Context of the game board. // * @param deleteId The last move, which we want to delete from union tree // * // */ // private static void evalDeleteGT // ( // final Context context, // final int deleteId // ) // { // //System.out.println(" +++++++++++++++++++++++++++++++ "); // final ContainerState state = context.state().containerStates()[0]; // final SiteType type = SiteType.Edge; // final int player = state.who(deleteId, type); // final int numplayers = context.game().players().count(); // //System.out.println("gt delete player deleteId eval :"+ deleteId); // //System.out.println("gt delete player player :"+ player); // //System.out.println("gt delete player what :"+ state.what(deleteId, type)); // // if (player < 1 || player > numplayers + 1) // { // //System.out.println(" return fron DeleteGT"); // return; // } // // if ((player >= 1) && (player <= numplayers)) // { // deleteGT(context, deleteId, player, player); // deleteGT(context, deleteId, numplayers + 1, player); // } // else // { // for (int i = 1; i<= numplayers + 1; i++) // { // //System.out.println("gt delete player i :"+ i); // deleteGT(context, deleteId, i, player); // } // } // } // // //----------------------------------------------------------------- // // private static void deleteGT // ( // final Context context, // final int deleteId, // final int playerUF, // final int compareId // ) // { // final Topology graph = context.topology(); // final ContainerState state = context.state().containerStates()[0]; // final int totalEdges = graph.edges().size(); // final int totalVertices = graph.vertices().size(); // final int numplayers = context.game().players().count(); // //final Edge kEdge = graph.edges().get(deleteId); // // for (int i = 0; i < totalVertices; i++) // { // state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].clearParent(i); // this loop uses to clear all // state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].clearItemsList(i); // state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].setParent(i, i); // state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].setItem(i, i); // } // //System.out.println(" compareId :"+ compareId +" numplayers :"+ numplayers); // for (int k = 0; k < totalEdges; k++) // { // if (k != deleteId) // { // if // ( // ( // (playerUF <= numplayers) // && // ((state.who(k, SiteType.Edge) == compareId) || (state.who(k, SiteType.Edge) == numplayers + 1)) // ) // || // ( // (playerUF == numplayers + 1) // && // (state.who(k, SiteType.Edge) != 0) // ) // ) // { // final Edge kEdge = graph.edges().get(k); // final int vA = kEdge.vA().index(); // final int vB = kEdge.vB().index(); // final int rootP = find(vA, state.unionInfo(AbsoluteDirection.Adjacent)[playerUF]); // final int rootQ = find(vB, state.unionInfo(AbsoluteDirection.Adjacent)[playerUF]); // // if (rootP == rootQ) // continue; // // if (state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].getGroupSize(rootP) < state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].getGroupSize(rootQ)) // { // state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].setParent(rootP, rootQ); // state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].mergeItemsLists(rootQ, rootP); // } // else // { // state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].setParent(rootQ, rootP); // state.unionInfo(AbsoluteDirection.Adjacent)[playerUF].mergeItemsLists(rootP, rootQ); // } // } // } // } // } // // //----------------------------------------------------------------- // // /** // * @param siteId The last move of the game. // * @param validPosition neighbourList. // * @param libertyFlag Because all the games need not to compute liberty. // * @param uf The object of the union-find-delete(). // * @param whoSiteId Player type of last move. // * // * Remarks This function will not return any things. // * It able to connect the last movement with the existing union-tree. // * Basically, the rank base union-find is chosen in this implementation. // * So, that the height of the union tree will be minimum. // */ // private static void union // ( // final int siteId, // final TIntArrayList validPosition, // final boolean libertyFlag, // final UnionInfoD uf, // final int whoSiteId // ) // { // final int validPositionSz = validPosition.size(); // // // Start out with a new little group containing just siteId // uf.setItem(siteId, siteId); // uf.setParent(siteId, siteId); // // if (libertyFlag) // uf.setItemWithOrthoNeighbors(siteId, siteId); // // for (int i = 0; i < validPositionSz; i++) // { // final int ni = validPosition.getQuick(i); // boolean connectflag = true; // // if (uf.getParent(ni) != Constants.UNUSED) // { // for (int j = i + 1; j < validPositionSz; j++) // { // final int nj = validPosition.getQuick(j); // if (connected(ni, nj, uf)) // { // connectflag = false; // break; // } // } // if (connectflag) // { // final int rootP = find(ni, uf); // final int rootQ = find(siteId, uf); // // if (rootP == rootQ) // return; // // if (uf.getGroupSize(rootP) < uf.getGroupSize(rootQ)) // { // uf.setParent(rootP, rootQ); // uf.mergeItemsLists(rootQ, rootP); // // if (libertyFlag) // uf.mergeItemWithOrthoNeighbors(rootQ, rootP); // } // else // { // uf.setParent(rootQ, rootP); // uf.mergeItemsLists(rootP, rootQ); // // if (libertyFlag) // uf.mergeItemWithOrthoNeighbors(rootP, rootQ); // } // } // } // } // } // // //----------------------------------------------------------------- // // /** // * @param context The current Context of the game board. // * @param deleteId deleteId, which we want to delete from the union tree. // * @param dirnChoice Direction // * // * Remarks: It uses only delete friendly game stones. // */ // public static void evalNoLibertyFriendlyD // ( // final Context context, // final int deleteId, // final AbsoluteDirection dirnChoice // ) // { // final SiteType type = getSiteType(context); // final int cid = context.containerId()[deleteId]; // final ContainerState state = context.state().containerStates()[cid]; // final int deletePlayer = state.who(deleteId, type);//it needs to change // // deletion(type, context, deleteId, dirnChoice, false, false, state.unionInfo(dirnChoice)[deletePlayer], deletePlayer); // } // // //----------------------------------------------------------------- // // /** // * @param context The current Context of the game board. // * @param deleteId deleteId, which we want to delete from the union tree. // * @param dirnChoice The direction. // * // * Remarks: It is used in the blocking game stone delete game // * stone from all the opponent union trees. // * // */ // public static void evalDeletionForBlocking // ( // final Context context, // final int deleteId, // final AbsoluteDirection dirnChoice // ) // { // final SiteType type = getSiteType(context); // final int cid = context.containerId()[deleteId]; // final ContainerState state = context.state().containerStates()[cid]; // final int currentPlayer = state.who(deleteId, type); // final int numPlayers = context.game().players().count(); // // for (int deletePlayer = 1; deletePlayer <= numPlayers; deletePlayer++) // { // if (currentPlayer != deletePlayer) // { // deletion(type, context, deleteId, dirnChoice, false, true, state.unionInfoBlocking(dirnChoice)[deletePlayer], deletePlayer); // } // } // } // // //------------------------------------------------------------------------- // // /** // * @param verticesList List of topology elements // * // * @return List of indices of the given elements // */ // public static TIntArrayList elementIndices(final List<? extends TopologyElement> verticesList) // { // final int verticesListSz = verticesList.size(); // final TIntArrayList integerVerticesList = new TIntArrayList(verticesListSz); // // for (int i = 0; i < verticesListSz; i++) // { // integerVerticesList.add(verticesList.get(i).index()); // } // return integerVerticesList; // } // // //------------------------------------------------------------------------- // // /** // * @param type The specific graph element type. // * @param state The current state of the game board. // * @param siteId The location to delete game stone from any the union tree. // * @param numPlayer The total number of players. // * @param nList The neighbour position of the siteId. // * @param uf The UFD object // * @param whoSiteId The type of union tree. // * @return The list of the liberties // * // * Remarks: This function is used to the general preprocessing of // * deletion in UFD frameworks. // * // */ // public static TIntArrayList preProcessingLiberties // ( // final SiteType type, // final ContainerState state, // final int siteId, // final int numPlayer, // final TIntArrayList nList, // final UnionInfoD uf, // final int whoSiteId // ) // { // final int nListSz = nList.size(); // final TIntArrayList neighbourList = new TIntArrayList(nListSz); // // for (int i = 0; i < nListSz; i++) // { // final int ni = nList.getQuick(i); // // if // ( // ((state.who(ni, type) == whoSiteId) && (whoSiteId != numPlayer + 1)) // || // ((state.who(ni, type) != 0) && (whoSiteId == numPlayer + 1)) // ) // { // neighbourList.add(ni); // } // else // { // uf.setItemWithOrthoNeighbors(siteId, ni); // } // } // // return neighbourList; // } // // //----------------------------------------------------------------------------- // // /** // * // * @param context The current game context. // * // * @return type of graph elements. // */ // private static SiteType getSiteType(final Context context) // { // /* // final SiteType type; // if(context.activeGame().isEdgeGame()) type = SiteType.Edge; // else if(context.activeGame().isCellGame()) type = SiteType.Cell; // else type = SiteType.Vertex;*/ // // return (context.game().board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell); // } // // //----------------------------------------------------------------------------- // // /** // * // * @param position1 Integer position. // * @param position2 Integer position. // * @param uf Object of union-find. // * @param whoSiteId The current player type. // * // * @return check Are the position1 and position2 in the same union tree or not? // */ // private static boolean connected // ( // final int position1, // final int position2, // final UnionInfoD uf // ) // { // final int find1 = find(position1, uf); // return uf.isSameGroup(find1, position2); // } // // //---------------------------------------------------------------------------- // // /** // * // * @param position A cell number. // * @param uf Object of union-find. // * // * @return The root of the position. // */ // private static int find(final int position, final UnionInfoD uf) // { // final int parentId = uf.getParent(position); // // if ((parentId == position) || (parentId == Constants.UNUSED)) // return position; // else // return find(parentId, uf); // } }
27,441
32.837238
170
java
Ludii
Ludii-master/Core/src/other/uf/UnionInfo.java
package other.uf; import java.io.Serializable; import java.util.Arrays; import java.util.BitSet; /** * Contains all the info/storages for the Union-find. * * @author tahmina */ public class UnionInfo implements Serializable { private static final long serialVersionUID = 1L; /** Returns the parent of the site in the union tree. */ protected final int[] parent; protected final BitSet[] itemsList; protected final int totalsize; /** * Constructor * @param totalElements The size of the game board. */ public UnionInfo(final int totalElements) { totalsize = totalElements; //System.out.println("Uf :"+totalsize); parent = new int[totalElements]; itemsList = new BitSet[totalElements]; for (int i = 0; i < totalElements; i++) { parent[i] = i; itemsList[i] = null; } } /** * Copy constructor * @param other The Object of UnionInfo. */ public UnionInfo(final UnionInfo other) { totalsize = other.totalsize; parent = Arrays.copyOf(other.parent, other.parent.length); itemsList = new BitSet[other.itemsList.length]; for (int i = 0; i < other.itemsList.length; ++i) { if (other.itemsList[i] != null) { itemsList[i] = (BitSet) other.itemsList[i].clone(); } } } /** * Set the parents. * * @param childIndex The index of the child. * @param parentIndex The index of the parent. */ public void setParent(final int childIndex, final int parentIndex) { parent[childIndex] = parentIndex; } /** * @param childIndex The index of the child. * @return The index of the parent. */ public int getParent(final int childIndex) { return parent[childIndex]; } /** * @param parentIndex The index of the parent. * @return A bitset. */ public BitSet getItemsList(final int parentIndex) { return itemsList[parentIndex]; } /** * Set an item. * * @param parentIndex The index of the parent. * @param childIndex The index of the child. */ public void setItem(final int parentIndex, final int childIndex) { itemsList[parentIndex] = new BitSet(totalsize); itemsList[parentIndex].set(childIndex); } /** * Merge two item lists. * * @param parentIndex1 The index of the parent 1. * @param parentIndex2 The index of the parent 2. */ public void mergeItemsLists(final int parentIndex1, final int parentIndex2) { itemsList[parentIndex1].or(itemsList[parentIndex2]); itemsList[parentIndex2].clear(); } /** * @param parentIndex The index of the parent. * @param childIndex The index of the child. * @return True if they are in the same group. */ public boolean isSameGroup(final int parentIndex, final int childIndex) { if (itemsList[parentIndex] == null) return false; return itemsList[parentIndex].get(childIndex); } /** * @param parentIndex The parent index. * @return The size of the group. */ public int getGroupSize(final int parentIndex) { if (itemsList[parentIndex] == null) return 0; return itemsList[parentIndex].cardinality(); } }
3,054
20.821429
76
java
Ludii
Ludii-master/Core/src/other/uf/UnionInfoD.java
package other.uf; import java.io.Serializable; import java.util.Arrays; import java.util.BitSet; import main.Constants; /** * Contains all the info/storages for the Union-find-delete. * * @author tahmina */ public class UnionInfoD implements Serializable { private static final long serialVersionUID = 1L; /** Returns the parent of the site in the union tree. */ protected final int[] parent; /** * Indexed by parent of a group. Gives a BitSet of all sites that are part of * that group */ protected final BitSet[] itemsList; /** * Indexed by parent of a group. Gives a BitSet of all sites that are part of * that group, plus the list of all orthogonal neighbours around the group. */ protected final BitSet[] itemWithOrthoNeighbors; protected final int totalsize; /** * Constructor. * * @param totalElements The size of the game board. * @param numberOfPlayers The total number of players. * @param blocking True if this data is for blocking tests. */ public UnionInfoD(final int totalElements, final int numberOfPlayers, final boolean blocking) { totalsize = totalElements; // System.out.println(" UFD totalSize : "+ totalsize); parent = new int[totalElements]; itemsList = new BitSet[totalElements]; itemWithOrthoNeighbors = new BitSet[totalElements]; if (blocking) { itemsList[0] = new BitSet(totalsize); itemsList[0].set(0, totalElements); } else { for (int i = 0; i < totalElements; i++) { parent[i] = Constants.UNUSED; } } } /** * Copy constructor * * @param other The Object of UnionInfo. */ public UnionInfoD(final UnionInfoD other) { totalsize = other.totalsize; parent = Arrays.copyOf(other.parent, other.parent.length); itemsList = new BitSet[other.itemsList.length]; for (int i = 0; i < other.itemsList.length; ++i) { if (other.itemsList[i] != null) { itemsList[i] = (BitSet) other.itemsList[i].clone(); } } if (other.itemWithOrthoNeighbors != null) { itemWithOrthoNeighbors = new BitSet[other.itemWithOrthoNeighbors.length]; for (int i = 0; i < other.itemWithOrthoNeighbors.length; ++i) { if (other.itemWithOrthoNeighbors[i] != null) { itemWithOrthoNeighbors[i] = (BitSet) other.itemWithOrthoNeighbors[i].clone(); } } } else { itemWithOrthoNeighbors = null; } } /** * Set the parent of the given child index to the given parent index. * * @param childIndex The index of the child. * @param parentIndex The index of the parent. */ public void setParent(final int childIndex, final int parentIndex) { parent[childIndex] = parentIndex; } /** * Clear the parents. * * @param childIndex The index of the child. */ public void clearParent(final int childIndex) { parent[childIndex] = Constants.UNUSED; } /** * @param childIndex The index of the child. * @return The index of the parent. */ public int getParent(final int childIndex) { return parent[childIndex]; } /** * @param parentIndex The index of the parent of a group. * @return BitSet of all sites that are part of the group. */ public BitSet getItemsList(final int parentIndex) { if (itemsList[parentIndex] == null) { itemsList[parentIndex] = new BitSet(totalsize); } return itemsList[parentIndex]; } /** * Clear the items in the list. * * @param parentIndex The index of the parent. */ public void clearItemsList(final int parentIndex) { itemsList[parentIndex] = null; } /** * @param parentIndex The index of the parent. * @param childIndex The index of the child. * @return True if they are in the same group. */ public boolean isSameGroup(final int parentIndex, final int childIndex) { if (itemsList[parentIndex] == null) return false; return itemsList[parentIndex].get(childIndex); } /** * Tell items list of given parentIndex that its group contains given childIndex * * @param parentIndex The index of the parent. * @param childIndex The index of the child. */ public void setItem(final int parentIndex, final int childIndex) { if (itemsList[parentIndex] == null) { itemsList[parentIndex] = new BitSet(totalsize); } itemsList[parentIndex].set(childIndex); } /** * Merge two lists. * * @param parentIndex1 The index of the parent 1. * @param parentIndex2 The index of the parent 2. */ public void mergeItemsLists(final int parentIndex1, final int parentIndex2) { getItemsList(parentIndex1).or(getItemsList(parentIndex2)); itemsList[parentIndex2] = null; } /** * @param parentIndex The index of the parent. * @return The size of the group from an index. */ public int getGroupSize(final int parentIndex) { if (itemsList[parentIndex] == null) return 0; return itemsList[parentIndex].cardinality(); } // ----------------------------------- For Liberty Calculations----------------- /** * @param parentIndex The parent index. * @return The items which are orthogonally neighbours. */ public BitSet getAllItemWithOrthoNeighbors(final int parentIndex) { if (itemWithOrthoNeighbors[parentIndex] == null) { itemWithOrthoNeighbors[parentIndex] = new BitSet(totalsize); } return itemWithOrthoNeighbors[parentIndex]; } /** * Clear the list of orthogonal neighbours. * * @param parentIndex The parent index. */ public void clearAllitemWithOrthoNeighbors(final int parentIndex) { itemWithOrthoNeighbors[parentIndex] = null; } /** * Tell the itemWithOrthoNeighbors group of given parent index that it includes * the given child index * * @param parentIndex The index of the parent. * @param childIndex The index of the child. */ public void setItemWithOrthoNeighbors(final int parentIndex, final int childIndex) { if (itemWithOrthoNeighbors[parentIndex] == null) { itemWithOrthoNeighbors[parentIndex] = new BitSet(totalsize); } itemWithOrthoNeighbors[parentIndex].set(childIndex); } /** * Merge two list of orthogonal neighbours. * * @param parentIndex1 The parent 1. * @param parentIndex2 The parent 2. */ public void mergeItemWithOrthoNeighbors(final int parentIndex1, final int parentIndex2) { getAllItemWithOrthoNeighbors(parentIndex1).or(getAllItemWithOrthoNeighbors(parentIndex2)); itemWithOrthoNeighbors[parentIndex2] = null; } }
6,354
22.890977
94
java
Ludii
Ludii-master/Evaluation/src/analysis/Complexity.java
package analysis; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.concurrent.ThreadLocalRandom; import game.Game; import game.types.play.RepetitionType; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TObjectDoubleHashMap; import compiler.Compiler; import main.grammar.Description; import main.grammar.Report; import main.options.UserSelections; import other.context.Context; import other.trial.Trial; /** * Methods to estimate various complexity measures using random trials. * * @author Dennis Soemers and Matthew.Stephenson */ public class Complexity { //------------------------------------------------------------------------- /** * Estimates average branching factor for the given game by running random trials * for the given number of seconds. * * @param gameResource Path for game's resource path * @param numSeconds * @return A map from Strings to doubles: <br> * "Avg Trial Branching Factor" --> estimated average branching factor per trial <br> * "Avg State Branching Factor" --> estimated average branching factor per state <br> * "Num Trials" --> number of trials over which we estimated */ public static TObjectDoubleHashMap<String> estimateBranchingFactor ( final String gameResource, // final GameOptions gameOptions, // final int[] optionSelections, final UserSelections userSelections, final double numSeconds ) { // WARNING: do NOT modify this method to directly take a compiled game as argument // we may have to modify the game object itself by getting rid of custom playout // implementations, because they cannot properly store all the data we need to store. // First compile our game String desc = ""; // First try to load from memory try ( final BufferedReader rdr = new BufferedReader(new InputStreamReader(Complexity.class.getResourceAsStream(gameResource))) ) { String line; while ((line = rdr.readLine()) != null) desc += line + "\n"; } catch (final Exception e) { // Second try to load from file try ( final BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(gameResource), "UTF-8")); ) { String line; while ((line = rdr.readLine()) != null) desc += line + "\n"; } catch (final Exception e2) { e.printStackTrace(); } } final Game game = (Game)Compiler.compile ( new Description(desc), userSelections, new Report(), false ); // Disable custom playout implementations if they cannot properly store // history of legal moves per state. game.disableMemorylessPlayouts(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); trial.storeLegalMovesHistorySizes(); System.gc(); long stopAt = 0L; final long start = System.nanoTime(); final long abortAt = start + (long) Math.ceil(numSeconds * 1000000000L); int numTrials = 0; long numStates = 0L; long sumBranchingFactors = 0L; double sumAvgTrialBranchingFactors = 0.0; while (stopAt < abortAt) { game.start(context); final Trial endTrial = game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); final int numDecisions = endTrial.numMoves() - endTrial.numInitialPlacementMoves(); long trialSumBranchingFactors = 0L; final TIntArrayList branchingFactors = endTrial.auxilTrialData().legalMovesHistorySizes(); for (int i = 0; i < branchingFactors.size(); ++i) { trialSumBranchingFactors += branchingFactors.getQuick(i); } numStates += branchingFactors.size(); sumBranchingFactors += trialSumBranchingFactors; sumAvgTrialBranchingFactors += trialSumBranchingFactors / (double) numDecisions; ++numTrials; stopAt = System.nanoTime(); } final TObjectDoubleHashMap<String> map = new TObjectDoubleHashMap<String>(); map.put("Avg Trial Branching Factor", sumAvgTrialBranchingFactors / numTrials); map.put("Avg State Branching Factor", sumBranchingFactors / (double) numStates); map.put("Num Trials", numTrials); return map; } /** * Estimates average game lengths for the given game by running random trials * for the given number of seconds. * * @param game * @param numSeconds * @return A map from Strings to doubles: <br> * "Avg Num Decisions" --> average number of decisions per trial <br> * "Avg Num Player Switches" --> average number of switches of player-to-move per trial <br> * "Num Trials" --> number of trials over which we estimated */ public static TObjectDoubleHashMap<String> estimateGameLength ( final Game game, final double numSeconds ) { final Trial trial = new Trial(game); final Context context = new Context(game, trial); System.gc(); long stopAt = 0L; final long start = System.nanoTime(); final long abortAt = start + (long) Math.ceil(numSeconds * 1000000000L); int numTrials = 0; long numDecisions = 0L; long numPlayerSwitches = 0L; while (stopAt < abortAt) { game.start(context); final Trial endTrial = game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); numDecisions += endTrial.numMoves() - endTrial.numInitialPlacementMoves(); numPlayerSwitches += (context.state().numTurn() - 1); ++numTrials; stopAt = System.nanoTime(); } final TObjectDoubleHashMap<String> map = new TObjectDoubleHashMap<String>(); map.put("Avg Num Decisions", numDecisions / (double) numTrials); map.put("Avg Num Player Switches", numPlayerSwitches / (double) numTrials); map.put("Num Trials", numTrials); return map; } //------------------------------------------------------------------------- /** * Estimates game tree complexity for the given game by running random trials * for the given number of seconds. * * @param gameResource Path for game's resource path * @param userSelections * @param numSeconds * @param forceNoStateRepetitionRule If true, we force the game to use a No State Repetition rule * @return A map from Strings to doubles: <br> * "Avg Num Decisions" --> average number of decisions per trial <br> * "Avg Trial Branching Factor" --> estimated average branching factor per trial <br> * "Estimated Complexity Power" --> power (which 10 should be raised to) of * estimated game tree complexity b^d <br> * "Num Trials" --> number of trials over which we estimated */ public static TObjectDoubleHashMap<String> estimateGameTreeComplexity ( final String gameResource, final UserSelections userSelections, final double numSeconds, final boolean forceNoStateRepetitionRule ) { // WARNING: do NOT modify this method to directly take a compiled game as argument // we may have to modify the game object itself by getting rid of custom playout // implementations, because they cannot properly store all the data we need to store. // First compile our game String desc = ""; // First try to load from memory try ( final BufferedReader rdr = new BufferedReader(new InputStreamReader(Complexity.class.getResourceAsStream(gameResource))) ) { String line; while ((line = rdr.readLine()) != null) desc += line + "\n"; } catch (final Exception e) { // Second try to load from file try ( final BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(gameResource), "UTF-8")); ) { String line; while ((line = rdr.readLine()) != null) desc += line + "\n"; } catch (final Exception e2) { e.printStackTrace(); } } final Game game = (Game)Compiler.compile ( new Description(desc), userSelections, new Report(), false ); // disable custom playout implementations if they cannot properly store history of legal moves per state game.disableMemorylessPlayouts(); if (forceNoStateRepetitionRule) game.metaRules().setRepetitionType(RepetitionType.Positional); final Trial trial = new Trial(game); final Context context = new Context(game, trial); trial.storeLegalMovesHistorySizes(); System.gc(); long stopAt = 0L; final long start = System.nanoTime(); final long abortAt = start + (long) Math.ceil(numSeconds * 1000000000L); int numTrials = 0; long sumNumDecisions = 0L; double sumAvgTrialBranchingFactors = 0.0; while (stopAt < abortAt) { game.start(context); final Trial endTrial = game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); final int numDecisions = endTrial.numMoves() - endTrial.numInitialPlacementMoves(); long trialSumBranchingFactors = 0L; final TIntArrayList branchingFactors = endTrial.auxilTrialData().legalMovesHistorySizes(); for (int i = 0; i < branchingFactors.size(); ++i) { trialSumBranchingFactors += branchingFactors.getQuick(i); } sumAvgTrialBranchingFactors += trialSumBranchingFactors / (double) numDecisions; sumNumDecisions += numDecisions; ++numTrials; stopAt = System.nanoTime(); } final TObjectDoubleHashMap<String> map = new TObjectDoubleHashMap<String>(); final double d = sumNumDecisions / (double) numTrials; final double b = sumAvgTrialBranchingFactors / numTrials; map.put("Avg Num Decisions", d); map.put("Avg Trial Branching Factor", b); map.put("Estimated Complexity Power", d * Math.log10(b)); map.put("Num Trials", numTrials); return map; } //------------------------------------------------------------------------- }
9,681
30.333333
123
java
Ludii
Ludii-master/Evaluation/src/experiments/fastGameLengths/FastGameLengths.java
package experiments.fastGameLengths; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import game.Game; import gnu.trove.list.array.TIntArrayList; import main.Constants; import main.Status; import main.math.statistics.Stats; import other.AI; import other.GameLoader; import other.context.Context; import other.model.Model; import other.trial.Trial; import search.flat.HeuristicSampling; import search.mcts.MCTS; import search.mcts.backpropagation.MonteCarloBackprop; import search.mcts.finalmoveselection.RobustChild; import search.mcts.playout.HeuristicPlayout; import search.mcts.selection.UCB1; import search.minimax.AlphaBetaSearch; //----------------------------------------------------------------------------- /** * Experiments to test Heuristic Sampling for fast game length estimates. * @author cambolbro */ public class FastGameLengths { // Expected game lengths are from the Game Complexity wikipedia page: // https://en.wikipedia.org/wiki/Game_complexity // -1 means average game length is not know for this game. private final List<String> output = new ArrayList<>(); /** Decimal format for printing. */ private final static DecimalFormat df = new DecimalFormat("#.###"); public enum GameName { //ArdRi(2, -1), Breakthrough(2, -1), //Hnefatafl(2, -1), //Oware(3, 60), //Tablut(4, -1), //Reversi(2, 58), //Quoridor(1, 150), //Go(1, 150), //Hex(2, 50), //Connect6(2, 30), //Domineering(2, 30), //Amazons(3, 84), //Fanorona(2, 44), //Yavalath(4, -1), NineMensMorris(3, 50), TicTacToe(3, 9), ConnectFour(3, 36), EnglishDraughts(3, 70), GoMoku(3, 30), LinesOfAction(3, 44), Halma(3, -1), Chess(3, 70), Shogi(3, 115), ; //------------------------------------- private int depth = 0; // search depth private int expected = -1; // expected length //------------------------------------- private GameName(final int depth, final int expected) { this.depth = depth; this.expected = expected; } //------------------------------------- public int depth() { return depth; } public int expected() { return expected; } } //------------------------------------------------------------------------- void test() { //test(GameName.NineMensMorris); for (final GameName gameName : GameName.values()) { //if (gameName.ordinal() >= GameName.EnglishDraughts.ordinal()) //if (gameName.ordinal() >= GameName.Shogi.ordinal()) if (gameName.ordinal() >= GameName.Breakthrough.ordinal()) test(gameName); //break; } } void test(final GameName gameName) { Game game = null; switch (gameName) { case NineMensMorris: game = GameLoader.loadGameFromName("Nine Men's Morris.lud"); break; case Chess: game = GameLoader.loadGameFromName("Chess.lud"); break; case ConnectFour: game = GameLoader.loadGameFromName("Connect Four.lud"); break; case EnglishDraughts: game = GameLoader.loadGameFromName("English Draughts.lud"); break; case GoMoku: game = GameLoader.loadGameFromName("GoMoku.lud"); break; case Halma: game = GameLoader.loadGameFromName("Halma.lud", Arrays.asList("Board Size/6x6")); break; case Breakthrough: game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/6x6")); break; case LinesOfAction: game = GameLoader.loadGameFromName("Lines of Action.lud"); break; case Shogi: game = GameLoader.loadGameFromName("Shogi.lud"); break; case TicTacToe: game = GameLoader.loadGameFromName("Tic-Tac-Toe.lud"); break; } System.out.println("=================================================="); System.out.println("Loaded game " + game.name() + ", " + gameName.expected() + " moves expected."); output.clear(); output.add(" ["); output.add(" [ (" + game.name() + ") " + gameName.expected() + " ]"); try { // lengthRandomParallel(game, 100); // // System.out.println("BF (parallel) = " + branchingFactorParallel(game, 10)); int threshold = 2; for (int hs = 0; hs < 4; hs++) { lengthHS(gameName, game, threshold, true); threshold *= 2; } // if // ( // gameName == GameName.NineMensMorris // || // gameName == GameName.EnglishDraughts // ) // { // // Repeat without HS continuation // threshold = 2; // for (int hs = 0; hs < 4; hs++) // { // lengthHS(gameName, game, threshold, false); // threshold *= 2; // } // } // // for (int depth = 1; depth <= 2; depth++) // //for (int depth = 1; depth <= gameName.depth(); depth++) // lengthAlphaBeta(gameName, game, depth); lengthAlphaBeta(gameName, game, 3); lengthUCT(gameName, game, 1000); //compareUCThs(gameName, game, 1000); } catch (final Exception e) { e.printStackTrace(); } output.add(" ]"); for (final String str : output) System.out.println(str); } //------------------------------------------------------------------------- @SuppressWarnings("static-method") public int gameLength(final Trial trial, final Game game) { //return trial.numLogicalDecisions(game); //return trial.numMoves() - trial.numForcedPasses(); return trial.numTurns() - trial.numForcedPasses(); } //------------------------------------------------------------------------- /** * @param game Single game object shared between threads. */ void compareUCThs ( final GameName gameName, final Game game, final int iterations ) throws Exception { final int MaxTrials = 1000; final long startAt = System.nanoTime(); AI aiA = null; AI aiB = null; System.out.println("\nUCT (" + iterations + " iterations)."); // Run trials concurrently final ExecutorService executor = Executors.newFixedThreadPool(MaxTrials); final List<Future<TrialRecord>> futures = new ArrayList<>(MaxTrials); final CountDownLatch latch = new CountDownLatch(MaxTrials); for (int t = 0; t < MaxTrials; t++) { final int starter = t % 2; final List<AI> ais = new ArrayList<>(); ais.add(null); // null placeholder for player 0 final String heuristicsFilePath = "src/experiments/fastGameLengths/Heuristics_" + gameName + "_Good.txt"; try { //aiA = new AlphaBetaSearch(heuristicsFilePath); aiA = MCTS.createUCT(); aiB = new MCTS ( new UCB1(), new HeuristicPlayout(heuristicsFilePath), new MonteCarloBackprop(), new RobustChild() ); aiB.setFriendlyName("UCThs"); } catch (final Exception e) { e.printStackTrace(); } if (starter == 0) { ais.add(aiA); ais.add(aiB); } else { ais.add(aiB); ais.add(aiA); } futures.add ( executor.submit ( () -> { final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); for (int p = 1; p <= game.players().count(); ++p) ais.get(p).initAI(game, p); final Model model = context.model(); while (!trial.over()) model.startNewStep(context, ais, -1, iterations, -1, 0); final Status status = context.trial().status(); System.out.print(status.winner()); latch.countDown(); return new TrialRecord(starter, trial); } ) ); } latch.await(); // wait for all trials to finish final double secs = (System.nanoTime() - startAt) / 1000000000.0; System.out.println("UCT (" + iterations + ") " + secs + "s (" + (secs / MaxTrials) + "s per game)."); showResults(game, "UCThs Results", MaxTrials, futures, secs); executor.shutdown(); } //------------------------------------------------------------------------- /** * @param game Single game object shared between threads. */ void lengthUCT ( final GameName gameName, final Game game, final int iterations ) throws Exception { final int MaxTrials = 10; //100; //10; final long startAt = System.nanoTime(); AI aiA = null; AI aiB = null; System.out.println("\nUCT (" + iterations + " iterations)."); // Run trials concurrently final ExecutorService executor = Executors.newFixedThreadPool(MaxTrials); final List<Future<TrialRecord>> futures = new ArrayList<>(MaxTrials); final CountDownLatch latch = new CountDownLatch(MaxTrials); for (int t = 0; t < MaxTrials; t++) { final int starter = t % 2; final List<AI> ais = new ArrayList<>(); ais.add(null); // null placeholder for player 0 aiA = MCTS.createUCT(); aiB = MCTS.createUCT(); if (starter == 0) { ais.add(aiA); ais.add(aiB); } else { ais.add(aiB); ais.add(aiA); } //futures.add(future.runTrial(executor, game, ais, starter, iterations)); futures.add ( executor.submit ( () -> { final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); for (int p = 1; p <= game.players().count(); ++p) ais.get(p).initAI(game, p); final Model model = context.model(); while (!trial.over()) model.startNewStep(context, ais, -1, iterations, -1, 0); final Status status = context.trial().status(); System.out.print(status.winner()); latch.countDown(); return new TrialRecord(starter, trial); } ) ); } latch.await(); // wait for all trials to finish final double secs = (System.nanoTime() - startAt) / 1000000000.0; System.out.println("\nUCT (" + iterations + ") " + secs + "s (" + (secs / MaxTrials) + "s per game)."); showResults(game, "UCT", MaxTrials, futures, secs); executor.shutdown(); } //------------------------------------------------------------------------- /** * @param game Single game object shared between threads. */ final void lengthHS ( final GameName gameName, final Game game, final int fraction, final boolean continuation ) throws Exception { final int MaxTrials = 100; final long startAt = System.nanoTime(); AI aiA = null; AI aiB = null; //System.out.println("\nHS (1/" + fraction + ")" + (continuation ? "*" : "") + "."); final String label = "HS 1/" + fraction + (continuation ? "" : "-"); System.out.println("\n" + label + ":"); // Run trials concurrently final ExecutorService executor = Executors.newFixedThreadPool(MaxTrials); final List<Future<TrialRecord>> futures = new ArrayList<>(MaxTrials); final CountDownLatch latch = new CountDownLatch(MaxTrials); for (int t = 0; t < MaxTrials; t++) { final int starter = t % 2; final List<AI> ais = new ArrayList<>(); ais.add(null); // null placeholder for player 0 final String heuristicsFilePath = "src/experiments/fastGameLengths/Heuristics_" + gameName + "_Good.txt"; aiA = new HeuristicSampling(heuristicsFilePath); aiB = new HeuristicSampling(heuristicsFilePath); ((HeuristicSampling)aiA).setThreshold(fraction); ((HeuristicSampling)aiB).setThreshold(fraction); ((HeuristicSampling)aiA).setContinuation(continuation); ((HeuristicSampling)aiB).setContinuation(continuation); if (t % 2 == 0) { ais.add(aiA); ais.add(aiB); } else { ais.add(aiB); ais.add(aiA); } futures.add ( executor.submit ( () -> { final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); for (int p = 1; p <= game.players().count(); ++p) ais.get(p).initAI(game, p); final Model model = context.model(); while (!trial.over()) model.startNewStep(context, ais, -1, -1, 1, 0); latch.countDown(); return new TrialRecord(starter, trial); } ) ); } latch.await(); // wait for all trials to finish final double secs = (System.nanoTime() - startAt) / 1000000000.0; System.out.println("Heuristic Sampling (1/" + fraction + ") " + secs + "s (" + (secs / MaxTrials) + "s per game)."); showResults(game, label, MaxTrials, futures, secs); executor.shutdown(); } //------------------------------------------------------------------------- /** * @param game Single game object shared between threads. */ void lengthAlphaBeta ( final GameName gameName, final Game game, final int depth ) throws Exception { final int MaxTrials = 10; //100; final long startAt = System.nanoTime(); AI aiA = null; AI aiB = null; final String label = "AB " + depth; System.out.println("\n" + label + ":"); // Run trials concurrently final ExecutorService executor = Executors.newFixedThreadPool(MaxTrials); final List<Future<TrialRecord>> futures = new ArrayList<>(MaxTrials); final CountDownLatch latch = new CountDownLatch(MaxTrials); for (int t = 0; t < MaxTrials; t++) { final int starter = t % 2; final List<AI> ais = new ArrayList<>(); ais.add(null); // null placeholder for player 0 final String heuristicsFilePath = "src/experiments/fastGameLengths/Heuristics_" + gameName + "_Good.txt"; aiA = new AlphaBetaSearch(heuristicsFilePath); aiB = new AlphaBetaSearch(heuristicsFilePath); //aiB = new AlphaBetaSearch("src/experiments/fastGameLengths/Heuristics_Tablut_Current.txt"); if (t % 2 == 0) { ais.add(aiA); ais.add(aiB); } else { ais.add(aiB); ais.add(aiA); } futures.add ( executor.submit ( () -> { final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); for (int p = 1; p <= game.players().count(); ++p) ais.get(p).initAI(game, p); final Model model = context.model(); while (!trial.over()) model.startNewStep(context, ais, -1, -1, depth, 0); latch.countDown(); return new TrialRecord(starter, trial); } ) ); } latch.await(); // wait for all trials to finish final double secs = (System.nanoTime() - startAt) / 1000000000.0; System.out.println("Alpha-Beta (" + depth + ") in " + secs + "s (" + (secs / MaxTrials) + "s per game)."); showResults(game, label, MaxTrials, futures, secs); executor.shutdown(); } //------------------------------------------------------------------------- void showResults ( final Game game, final String label, final int numTrials, final List<Future<TrialRecord>> futures, final double secs ) throws Exception { // Accumulate wins per player final Stats stats = new Stats(label); final double[] results = new double[Constants.MAX_PLAYERS + 1]; for (int t = 0; t < numTrials; t++) { final TrialRecord trialRecord = futures.get(t).get(); final Trial trial = trialRecord.trial(); final int length = gameLength(trial, game); //System.out.print((t == 0 ? "\n" : "") + length + " "); if (length < 1000) stats.addSample(gameLength(trial, game)); final int result = trial.status().winner(); //futures.get(t).get().intValue(); if (result == 0) { // Draw: share win results[0] += 0.5; results[1] += 0.5; } else { // Reward winning AI if (trialRecord.starter() == 0) { if (result == 1) results[0]++; else results[1]++; } else { if (result == 1) results[1]++; else results[0]++; } } //System.out.println(trialRecord.starter() + " => " + trial.status().winner()); } //System.out.println("\naiA=" + results[0] + ", aiB=" + results[1] + "."); System.out.println("aiA success rate " + results[0] / numTrials * 100 + "%."); //+ ", aiB=" + results[1] + "."); stats.measure(); stats.showFull(); formatOutput(stats, numTrials, secs); //System.out.println("Expected length is " + (gameName.expected() == -1 ? "not known" : gameName.expected()) + "."); } //------------------------------------------------------------------------- double lengthRandomSerial(final Game game, final int numTrials) { final long startAt = System.nanoTime(); final Trial refTrial = new Trial(game); final Context context = new Context(game, refTrial); final Stats stats = new Stats("Serial Random"); //int totalLength = 0; for (int t = 0; t < numTrials; t++) { game.start(context); final Trial trial = game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); //totalLength += trial.numLogicalDecisions(game); stats.addSample(gameLength(trial, game)); } stats.measure(); final double secs = (System.nanoTime() - startAt) / 1000000000.0; stats.showFull(); System.out.println("Serial in " + secs + "s."); return stats.mean(); } double lengthRandomParallel(final Game game, final int numTrials) throws Exception { final long startAt = System.nanoTime(); final ExecutorService executor = Executors.newFixedThreadPool(numTrials); final List<Future<Trial>> futures = new ArrayList<Future<Trial>>(numTrials); final CountDownLatch latch = new CountDownLatch(numTrials); for (int t = 0; t < numTrials; t++) { final Trial trial = new Trial(game); final Context context = new Context(game, trial); //trial.storeLegalMovesHistorySizes(); futures.add ( executor.submit ( () -> { game.start(context); game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); latch.countDown(); return trial; } ) ); } latch.await(); // wait for all trials to finish // Accumulate lengths over all trials final String label = "Random"; final Stats stats = new Stats(label); //double totalLength = 0; for (int t = 0; t < numTrials; t++) { final Trial trial = futures.get(t).get(); stats.addSample(gameLength(trial, game)); } stats.measure(); final double secs = (System.nanoTime() - startAt) / 1000000000.0; stats.showFull(); System.out.println("Random concurrent in " + secs + "s (" + (secs / numTrials) +"s per game)."); formatOutput(stats, numTrials, secs); executor.shutdown(); return stats.mean(); } void formatOutput(final Stats stats, final int numTrials, final double secs) { output.add ( " [ (" + stats.label() + ") " + stats.n() + " " + df.format(stats.mean()) + " " + (int)stats.min() + " " + (int)stats.max() + " " + df.format(stats.sd()) + " " + df.format(stats.se()) + " " + df.format(stats.ci()) + " " + df.format(secs / numTrials * 1000.0) + " ]" ); } //------------------------------------------------------------------------- // double branchingFactorSerial(final Game game, final int numTrials) // { // final long startAt = System.nanoTime(); // // final Trial trial = new Trial(game); // final Context context = new Context(game, trial); // // int totalDecisions = 0; // // for (int t = 0; t < numTrials; t++) // { // game.start(context); // final Trial endTrial = game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); // final int numDecisions = endTrial.numMoves() - endTrial.numInitialPlacementMoves(); // totalDecisions += numDecisions; // } // // final double secs = (System.nanoTime() - startAt) / 1000000000.0; // System.out.println("BF serial in " + secs + "s."); // // return totalDecisions / (double)numTrials; // } static double branchingFactorParallel ( final Game game, final int numTrials ) throws Exception { //final long startAt = System.nanoTime(); // Disable custom playouts that cannot properly store history of legal moves per state game.disableMemorylessPlayouts(); final ExecutorService executor = Executors.newFixedThreadPool(numTrials); final List<Future<Trial>> futures = new ArrayList<Future<Trial>>(numTrials); final CountDownLatch latch = new CountDownLatch(numTrials); for (int t = 0; t < numTrials; t++) { final Trial trial = new Trial(game); final Context context = new Context(game, trial); trial.storeLegalMovesHistorySizes(); futures.add ( executor.submit ( () -> { game.start(context); game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); latch.countDown(); return trial; } ) ); } latch.await(); // wait for all trials to finish // Accumulate total BFs over all trials double totalBF = 0; for (int t = 0; t < numTrials; t++) { final Trial trial = futures.get(t).get(); //final Trial trial = playedContexts.get(t).get(); final TIntArrayList branchingFactors = trial.auxilTrialData().legalMovesHistorySizes(); double bfAcc = 0; if (branchingFactors.size() > 0) { for (int m = 0; m < branchingFactors.size(); m++) bfAcc += branchingFactors.getQuick(m); bfAcc /= branchingFactors.size(); } totalBF += bfAcc; } //final double secs = (System.nanoTime() - startAt) / 1000000000.0; //System.out.println("secs=" + secs); executor.shutdown(); return totalBF / numTrials; } //------------------------------------------------------------------------- public static void main(final String[] args) { final FastGameLengths sd = new FastGameLengths(); sd.test(); } //------------------------------------------------------------------------- }
21,893
24.577103
118
java
Ludii
Ludii-master/Evaluation/src/experiments/fastGameLengths/TrialRecord.java
package experiments.fastGameLengths; import other.trial.Trial; /** * Record of a trial result for evaluation experiments. * @author cambolbro */ public class TrialRecord { private int starter; private Trial trial; public TrialRecord(final int starter, final Trial trial) { this.starter = starter; this.trial = trial; } public int starter() { return starter; } public Trial trial() { return trial; } }
431
13.4
57
java
Ludii
Ludii-master/Evaluation/src/experiments/fastGameLengths/UCTCounts.java
package experiments.fastGameLengths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import game.Game; import game.rules.play.moves.Moves; import other.AI; import other.GameLoader; import other.context.Context; import other.model.Model; import other.trial.Trial; import search.mcts.MCTS; //----------------------------------------------------------------------------- /** * Experiments to test number of visits per move for low iteration counts. * @author cambolbro */ public class UCTCounts { //------------------------------------------------------------------------- /** * @param game The game to test. */ @SuppressWarnings("static-method") void runUCT(final Game game) { final List<AI> ais = new ArrayList<>(); ais.add(null); // null placeholder for player 0 ais.add(MCTS.createUCT()); ais.add(MCTS.createUCT()); for (int p = 1; p <= game.players().count(); ++p) { ((MCTS)ais.get(p)).setTreeReuse(false); ais.get(p).initAI(game, p); } final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final Model model = context.model(); int turn = 0; while (!trial.over()) { System.out.println("======================\nTurn " + turn + ":"); final Moves moves = game.moves(context); final int bf = moves.count(); System.out.println("State has " + bf + " moves..."); for (int n = 0; n < 10; n++) { final int iterations = bf * (int)Math.pow(2, n); System.out.print("n=" + n + " (" + iterations + " it.s):"); model.startNewStep(context, ais, -1, iterations, -1, 0); } turn++; } System.out.println("Result is: " + trial); } //------------------------------------------------------------------------- void test() { final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/7x7")); System.out.println("=================================================="); //System.out.println("Loaded game " + game.name() + ", " + gameName.expected() + " moves expected."); runUCT(game); } //------------------------------------------------------------------------- public static void main(final String[] args) { final UCTCounts app = new UCTCounts(); app.test(); } //------------------------------------------------------------------------- }
2,384
24.645161
103
java
Ludii
Ludii-master/Evaluation/src/experiments/strategicDimension/FutureTrial.java
package experiments.strategicDimension; import java.util.concurrent.Future; import game.Game; /** * Future trial for concurrent SD trials. * @author cambolbro */ public interface FutureTrial { /** * @param game The single game object, shared across threads. * @param trialId The index of this trial within its epoch. * @param lower Lower iteration count of this epoch for inferior agent. * @param upper Upper iteration count of this epoch for superior agent. * @return Result of trial relative to superior agent (0=loss, 0.5=draw, 1=win). */ public Future<Double> runTrial ( final Game game, final int trialId, final int lower, final int upper ); }
716
27.68
86
java
Ludii
Ludii-master/Evaluation/src/experiments/strategicDimension/FutureTrialAB.java
package experiments.strategicDimension; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import game.Game; import main.Status; import other.AI; import other.context.Context; import other.move.Move; import other.trial.Trial; import search.minimax.AlphaBetaSearch; //----------------------------------------------------------------------------- /** * Thread for running AB version of SD trial. * @author cambolbro */ public class FutureTrialAB implements FutureTrial { private ExecutorService executor = Executors.newSingleThreadExecutor(); /** * @param game The single game object, shared across threads. * @param trialId The index of this trial within its epoch. * @param lower Lower iteration count of this epoch for inferior agent. * @param upper Upper iteration count of this epoch for superior agent. * @return Result of trial relative to superior agent (0=loss, 0.5=draw, 1=win). */ @Override public Future<Double> runTrial ( final Game game, final int trialId, final int lower, final int upper ) { return executor.submit(() -> { //System.out.println("Submitted id=" + id + ", lower=" + lower + ", upper=" + upper + "."); final int numPlayers = game.players().count(); final int pidHigher = 1 + trialId % numPlayers; // alternate between players final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // Set up AIs final List<AI> agents = new ArrayList<AI>(); agents.add(null); // null player 0 for (int pid = 1; pid < numPlayers + 1; pid++) { final AI ai = new AlphaBetaSearch(); ai.initAI(game, pid); agents.add(ai); } while (!context.trial().over()) { final int mover = context.state().mover(); if (mover < 1 || mover > numPlayers) System.out.println("** Bad mover index: " + mover); final AI agent = agents.get(mover); final Move move = agent.selectAction ( game, new Context(context), -1, -1, (mover == pidHigher ? upper : lower) ); game.apply(context, move); //if (trial.numberOfTurns() % 10 == 0) // System.out.print("."); } //System.out.println(trialId + ": " + context.trial().status() + " (P" + pidHigher + " is superior)."); final Status status = context.trial().status(); System.out.print(status.winner()); if (status.winner() == 0) return Double.valueOf(0.5); // is a draw if (status.winner() == pidHigher) return Double.valueOf(1); // superior player wins return Double.valueOf(0); // superior player does not win }); } }
2,886
28.459184
106
java
Ludii
Ludii-master/Evaluation/src/experiments/strategicDimension/FutureTrialMC.java
package experiments.strategicDimension; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import game.Game; import main.Status; import other.AI; import other.context.Context; import other.move.Move; import other.trial.Trial; import search.mcts.MCTS; /** * Thread for running MC version of SD trial. * @author cambolbro */ public class FutureTrialMC implements FutureTrial { private ExecutorService executor = Executors.newSingleThreadExecutor(); /** * @param game The single game object, shared across threads. * @param trialId The index of this trial within its epoch. * @param lower Lower iteration count of this epoch for inferior agent. * @param upper Upper iteration count of this epoch for superior agent. * @return Result of trial relative to superior agent (0=loss, 0.5=draw, 1=win). */ @Override public Future<Double> runTrial ( final Game game, final int trialId, final int lower, final int upper ) { return executor.submit(() -> { //System.out.println("Submitted id=" + id + ", lower=" + lower + ", upper=" + upper + "."); final int numPlayers = game.players().count(); final int pidHigher = 1 + trialId % 2; // alternate between P1 and P2 final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // Set up AIs final List<AI> agents = new ArrayList<AI>(); agents.add(null); // null player 0 for (int pid = 1; pid < numPlayers + 1; pid++) { final AI ai = MCTS.createUCT(); ai.initAI(game, pid); agents.add(ai); } while (!context.trial().over()) { final int mover = context.state().mover(); final AI agent = agents.get(mover); final Move move = agent.selectAction ( game, new Context(context), -1, (mover == pidHigher ? upper : lower), -1 ); game.apply(context, move); //if (trial.numberOfTurns() % 10 == 0) // System.out.print("."); } //System.out.println(trialId + ": " + context.trial().status() + " (P" + pidHigher + " is superior)."); final Status status = context.trial().status(); System.out.print(status.winner()); if (status.winner() == 0) return Double.valueOf(0.5); // is a draw if (status.winner() == pidHigher) return Double.valueOf(1); // higher iteration count wins return Double.valueOf(0); }); } }
2,648
27.483871
106
java
Ludii
Ludii-master/Evaluation/src/experiments/strategicDimension/StrategicDimension.java
package experiments.strategicDimension; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import game.Game; import gnu.trove.list.array.TIntArrayList; import other.GameLoader; import other.context.Context; import other.trial.Trial; //----------------------------------------------------------------------------- /** * Experiments to test Strategic Dimension. * @author cambolbro */ public class StrategicDimension { static void test() { //final Game game = GameLoader.loadGameFromName("Tic-Tac-Toe.lud"); //final Game game = GameLoader.loadGameFromName("Breakthrough.lud"); //final Game game = GameLoader.loadGameFromName("Chess.lud"); //final Game game = GameLoader.loadGameFromName("Amazons.lud"); //final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/4x4")); //final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/5x5")); //final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/6x6")); //final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/7x7")); final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/8x8")); //final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/9x9")); //final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/10x10")); //final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/11x11")); //final Game game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/12x12")); //final Game game = GameLoader.loadGameFromName("Breakthrough (No AI).lud", Arrays.asList("Board Size/4x4")); //final Game game = GameLoader.loadGameFromName("Breakthrough (No AI).lud", Arrays.asList("Board Size/5x5")); //final Game game = GameLoader.loadGameFromName("Breakthrough (No AI).lud", Arrays.asList("Board Size/6x6")); //final Game game = GameLoader.loadGameFromName("Breakthrough (No AI).lud", Arrays.asList("Board Size/7x7")); //final Game game = GameLoader.loadGameFromName("Breakthrough (No AI).lud", Arrays.asList("Board Size/8x8")); System.out.println("Game " + game.name() + " loaded."); // game.disableMemorylessPlayouts(); final double bf = branchingFactorParallel(game); System.out.println("Average branching factor is " + bf + "."); // Run pairings //final List<Double> winRates = runEpochs(game, Double.valueOf(bf)); final List<Double> winRates = runEpochs(game, null); System.out.println("Win rates are: " + winRates); // Estimate SD // ... } //------------------------------------------------------------------------- /** * @param game Single game object shared between threads. * @param bf Average branching factor (null for AB search). * @return List of superior win rates for each epoch. */ final static List<Double> runEpochs(final Game game, final Double bf) { final int NUM_EPOCHS = 4; final int TRIALS_PER_EPOCH = 50; final boolean isMC = (bf != null); final List<Double> winRates = new ArrayList<>(); int baseIterations = isMC ? (int)(bf.doubleValue() / 4 + 0.5) : 0; // Generate result for each pairing for (int epoch = 0; epoch < NUM_EPOCHS; epoch++) { final int lower = isMC ? baseIterations : epoch + 1; final int upper = isMC ? lower * 2 : lower + 1; System.out.println("\nEpoch " + epoch + ": " + lower + " vs " + upper + "..."); // Run trials concurrently final List<Future<Double>> results = new ArrayList<>(TRIALS_PER_EPOCH); for (int t = 0; t < TRIALS_PER_EPOCH; t++) { final FutureTrial future = isMC ? new FutureTrialMC() : new FutureTrialAB(); results.add(future.runTrial(game, t, lower, upper)); } // Accumulate win rates for superior agent over all trials double winRate = 0; try { for (int t = 0; t < TRIALS_PER_EPOCH; t++) winRate += results.get(t).get().doubleValue(); } catch (final InterruptedException | ExecutionException e) { e.printStackTrace(); //fail(); } winRate /= TRIALS_PER_EPOCH; winRates.add(Double.valueOf(winRate)); System.out.println("\nSuperior win rate is " + winRate + "."); // Step to next iteration baseIterations = upper; } return winRates; } //------------------------------------------------------------------------- static double branchingFactor(final Game game) { final int NUM_TRIALS = 10; //final long startAt = System.nanoTime(); final Trial trial = new Trial(game); final Context context = new Context(game, trial); int totalDecisions = 0; for (int t = 0; t < NUM_TRIALS; t++) { game.start(context); final Trial endTrial = game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); final int numDecisions = endTrial.numMoves() - endTrial.numInitialPlacementMoves(); totalDecisions += numDecisions; } //final double secs = (System.nanoTime() - startAt) / 1000000000.0; //System.out.println("secs=" + secs); return totalDecisions / (double)NUM_TRIALS; } static double branchingFactorParallel(final Game game) { final int NUM_TRIALS = 10; //final long startAt = System.nanoTime(); final ExecutorService executorService = Executors.newFixedThreadPool(NUM_TRIALS); final List<Future<Context>> playedContexts = new ArrayList<Future<Context>>(NUM_TRIALS); for (int t = 0; t < NUM_TRIALS; t++) { final Trial trial = new Trial(game); final Context context = new Context(game, trial); trial.storeLegalMovesHistorySizes(); playedContexts.add ( executorService.submit ( () -> { game.start(context); game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); return context; } ) ); } // Accumulate total BFs over all trials double totalBF = 0; try { for (int t = 0; t < NUM_TRIALS; t++) { final Context context = playedContexts.get(t).get(); final TIntArrayList branchingFactors = context.trial().auxilTrialData().legalMovesHistorySizes(); int bfAcc = 0; for (int m = 0; m < branchingFactors.size(); m++) bfAcc += branchingFactors.getQuick(m); final double avgBfThisTrial = bfAcc / (double)branchingFactors.size(); totalBF += avgBfThisTrial; } } catch (final InterruptedException | ExecutionException e) { e.printStackTrace(); //fail(); } //final double secs = (System.nanoTime() - startAt) / 1000000000.0; //System.out.println("secs=" + secs); return totalBF / NUM_TRIALS; } //------------------------------------------------------------------------- public static void main(String[] args) { StrategicDimension.test(); } //------------------------------------------------------------------------- }
7,176
31.922018
111
java
Ludii
Ludii-master/Evaluation/src/experiments/testUCThs/TestUCThs.java
package experiments.testUCThs; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import experiments.fastGameLengths.TrialRecord; import game.Game; import gnu.trove.list.array.TIntArrayList; import main.Constants; import main.Status; import main.math.statistics.Stats; import other.AI; import other.GameLoader; import other.context.Context; import other.model.Model; import other.trial.Trial; import search.mcts.MCTS; import search.mcts.backpropagation.MonteCarloBackprop; import search.mcts.finalmoveselection.RobustChild; import search.mcts.playout.HeuristicPlayout; import search.mcts.selection.UCB1; import search.minimax.AlphaBetaSearch; //----------------------------------------------------------------------------- /** * Experiments to test Heuristic Sampling for fast game length estimates. * @author cambolbro */ public class TestUCThs { // Expected game lengths are from the Game Complexity wikipedia page: // https://en.wikipedia.org/wiki/Game_complexity // -1 means average game length is not know for this game. private final List<String> output = new ArrayList<>(); /** Decimal format for printing. */ private final static DecimalFormat df = new DecimalFormat("#.###"); public enum GameName { //ArdRi(2, -1), Breakthrough(2, -1), //Hnefatafl(2, -1), //Oware(3, 60), Tablut(4, -1), //Reversi(2, 58), //Quoridor(1, 150), //Go(1, 150), //Hex(2, 50), //Connect6(2, 30), //Domineering(2, 30), //Amazons(3, 84), //Fanorona(2, 44), Yavalath(4, -1), Clobber(3, -1), NineMensMorris(3, 50), TicTacToe(3, 9), ConnectFour(3, 36), EnglishDraughts(3, 70), GoMoku(3, 30), LinesOfAction(3, 44), Halma(3, -1), Chess(3, 70), Shogi(3, 115), ; //------------------------------------- private int depth = 0; // search depth private int expected = -1; // expected length //------------------------------------- private GameName(final int depth, final int expected) { this.depth = depth; this.expected = expected; } //------------------------------------- public int depth() { return depth; } public int expected() { return expected; } } //------------------------------------------------------------------------- void test() { // test(GameName.TicTacToe); // test(GameName.Yavalath); // test(GameName.Tablut); // test(GameName.Halma); // test(GameName.NineMensMorris); // test(GameName.Breakthrough); test(GameName.ConnectFour); // test(GameName.Clobber); // for (final GameName gameName : GameName.values()) // test(gameName); } void test(final GameName gameName) { Game game = null; switch (gameName) { case Tablut: game = GameLoader.loadGameFromName("Tablut.lud"); break; case Yavalath: game = GameLoader.loadGameFromName("Yavalath.lud"); //, Arrays.asList("Board Size/4x4")); break; case Clobber: game = GameLoader.loadGameFromName("Clobber.lud", Arrays.asList("Rows/6", "Columns/6")); break; case NineMensMorris: game = GameLoader.loadGameFromName("Nine Men's Morris.lud"); break; case Chess: game = GameLoader.loadGameFromName("Chess.lud"); break; case ConnectFour: game = GameLoader.loadGameFromName("Connect Four.lud"); break; case EnglishDraughts: game = GameLoader.loadGameFromName("English Draughts.lud"); break; case GoMoku: game = GameLoader.loadGameFromName("GoMoku.lud"); break; case Halma: game = GameLoader.loadGameFromName("Halma.lud", Arrays.asList("Board Size/6x6")); break; case Breakthrough: game = GameLoader.loadGameFromName("Breakthrough.lud", Arrays.asList("Board Size/6x6")); break; case LinesOfAction: game = GameLoader.loadGameFromName("Lines of Action.lud"); break; case Shogi: game = GameLoader.loadGameFromName("Shogi.lud"); break; case TicTacToe: game = GameLoader.loadGameFromName("Tic-Tac-Toe.lud"); break; } System.out.println("=================================================="); System.out.println("Loaded game " + game.name() + "."); output.clear(); output.add(" ["); output.add(" [ (" + game.name() + ") ]"); try { final int depth = 4; final double bf = branchingFactorParallel(game, 10); final int fullMinimax = (int)(Math.pow(bf, depth) + 0.5); // similar to N-ply minimax search final int iterations = (int)(Math.sqrt(fullMinimax) + 0.5); // similar to N-ply AB search System.out.println("depth=" + depth + ", BF=" + bf + ", iterations=" + iterations + "."); compareUCThs(gameName, game, iterations, depth); } catch (final Exception e) { e.printStackTrace(); } output.add(" ]"); for (final String str : output) System.out.println(str); } //------------------------------------------------------------------------- public static int gameLength(final Trial trial, final Game game) { //return trial.numLogicalDecisions(game); //return trial.numMoves() - trial.numForcedPasses(); return trial.numTurns() - trial.numForcedPasses(); } //------------------------------------------------------------------------- /** * @param game Single game object shared between threads. */ static void compareUCThs ( final GameName gameName, final Game game, final int iterations, final int depth ) throws Exception { final int MaxTrials = 1000; final long startAt = System.nanoTime(); AI aiA = null; AI aiB = null; System.out.println("\nUCT (" + iterations + " iterations)."); // Run trials concurrently final ExecutorService executor = Executors.newFixedThreadPool(MaxTrials); final List<Future<TrialRecord>> futures = new ArrayList<>(MaxTrials); final CountDownLatch latch = new CountDownLatch(MaxTrials); for (int t = 0; t < MaxTrials; t++) { final int starter = t % 2; final List<AI> ais = new ArrayList<>(); ais.add(null); // null placeholder for player 0 final String heuristicsFilePath = "src/experiments/fastGameLengths/Heuristics_" + gameName + "_Good.txt"; try { aiA = new AlphaBetaSearch(heuristicsFilePath); //aiA = MCTS.createUCT(); //aiA = new RandomAI(); //aiB = MCTS.createUCT(); // aiA = new MCTS // ( // new UCB1(), // new HeuristicPlayout(heuristicsFilePath), // new RobustChild() // ); // aiA.setFriendlyName("UCThs1/1"); aiB = new MCTS ( new UCB1(), new HeuristicPlayout(heuristicsFilePath), new MonteCarloBackprop(), new RobustChild() ); aiB.setFriendlyName("UCThs1/1"); //aiB = new RandomAI(); } catch (final Exception e) { e.printStackTrace(); } // Alternate which AI starts if (starter == 0) { ais.add(aiA); ais.add(aiB); } else { ais.add(aiB); ais.add(aiA); } futures.add ( executor.submit ( () -> { final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); for (int p = 1; p <= game.players().count(); ++p) ais.get(p).initAI(game, p); final Model model = context.model(); while (!trial.over()) model.startNewStep(context, ais, -1, iterations, depth, 0); final Status status = context.trial().status(); System.out.print(status.winner()); latch.countDown(); return new TrialRecord(starter, trial); } ) ); } latch.await(); // wait for all trials to finish final double secs = (System.nanoTime() - startAt) / 1000000000.0; System.out.println("UCT (" + iterations + ") " + secs + "s (" + (secs / MaxTrials) + "s per game)."); showResults(game, "UCThs Results", MaxTrials, futures, secs, aiA, aiB); executor.shutdown(); } //------------------------------------------------------------------------- // /** // * @param game Single game object shared between threads. // */ // void lengthUCT // ( // final GameName gameName, final Game game, final int iterations // ) throws Exception // { // final int MaxTrials = 10; //100; //10; // // final long startAt = System.nanoTime(); // // AI aiA = null; // AI aiB = null; // // System.out.println("\nUCT (" + iterations + " iterations)."); // // // Run trials concurrently // final ExecutorService executor = Executors.newFixedThreadPool(MaxTrials); // final List<Future<TrialRecord>> futures = new ArrayList<>(MaxTrials); // // final CountDownLatch latch = new CountDownLatch(MaxTrials); // // for (int t = 0; t < MaxTrials; t++) // { // final int starter = t % 2; // // final List<AI> ais = new ArrayList<>(); // ais.add(null); // null placeholder for player 0 // // aiA = MCTS.createUCT(); // aiB = MCTS.createUCT(); // // if (starter == 0) // { // ais.add(aiA); // ais.add(aiB); // } // else // { // ais.add(aiB); // ais.add(aiA); // } // // //futures.add(future.runTrial(executor, game, ais, starter, iterations)); // futures.add // ( // executor.submit // ( // () -> // { // final Trial trial = new Trial(game); // final Context context = new Context(game, trial); // // game.start(context); // // for (int p = 1; p <= game.players().count(); ++p) // ais.get(p).initAI(game, p); // // final Model model = context.model(); // while (!trial.over()) // model.startNewStep(context, ais, -1, iterations, -1, 0); // // final Status status = context.trial().status(); // System.out.print(status.winner()); // // latch.countDown(); // // return new TrialRecord(starter, trial); // } // ) // ); // } // // latch.await(); // wait for all trials to finish // // final double secs = (System.nanoTime() - startAt) / 1000000000.0; // System.out.println("\nUCT (" + iterations + ") " + secs + "s (" + (secs / MaxTrials) + "s per game)."); // // showResults(game, "UCT", MaxTrials, futures, secs); // // executor.shutdown(); // } // // //------------------------------------------------------------------------- // // /** // * @param game Single game object shared between threads. // */ // final void lengthHS // ( // final GameName gameName, final Game game, // final int fraction, final boolean continuation // ) throws Exception // { // final int MaxTrials = 100; // // final long startAt = System.nanoTime(); // // AI aiA = null; // AI aiB = null; // // //System.out.println("\nHS (1/" + fraction + ")" + (continuation ? "*" : "") + "."); // final String label = "HS 1/" + fraction + (continuation ? "" : "-"); // System.out.println("\n" + label + ":"); // // // Run trials concurrently // final ExecutorService executor = Executors.newFixedThreadPool(MaxTrials); // final List<Future<TrialRecord>> futures = new ArrayList<>(MaxTrials); // // final CountDownLatch latch = new CountDownLatch(MaxTrials); // // for (int t = 0; t < MaxTrials; t++) // { // final int starter = t % 2; // // final List<AI> ais = new ArrayList<>(); // ais.add(null); // null placeholder for player 0 // // final String heuristicsFilePath = "src/experiments/fastGameLengths/Heuristics_" + gameName + "_Good.txt"; // aiA = new HeuristicSampling(heuristicsFilePath); // aiB = new HeuristicSampling(heuristicsFilePath); // // ((HeuristicSampling)aiA).setThreshold(fraction); // ((HeuristicSampling)aiB).setThreshold(fraction); // // ((HeuristicSampling)aiA).setContinuation(continuation); // ((HeuristicSampling)aiB).setContinuation(continuation); // // if (t % 2 == 0) // { // ais.add(aiA); // ais.add(aiB); // } // else // { // ais.add(aiB); // ais.add(aiA); // } // // futures.add // ( // executor.submit // ( // () -> // { // final Trial trial = new Trial(game); // final Context context = new Context(game, trial); // // game.start(context); // // for (int p = 1; p <= game.players().count(); ++p) // ais.get(p).initAI(game, p); // // final Model model = context.model(); // while (!trial.over()) // model.startNewStep(context, ais, -1, -1, 1, 0); // // latch.countDown(); // // return new TrialRecord(starter, trial); // } // ) // ); // } // // latch.await(); // wait for all trials to finish // // final double secs = (System.nanoTime() - startAt) / 1000000000.0; // System.out.println("Heuristic Sampling (1/" + fraction + ") " + secs + "s (" + (secs / MaxTrials) + "s per game)."); // // showResults(game, label, MaxTrials, futures, secs); // // executor.shutdown(); // } // // //------------------------------------------------------------------------- // // /** // * @param game Single game object shared between threads. // */ // void lengthAlphaBeta // ( // final GameName gameName, final Game game, final int depth // ) throws Exception // { // final int MaxTrials = 10; //100; // // final long startAt = System.nanoTime(); // // AI aiA = null; // AI aiB = null; // // final String label = "AB " + depth; // System.out.println("\n" + label + ":"); // // // Run trials concurrently // final ExecutorService executor = Executors.newFixedThreadPool(MaxTrials); // final List<Future<TrialRecord>> futures = new ArrayList<>(MaxTrials); // // final CountDownLatch latch = new CountDownLatch(MaxTrials); // // for (int t = 0; t < MaxTrials; t++) // { // final int starter = t % 2; // // final List<AI> ais = new ArrayList<>(); // ais.add(null); // null placeholder for player 0 // // final String heuristicsFilePath = "src/experiments/fastGameLengths/Heuristics_" + gameName + "_Good.txt"; // aiA = new AlphaBetaSearch(heuristicsFilePath); // aiB = new AlphaBetaSearch(heuristicsFilePath); // //aiB = new AlphaBetaSearch("src/experiments/fastGameLengths/Heuristics_Tablut_Current.txt"); // // if (t % 2 == 0) // { // ais.add(aiA); // ais.add(aiB); // } // else // { // ais.add(aiB); // ais.add(aiA); // } // // futures.add // ( // executor.submit // ( // () -> // { // final Trial trial = new Trial(game); // final Context context = new Context(game, trial); // // game.start(context); // // for (int p = 1; p <= game.players().count(); ++p) // ais.get(p).initAI(game, p); // // final Model model = context.model(); // while (!trial.over()) // model.startNewStep(context, ais, -1, -1, depth, 0); // // latch.countDown(); // // return new TrialRecord(starter, trial); // } // ) // ); // } // // latch.await(); // wait for all trials to finish // // // final double secs = (System.nanoTime() - startAt) / 1000000000.0; // System.out.println("Alpha-Beta (" + depth + ") in " + secs + "s (" + (secs / MaxTrials) + "s per game)."); // // showResults(game, label, MaxTrials, futures, secs); // // executor.shutdown(); // } // //------------------------------------------------------------------------- static void showResults ( final Game game, final String label, final int numTrials, final List<Future<TrialRecord>> futures, final double secs, final AI aiA, final AI aiB ) throws Exception { // Accumulate wins per player final Stats statsA = new Stats(label); final Stats statsB = new Stats(label); final double[] results = new double[Constants.MAX_PLAYERS + 1]; for (int t = 0; t < numTrials; t++) { final TrialRecord trialRecord = futures.get(t).get(); final Trial trial = trialRecord.trial(); //final int length = gameLength(trial, game); //System.out.print((t == 0 ? "\n" : "") + length + " "); final int result = trial.status().winner(); //futures.get(t).get().intValue(); if (result == 0) { // Draw: share win results[0] += 0.5; results[1] += 0.5; } else { // Reward winning AI if (trialRecord.starter() == 0) { if (result == 1) results[0]++; else results[1]++; } else { if (result == 1) results[1]++; else results[0]++; } } double resultA = 0; double resultB = 0; if (result == 0) { // Draw resultA = 0.5; resultB = 0.5; } else { if (trialRecord.starter() == 0) { if (result == 1) resultA = 1; else resultB = 1; } else { if (result == 1) resultB = 1; else resultA = 1; } } statsA.addSample(resultA); statsB.addSample(resultB); //System.out.println(trialRecord.starter() + " => " + trial.status().winner()); } //System.out.println("\naiA=" + results[0] + ", aiB=" + results[1] + "."); System.out.println(aiA.friendlyName() + " success rate " + results[0] * 100.0 / numTrials + "%."); //+ ", aiB=" + results[1] + "."); System.out.println(aiB.friendlyName() + " success rate " + results[1] * 100.0 / numTrials + "%."); //+ ", aiB=" + results[1] + "."); statsA.measure(); System.out.print(aiA.friendlyName()); statsA.showFull(); statsB.measure(); System.out.print(aiB.friendlyName()); statsB.showFull(); //formatOutput(stats, numTrials, secs); //System.out.println("Expected length is " + (gameName.expected() == -1 ? "not known" : gameName.expected()) + "."); } //------------------------------------------------------------------------- static double lengthRandomSerial(final Game game, final int numTrials) { final long startAt = System.nanoTime(); final Trial refTrial = new Trial(game); final Context context = new Context(game, refTrial); final Stats stats = new Stats("Serial Random"); //int totalLength = 0; for (int t = 0; t < numTrials; t++) { game.start(context); final Trial trial = game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); //totalLength += trial.numLogicalDecisions(game); stats.addSample(gameLength(trial, game)); } stats.measure(); final double secs = (System.nanoTime() - startAt) / 1000000000.0; stats.showFull(); System.out.println("Serial in " + secs + "s."); return stats.mean(); } double lengthRandomParallel(final Game game, final int numTrials) throws Exception { final long startAt = System.nanoTime(); final ExecutorService executor = Executors.newFixedThreadPool(numTrials); final List<Future<Trial>> futures = new ArrayList<Future<Trial>>(numTrials); final CountDownLatch latch = new CountDownLatch(numTrials); for (int t = 0; t < numTrials; t++) { final Trial trial = new Trial(game); final Context context = new Context(game, trial); //trial.storeLegalMovesHistorySizes(); futures.add ( executor.submit ( () -> { game.start(context); game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); latch.countDown(); return trial; } ) ); } latch.await(); // wait for all trials to finish // Accumulate lengths over all trials final String label = "Random"; final Stats stats = new Stats(label); //double totalLength = 0; for (int t = 0; t < numTrials; t++) { final Trial trial = futures.get(t).get(); stats.addSample(gameLength(trial, game)); } stats.measure(); final double secs = (System.nanoTime() - startAt) / 1000000000.0; stats.showFull(); System.out.println("Random concurrent in " + secs + "s (" + (secs / numTrials) +"s per game)."); formatOutput(stats, numTrials, secs); executor.shutdown(); return stats.mean(); } //------------------------------------------------------------------------- void formatOutput(final Stats stats, final int numTrials, final double secs) { output.add ( " [ (" + stats.label() + ") " + stats.n() + " " + df.format(stats.mean()) + " " + (int)stats.min() + " " + (int)stats.max() + " " + df.format(stats.sd()) + " " + df.format(stats.se()) + " " + df.format(stats.ci()) + " " + df.format(secs / numTrials * 1000.0) + " ]" ); } //------------------------------------------------------------------------- // double branchingFactorSerial(final Game game, final int numTrials) // { // final long startAt = System.nanoTime(); // // final Trial trial = new Trial(game); // final Context context = new Context(game, trial); // // int totalDecisions = 0; // // for (int t = 0; t < numTrials; t++) // { // game.start(context); // final Trial endTrial = game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); // final int numDecisions = endTrial.numMoves() - endTrial.numInitialPlacementMoves(); // totalDecisions += numDecisions; // } // // final double secs = (System.nanoTime() - startAt) / 1000000000.0; // System.out.println("BF serial in " + secs + "s."); // // return totalDecisions / (double)numTrials; // } static double branchingFactorParallel ( final Game game, final int numTrials ) throws Exception { //final long startAt = System.nanoTime(); // Disable custom playouts that cannot properly store history of legal moves per state game.disableMemorylessPlayouts(); final ExecutorService executor = Executors.newFixedThreadPool(numTrials); final List<Future<Trial>> futures = new ArrayList<Future<Trial>>(numTrials); final CountDownLatch latch = new CountDownLatch(numTrials); for (int t = 0; t < numTrials; t++) { final Trial trial = new Trial(game); final Context context = new Context(game, trial); trial.storeLegalMovesHistorySizes(); futures.add ( executor.submit ( () -> { game.start(context); game.playout(context, null, 1.0, null, -1, -1, ThreadLocalRandom.current()); latch.countDown(); return trial; } ) ); } latch.await(); // wait for all trials to finish // Accumulate total BFs over all trials double totalBF = 0; for (int t = 0; t < numTrials; t++) { final Trial trial = futures.get(t).get(); //final Trial trial = playedContexts.get(t).get(); final TIntArrayList branchingFactors = trial.auxilTrialData().legalMovesHistorySizes(); double bfAcc = 0; if (branchingFactors.size() > 0) { for (int m = 0; m < branchingFactors.size(); m++) bfAcc += branchingFactors.getQuick(m); bfAcc /= branchingFactors.size(); } totalBF += bfAcc; } //final double secs = (System.nanoTime() - startAt) / 1000000000.0; //System.out.println("secs=" + secs); executor.shutdown(); return totalBF / numTrials; } //------------------------------------------------------------------------- public static void main(final String[] args) { final TestUCThs app = new TestUCThs(); app.test(); } //------------------------------------------------------------------------- }
23,362
25.191704
135
java
Ludii
Ludii-master/Evaluation/src/metrics/Evaluation.java
package metrics; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import metrics.designer.IdealDuration; import metrics.designer.SkillTrace; import metrics.multiple.MultiMetricFramework.MultiMetricValue; import metrics.multiple.metrics.BoardSitesOccupied; import metrics.multiple.metrics.BranchingFactor; import metrics.multiple.metrics.DecisionFactor; import metrics.multiple.metrics.Drama; import metrics.multiple.metrics.MoveDistance; import metrics.multiple.metrics.MoveEvaluation; import metrics.multiple.metrics.PieceNumber; import metrics.multiple.metrics.ScoreDifference; import metrics.multiple.metrics.StateEvaluationDifference; import metrics.single.boardCoverage.BoardCoverageDefault; import metrics.single.boardCoverage.BoardCoverageFull; import metrics.single.boardCoverage.BoardCoverageUsed; import metrics.single.complexity.DecisionMoves; import metrics.single.complexity.GameTreeComplexity; import metrics.single.complexity.StateSpaceComplexity; import metrics.single.duration.DurationActions; import metrics.single.duration.DurationMoves; import metrics.single.duration.DurationTurns; import metrics.single.duration.DurationTurnsNotTimeouts; import metrics.single.duration.DurationTurnsStdDev; import metrics.single.outcome.AdvantageP1; import metrics.single.outcome.Balance; import metrics.single.outcome.Completion; import metrics.single.outcome.Drawishness; import metrics.single.outcome.OutcomeUniformity; import metrics.single.outcome.Timeouts; import metrics.single.stateEvaluation.LeadChange; import metrics.single.stateEvaluation.Stability; import metrics.single.stateEvaluation.clarity.ClarityNarrowness; import metrics.single.stateEvaluation.clarity.ClarityVariance; import metrics.single.stateEvaluation.decisiveness.DecisivenessMoves; import metrics.single.stateEvaluation.decisiveness.DecisivenessThreshold; import metrics.single.stateRepetition.PositionalRepetition; import metrics.single.stateRepetition.SituationalRepetition; import other.concept.Concept; //----------------------------------------------------------------------------- /** * Access point for evaluation functionality. * * @author cambolbro and matthew.stephenson */ public class Evaluation { public static final int MAX_ENTRIES = (int) Math.pow(2, 20); // Cached state evaluations private final LinkedHashMap<Long, Double> stateEvaluationCache = new LinkedHashMap<Long, Double>() { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(final Map.Entry<Long, Double> eldest) { return size() > MAX_ENTRIES; } }; private final LinkedHashMap<Long, Double> stateAfterMoveEvaluationCache = new LinkedHashMap<Long, Double>() { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(final Map.Entry<Long, Double> eldest) { return size() > MAX_ENTRIES; } }; private final List<Metric> dialogMetrics = new ArrayList<>(); { // Outcome dialogMetrics.add(new AdvantageP1()); dialogMetrics.add(new Balance()); dialogMetrics.add(new Completion()); dialogMetrics.add(new Drawishness()); dialogMetrics.add(new Timeouts()); // Other dialogMetrics.add(new BoardCoverageDefault()); dialogMetrics.add(new DecisivenessMoves()); // Designer dialogMetrics.add(new IdealDuration()); dialogMetrics.add(new SkillTrace()); } //------------------------------------------------------------------------- private final List<Metric> reconstructionMetrics = new ArrayList<>(); { reconstructionMetrics.add(new DurationTurns()); reconstructionMetrics.add(new DurationTurnsStdDev()); reconstructionMetrics.add(new DurationTurnsNotTimeouts()); reconstructionMetrics.add(new Timeouts()); reconstructionMetrics.add(new DecisionMoves()); reconstructionMetrics.add(new BoardCoverageDefault()); reconstructionMetrics.add(new AdvantageP1()); reconstructionMetrics.add(new Balance()); reconstructionMetrics.add(new Completion()); reconstructionMetrics.add(new Drawishness()); reconstructionMetrics.add(new PieceNumber(MultiMetricValue.Average, Concept.PieceNumberAverage)); reconstructionMetrics.add(new BoardSitesOccupied(MultiMetricValue.Average, Concept.BoardSitesOccupiedAverage)); reconstructionMetrics.add(new BranchingFactor(MultiMetricValue.Average, Concept.BranchingFactorAverage)); reconstructionMetrics.add(new MoveDistance(MultiMetricValue.Average, Concept.DecisionFactorAverage)); } //------------------------------------------------------------------------- private final List<Metric> conceptMetrics = new ArrayList<>(); { // Single ----------------------------------------------------------------------- // Duration conceptMetrics.add(new DurationActions()); conceptMetrics.add(new DurationMoves()); conceptMetrics.add(new DurationTurns()); conceptMetrics.add(new DurationTurnsStdDev()); conceptMetrics.add(new DurationTurnsNotTimeouts()); // State Repetition conceptMetrics.add(new PositionalRepetition()); conceptMetrics.add(new SituationalRepetition()); // State Evaluation conceptMetrics.add(new ClarityNarrowness()); conceptMetrics.add(new ClarityVariance()); conceptMetrics.add(new DecisivenessMoves()); conceptMetrics.add(new DecisivenessThreshold()); conceptMetrics.add(new LeadChange()); conceptMetrics.add(new Stability()); // Complexity conceptMetrics.add(new DecisionMoves()); conceptMetrics.add(new GameTreeComplexity()); conceptMetrics.add(new StateSpaceComplexity()); // Board Coverage conceptMetrics.add(new BoardCoverageDefault()); conceptMetrics.add(new BoardCoverageFull()); conceptMetrics.add(new BoardCoverageUsed()); // Outcome conceptMetrics.add(new AdvantageP1()); conceptMetrics.add(new Balance()); conceptMetrics.add(new Completion()); conceptMetrics.add(new Drawishness()); conceptMetrics.add(new Timeouts()); conceptMetrics.add(new OutcomeUniformity()); // Multi ----------------------------------------------------------------------- // Drama (uses state evaluation) conceptMetrics.add(new Drama(MultiMetricValue.Average, Concept.DramaAverage)); conceptMetrics.add(new Drama(MultiMetricValue.Median, Concept.DramaMedian)); conceptMetrics.add(new Drama(MultiMetricValue.Max, Concept.DramaMaximum)); conceptMetrics.add(new Drama(MultiMetricValue.Min, Concept.DramaMinimum)); conceptMetrics.add(new Drama(MultiMetricValue.Variance, Concept.DramaVariance)); conceptMetrics.add(new Drama(MultiMetricValue.ChangeAverage, Concept.DramaChangeAverage)); conceptMetrics.add(new Drama(MultiMetricValue.ChangeSign, Concept.DramaChangeSign)); conceptMetrics.add(new Drama(MultiMetricValue.ChangeLineBestFit, Concept.DramaChangeLineBestFit)); conceptMetrics.add(new Drama(MultiMetricValue.ChangeNumTimes, Concept.DramaChangeNumTimes)); conceptMetrics.add(new Drama(MultiMetricValue.MaxIncrease, Concept.DramaMaxIncrease)); conceptMetrics.add(new Drama(MultiMetricValue.MaxDecrease, Concept.DramaMaxDecrease)); // Move Evaluation (uses state evaluation) conceptMetrics.add(new MoveEvaluation(MultiMetricValue.Average, Concept.MoveEvaluationAverage)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.Median, Concept.MoveEvaluationMedian)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.Max, Concept.MoveEvaluationMaximum)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.Min, Concept.MoveEvaluationMinimum)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.Variance, Concept.MoveEvaluationVariance)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.ChangeAverage, Concept.MoveEvaluationChangeAverage)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.ChangeSign, Concept.MoveEvaluationChangeSign)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.ChangeLineBestFit, Concept.MoveEvaluationChangeLineBestFit)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.ChangeNumTimes, Concept.MoveEvaluationChangeNumTimes)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.MaxIncrease, Concept.MoveEvaluationMaxIncrease)); conceptMetrics.add(new MoveEvaluation(MultiMetricValue.MaxDecrease, Concept.MoveEvaluationMaxDecrease)); // State Evaluation Difference (uses state evaluation) conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.Average, Concept.StateEvaluationDifferenceAverage)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.Median, Concept.StateEvaluationDifferenceMedian)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.Max, Concept.StateEvaluationDifferenceMaximum)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.Min, Concept.StateEvaluationDifferenceMinimum)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.Variance, Concept.StateEvaluationDifferenceVariance)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.ChangeAverage, Concept.StateEvaluationDifferenceChangeAverage)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.ChangeSign, Concept.StateEvaluationDifferenceChangeSign)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.ChangeLineBestFit, Concept.StateEvaluationDifferenceChangeLineBestFit)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.ChangeNumTimes, Concept.StateEvaluationDifferenceChangeNumTimes)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.MaxIncrease, Concept.StateEvaluationDifferenceMaxIncrease)); conceptMetrics.add(new StateEvaluationDifference(MultiMetricValue.MaxDecrease, Concept.StateEvaluationDifferenceMaxDecrease)); // Board Sites Occupied conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.Average, Concept.BoardSitesOccupiedAverage)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.Median, Concept.BoardSitesOccupiedMedian)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.Max, Concept.BoardSitesOccupiedMaximum)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.Min, Concept.BoardSitesOccupiedMinimum)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.Variance, Concept.BoardSitesOccupiedVariance)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.ChangeAverage, Concept.BoardSitesOccupiedChangeAverage)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.ChangeSign, Concept.BoardSitesOccupiedChangeSign)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.ChangeLineBestFit, Concept.BoardSitesOccupiedChangeLineBestFit)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.ChangeNumTimes, Concept.BoardSitesOccupiedChangeNumTimes)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.MaxIncrease, Concept.BoardSitesOccupiedMaxIncrease)); conceptMetrics.add(new BoardSitesOccupied(MultiMetricValue.MaxDecrease, Concept.BoardSitesOccupiedMaxDecrease)); // Branching Factor conceptMetrics.add(new BranchingFactor(MultiMetricValue.Average, Concept.BranchingFactorAverage)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.Median, Concept.BranchingFactorMedian)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.Max, Concept.BranchingFactorMaximum)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.Min, Concept.BranchingFactorMinimum)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.Variance, Concept.BranchingFactorVariance)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.ChangeAverage, Concept.BranchingFactorChangeAverage)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.ChangeSign, Concept.BranchingFactorChangeSign)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.ChangeLineBestFit, Concept.BranchingFactorChangeLineBestFit)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.ChangeNumTimes, Concept.BranchingFactorChangeNumTimesn)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.MaxIncrease, Concept.BranchingFactorChangeMaxIncrease)); conceptMetrics.add(new BranchingFactor(MultiMetricValue.MaxDecrease, Concept.BranchingFactorChangeMaxDecrease)); // Decision Factor conceptMetrics.add(new DecisionFactor(MultiMetricValue.Average, Concept.DecisionFactorAverage)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.Median, Concept.DecisionFactorMedian)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.Max, Concept.DecisionFactorMaximum)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.Min, Concept.DecisionFactorMinimum)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.Variance, Concept.DecisionFactorVariance)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.ChangeAverage, Concept.DecisionFactorChangeAverage)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.ChangeSign, Concept.DecisionFactorChangeSign)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.ChangeLineBestFit, Concept.DecisionFactorChangeLineBestFit)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.ChangeNumTimes, Concept.DecisionFactorChangeNumTimes)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.MaxIncrease, Concept.DecisionFactorMaxIncrease)); conceptMetrics.add(new DecisionFactor(MultiMetricValue.MaxDecrease, Concept.DecisionFactorMaxDecrease)); // Move Distance conceptMetrics.add(new MoveDistance(MultiMetricValue.Average, Concept.MoveDistanceAverage)); conceptMetrics.add(new MoveDistance(MultiMetricValue.Median, Concept.MoveDistanceMedian)); conceptMetrics.add(new MoveDistance(MultiMetricValue.Max, Concept.MoveDistanceMaximum)); conceptMetrics.add(new MoveDistance(MultiMetricValue.Min, Concept.MoveDistanceMinimum)); conceptMetrics.add(new MoveDistance(MultiMetricValue.Variance, Concept.MoveDistanceVariance)); conceptMetrics.add(new MoveDistance(MultiMetricValue.ChangeAverage, Concept.MoveDistanceChangeAverage)); conceptMetrics.add(new MoveDistance(MultiMetricValue.ChangeSign, Concept.MoveDistanceChangeSign)); conceptMetrics.add(new MoveDistance(MultiMetricValue.ChangeLineBestFit, Concept.MoveDistanceChangeLineBestFit)); conceptMetrics.add(new MoveDistance(MultiMetricValue.ChangeNumTimes, Concept.MoveDistanceChangeNumTimes)); conceptMetrics.add(new MoveDistance(MultiMetricValue.MaxIncrease, Concept.MoveDistanceMaxIncrease)); conceptMetrics.add(new MoveDistance(MultiMetricValue.MaxDecrease, Concept.MoveDistanceMaxDecrease)); // Piece Number conceptMetrics.add(new PieceNumber(MultiMetricValue.Average, Concept.PieceNumberAverage)); conceptMetrics.add(new PieceNumber(MultiMetricValue.Median, Concept.PieceNumberMedian)); conceptMetrics.add(new PieceNumber(MultiMetricValue.Max, Concept.PieceNumberMaximum)); conceptMetrics.add(new PieceNumber(MultiMetricValue.Min, Concept.PieceNumberMinimum)); conceptMetrics.add(new PieceNumber(MultiMetricValue.Variance, Concept.PieceNumberVariance)); conceptMetrics.add(new PieceNumber(MultiMetricValue.ChangeAverage, Concept.PieceNumberChangeAverage)); conceptMetrics.add(new PieceNumber(MultiMetricValue.ChangeSign, Concept.PieceNumberChangeSign)); conceptMetrics.add(new PieceNumber(MultiMetricValue.ChangeLineBestFit, Concept.PieceNumberChangeLineBestFit)); conceptMetrics.add(new PieceNumber(MultiMetricValue.ChangeNumTimes, Concept.PieceNumberChangeNumTimes)); conceptMetrics.add(new PieceNumber(MultiMetricValue.MaxIncrease, Concept.PieceNumberMaxIncrease)); conceptMetrics.add(new PieceNumber(MultiMetricValue.MaxDecrease, Concept.PieceNumberMaxDecrease)); // Score Difference conceptMetrics.add(new ScoreDifference(MultiMetricValue.Average, Concept.ScoreDifferenceAverage)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.Median, Concept.ScoreDifferenceMedian)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.Max, Concept.ScoreDifferenceMaximum)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.Min, Concept.ScoreDifferenceMinimum)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.Variance, Concept.ScoreDifferenceVariance)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.ChangeAverage, Concept.ScoreDifferenceChangeAverage)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.ChangeSign, Concept.ScoreDifferenceChangeSign)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.ChangeLineBestFit, Concept.ScoreDifferenceChangeLineBestFit)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.ChangeNumTimes, Concept.ScoreDifferenceChangeNumTimes)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.MaxIncrease, Concept.ScoreDifferenceMaxIncrease)); conceptMetrics.add(new ScoreDifference(MultiMetricValue.MaxDecrease, Concept.ScoreDifferenceMaxDecrease)); } //------------------------------------------------------------------------- public List<Metric> dialogMetrics() { return Collections.unmodifiableList(dialogMetrics); } public List<Metric> reconstructionMetrics() { return Collections.unmodifiableList(reconstructionMetrics); } public List<Metric> conceptMetrics() { return Collections.unmodifiableList(conceptMetrics); } //------------------------------------------------------------------------- public double getStateEvaluationCacheValue(final long key) { // put is needed to update eldest value. stateEvaluationCache.put(Long.valueOf(key), stateEvaluationCache.get(Long.valueOf(key))); return stateEvaluationCache.get(Long.valueOf(key)).doubleValue(); } public double getStateAfterMoveEvaluationCache(final long key) { // put is needed to update eldest value. stateAfterMoveEvaluationCache.put(Long.valueOf(key), stateAfterMoveEvaluationCache.get(Long.valueOf(key))); return stateAfterMoveEvaluationCache.get(Long.valueOf(key)).doubleValue(); } public void putStateEvaluationCacheValue(final long key, final double value) { stateEvaluationCache.put(Long.valueOf(key), Double.valueOf(value)); } public void putStateAfterMoveEvaluationCache(final long key, final double value) { stateAfterMoveEvaluationCache.put(Long.valueOf(key), Double.valueOf(value)); } public boolean stateEvaluationCacheContains(final long key) { return stateEvaluationCache.containsKey(Long.valueOf(key)); } public boolean stateAfterMoveEvaluationCacheContains(final long key) { return stateAfterMoveEvaluationCache.containsKey(Long.valueOf(key)); } //------------------------------------------------------------------------- }
18,565
53.766962
140
java
Ludii
Ludii-master/Evaluation/src/metrics/Metric.java
package metrics; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.multiple.MultiMetricFramework.MultiMetricValue; import other.concept.Concept; import other.trial.Trial; //----------------------------------------------------------------------------- /** * Base class for game metrics. * @author cambolbro and matthew.stephenson */ public abstract class Metric { //----------------------------------------- /** Unique name for this metric. */ private final String name; /** Brief description of what this metric measures. */ private final String notes; /** Range of possible values.*/ private final Range<Double, Double> range; /** Concept associated with this Metric. */ private final Concept concept; /** Process for calculating the metric value, if a multi-metric. Otherwise null. */ private final MultiMetricValue multiMetricValue; //------------------------------------------------------------------------- public Metric ( final String name, final String notes, final double min, final double max, final Concept concept ) { this(name, notes, min, max, concept, null); } public Metric ( final String name, final String notes, final double min, final double max, final Concept concept, final MultiMetricValue multiMetricValue ) { this.name = new String(name); this.notes = new String(notes); range = new Range<Double, Double>(Double.valueOf(min), Double.valueOf(max)); this.concept = concept; this.multiMetricValue = multiMetricValue; } //------------------------------------------------------------------------- public String name() { return name; } public String notes() { return notes; } public double min() { return range.min().intValue(); } public double max() { return range.max().intValue(); } public Concept concept() { return concept; } public MultiMetricValue multiMetricValue() { return multiMetricValue; } //------------------------------------------------------------------------- /** * Apply this metric. * @param game The game to run. * @param trials At least one trial to be measured, may be multiple trials. * @return Evaluation of the specified trial(s) according to this metric. */ public abstract Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ); //------------------------------------------------------------------------- }
2,514
21.455357
84
java
Ludii
Ludii-master/Evaluation/src/metrics/Range.java
package metrics; /** * Defines two values of a specified type. * @author cambolbro */ public class Range<E1, E2> { private final E1 min; private final E2 max; public Range(final E1 min, final E2 max) { this.min = min; this.max = max; } public E1 min() { return min; } public E2 max() { return max; } }
398
13.25
45
java
Ludii
Ludii-master/Evaluation/src/metrics/Utils.java
package metrics; import java.util.ArrayList; import java.util.Arrays; import org.apache.commons.rng.RandomProviderState; import org.apache.commons.rng.core.RandomProviderDefaultState; import game.Game; import main.Constants; import other.RankUtils; import other.context.Context; import other.context.TempContext; import other.move.Move; import other.state.container.ContainerState; import other.topology.TopologyElement; import other.trial.Trial; import search.minimax.AlphaBetaSearch; /** * Helpful functions for metric analysis. * * @author Matthew.Stephenson */ public class Utils { //------------------------------------------------------------------------- /** * @param game * @param rngState * @return A new context for a given game and RNG. */ public static Context setupNewContext(final Game game, final RandomProviderState rngState) { final Context context = new Context(game, new Trial(game)); context.rng().restoreState(rngState); context.reset(); context.state().initialise(context.currentInstanceContext().game()); game.start(context); context.trial().setStatus(null); return context; } public static Context setupTrialContext(final Game game, final RandomProviderState rngState, final Trial trial) { final Context context = setupNewContext(game, rngState); for (final Move m : trial.generateRealMovesList()) game.apply(context, m); return context; } //------------------------------------------------------------------------- /** * The number of pieces on the board */ public static int numPieces(final Context context) { int numPieces = 0; final ContainerState cs = context.containerState(0); for (int i = 0; i < context.board().topology().getAllGraphElements().size(); i++) { final TopologyElement element = context.board().topology().getAllGraphElements().get(i); if (context.game().isStacking()) numPieces += cs.sizeStack(element.index(), element.elementType()); else numPieces += cs.count(element.index(), element.elementType()); } return numPieces; } //------------------------------------------------------------------------- /** * A list of all board sites which have a piece on them. */ public static ArrayList<TopologyElement> boardAllSitesCovered(final Context context) { final ArrayList<TopologyElement> boardSitesCovered = new ArrayList<>(); final ContainerState cs = context.containerState(0); for (final TopologyElement topologyElement : context.board().topology().getAllGraphElements()) if (cs.what(topologyElement.index(), topologyElement.elementType()) != 0) boardSitesCovered.add(topologyElement); return boardSitesCovered; } /** * A list of all used board sites which have a piece on them. */ public static ArrayList<TopologyElement> boardUsedSitesCovered(final Context context) { final ArrayList<TopologyElement> boardSitesCovered = new ArrayList<>(); final ContainerState cs = context.containerState(0); for (final TopologyElement topologyElement : context.board().topology().getAllUsedGraphElements(context.game())) if (cs.what(topologyElement.index(), topologyElement.elementType()) != 0) boardSitesCovered.add(topologyElement); return boardSitesCovered; } /** * A list of all default board sites which have a piece on them. */ public static ArrayList<TopologyElement> boardDefaultSitesCovered(final Context context) { final ArrayList<TopologyElement> boardSitesCovered = new ArrayList<>(); final ContainerState cs = context.containerState(0); for (final TopologyElement topologyElement : context.board().topology().getGraphElements(context.board().defaultSite())) if (cs.what(topologyElement.index(), topologyElement.elementType()) != 0) boardSitesCovered.add(topologyElement); return boardSitesCovered; } //------------------------------------------------------------------------- /** * Returns an evaluation between -1 and 1 for the current (context) state of the mover. */ public static double evaluateState(final Evaluation evaluation, final Context context, final int mover) { final Context instanceContext = context.currentInstanceContext(); final AlphaBetaSearch agent = new AlphaBetaSearch(false); agent.initAI(instanceContext.game(), mover); final long rngHashcode = Arrays.hashCode(((RandomProviderDefaultState) instanceContext.rng().saveState()).getState()); final long stateAndMoverHash = instanceContext.state().fullHash() ^ mover ^ rngHashcode; if (instanceContext.trial().over() || !instanceContext.active(mover)) { // Terminal node (at least for mover) return RankUtils.agentUtilities(instanceContext)[mover]; } else if (evaluation.stateEvaluationCacheContains(stateAndMoverHash)) { return evaluation.getStateEvaluationCacheValue(stateAndMoverHash); } else { // Heuristic evaluation float heuristicScore = agent.heuristicValueFunction().computeValue(instanceContext, mover, AlphaBetaSearch.ABS_HEURISTIC_WEIGHT_THRESHOLD); for (final int opp : agent.opponents(mover)) { if (instanceContext.active(opp)) heuristicScore -= agent.heuristicValueFunction().computeValue(instanceContext, opp, AlphaBetaSearch.ABS_HEURISTIC_WEIGHT_THRESHOLD); else if (instanceContext.winners().contains(opp)) heuristicScore -= AlphaBetaSearch.PARANOID_OPP_WIN_SCORE; } // Invert scores if players swapped (only works for two player games) if (instanceContext.state().playerToAgent(mover) != mover) heuristicScore = -heuristicScore; // Normalise to between -1 and 1 final double heuristicScoreTanh = Math.tanh(heuristicScore); evaluation.putStateEvaluationCacheValue(stateAndMoverHash, heuristicScoreTanh); return heuristicScoreTanh; } } /** * Returns an evaluation of a given move from the current (context) state. */ public static Double evaluateMove(final Evaluation evaluation, final Context context, final Move move) { final long rngHashcode = Arrays.hashCode(((RandomProviderDefaultState) context.rng().saveState()).getState()); final long stateAndMoveHash = context.state().fullHash() ^ move.toTrialFormat(context).hashCode() ^ rngHashcode; if (evaluation.stateAfterMoveEvaluationCacheContains(stateAndMoveHash)) return Double.valueOf(evaluation.getStateAfterMoveEvaluationCache(stateAndMoveHash)); final TempContext copyContext = new TempContext(context); copyContext.game().apply(copyContext, move); final double stateEvaluationAfterMove = evaluateState(evaluation, copyContext, move.mover()); evaluation.putStateAfterMoveEvaluationCache(stateAndMoveHash, stateEvaluationAfterMove); return Double.valueOf(stateEvaluationAfterMove); } /** * Returns an evaluation between 0 and 1 for the current (context) state of each player. */ public static ArrayList<Double> allPlayerStateEvaluations(final Evaluation evaluation, final Context context) { final ArrayList<Double> allPlayerStateEvalations = new ArrayList<>(); allPlayerStateEvalations.add(Double.valueOf(-1.0)); for (int i = 1; i <= context.game().players().count(); i++) allPlayerStateEvalations.add(Double.valueOf(evaluateState(evaluation, context, i))); return allPlayerStateEvalations; } //------------------------------------------------------------------------- /** * Get the highest ranked players based on the final player rankings. */ public static ArrayList<Integer> highestRankedPlayers(final Trial trial, final Context context) { if (context.game().players().count() <= 0) return null; final ArrayList<Integer> highestRankedPlayers = new ArrayList<>(); double highestRanking = -Constants.INFINITY; for (int i = 1; i <= context.game().players().count(); i++) if (RankUtils.agentUtilities(context)[i] > highestRanking) highestRanking = RankUtils.agentUtilities(context)[i]; for (int i = 1; i <= context.game().players().count(); i++) if (RankUtils.agentUtilities(context)[i] == highestRanking) highestRankedPlayers.add(Integer.valueOf(i)); return highestRankedPlayers; } //------------------------------------------------------------------------- // public static double UCTEvaluateState(final Context context, final int mover) // { // if (!context.active(mover)) // return RankUtils.rankToUtil(context.trial().ranking()[mover], context.game().players().count()); // // final MCTS agent = MCTS.createUCT(); // agent.initAI(context.game(), mover); // agent.setAutoPlaySeconds(-1); // agent.selectAction(context.game(), context, 0.1, -1, -1); // return agent.estimateValue(); // } //------------------------------------------------------------------------- // public static double ABEvaluateState(final Context context, final int mover) // { // final AlphaBetaSearch agent = new AlphaBetaSearch(false); // agent.initAI(context.game(), mover); // return agent.alphaBeta(context, 0, -1, -1, mover, -1); // } //------------------------------------------------------------------------- // /* // * Returns the heuristic estimation of the current state of a context object, for a given player Id. // * Same code used in AlphaBetaSearch. // */ // public static double HeuristicEvaluateState(final Context context, final int mover) // { // final AlphaBetaSearch agent = new AlphaBetaSearch(false); // agent.initAI(context.game(), mover); // // if (context.trial().over() || !context.active(mover)) // { // // Terminal node (at least for mover) // return RankUtils.agentUtilities(context)[mover] * AlphaBetaSearch.BETA_INIT; // } // else // { // // Heuristic evaluation // float heuristicScore = agent.heuristicValueFunction().computeValue(context, mover, AlphaBetaSearch.ABS_HEURISTIC_WEIGHT_THRESHOLD); // // for (final int opp : agent.opponents(mover)) // { // if (context.active(opp)) // heuristicScore -= agent.heuristicValueFunction().computeValue(context, opp, AlphaBetaSearch.ABS_HEURISTIC_WEIGHT_THRESHOLD); // else if (context.winners().contains(opp)) // heuristicScore -= AlphaBetaSearch.PARANOID_OPP_WIN_SCORE; // } // // // Invert scores if players swapped // if (context.state().playerToAgent(mover) != mover) // heuristicScore = -heuristicScore; // // return Math.tanh(heuristicScore); // } // } //------------------------------------------------------------------------- }
10,404
35.128472
142
java
Ludii
Ludii-master/Evaluation/src/metrics/designer/IdealDuration.java
package metrics.designer; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import other.trial.Trial; /** * Average number or turns in a game, based on an ideal range. * * @author matthew.stephenson */ public class IdealDuration extends Metric { private double minTurn = 0; private double maxTurn = 1000; //------------------------------------------------------------------------- /** * Constructor */ public IdealDuration() { super ( "Ideal Duration", "Average number or turns in a game, based on an ideal range.", 0.0, 1.0, null ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // // // 1- +-------+__ // /| | \__ // / | | \__ // / | | \__ // / | | \__ // 0- +----+-------+--------------+--- // 0 Min Max 2*Max double tally = 0; for (final Trial trial : trials) { final int numTurns = trial.numTurns(); double score = 1; if (numTurns < minTurn) score = numTurns / minTurn; else if (numTurns > maxTurn) score = 1 - Math.min(1, (numTurns - maxTurn) / maxTurn); tally += score; } return Double.valueOf(tally / trials.length); } //------------------------------------------------------------------------- public void setMinTurn(final double minTurn) { this.minTurn = minTurn; } public void setMaxTurn(final double maxTurn) { this.maxTurn = maxTurn; } //------------------------------------------------------------------------- }
1,839
19
76
java
Ludii
Ludii-master/Evaluation/src/metrics/designer/SkillTrace.java
package metrics.designer; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.UnixPrintWriter; import main.math.LinearRegression; import metrics.Evaluation; import metrics.Metric; import other.AI; import other.RankUtils; import other.context.Context; import other.model.Model; import other.trial.Trial; import search.mcts.MCTS; /** * Skill trace of the game. * NOTE. This metric doesn't work with stored trials, and must instead generate new trials each time. * NOTE. Only works games that are supported by UCT * * @author matthew.stephenson and Dennis Soemers */ public class SkillTrace extends Metric { // Number of matches (iteration count doubles each time) private int numMatches = 8; // Number of trials per match private int numTrialsPerMatch = 30; // A hard time limit in seconds, after which any future trials are aborted private int hardTimeLimit = 180; // Output path for more details results private String outputPath = ""; // Database storage options private boolean addToDatabaseFile = false; private String combinedResultsOutputPath = "SkillTraceResults.csv"; //------------------------------------------------------------------------- /** * Constructor */ public SkillTrace() { super ( "Skill trace", "Skill trace of the game.", 0.0, 1.0, null ); } //------------------------------------------------------------------------- @SuppressWarnings("boxing") @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { String outputString = ""; final List<Double> strongAIResults = new ArrayList<>(); double areaEstimate = 0.0; final long startTime = System.currentTimeMillis(); final List<AI> ais = new ArrayList<AI>(game.players().count() + 1); ais.add(null); for (int p = 1; p <= game.players().count(); ++p) ais.add(MCTS.createUCT()); final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); final int bf = game.moves(context).count(); System.out.println(numTrialsPerMatch + " trials per level, time limit " + hardTimeLimit + "s, BF=" + bf + "."); outputString += numTrialsPerMatch + " trials per level, time limit " + hardTimeLimit + "s, BF=" + bf + ".\n"; int weakIterationValue = 2; int matchCount = 0; for (/**/; matchCount < numMatches; matchCount++) { double strongAIAvgResult = 0.0; int strongAgentIdx = 1; for (int i = 0; i < numTrialsPerMatch; ++i) { game.start(context); for (int p = 1; p <= game.players().count(); ++p) ais.get(p).initAI(game, p); final Model model = context.model(); while (!trial.over()) { final int mover = context.state().playerToAgent(context.state().mover()); final int numIterations; if (mover == strongAgentIdx) numIterations = weakIterationValue * 2; else numIterations = weakIterationValue; model.startNewStep(context, ais, -1.0, numIterations * game.moves(context).count(), -1, 0.0); } // Record the utility of the strong agent strongAIAvgResult += RankUtils.agentUtilities(context)[strongAgentIdx]; // Change which player is controlled by the strong agent ++strongAgentIdx; if (strongAgentIdx > game.players().count()) strongAgentIdx = 1; // Check the current time, and if we have elapsed the limit then abort. if (System.currentTimeMillis() > (startTime + hardTimeLimit*1000)) break; } // If we didn't finish all trials in time, then ignore the match results if (System.currentTimeMillis() > (startTime + hardTimeLimit*1000)) { System.out.println("Aborting after " + String.valueOf(matchCount) + " levels."); outputString += "Aborting after " + String.valueOf(matchCount) + " levels.\n"; break; } strongAIAvgResult /= numTrialsPerMatch; strongAIResults.add(Double.valueOf(strongAIAvgResult)); areaEstimate += Math.max(strongAIAvgResult, 0.0); weakIterationValue *= 2; // Print match results in console System.out.println("Level " + (matchCount+1) + ", strong AI result: " + strongAIAvgResult); outputString += "Level " + (matchCount+1) + ", strong AI result: " + strongAIAvgResult + "\n"; } // Predict next step y value. final double[] xAxis = IntStream.range(0, strongAIResults.size()).asDoubleStream().toArray(); final double[] yAxis = strongAIResults.stream().mapToDouble(Double::doubleValue).toArray(); final LinearRegression linearRegression = new LinearRegression(xAxis, yAxis); double yValueNextStep = linearRegression.predict(numMatches+1); yValueNextStep = Math.max(Math.min(yValueNextStep, 1.0), 0.0); // No matches were able to be completed within the time limit. if (matchCount == 0) return Double.valueOf(0); final double skillTrace = yValueNextStep + (1-yValueNextStep)*(areaEstimate/matchCount); final double secs = (System.currentTimeMillis() - startTime) / 1000.0; System.out.println(String.format("Skill trace %.3f in %.3fs (slope error %.3f, intercept error %.3f).", skillTrace, secs, linearRegression.slopeStdErr(), linearRegression.interceptStdErr())); outputString += String.format("Skill trace %.3f in %.3fs (slope error %.3f, intercept error %.3f).", skillTrace, secs, linearRegression.slopeStdErr(), linearRegression.interceptStdErr()); // Store outputString in a text file if specified. if (outputPath.length() > 1) { final String outputSkillTracePath = outputPath + game.name() + "_skillTrace.txt"; try (final PrintWriter writer = new UnixPrintWriter(new File(outputSkillTracePath), "UTF-8")) { writer.println(outputString); } catch (final FileNotFoundException | UnsupportedEncodingException e2) { e2.printStackTrace(); } } // Append output as an entry of the csv defined in "combinedResultsOutputPath", for uploading to Database. if (addToDatabaseFile) { try (final PrintWriter writer = new PrintWriter(new FileOutputStream(new File(combinedResultsOutputPath()), true))) { String entryString = ""; entryString += game.name() + ","; entryString += game.metadata().info().getId().get(0) + ","; entryString += skillTrace + ","; entryString += numTrialsPerMatch + ","; entryString += matchCount + ","; entryString += hardTimeLimit + ","; entryString += linearRegression.slopeStdErr() + ","; entryString += linearRegression.interceptStdErr(); writer.println(entryString); } catch (final FileNotFoundException e2) { e2.printStackTrace(); } } return Double.valueOf(skillTrace); } public void setNumMatches(final int numMatches) { this.numMatches = numMatches; } public void setNumTrialsPerMatch(final int numTrialsPerMatch) { this.numTrialsPerMatch = numTrialsPerMatch; } public void setHardTimeLimit(final int hardTimeLimit) { this.hardTimeLimit = hardTimeLimit; } public void setOutputPath(final String s) { outputPath = s; } public void setCombinedResultsOutputPath(final String combinedResultsOutputPath) { this.combinedResultsOutputPath = combinedResultsOutputPath; } public void setAddToDatabaseFile(final boolean addToDatabaseFile) { this.addToDatabaseFile = addToDatabaseFile; } public String combinedResultsOutputPath() { return combinedResultsOutputPath; } //------------------------------------------------------------------------- }
7,817
29.779528
193
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/MultiMetricFramework.java
package metrics.multiple; import java.util.ArrayList; import java.util.Arrays; import java.util.stream.IntStream; import java.util.stream.Stream; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.math.LinearRegression; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.trial.Trial; @SuppressWarnings("static-method") public abstract class MultiMetricFramework extends Metric { public enum MultiMetricValue { Average, Median, Max, Min, Variance, ChangeAverage, ChangeSign, ChangeLineBestFit, ChangeNumTimes, MaxIncrease, MaxDecrease } //------------------------------------------------------------------------- public MultiMetricFramework ( final String name, final String notes, final double min, final double max, final Concept concept, final MultiMetricValue multiMetricValue ) { super(name, notes, min, max, concept, multiMetricValue); } //------------------------------------------------------------------------- public abstract Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context); //------------------------------------------------------------------------- public Double[][] getMetricValueLists(final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates) { final ArrayList<Double[]> metricValueLists = new ArrayList<>(); for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; final Context context = Utils.setupNewContext(game, rngState); metricValueLists.add(getMetricValueList(evaluation, trial, context)); } return metricValueLists.toArray(new Double[0][0]); } //------------------------------------------------------------------------- public double metricAverage(final Double[][] metricValues) { double metricAverageFinal = 0.0; for (final Double[] valueList : metricValues) { double metricAverage = 0.0; if (valueList.length > 0) for (final Double value : valueList) metricAverage += value.doubleValue() / valueList.length; metricAverageFinal += metricAverage; } return metricAverageFinal / metricValues.length; } public double metricMedian(final Double[][] metricValues) { double metricMedianFinal = 0.0; for (final Double[] valueList : metricValues) { double metricMedian = 0; if (valueList.length > 1) { Arrays.sort(valueList); metricMedian = valueList[valueList.length/2].doubleValue(); } metricMedianFinal += metricMedian; } return metricMedianFinal / metricValues.length; } public double metricMax(final Double[][] metricValues) { double metricMaxFinal = 0.0; for (final Double[] valueList : metricValues) { double metricMax = 0.0; for (final Double value : valueList) metricMax = Math.max(metricMax, value.doubleValue()); metricMaxFinal += metricMax; } return metricMaxFinal / metricValues.length; } public double metricMin(final Double[][] metricValues) { double metricMinFinal = 0.0; for (final Double[] valueList : metricValues) { double metricMin = 0.0; for (final Double value : valueList) metricMin = Math.min(metricMin, value.doubleValue()); metricMinFinal += metricMin; } return metricMinFinal / metricValues.length; } public double metricVariance(final Double[][] metricValues) { double metricVarianceFinal = 0.0; for (final Double[] valueList : metricValues) { double metricVariance = 0.0; if (valueList.length > 1) { double metricAverage = 0.0; for (final Double value : valueList) metricAverage += value.doubleValue() / valueList.length; for (final Double value : valueList) metricVariance += Math.pow(value.doubleValue() - metricAverage, 2) / valueList.length; } metricVarianceFinal += metricVariance; } return metricVarianceFinal / metricValues.length; } public double metricMaxIncrease(final Double[][] metricValues) { double metricMaxFinal = 0.0; for (final Double[] valueList : metricValues) { double metricMax = 0.0; if (valueList.length > 1) { double lastValue = valueList[0].doubleValue(); for (final Double value : valueList) { final double change = value.doubleValue() - lastValue; metricMax = Math.max(metricMax, change); lastValue = value.doubleValue(); } } metricMaxFinal += metricMax; } return metricMaxFinal / metricValues.length; } public double metricMaxDecrease(final Double[][] metricValues) { double metricMaxFinal = 0.0; for (final Double[] valueList : metricValues) { double metricMax = 0.0; if (valueList.length > 1) { double lastValue = valueList[0].doubleValue(); for (final Double value : valueList) { final double change = value.doubleValue() - lastValue; metricMax = Math.min(metricMax, change); lastValue = value.doubleValue(); } } metricMaxFinal += metricMax; } return metricMaxFinal / metricValues.length; } /** The slope of the least squares line of best fit. */ public double metricChangeLineBestFit(final Double[][] metricValues) { double metricChangeFinal = 0.0; for (final Double[] valueList : metricValues) { double linearRegressionSlope = 0.0; if (valueList.length > 1) { final double[] xAxis = IntStream.range(0, valueList.length).asDoubleStream().toArray(); final double[] yAxis = Stream.of(valueList).mapToDouble(Double::doubleValue).toArray(); final LinearRegression linearRegression = new LinearRegression(xAxis, yAxis); linearRegressionSlope = linearRegression.slope(); } metricChangeFinal += linearRegressionSlope; } return metricChangeFinal / metricValues.length; } /** The average increase */ public double metricChangeAverage(final Double[][] metricValues) { double metricChangeFinal = 0.0; for (final Double[] valueList : metricValues) { // double metricChange = 0.0; // double lastValue = valueList[0].doubleValue(); // for (final Double value : valueList) // { // final double change = value.doubleValue() - lastValue; // metricChange += change / (valueList.length-1); // lastValue = value.doubleValue(); // } double metricChange = 0.0; if (valueList.length > 1) { final double firstValue = valueList[0].doubleValue(); final double lastValue = valueList[valueList.length-1].doubleValue(); metricChange = (lastValue - firstValue) / (valueList.length-1); } metricChangeFinal += metricChange; } return metricChangeFinal / metricValues.length; } /** The average number of times the value increased versus decreased. */ public double metricChangeSign(final Double[][] metricValues) { double metricChangeFinal = 0.0; for (final Double[] valueList : metricValues) { double metricChange = 0.0; if (valueList.length > 1) { double lastValue = valueList[0].doubleValue(); for (final Double value : valueList) { double change = value.doubleValue() - lastValue; if (change > 0) change = 1; else if (change < 0) change = -1; else change = 0; metricChange += change / (valueList.length-1); lastValue = value.doubleValue(); } } metricChangeFinal += metricChange; } return metricChangeFinal / metricValues.length; } /** The average number of times the direction changed. */ public double metricChangeNumTimes(final Double[][] metricValues) { double metricChangeFinal = 0.0; for (final Double[] valueList : metricValues) { double metricChange = 0.0; if (valueList.length > 1) { double valueChangeDirection = 0.0; // If 1.0 then increasing, if -1.0 then decreasing double lastValue = valueList[0].doubleValue(); for (final Double value : valueList) { double direction = 0.0; if (value.doubleValue() > lastValue) direction = 1.0; if (value.doubleValue() < lastValue) direction = -1.0; if (direction != 0.0 && valueChangeDirection != direction) metricChange += 1 / (valueList.length-1); valueChangeDirection = direction; lastValue = value.doubleValue(); } } metricChangeFinal += metricChange; } return metricChangeFinal / metricValues.length; } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Zero player games cannot be computed. if (game.hasSubgames() || game.isSimultaneousMoveGame() || game.players().count() == 0) return null; final Double[][] metricValues = getMetricValueLists(game, evaluation, trials, randomProviderStates); switch (multiMetricValue()) { case Average: return Double.valueOf(metricAverage(metricValues)); case Median: return Double.valueOf(metricMedian(metricValues)); case Max: return Double.valueOf(metricMax(metricValues)); case Min: return Double.valueOf(metricMin(metricValues)); case Variance: return Double.valueOf(metricVariance(metricValues)); case ChangeAverage: return Double.valueOf(metricChangeAverage(metricValues)); case ChangeSign: return Double.valueOf(metricChangeSign(metricValues)); case ChangeLineBestFit: return Double.valueOf(metricChangeLineBestFit(metricValues)); case ChangeNumTimes: return Double.valueOf(metricChangeNumTimes(metricValues)); case MaxIncrease: return Double.valueOf(metricMaxIncrease(metricValues)); case MaxDecrease: return Double.valueOf(metricMaxDecrease(metricValues)); default: return null; } } //------------------------------------------------------------------------- }
9,993
27.718391
156
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/metrics/BoardSitesOccupied.java
package metrics.multiple.metrics; import java.util.ArrayList; import metrics.Evaluation; import metrics.Utils; import metrics.multiple.MultiMetricFramework; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Percentage of board sites which have a piece on it. * Note. Only looks at the default site type. * * @author matthew.stephenson */ public class BoardSitesOccupied extends MultiMetricFramework { //------------------------------------------------------------------------- /** * Constructor */ public BoardSitesOccupied(final MultiMetricValue multiMetricValue, final Concept concept) { super ( "Board Sites Occupied " + multiMetricValue.name(), "Percentage of board sites which have a piece on it.", 0.0, 1.0, concept, multiMetricValue ); } //------------------------------------------------------------------------- @Override public Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context) { final ArrayList<Double> valueList = new ArrayList<>(); final int numberDefaultBoardSites = context.board().topology().getGraphElements(context.board().defaultSite()).size(); valueList.add(Double.valueOf(Double.valueOf(Utils.boardDefaultSitesCovered(context).size()).doubleValue() / numberDefaultBoardSites)); for (final Move m : trial.generateRealMovesList()) { context.game().apply(context, m); valueList.add(Double.valueOf(Double.valueOf(Utils.boardDefaultSitesCovered(context).size()).doubleValue() / numberDefaultBoardSites)); } return valueList.toArray(new Double[0]); } //------------------------------------------------------------------------- }
1,739
28
137
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/metrics/BranchingFactor.java
package metrics.multiple.metrics; import java.util.ArrayList; import main.Constants; import metrics.Evaluation; import metrics.multiple.MultiMetricFramework; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Number of possible moves. * * @author matthew.stephenson */ public class BranchingFactor extends MultiMetricFramework { //------------------------------------------------------------------------- /** * Constructor */ public BranchingFactor(final MultiMetricValue multiMetricValue, final Concept concept) { super ( "Branching Factor " + multiMetricValue.name(), "Number of possible moves.", 0.0, Constants.INFINITY, concept, multiMetricValue ); } //------------------------------------------------------------------------- @Override public Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context) { final ArrayList<Double> valueList = new ArrayList<>(); for (final Move m : trial.generateRealMovesList()) { valueList.add(Double.valueOf(context.game().moves(context).moves().size())); context.game().apply(context, m); } return valueList.toArray(new Double[0]); } //------------------------------------------------------------------------- }
1,329
22.75
106
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/metrics/DecisionFactor.java
package metrics.multiple.metrics; import java.util.ArrayList; import main.Constants; import metrics.Evaluation; import metrics.multiple.MultiMetricFramework; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Number of possible moves, when greater than 1. * * @author matthew.stephenson */ public class DecisionFactor extends MultiMetricFramework { //------------------------------------------------------------------------- /** * Constructor */ public DecisionFactor(final MultiMetricValue multiMetricValue, final Concept concept) { super ( "Decision Factor " + multiMetricValue.name(), "Number of possible moves, when greater than 1.", 0.0, Constants.INFINITY, concept, multiMetricValue ); } //------------------------------------------------------------------------- @Override public Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context) { final ArrayList<Double> valueList = new ArrayList<>(); for (final Move m : trial.generateRealMovesList()) { if (context.game().moves(context).moves().size() > 1) valueList.add(Double.valueOf(context.game().moves(context).moves().size())); context.game().apply(context, m); } return valueList.toArray(new Double[0]); } //------------------------------------------------------------------------- }
1,431
23.689655
106
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/metrics/Drama.java
package metrics.multiple.metrics; import java.util.ArrayList; import java.util.Collections; import metrics.Evaluation; import metrics.Utils; import metrics.multiple.MultiMetricFramework; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Difference between the winning players state evaluation and the maximum state evaluation of any player. * * @author matthew.stephenson */ public class Drama extends MultiMetricFramework { //------------------------------------------------------------------------- /** * Constructor */ public Drama(final MultiMetricValue multiMetricValue, final Concept concept) { super ( "Drama " + multiMetricValue.name(), "Difference between the winning players state evaluation and the 'maximum state evaluation of any player.", 0.0, 1.0, concept, multiMetricValue ); } //------------------------------------------------------------------------- @Override public Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context) { final ArrayList<Double> valueList = new ArrayList<>(); // Get the highest ranked players based on the final player rankings. final ArrayList<Integer> highestRankedPlayers = Utils.highestRankedPlayers(trial, context); if (highestRankedPlayers.size() > 0) { for (final Move m : trial.generateRealMovesList()) { // Get the highest state evaluation for any player. final ArrayList<Double> allPlayerStateEvaluations = Utils.allPlayerStateEvaluations(evaluation, context); final double highestStateEvaluation = Collections.max(allPlayerStateEvaluations).doubleValue(); // Get the average difference between the winning player(s) and the highest state evaluation. double differenceBetweenWinnersAndMax = 0.0; for (final int highestRankedPlayer : highestRankedPlayers) { final double playerStateEvaluation = allPlayerStateEvaluations.get(highestRankedPlayer).doubleValue(); differenceBetweenWinnersAndMax += (highestStateEvaluation-playerStateEvaluation)/highestRankedPlayers.size(); } valueList.add(Double.valueOf(differenceBetweenWinnersAndMax)); context.game().apply(context, m); } } else { System.out.println("ERROR, highestRankedPlayers list is empty"); } return valueList.toArray(new Double[0]); } //------------------------------------------------------------------------- }
2,486
29.703704
114
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/metrics/MoveDistance.java
package metrics.multiple.metrics; import java.util.ArrayList; import game.types.board.RelationType; import game.types.board.SiteType; import main.Constants; import metrics.Evaluation; import metrics.multiple.MultiMetricFramework; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.topology.Topology; import other.trial.Trial; /** * The distance traveled by pieces when they move around the board. * Note. Only for moves between same site type * * @author matthew.stephenson */ public class MoveDistance extends MultiMetricFramework { //------------------------------------------------------------------------- /** * Constructor */ public MoveDistance(final MultiMetricValue multiMetricValue, final Concept concept) { super ( "Move Distance " + multiMetricValue.name(), "The distance traveled by pieces when they move around the board.", 0.0, Constants.INFINITY, concept, multiMetricValue ); } //------------------------------------------------------------------------- @Override public Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context) { final Topology boardTopology = context.board().topology(); if (context.game().booleanConcepts().get(Concept.Cell.id())) boardTopology.preGenerateDistanceToEachElementToEachOther(SiteType.Cell, RelationType.Adjacent); if (context.game().booleanConcepts().get(Concept.Edge.id())) boardTopology.preGenerateDistanceToEachElementToEachOther(SiteType.Edge, RelationType.Adjacent); if (context.game().booleanConcepts().get(Concept.Vertex.id())) boardTopology.preGenerateDistanceToEachElementToEachOther(SiteType.Vertex, RelationType.Adjacent); final ArrayList<Double> valueList = new ArrayList<>(); for (final Move m : trial.generateRealMovesList()) { final SiteType moveType = m.fromType(); if ( m.fromType() == m.toType() && m.from() < boardTopology.numSites(moveType) && m.to() < boardTopology.numSites(moveType) && m.from() != m.to() ) { valueList.add(Double.valueOf(boardTopology.distancesToOtherSite(moveType)[m.from()][m.to()])); } context.game().apply(context, m); } return valueList.toArray(new Double[0]); } //------------------------------------------------------------------------- }
2,382
26.709302
106
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/metrics/MoveEvaluation.java
package metrics.multiple.metrics; import java.util.ArrayList; import metrics.Evaluation; import metrics.Utils; import metrics.multiple.MultiMetricFramework; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Evaluation values for each move. * * @author matthew.stephenson */ public class MoveEvaluation extends MultiMetricFramework { //------------------------------------------------------------------------- /** * Constructor */ public MoveEvaluation(final MultiMetricValue multiMetricValue, final Concept concept) { super ( "Move Evaluation " + multiMetricValue.name(), "Evaluation values for each move.", 0.0, 1.0, concept, multiMetricValue ); } //------------------------------------------------------------------------- @Override public Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context) { final ArrayList<Double> valueList = new ArrayList<>(); for (final Move m : trial.generateRealMovesList()) { valueList.add(Utils.evaluateMove(evaluation, context, m)); context.game().apply(context, m); } return valueList.toArray(new Double[0]); } //------------------------------------------------------------------------- }
1,305
22.745455
106
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/metrics/PieceNumber.java
package metrics.multiple.metrics; import java.util.ArrayList; import main.Constants; import metrics.Evaluation; import metrics.Utils; import metrics.multiple.MultiMetricFramework; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * The number of pieces on the board. * * @author matthew.stephenson */ public class PieceNumber extends MultiMetricFramework { //------------------------------------------------------------------------- /** * Constructor */ public PieceNumber(final MultiMetricValue multiMetricValue, final Concept concept) { super ( "Piece Number " + multiMetricValue.name(), "The number of pieces on the board.", 0.0, Constants.INFINITY, concept, multiMetricValue ); } //------------------------------------------------------------------------- @Override public Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context) { final ArrayList<Double> valueList = new ArrayList<>(); valueList.add(Double.valueOf(Utils.numPieces(context))); for (final Move m : trial.generateRealMovesList()) { context.game().apply(context, m); valueList.add(Double.valueOf(Utils.numPieces(context))); } return valueList.toArray(new Double[0]); } //------------------------------------------------------------------------- }
1,398
22.711864
106
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/metrics/ScoreDifference.java
package metrics.multiple.metrics; import java.util.ArrayList; import main.Constants; import metrics.Evaluation; import metrics.multiple.MultiMetricFramework; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Difference in player scores. * * @author matthew.stephenson */ public class ScoreDifference extends MultiMetricFramework { //------------------------------------------------------------------------- /** * Constructor */ public ScoreDifference(final MultiMetricValue multiMetricValue, final Concept concept) { super ( "Score Difference " + multiMetricValue.name(), "Difference in player scores.", 0.0, Constants.INFINITY, concept, multiMetricValue ); } //------------------------------------------------------------------------- @Override public Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context) { final ArrayList<Double> valueList = new ArrayList<>(); valueList.add(Double.valueOf(getScoreDiscrepancy(context))); for (final Move m : trial.generateRealMovesList()) { context.game().apply(context, m); valueList.add(Double.valueOf(getScoreDiscrepancy(context))); } return valueList.toArray(new Double[0]); } //------------------------------------------------------------------------- private static double getScoreDiscrepancy(final Context context) { if (!context.game().requiresScore()) return 0.0; final int numPlayers = context.game().players().count(); final int[] score = new int[numPlayers + 1]; for (int p = 1; p <= numPlayers; p++) score[p] += context.score(p); // Find maximum discrepancy double maxDisc = 0.0; for (int pa = 1; pa <= numPlayers; pa++) { for (int pb = pa+1; pb <= numPlayers; pb++) { final double disc = Math.abs(score[pa] - score[pb]); if (disc > maxDisc) maxDisc = disc; } } return maxDisc; } //------------------------------------------------------------------------- }
2,061
23.547619
106
java
Ludii
Ludii-master/Evaluation/src/metrics/multiple/metrics/StateEvaluationDifference.java
package metrics.multiple.metrics; import java.util.ArrayList; import metrics.Evaluation; import metrics.Utils; import metrics.multiple.MultiMetricFramework; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Difference in player state evaluations. * * @author matthew.stephenson */ public class StateEvaluationDifference extends MultiMetricFramework { //------------------------------------------------------------------------- /** * Constructor */ public StateEvaluationDifference(final MultiMetricValue multiMetricValue, final Concept concept) { super ( "State Evaluation Difference " + multiMetricValue.name(), "Difference in player state evaluations.", 0.0, 1.0, concept, multiMetricValue ); } //------------------------------------------------------------------------- @Override public Double[] getMetricValueList(final Evaluation evaluation, final Trial trial, final Context context) { final ArrayList<Double> valueList = new ArrayList<>(); valueList.add(Double.valueOf(getStateEvaluationDiscrepancy(evaluation, context))); for (final Move m : trial.generateRealMovesList()) { context.game().apply(context, m); valueList.add(Double.valueOf(getStateEvaluationDiscrepancy(evaluation, context))); } return valueList.toArray(new Double[0]); } //------------------------------------------------------------------------- private static double getStateEvaluationDiscrepancy(final Evaluation evaluation, final Context context) { final int numPlayers = context.game().players().count(); final ArrayList<Double> allPlayerStateEvaluations = Utils.allPlayerStateEvaluations(evaluation, context); // Find maximum discrepancy double maxDisc = 0.0; for (int pa = 1; pa <= numPlayers; pa++) { for (int pb = pa+1; pb <= numPlayers; pb++) { final double disc = Math.abs(allPlayerStateEvaluations.get(pa).doubleValue() - allPlayerStateEvaluations.get(pb).doubleValue()); if (disc > maxDisc) maxDisc = disc; } } return maxDisc; } //------------------------------------------------------------------------- }
2,183
27
132
java
Ludii
Ludii-master/Evaluation/src/metrics/single/boardCoverage/BoardCoverageDefault.java
package metrics.single.boardCoverage; import java.util.HashSet; import java.util.Set; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.topology.TopologyElement; import other.trial.Trial; /** * Percentage of default board sites which a piece was placed on at some point. * * @author matthew.stephenson */ public class BoardCoverageDefault extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public BoardCoverageDefault() { super ( "Board Coverage Default", "Percentage of default board sites which a piece was placed on at some point.", 0.0, 1.0, Concept.BoardCoverageDefault ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { double numSitesCovered = 0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Record all sites covered in this trial. final Set<TopologyElement> sitesCovered = new HashSet<TopologyElement>(); sitesCovered.addAll(Utils.boardDefaultSitesCovered(context)); for (final Move m : trial.generateRealMovesList()) { context.game().apply(context, m); sitesCovered.addAll(Utils.boardDefaultSitesCovered(context)); } numSitesCovered += ((double) sitesCovered.size()) / context.board().topology().getGraphElements(context.board().defaultSite()).size(); } return Double.valueOf(numSitesCovered / trials.length); } }
2,066
24.518519
137
java
Ludii
Ludii-master/Evaluation/src/metrics/single/boardCoverage/BoardCoverageFull.java
package metrics.single.boardCoverage; import java.util.HashSet; import java.util.Set; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.topology.TopologyElement; import other.trial.Trial; /** * Percentage of all board sites (cell, vertex and edge) which a piece was placed on at some point. * * @author matthew.stephenson */ public class BoardCoverageFull extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public BoardCoverageFull() { super ( "Board Coverage Full", "Percentage of all board sites (cell, vertex and edge) which a piece was placed on at some point.", 0.0, 1.0, Concept.BoardCoverageFull ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { double numSitesCovered = 0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Record all sites covered in this trial. final Set<TopologyElement> sitesCovered = new HashSet<TopologyElement>(); sitesCovered.addAll(Utils.boardAllSitesCovered(context)); for (final Move m : trial.generateRealMovesList()) { context.game().apply(context, m); sitesCovered.addAll(Utils.boardAllSitesCovered(context)); } numSitesCovered += ((double) sitesCovered.size()) / context.board().topology().getAllGraphElements().size(); } return Double.valueOf(numSitesCovered / trials.length); } }
2,060
24.444444
111
java
Ludii
Ludii-master/Evaluation/src/metrics/single/boardCoverage/BoardCoverageUsed.java
package metrics.single.boardCoverage; import java.util.HashSet; import java.util.Set; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.topology.TopologyElement; import other.trial.Trial; /** * Percentage of used board sites (detected automatically based on the games rule description) which a piece was placed on at some point. * * @author matthew.stephenson */ public class BoardCoverageUsed extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public BoardCoverageUsed() { super ( "Board Coverage Used", "Percentage of used board sites (detected automatically based on the games rule description) which a piece was placed on at some point.", 0.0, 1.0, Concept.BoardCoverageUsed ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { double numSitesCovered = 0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Record all sites covered in this trial. final Set<TopologyElement> sitesCovered = new HashSet<TopologyElement>(); sitesCovered.addAll(Utils.boardUsedSitesCovered(context)); for (final Move m : trial.generateRealMovesList()) { context.game().apply(context, m); sitesCovered.addAll(Utils.boardUsedSitesCovered(context)); } numSitesCovered += ((double) sitesCovered.size()) / context.board().topology().getAllUsedGraphElements(context.game()).size(); } return Double.valueOf(numSitesCovered / trials.length); } }
2,155
25.617284
140
java
Ludii
Ludii-master/Evaluation/src/metrics/single/complexity/DecisionMoves.java
package metrics.single.complexity; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Percentage number of states in the trial where there was more than 1 possible move. * * @author matthew.stephenson */ public class DecisionMoves extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public DecisionMoves() { super ( "Decision Moves", "Percentage number of states in the trial where there was more than 1 possible move.", 0.0, 1.0, Concept.DecisionMoves ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { double avgNumDecisionMoves = 0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Record the number of possible options for each move. double numDecisionMoves = 0; for (final Move m : trial.generateRealMovesList()) { if (context.game().moves(context).moves().size() > 1) numDecisionMoves++; context.game().apply(context, m); } avgNumDecisionMoves += numDecisionMoves / trial.generateRealMovesList().size(); } return Double.valueOf(avgNumDecisionMoves / trials.length); } //------------------------------------------------------------------------- }
1,913
22.925
90
java
Ludii
Ludii-master/Evaluation/src/metrics/single/complexity/GameTreeComplexity.java
package metrics.single.complexity; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.Constants; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Estimate of the number of possible distinct play traces. * https://www.pipmodern.com/post/complexity-state-space-game-tree * * @author matthew.stephenson */ public class GameTreeComplexity extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public GameTreeComplexity() { super ( "Game Tree Complexity", "Estimate of the number of possible distinct play traces. ", 0.0, Constants.INFINITY, Concept.GameTreeComplexity ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { double gameTreeComplexity = 0.0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); double branchingFactor = 0.0; for (final Move m : trial.generateRealMovesList()) { branchingFactor += context.game().moves(context).moves().size() / trial.generateRealMovesList().size(); context.game().apply(context, m); } gameTreeComplexity += trial.generateRealMovesList().size() * Math.log10(branchingFactor); } return Double.valueOf(gameTreeComplexity / trials.length); } }
1,877
23.710526
107
java
Ludii
Ludii-master/Evaluation/src/metrics/single/complexity/StateSpaceComplexity.java
package metrics.single.complexity; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.Constants; import metrics.Evaluation; import metrics.Metric; import other.concept.Concept; import other.trial.Trial; /** * Estimate of the total number of possible game board states. * https://www.pipmodern.com/post/complexity-state-space-game-tree * * @author matthew.stephenson */ public class StateSpaceComplexity extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public StateSpaceComplexity() { super ( "State Space Complexity", "Estimate of the total number of possible game board states.", 0.0, Constants.INFINITY, Concept.StateTreeComplexity ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { if (game.hasSubgames() || game.isSimultaneousMoveGame()) return null; long maxStatePossibilites = game.numComponents() + 1; if (game.isStacking()) maxStatePossibilites *= Constants.MAX_STACK_HEIGHT; else if (game.requiresCount()) maxStatePossibilites *= game.maxCount(); if (game.requiresLocalState()) maxStatePossibilites *= game.maximalLocalStates(); if (game.requiresRotation()) maxStatePossibilites *= game.maximalRotationStates(); if (game.requiresPieceValue()) maxStatePossibilites *= game.maximalValue(); if (game.hiddenInformation()) maxStatePossibilites *= Math.pow(2, 7); return Double.valueOf(game.board().topology().getAllUsedGraphElements(game).size() * Math.log10(maxStatePossibilites)); } }
1,780
24.442857
121
java
Ludii
Ludii-master/Evaluation/src/metrics/single/duration/DurationActions.java
package metrics.single.duration; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.Constants; import metrics.Evaluation; import metrics.Metric; import other.concept.Concept; import other.move.Move; import other.trial.Trial; /** * Number of actions in a game. * * @author matthew.stephenson */ public class DurationActions extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public DurationActions() { super ( "Duration Actions", "Number of actions in a game.", 0.0, Constants.INFINITY, Concept.DurationActions ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Count the number of actions. double actionTally = 0; for (final Trial trial : trials) for (final Move m : trial.generateRealMovesList()) actionTally += m.actions().size(); return Double.valueOf(actionTally / trials.length); } //------------------------------------------------------------------------- }
1,231
19.196721
76
java
Ludii
Ludii-master/Evaluation/src/metrics/single/duration/DurationMoves.java
package metrics.single.duration; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.Constants; import metrics.Evaluation; import metrics.Metric; import other.concept.Concept; import other.trial.Trial; /** * Number of moves in a game. * * @author matthew.stephenson */ public class DurationMoves extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public DurationMoves() { super ( "Duration Moves", "Number of moves in a game.", 0.0, Constants.INFINITY, Concept.DurationMoves ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Count the number of moves. double moveTally = 0; for (final Trial trial : trials) moveTally += trial.numberRealMoves(); return Double.valueOf(moveTally / trials.length); } //------------------------------------------------------------------------- }
1,137
18.288136
76
java
Ludii
Ludii-master/Evaluation/src/metrics/single/duration/DurationTurns.java
package metrics.single.duration; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.Constants; import metrics.Evaluation; import metrics.Metric; import other.concept.Concept; import other.trial.Trial; /** * Number of turns in a game. * * @author matthew.stephenson */ public class DurationTurns extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public DurationTurns() { super ( "Duration Turns", "Number of turns in a game.", 0.0, Constants.INFINITY, Concept.DurationTurns ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Count the number of turns. double turnTally = 0; for (final Trial trial : trials) turnTally += trial.numTurns(); return Double.valueOf(turnTally / trials.length); } //------------------------------------------------------------------------- }
1,130
18.169492
76
java
Ludii
Ludii-master/Evaluation/src/metrics/single/duration/DurationTurnsNotTimeouts.java
package metrics.single.duration; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.Constants; import main.Status.EndType; import metrics.Evaluation; import metrics.Metric; import other.concept.Concept; import other.trial.Trial; /** * Number of turns in a game (excluding timeouts). * * @author matthew.stephenson */ public class DurationTurnsNotTimeouts extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public DurationTurnsNotTimeouts() { super ( "Duration Turns Not Timeouts", "Number of turns in a game (excluding timeouts).", 0.0, Constants.INFINITY, Concept.DurationTurnsNotTimeouts ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Count the number of turns. double turnTally = 0; double numTrials = 0; for (final Trial trial : trials) { final boolean trialTimedOut = trial.status().endType() == EndType.MoveLimit || trial.status().endType() == EndType.TurnLimit; if (!trialTimedOut) { turnTally += trial.numTurns(); numTrials++; } } // Check if all trials timed out if (numTrials == 0) { if (game.players().count() <= 1) return Double.valueOf(1); else return Double.valueOf(game.getMaxTurnLimit() * game.players().count()); } return Double.valueOf(turnTally / numTrials); } //------------------------------------------------------------------------- }
1,679
20.538462
128
java
Ludii
Ludii-master/Evaluation/src/metrics/single/duration/DurationTurnsStdDev.java
package metrics.single.duration; import java.util.ArrayList; import java.util.List; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.Constants; import metrics.Evaluation; import metrics.Metric; import other.concept.Concept; import other.trial.Trial; /** * Number of turns in a game (std dev). * * @author matthew.stephenson */ public class DurationTurnsStdDev extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public DurationTurnsStdDev() { super ( "Duration Turns Std Dev", "Number of turns in a game (std dev).", 0.0, Constants.INFINITY, Concept.DurationTurnsStdDev ); } //------------------------------------------------------------------------- private static double calculateSD(final List<Integer> turnTally) { double sum = 0.0; double standardDeviation = 0.0; final int length = turnTally.size(); for(final int num : turnTally) sum += num; final double mean = sum/length; for(final int num: turnTally) standardDeviation += Math.pow(num - mean, 2); return Math.sqrt(standardDeviation/length); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Count the number of turns. final List<Integer> turnTally = new ArrayList<>(); for (final Trial trial : trials) turnTally.add(Integer.valueOf(trial.numTurns())); return Double.valueOf(calculateSD(turnTally)); } //------------------------------------------------------------------------- }
1,798
21.209877
76
java
Ludii
Ludii-master/Evaluation/src/metrics/single/outcome/AdvantageP1.java
package metrics.single.outcome; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.RankUtils; import other.concept.Concept; import other.context.Context; import other.trial.Trial; /** * Percentage of games where player 1 won. Draws and multi-player results calculated as partial wins. * * @author matthew.stephenson */ public class AdvantageP1 extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public AdvantageP1() { super ( "AdvantageP1", "Percentage of games where player 1 won. Draws and multi-player results calculated as partial wins.", 0.0, 1.0, Concept.AdvantageP1 ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { if (game.players().count() <= 1) return null; double p1Wins = 0.0; for (int i = 0; i < trials.length; i++) { final Trial trial = trials[i]; final RandomProviderState rng = randomProviderStates[i]; final Context context = Utils.setupTrialContext(game, rng, trial); p1Wins += (RankUtils.agentUtilities(context)[1] + 1.0) / 2.0; } return Double.valueOf(p1Wins / trials.length); } //------------------------------------------------------------------------- }
1,530
21.514706
105
java
Ludii
Ludii-master/Evaluation/src/metrics/single/outcome/Balance.java
package metrics.single.outcome; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.RankUtils; import other.concept.Concept; import other.context.Context; import other.trial.Trial; /** * Similarity between player win-rates. Draws and multi-player results calculated as partial wins. * * @author cambolbro and matthew.stephenson */ public class Balance extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public Balance() { super ( "Balance", "Similarity between player win-rates. Draws and multi-player results calculated as partial wins.", 0.0, 1.0, Concept.Balance ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { final int numPlayers = game.players().count(); if (numPlayers <= 1) return null; // Count number of wins per player final int[] wins = new int[numPlayers + 1]; for (int i = 0; i < trials.length; i++) { final Trial trial = trials[i]; final RandomProviderState rng = randomProviderStates[i]; final Context context = Utils.setupTrialContext(game, rng, trial); for (int p = 1; p <= numPlayers; p++) wins[p] += (RankUtils.agentUtilities(context)[p] + 1.0) / 2.0; } // Get mean win rate over all players final double[] rate = new double[numPlayers + 1]; for (int p = 1; p <= numPlayers; p++) rate[p] = wins[p] / (double)trials.length; // Find maximum discrepancy double maxDisc = 0.0; for (int pa = 1; pa <= numPlayers; pa++) { for (int pb = pa+1; pb <= numPlayers; pb++) { final double disc = Math.abs(rate[pa] - rate[pb]); if (disc > maxDisc) maxDisc = disc; } } return Double.valueOf(1.0 - maxDisc); } //------------------------------------------------------------------------- }
2,103
22.909091
102
java
Ludii
Ludii-master/Evaluation/src/metrics/single/outcome/Completion.java
package metrics.single.outcome; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import other.concept.Concept; import other.trial.Trial; /** * Percentage of games which have a winner (not draw or timeout). * * @author cambolbro and matthew.stephenson */ public class Completion extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public Completion() { super ( "Completion", "Percentage of games which have a winner (not draw or timeout).", 0.0, 1.0, Concept.Completion ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Count number of completed games double completedGames = 0.0; for (int i = 0; i < trials.length; i++) { final Trial trial = trials[i]; if (trial.status().winner() != 0) completedGames++; } return Double.valueOf(completedGames / trials.length); } //------------------------------------------------------------------------- }
1,257
18.968254
76
java
Ludii
Ludii-master/Evaluation/src/metrics/single/outcome/Drawishness.java
package metrics.single.outcome; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.RankUtils; import other.concept.Concept; import other.context.Context; import other.trial.Trial; /** * Percentage of games which end in a draw (not including timeouts). * * @author matthew.stephenson */ public class Drawishness extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public Drawishness() { super ( "Drawishness", "Percentage of games which end in a draw (not including timeouts).", 0.0, 1.0, Concept.Drawishness ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { final int numPlayers = game.players().count(); if (numPlayers <= 1) return null; // Count number of draws double naturalDraws = 0.0; for (int i = 0; i < trials.length; i++) { final Trial trial = trials[i]; final RandomProviderState rng = randomProviderStates[i]; final Context context = Utils.setupTrialContext(game, rng, trial); // No players have won/lost. boolean allRankingZero = true; for (int j = 1; j < RankUtils.agentUtilities(context).length; j++) { if (RankUtils.agentUtilities(context)[j] != 0.0) { allRankingZero = false; break; } } if (allRankingZero) naturalDraws++; } return Double.valueOf(naturalDraws / trials.length); } //------------------------------------------------------------------------- }
1,776
20.409639
76
java
Ludii
Ludii-master/Evaluation/src/metrics/single/outcome/OutcomeUniformity.java
package metrics.single.outcome; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.math.statistics.Stats; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.RankUtils; import other.concept.Concept; import other.context.Context; import other.trial.Trial; /** * Inverse of the per-player variance in outcomes over all trials, * averaged over all players. * * @author Dennis Soemers */ public class OutcomeUniformity extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public OutcomeUniformity() { super ( "OutcomeUniformity", "Inverse of the per-player variance in outcomes over all trials, averaged over all players.", 0.0, 1.0, Concept.OutcomeUniformity ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { final int numPlayers = game.players().count(); if (numPlayers < 1) return null; final Stats[] playerStats = new Stats[numPlayers + 1]; for (int p = 1; p <= numPlayers; ++p) { playerStats[p] = new Stats(); } for (int i = 0; i < trials.length; ++i) { final Trial trial = trials[i]; final RandomProviderState rng = randomProviderStates[i]; final Context context = Utils.setupTrialContext(game, rng, trial); final double[] utils = RankUtils.agentUtilities(context); for (int p = 1; p <= numPlayers; ++p) { playerStats[p].addSample(utils[p]); } } double accum = 0.0; for (int p = 1; p <= numPlayers; ++p) { playerStats[p].measure(); accum += playerStats[p].varn(); } return Double.valueOf(1.0 - (accum / numPlayers)); } //------------------------------------------------------------------------- }
1,964
20.833333
97
java
Ludii
Ludii-master/Evaluation/src/metrics/single/outcome/Timeouts.java
package metrics.single.outcome; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.Status.EndType; import metrics.Evaluation; import metrics.Metric; import other.concept.Concept; import other.trial.Trial; /** * Percentage of games which end via timeout. * * @author cambolbro and matthew.stephenson */ public class Timeouts extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public Timeouts() { super ( "Timeouts", "Percentage of games which end via timeout.", 0.0, 1.0, Concept.Timeouts ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Count number of timeouts. double timeouts = 0.0; for (int i = 0; i < trials.length; i++) { final Trial trial = trials[i]; // Trial ended by timeout. final boolean trialTimedOut = trial.status().endType() == EndType.MoveLimit || trial.status().endType() == EndType.TurnLimit; if (trialTimedOut) timeouts++; } return Double.valueOf(timeouts / trials.length); } //------------------------------------------------------------------------- }
1,361
19.328358
128
java
Ludii
Ludii-master/Evaluation/src/metrics/single/stateEvaluation/LeadChange.java
package metrics.single.stateEvaluation; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Percentage number of times the expected winner changes. * * @author matthew.stephenson */ public class LeadChange extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public LeadChange() { super ( "Lead Change", "Percentage number of times the expected winner changes.", 0.0, 1.0, Concept.LeadChange ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Cannot perform move/state evaluation for matches. if (game.hasSubgames() || game.isSimultaneousMoveGame()) return null; double avgLeadChange = 0.0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Count number of times the expected winner changed. double leadChange = 0; Set<Integer> pastCurrentLeaders = new HashSet<>(); for (final Move m : trial.generateRealMovesList()) { final Set<Integer> currentLeaders = new HashSet<>(); final ArrayList<Double> allPlayerStateEvaluations = Utils.allPlayerStateEvaluations(evaluation, context); final double highestStateEvaluation = Collections.max(allPlayerStateEvaluations).doubleValue(); for (int j = 1; j < allPlayerStateEvaluations.size(); j++) if (allPlayerStateEvaluations.get(j).doubleValue() == highestStateEvaluation) currentLeaders.add(Integer.valueOf(j)); if (!pastCurrentLeaders.equals(currentLeaders)) leadChange++; pastCurrentLeaders = currentLeaders; context.game().apply(context, m); } avgLeadChange += leadChange / trial.generateRealMovesList().size(); } return Double.valueOf(avgLeadChange / trials.length); } //------------------------------------------------------------------------- }
2,614
25.414141
109
java
Ludii
Ludii-master/Evaluation/src/metrics/single/stateEvaluation/Stability.java
package metrics.single.stateEvaluation; import java.util.ArrayList; import java.util.List; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Average variance in each player's state evaluation. * * @author matthew.stephenson */ public class Stability extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public Stability() { super ( "Stability", "Average variance in each player's state evaluation.", 0.0, 1.0, Concept.Stability ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Cannot perform move/state evaluation for matches. if (game.hasSubgames() || game.isSimultaneousMoveGame()) return null; double avgStability = 0.0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Get the state evaluations for each player across the whole trial. final List<List<Double>> allPlayersStateEvaluationsAcrossTrial = new ArrayList<>(); for (int i = 0; i <= context.game().players().count(); i++) allPlayersStateEvaluationsAcrossTrial.add(new ArrayList<>()); final List<Move> realMoves = trial.generateRealMovesList(); for (int i = trial.numInitialPlacementMoves(); i < trial.numMoves(); i++) { final ArrayList<Double> allPlayerStateEvaluations = Utils.allPlayerStateEvaluations(evaluation, context); for (int j = 1; j < allPlayerStateEvaluations.size(); j++) allPlayersStateEvaluationsAcrossTrial.get(j).add(allPlayerStateEvaluations.get(j)); context.game().apply(context, realMoves.get(i - trial.numInitialPlacementMoves())); } // Record the average variance for each players state evaluations. double stateEvaluationVariance = 0.0; for (final List<Double> valueList : allPlayersStateEvaluationsAcrossTrial) { double metricAverage = 0.0; for (final Double value : valueList) metricAverage += value.doubleValue() / valueList.size(); double metricVariance = 0.0; for (final Double value : valueList) metricVariance += Math.pow(value.doubleValue() - metricAverage, 2) / valueList.size(); stateEvaluationVariance += metricVariance; } avgStability += stateEvaluationVariance; } return Double.valueOf(avgStability / trials.length); } //------------------------------------------------------------------------- }
3,047
27.485981
109
java
Ludii
Ludii-master/Evaluation/src/metrics/single/stateEvaluation/clarity/ClarityNarrowness.java
package metrics.single.stateEvaluation.clarity; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.math.statistics.Stats; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * The percentage of legal moves that have an evaluation value at least 75% above the difference between the max move evaluation value and average move evaluation value. * * @author matthew.stephenson */ public class ClarityNarrowness extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public ClarityNarrowness() { super ( "Clarity Narrowness", "The percentage of legal moves that have an evaluation value at least 75% above the difference between the max move evaluation value and average move evaluation value.", 0.0, 1.0, Concept.Narrowness ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { if (game.hasSubgames() || game.isSimultaneousMoveGame()) return null; double clarity = 0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Record all sites covered in this trial. final Stats moveNarrowness = new Stats(); for (final Move m : trial.generateRealMovesList()) { final Stats moveEvaluations = new Stats(); for (final Move legalMoves : context.game().moves(context).moves()) moveEvaluations.addSample(Utils.evaluateMove(evaluation, context, legalMoves).doubleValue()); moveEvaluations.measure(); final double maxEvaluation = moveEvaluations.max(); final double averageEvaluation = moveEvaluations.mean(); final double threshold = averageEvaluation + 0.75 * (maxEvaluation - averageEvaluation); int numberAboveThreshold = 0; for (int j = 0; j < moveEvaluations.n(); j++) if (moveEvaluations.get(j) > threshold) numberAboveThreshold++; moveNarrowness.addSample(moveEvaluations.n() == 0 ? 0 : numberAboveThreshold/moveEvaluations.n()); context.game().apply(context, m); } moveNarrowness.measure(); clarity += moveNarrowness.mean(); } return Double.valueOf(trials.length == 0 ? 0 : clarity / trials.length); } }
2,777
27.639175
173
java
Ludii
Ludii-master/Evaluation/src/metrics/single/stateEvaluation/clarity/ClarityVariance.java
package metrics.single.stateEvaluation.clarity; import org.apache.commons.rng.RandomProviderState; import game.Game; import main.math.statistics.Stats; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * The average variance in the evaluation values for the legal move. * * @author matthew.stephenson */ public class ClarityVariance extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public ClarityVariance() { super ( "Clarity Variance", "The average variance in the evaluation values for the legal moves.", 0.0, 1.0, Concept.Variance ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Cannot perform move/state evaluation for matches. if (game.hasSubgames() || game.isSimultaneousMoveGame()) return null; double clarity = 0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Record all sites covered in this trial. final Stats moveEvaluationVariance = new Stats(); for (final Move m : trial.generateRealMovesList()) { final Stats moveEvaluations = new Stats(); for (final Move legalMoves : context.game().moves(context).moves()) moveEvaluations.addSample(Utils.evaluateMove(evaluation, context, legalMoves).doubleValue()); moveEvaluations.measure(); moveEvaluationVariance.addSample(moveEvaluations.varn()); context.game().apply(context, m); } moveEvaluationVariance.measure(); clarity += moveEvaluationVariance.mean(); } return Double.valueOf(clarity / trials.length); } }
2,197
23.977273
98
java
Ludii
Ludii-master/Evaluation/src/metrics/single/stateEvaluation/decisiveness/DecisivenessMoves.java
package metrics.single.stateEvaluation.decisiveness; import java.util.ArrayList; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.trial.Trial; /** * Percentage number of moves after a winning player has a state evaluation above the decisiveness threshold. * * @author matthew.stephenson */ public class DecisivenessMoves extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public DecisivenessMoves() { super ( "Decisiveness Moves", "Percentage number of moves after a winning player has a state evaluation above the decisiveness threshold.", 0.0, 1.0, Concept.DecisivenessMoves ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Cannot perform move/state evaluation for matches. if (game.hasSubgames() || game.isSimultaneousMoveGame() || game.isSimulationMoveGame()) return null; double avgDecisivenessThreshold = 0.0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; final double decisivenessThreshold = DecisivenessThreshold.decisivenessThreshold(game, evaluation, trial, rngState); final Context context = Utils.setupNewContext(game, rngState); final ArrayList<Integer> highestRankedPlayers = Utils.highestRankedPlayers(trial, context); int turnAboveDecisivenessthreshold = trial.generateRealMovesList().size(); boolean aboveThresholdFound = false; for (int i = 0; i < trial.generateRealMovesList().size(); i++) { for (final Integer playerIndex : highestRankedPlayers) { if (Utils.evaluateState(evaluation, context, playerIndex.intValue()) > decisivenessThreshold) { aboveThresholdFound = true; turnAboveDecisivenessthreshold = i; break; } } if (aboveThresholdFound) break; try { context.game().apply(context, trial.getMove(i)); } catch(final Exception e) // To avoid a few exceptions in rare cases. { return null; } } avgDecisivenessThreshold += turnAboveDecisivenessthreshold/trial.generateRealMovesList().size(); } return Double.valueOf(avgDecisivenessThreshold / trials.length); } //------------------------------------------------------------------------- }
2,776
26.22549
119
java
Ludii
Ludii-master/Evaluation/src/metrics/single/stateEvaluation/decisiveness/DecisivenessThreshold.java
package metrics.single.stateEvaluation.decisiveness; import java.util.ArrayList; import org.apache.commons.rng.RandomProviderState; import game.Game; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Maximum state evaluation value achieved by non-winning player. * * @author matthew.stephenson */ public class DecisivenessThreshold extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public DecisivenessThreshold() { super ( "Decisiveness Threshold", "Maximum state evaluation value achieved by non-winning player.", 0.0, 1.0, Concept.DecisivenessThreshold ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { // Cannot perform move/state evaluation for matches. if (game.hasSubgames() || game.isSimultaneousMoveGame()) return null; double avgDecisivenessThreshold = 0.0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; final double decisivenessThreshold = decisivenessThreshold(game, evaluation, trial, rngState); avgDecisivenessThreshold += decisivenessThreshold; } return Double.valueOf(avgDecisivenessThreshold / trials.length); } //------------------------------------------------------------------------- public static double decisivenessThreshold(final Game game, final Evaluation evaluation, final Trial trial, final RandomProviderState rngState) { // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); double decisivenessThreshold = -1.0; final ArrayList<Integer> highestRankedPlayers = Utils.highestRankedPlayers(trial, context); for (final Move m : trial.generateRealMovesList()) { final ArrayList<Double> allPlayerStateEvaluations = Utils.allPlayerStateEvaluations(evaluation, context); for (int j = 1; j < allPlayerStateEvaluations.size(); j++) if (allPlayerStateEvaluations.get(j).doubleValue() > decisivenessThreshold && !highestRankedPlayers.contains(Integer.valueOf(j))) decisivenessThreshold = allPlayerStateEvaluations.get(j).doubleValue(); context.game().apply(context, m); } return decisivenessThreshold; } }
2,683
27.252632
144
java
Ludii
Ludii-master/Evaluation/src/metrics/single/stateRepetition/PositionalRepetition.java
package metrics.single.stateRepetition; import org.apache.commons.rng.RandomProviderState; import game.Game; import gnu.trove.list.array.TIntArrayList; import gnu.trove.list.array.TLongArrayList; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Percentage number of repeated positional states. * * @author matthew.stephenson */ public class PositionalRepetition extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public PositionalRepetition() { super ( "Positional Repetition", "Percentage number of repeated positional states.", 0.0, 1.0, Concept.PositionalRepetition ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { double avgStateRepeats = 0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Record the number of possible options for each move. final TLongArrayList trialStates = new TLongArrayList(); final TIntArrayList trialStateCounts = new TIntArrayList(); // Record the initial state. trialStates.add(context.state().stateHash()); trialStateCounts.add(1); for (final Move m : trial.generateRealMovesList()) { context.game().apply(context, m); final long currentState = context.state().stateHash(); final int currentStateIndex = trialStates.indexOf(currentState); if(currentStateIndex != -1) // If state was seen before { trialStateCounts.set(currentStateIndex, trialStateCounts.get(currentStateIndex) + 1); } else // If state is new { trialStates.add(currentState); trialStateCounts.add(1); } } final int numUniqueStates = trialStates.size(); final int numTotalStates = trialStateCounts.sum(); avgStateRepeats += 1.0 - (numUniqueStates / numTotalStates); } return Double.valueOf(avgStateRepeats / trials.length); } //------------------------------------------------------------------------- }
2,578
25.050505
90
java
Ludii
Ludii-master/Evaluation/src/metrics/single/stateRepetition/SituationalRepetition.java
package metrics.single.stateRepetition; import org.apache.commons.rng.RandomProviderState; import game.Game; import gnu.trove.list.array.TIntArrayList; import gnu.trove.list.array.TLongArrayList; import metrics.Evaluation; import metrics.Metric; import metrics.Utils; import other.concept.Concept; import other.context.Context; import other.move.Move; import other.trial.Trial; /** * Percentage number of repeated situational states. * * @author matthew.stephenson */ public class SituationalRepetition extends Metric { //------------------------------------------------------------------------- /** * Constructor */ public SituationalRepetition() { super ( "Situational Repetition", "Percentage number of repeated situational states.", 0.0, 1.0, Concept.SituationalRepetition ); } //------------------------------------------------------------------------- @Override public Double apply ( final Game game, final Evaluation evaluation, final Trial[] trials, final RandomProviderState[] randomProviderStates ) { double avgStateRepeats = 0; for (int trialIndex = 0; trialIndex < trials.length; trialIndex++) { // Get trial and RNG information final Trial trial = trials[trialIndex]; final RandomProviderState rngState = randomProviderStates[trialIndex]; // Setup a new instance of the game final Context context = Utils.setupNewContext(game, rngState); // Record the number of possible options for each move. final TLongArrayList trialStates = new TLongArrayList(); final TIntArrayList trialStateCounts = new TIntArrayList(); // Record the initial state. trialStates.add(context.state().fullHash()); trialStateCounts.add(1); for (final Move m : trial.generateRealMovesList()) { context.game().apply(context, m); final long currentState = context.state().fullHash(); final int currentStateIndex = trialStates.indexOf(currentState); if(currentStateIndex != -1) // If state was seen before { trialStateCounts.set(currentStateIndex, trialStateCounts.get(currentStateIndex) + 1); } else // If state is new { trialStates.add(currentState); trialStateCounts.add(1); } } final int numUniqueStates = trialStates.size(); final int numTotalStates = trialStateCounts.sum(); avgStateRepeats += 1.0 - (numUniqueStates / numTotalStates); } return Double.valueOf(avgStateRepeats / trials.length); } //------------------------------------------------------------------------- }
2,582
25.090909
90
java
Ludii
Ludii-master/Features/src/features/Feature.java
package features; import features.aspatial.AspatialFeature; import features.aspatial.InterceptFeature; import features.aspatial.PassMoveFeature; import features.aspatial.SwapMoveFeature; import features.spatial.AbsoluteFeature; import features.spatial.RelativeFeature; import game.Game; /** * Abstract class for features; can be spatial or aspatial. * * @author Dennis Soemers */ public abstract class Feature { //------------------------------------------------------------------------- /** * @param string * @return Feature constructed from given string */ public static Feature fromString(final String string) { if (string.contains("abs:")) return new AbsoluteFeature(string); else if (string.contains("rel:")) return new RelativeFeature(string); else return aspatialFromString(string); } //------------------------------------------------------------------------- /** * @param string * @return Aspatial feature constructed from given string */ private static AspatialFeature aspatialFromString(final String string) { if (string.equals("PassMove")) return PassMoveFeature.instance(); else if (string.equals("SwapMove")) return SwapMoveFeature.instance(); else if (string.equals("Intercept")) return InterceptFeature.instance(); else System.err.println("Cannot construct aspatial feature from string: " + string); return null; } //------------------------------------------------------------------------- /** * @param game Game to visualise for * @return Tikz code to visualise this feature in a Tikz environment in LaTeX. */ public abstract String generateTikzCode(final Game game); //------------------------------------------------------------------------- }
1,757
25.636364
82
java
Ludii
Ludii-master/Features/src/features/FeatureVector.java
package features; import gnu.trove.list.array.TIntArrayList; import main.collections.FVector; /** * Wrapper to represent a "vector" of features; internally, does not just hold a * single vector, but uses a sparse representation for binary (typically sparsely * active) spatial features, and a dense floats representation for aspatial features * (which are not necessarily binary). * * @author Dennis Soemers */ public class FeatureVector { //------------------------------------------------------------------------- /** Indices of spatial features that are active */ private final TIntArrayList activeSpatialFeatureIndices; /** Vector of values for aspatial features */ private final FVector aspatialFeatureValues; //------------------------------------------------------------------------- /** * Constructor * @param activeSpatialFeatureIndices * @param aspatialFeatureValues */ public FeatureVector(final TIntArrayList activeSpatialFeatureIndices, final FVector aspatialFeatureValues) { this.activeSpatialFeatureIndices = activeSpatialFeatureIndices; this.aspatialFeatureValues = aspatialFeatureValues; } //------------------------------------------------------------------------- /** * @return Indices of active spatial features (sparse representation) */ public TIntArrayList activeSpatialFeatureIndices() { return activeSpatialFeatureIndices; } /** * @return Vector of feature values for aspatial features (dense representation) */ public FVector aspatialFeatureValues() { return aspatialFeatureValues; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((activeSpatialFeatureIndices == null) ? 0 : activeSpatialFeatureIndices.hashCode()); result = prime * result + ((aspatialFeatureValues == null) ? 0 : aspatialFeatureValues.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof FeatureVector)) return false; final FeatureVector other = (FeatureVector) obj; if (activeSpatialFeatureIndices == null) { if (other.activeSpatialFeatureIndices != null) return false; } else if (!activeSpatialFeatureIndices.equals(other.activeSpatialFeatureIndices)) { return false; } if (aspatialFeatureValues == null) { if (other.aspatialFeatureValues != null) return false; } else if (!aspatialFeatureValues.equals(other.aspatialFeatureValues)) { return false; } return true; } //------------------------------------------------------------------------- @Override public String toString() { return "<Aspatial feature values: " + aspatialFeatureValues + ", Spatial indices: " + activeSpatialFeatureIndices + ">"; } //------------------------------------------------------------------------- }
2,963
25.464286
122
java
Ludii
Ludii-master/Features/src/features/WeightVector.java
package features; import main.collections.FVector; /** * Wrapper to represent a vector of weights. Internally stores it as just a single * vector, where the first N weights are for aspatial features, and the remaining * weights are for spatial features. * * @author Dennis Soemers */ public class WeightVector { //------------------------------------------------------------------------- /** Our vector of weights */ private final FVector weights; //------------------------------------------------------------------------- /** * Constructor * @param weights */ public WeightVector(final FVector weights) { this.weights = weights; } /** * Copy constructor * @param other */ public WeightVector(final WeightVector other) { this.weights = new FVector(other.weights); } //------------------------------------------------------------------------- /** * @param featureVector * @return Dot product of this weight vector with given feature vector */ public float dot(final FeatureVector featureVector) { final FVector aspatialFeatureValues = featureVector.aspatialFeatureValues(); // This dot product call will only use the first N weights, where N is the length // of the aspatial feature values vector final float aspatialFeaturesVal = aspatialFeatureValues.dot(weights); // For the spatial features, use this offset (to skip weights for aspatial features) final int offset = aspatialFeatureValues.dim(); return aspatialFeaturesVal + weights.dotSparse(featureVector.activeSpatialFeatureIndices(), offset); } //------------------------------------------------------------------------- /** * @return Vector containing all weights; first those for aspatial features, followed * by those for spatial features. */ public FVector allWeights() { return weights; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((weights == null) ? 0 : weights.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof WeightVector)) return false; final WeightVector other = (WeightVector) obj; if (weights == null) { if (other.weights != null) return false; } return weights.equals(other.weights); } //------------------------------------------------------------------------- }
2,514
23.182692
102
java
Ludii
Ludii-master/Features/src/features/aspatial/AspatialFeature.java
package features.aspatial; import features.Feature; import other.move.Move; import other.state.State; /** * An aspatial (i.e., not spatial) state-action feature. These features are not * necessarily binary, i.e. they can return floats. * * @author Dennis Soemers */ public abstract class AspatialFeature extends Feature { //------------------------------------------------------------------------- /** * @param state * @param move * @return Feature value for given move in given state. */ public abstract float featureVal(final State state, final Move move); //------------------------------------------------------------------------- @Override public String toString() { throw new UnsupportedOperationException(); } //------------------------------------------------------------------------- }
831
22.111111
79
java
Ludii
Ludii-master/Features/src/features/aspatial/InterceptFeature.java
package features.aspatial; import game.Game; import other.move.Move; import other.state.State; /** * Intercept feature (always a value of 1.0) * * @author Dennis Soemers */ public class InterceptFeature extends AspatialFeature { //------------------------------------------------------------------------- /** The singleton instance */ private static final InterceptFeature INSTANCE = new InterceptFeature(); //------------------------------------------------------------------------- /** * Private: singleton */ private InterceptFeature() { // Do nothing } //------------------------------------------------------------------------- @Override public float featureVal(final State state, final Move move) { return 1.f; } //------------------------------------------------------------------------- @Override public String toString() { return "Intercept"; } //------------------------------------------------------------------------- @Override public String generateTikzCode(final Game game) { return "\\node[rectangle,draw{,REL_POS}] ({LABEL}) {Intercept};"; } //------------------------------------------------------------------------- /** * @return The singleton instance */ public static InterceptFeature instance() { return INSTANCE; } //------------------------------------------------------------------------- }
1,395
19.835821
76
java
Ludii
Ludii-master/Features/src/features/aspatial/PassMoveFeature.java
package features.aspatial; import game.Game; import other.move.Move; import other.state.State; /** * Binary feature that has a value of 1.0 for any move that is a pass move. * * @author Dennis Soemers */ public class PassMoveFeature extends AspatialFeature { //------------------------------------------------------------------------- /** The singleton instance */ private static final PassMoveFeature INSTANCE = new PassMoveFeature(); //------------------------------------------------------------------------- /** * Private: singleton */ private PassMoveFeature() { // Do nothing } //------------------------------------------------------------------------- @Override public float featureVal(final State state, final Move move) { if (move.isPass()) return 1.f; else return 0.f; } //------------------------------------------------------------------------- @Override public String toString() { return "PassMove"; } //------------------------------------------------------------------------- @Override public String generateTikzCode(final Game game) { return "\\node[rectangle,draw{,REL_POS}] ({LABEL}) {Pass};"; } //------------------------------------------------------------------------- /** * @return The singleton instance */ public static PassMoveFeature instance() { return INSTANCE; } //------------------------------------------------------------------------- }
1,457
19.828571
76
java
Ludii
Ludii-master/Features/src/features/aspatial/SwapMoveFeature.java
package features.aspatial; import game.Game; import other.move.Move; import other.state.State; /** * Binary feature that has a value of 1.0 for any move that is a swap move. * * @author Dennis Soemers */ public class SwapMoveFeature extends AspatialFeature { //------------------------------------------------------------------------- /** The singleton instance */ private static final SwapMoveFeature INSTANCE = new SwapMoveFeature(); //------------------------------------------------------------------------- /** * Private: singleton */ private SwapMoveFeature() { // Do nothing } //------------------------------------------------------------------------- @Override public float featureVal(final State state, final Move move) { if (move.isSwap()) return 1.f; else return 0.f; } //------------------------------------------------------------------------- @Override public String toString() { return "SwapMove"; } //------------------------------------------------------------------------- @Override public String generateTikzCode(final Game game) { return "\\node[rectangle,draw{,REL_POS}] ({LABEL}) {Swap};"; } //------------------------------------------------------------------------- /** * @return The singleton instance */ public static SwapMoveFeature instance() { return INSTANCE; } //------------------------------------------------------------------------- }
1,457
19.828571
76
java
Ludii
Ludii-master/Features/src/features/feature_sets/BaseFeatureSet.java
package features.feature_sets; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import features.Feature; import features.FeatureVector; import features.WeightVector; import features.aspatial.AspatialFeature; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.cache.footprints.BaseFootprint; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.list.array.TIntArrayList; import main.collections.FVector; import main.collections.FastArrayList; import other.context.Context; import other.move.Move; import other.state.State; /** * Abstract class for Feature Sets (basically; things that can compute feature * vectors for game states + actions). * * @author Dennis Soemers */ public abstract class BaseFeatureSet { //------------------------------------------------------------------------- /** * Different implementations we have for evaluating feature sets. * * @author Dennis Soemers */ public static enum FeatureSetImplementations { NAIVE, TREE, SPATTERNET, JITSPATTERNET } //------------------------------------------------------------------------- /** Only spatial features with an absolute value greater than this are considered relevant for AI */ public static final float SPATIAL_FEATURE_WEIGHT_THRESHOLD = 0.001f; /** Reference to game for which we currently have instantiated features */ protected WeakReference<Game> game = new WeakReference<>(null); /** Vector of feature weights for which we have last instantiated features */ protected FVector spatialFeatureInitWeights = null; //------------------------------------------------------------------------- /** Array of aspatial features */ protected AspatialFeature[] aspatialFeatures; /** Array of features */ protected SpatialFeature[] spatialFeatures; //------------------------------------------------------------------------- /** * @return The array of aspatial features contained in this feature set */ public final AspatialFeature[] aspatialFeatures() { return aspatialFeatures; } /** * @return The array of spatial features contained in this feature set */ public final SpatialFeature[] spatialFeatures() { return spatialFeatures; } /** * @return The number of aspatial features in this feature set */ public final int getNumAspatialFeatures() { return aspatialFeatures.length; } /** * @return The number of spatial features in this feature set */ public final int getNumSpatialFeatures() { return spatialFeatures.length; } /** * @return Number of features in this feature set (spatial + aspatial features) */ public final int getNumFeatures() { return spatialFeatures.length + aspatialFeatures.length; } /** * @return Weak reference to game for which we last initialised */ public WeakReference<Game> gameRef() { return game; } /** * Lets the feature set initialise itself for a given game, array of supported players, and vector of weights * (for example, can instantiate features here). * @param newGame * @param supportedPlayers * @param weights */ public void init(final Game newGame, final int[] supportedPlayers, final WeightVector weights) { final FVector spatialOnlyWeights; if (weights == null) spatialOnlyWeights = null; else spatialOnlyWeights = weights.allWeights().range(aspatialFeatures.length, weights.allWeights().dim()); if (this.game.get() == newGame) { if (this.spatialFeatureInitWeights == null && spatialOnlyWeights == null) return; // Nothing to do, already instantiated else if (this.spatialFeatureInitWeights != null && this.spatialFeatureInitWeights.equals(spatialOnlyWeights)) return; // Also nothing to do here } this.game = new WeakReference<>(newGame); if (spatialOnlyWeights == null) spatialFeatureInitWeights = null; else spatialFeatureInitWeights = spatialOnlyWeights; // Need to instantiate instantiateFeatures(supportedPlayers); } /** * Lets the feature set instantiate its features * @param supportedPlayers */ protected abstract void instantiateFeatures(final int[] supportedPlayers); /** * Closes / cleans up cache of active features */ public abstract void closeCache(); /** * @param state * @param from * @param to * @param player * @return The complete footprint of all tests that may possibly be run * for computing proactive features of actions with the given from- and to- * positions. */ public abstract BaseFootprint generateFootprint ( final State state, final int from, final int to, final int player ); //------------------------------------------------------------------------- /** * @param context * @param action * @param thresholded * * @return A sparse feature vector for a single action */ public TIntArrayList computeSparseSpatialFeatureVector ( final Context context, final Move action, final boolean thresholded ) { return computeSparseSpatialFeatureVector(context.state(), context.trial().lastMove(), action, thresholded); } /** * @param context * @param actions * @param thresholded * * @return A list of sparse feature vectors (one for every given action in the given trial) */ public TIntArrayList[] computeSparseSpatialFeatureVectors ( final Context context, final FastArrayList<Move> actions, final boolean thresholded ) { return computeSparseSpatialFeatureVectors(context.state(), context.trial().lastMove(), actions, thresholded); } /** * @param state * @param lastDecisionMove * @param action * @param thresholded * * @return A spare feature vector for a single action */ public TIntArrayList computeSparseSpatialFeatureVector ( final State state, final Move lastDecisionMove, final Move action, final boolean thresholded ) { final int lastFrom = FeatureUtils.fromPos(lastDecisionMove); final int lastTo = FeatureUtils.toPos(lastDecisionMove); final int from = FeatureUtils.fromPos(action); final int to = FeatureUtils.toPos(action); // System.out.println("last decision move = " + trial.lastDecisionMove()); // System.out.println("lastFrom = " + lastFrom); // System.out.println("lastTo = " + lastTo); // System.out.println("from = " + from); // System.out.println("to = " + to); final TIntArrayList sparseFeatureVector = getActiveSpatialFeatureIndices(state, lastFrom, lastTo, from, to, action.mover(), thresholded); return sparseFeatureVector; } /** * @param state * @param lastDecisionMove * @param actions * @param thresholded * * @return A list of sparse feature vectors (one for every given action in the given trial) */ public TIntArrayList[] computeSparseSpatialFeatureVectors ( final State state, final Move lastDecisionMove, final FastArrayList<Move> actions, final boolean thresholded ) { final TIntArrayList[] sparseFeatureVectors = new TIntArrayList[actions.size()]; for (int i = 0; i < actions.size(); ++i) { final Move action = actions.get(i); sparseFeatureVectors[i] = computeSparseSpatialFeatureVector(state, lastDecisionMove, action, thresholded); } return sparseFeatureVectors; } /** * @param context * @param move * @return List of all active features for given move in given context (spatial and aspatial ones). * Non-binary features are considered to be active if their value is not equal to 0 */ public List<Feature> computeActiveFeatures(final Context context, final Move move) { final List<Feature> activeFeatures = new ArrayList<Feature>(); // Compute and add spatial features final Move lastDecisionMove = context.trial().lastMove(); final int lastFrom = FeatureUtils.fromPos(lastDecisionMove); final int lastTo = FeatureUtils.toPos(lastDecisionMove); final int from = FeatureUtils.fromPos(move); final int to = FeatureUtils.toPos(move); final TIntArrayList activeSpatialFeatureIndices = getActiveSpatialFeatureIndices ( context.state(), lastFrom, lastTo, from, to, move.mover(), false ); for (int i = 0; i < activeSpatialFeatureIndices.size(); ++i) { activeFeatures.add(spatialFeatures[activeSpatialFeatureIndices.getQuick(i)]); } // Compute and add active aspatial features for (final AspatialFeature feature : aspatialFeatures) { if (feature.featureVal(context.state(), move) != 0.f) activeFeatures.add(feature); } return activeFeatures; } /** * @param context * @param moves * @param thresholded * @return Features vectors for all the given moves in given context */ public FeatureVector[] computeFeatureVectors ( final Context context, final FastArrayList<Move> moves, final boolean thresholded ) { final FeatureVector[] featureVectors = new FeatureVector[moves.size()]; for (int i = 0; i < moves.size(); ++i) { featureVectors[i] = computeFeatureVector(context, moves.get(i), thresholded); } return featureVectors; } /** * @param context * @param move * @param thresholded Whether to use thresholding for spatial features * @return Feature vector for given move in given context */ public FeatureVector computeFeatureVector(final Context context, final Move move, final boolean thresholded) { // Compute active spatial feature indices final Move lastDecisionMove = context.trial().lastMove(); final int lastFrom = FeatureUtils.fromPos(lastDecisionMove); final int lastTo = FeatureUtils.toPos(lastDecisionMove); final int from = FeatureUtils.fromPos(move); final int to = FeatureUtils.toPos(move); final TIntArrayList activeSpatialFeatureIndices = getActiveSpatialFeatureIndices ( context.state(), lastFrom, lastTo, from, to, move.mover(), thresholded ); // Compute aspatial feature values final float[] aspatialFeatureValues = new float[aspatialFeatures.length]; for (int i = 0; i < aspatialFeatures.length; ++i) { aspatialFeatureValues[i] = aspatialFeatures[i].featureVal(context.state(), move); } return new FeatureVector(activeSpatialFeatureIndices, new FVector(aspatialFeatureValues)); } /** * @param state * @param lastMove * @param moves * @param thresholded * @return Features vectors for all the given moves in given context */ public FeatureVector[] computeFeatureVectors ( final State state, final Move lastMove, final FastArrayList<Move> moves, final boolean thresholded ) { final int lastFrom = FeatureUtils.fromPos(lastMove); final int lastTo = FeatureUtils.toPos(lastMove); final FeatureVector[] featureVectors = new FeatureVector[moves.size()]; for (int i = 0; i < moves.size(); ++i) { final Move move = moves.get(i); final int from = FeatureUtils.fromPos(move); final int to = FeatureUtils.toPos(move); final TIntArrayList activeSpatialFeatureIndices = getActiveSpatialFeatureIndices ( state, lastFrom, lastTo, from, to, move.mover(), thresholded ); final float[] aspatialFeatureValues = new float[aspatialFeatures.length]; for (int j = 0; j < aspatialFeatures.length; ++j) { aspatialFeatureValues[j] = aspatialFeatures[j].featureVal(state, move); } featureVectors[i] = new FeatureVector(activeSpatialFeatureIndices, new FVector(aspatialFeatureValues)); } return featureVectors; } //------------------------------------------------------------------------- /** * @param state * @param lastFrom * @param lastTo * @param from * @param to * @param player * @param thresholded * * @return A list of indices of all the features that are active for a * given state+action pair (where action is defined by from and * to positions) */ public abstract TIntArrayList getActiveSpatialFeatureIndices ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player, final boolean thresholded ); /** * @param state * @param lastFrom * @param lastTo * @param from * @param to * @param player * @return A list of all spatial feature instances that are active for a given * state+action pair (where action is defined by from and to positions) */ public abstract List<FeatureInstance> getActiveSpatialFeatureInstances ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player ); //------------------------------------------------------------------------- /** * @param targetGame * @param newFeature * @return Expanded feature set with the new feature added, or null in the case of failure. */ public abstract BaseFeatureSet createExpandedFeatureSet ( final Game targetGame, final SpatialFeature newFeature ); /** * @param targetGame * @param newFeatures * @return Expanded feature set with multiple new features added, or original object * if none of the new features were successfully added. */ public BaseFeatureSet createExpandedFeatureSet(final Game targetGame, final List<SpatialFeature> newFeatures) { BaseFeatureSet featureSet = this; for (final SpatialFeature feature : newFeatures) { final BaseFeatureSet expanded = featureSet.createExpandedFeatureSet(targetGame, feature); if (expanded != null) { featureSet = expanded; } } return featureSet; } //------------------------------------------------------------------------- /** * NOTE: implementation not very fast. * * @param s * @return Index of feature in this feature set that matches given string, or -1 if none found. */ public int findFeatureIndexForString(final String s) { for (int i = 0; i < aspatialFeatures.length; ++i) { if (aspatialFeatures[i].toString().equals(s)) return i; } for (int i = 0; i < spatialFeatures.length; ++i) { if (spatialFeatures[i].toString().equals(s)) return i; } return -1; } //------------------------------------------------------------------------- /** * Writes the feature set to a file * @param filepath Filepath to write to */ public void toFile(final String filepath) { try (final PrintWriter writer = new PrintWriter(filepath, "UTF-8")) { writer.print(toString()); } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public String toString() { final StringBuilder sb = new StringBuilder(); for (final AspatialFeature feature : aspatialFeatures) { sb.append(feature + System.lineSeparator()); } for (final SpatialFeature feature : spatialFeatures) { sb.append(feature + System.lineSeparator()); } return sb.toString(); } //------------------------------------------------------------------------- /** * Interface for move features keys (either proactive or reactive) * * @author Dennis Soemers */ public interface MoveFeaturesKey { /** @return Player index for the key */ public int playerIdx(); /** @return From position for the key */ public int from(); /** @return To position for the key */ public int to(); /** @return Last from position for the key */ public int lastFrom(); /** @return Last to position for the key */ public int lastTo(); } /** * Small class for objects used as keys in HashMaps related to proactive * features. * * @author Dennis Soemers */ public static class ProactiveFeaturesKey implements MoveFeaturesKey { //-------------------------------------------------------------------- /** Player index */ private int playerIdx = -1; /** from-position */ private int from = -1; /** to-position */ private int to = -1; /** Cached hash code */ private transient int cachedHashCode = -1; //-------------------------------------------------------------------- /** * Default constructor */ public ProactiveFeaturesKey() { // Do nothing } /** * Copy constructor * @param other */ public ProactiveFeaturesKey(final ProactiveFeaturesKey other) { resetData(other.playerIdx, other.from, other.to); } //-------------------------------------------------------------------- /** * Resets the data in this object and recomputes cached hash code * @param p Player Index * @param f From * @param t To */ public void resetData(final int p, final int f, final int t) { this.playerIdx = p; this.from = f; this.to = t; // Create and cache hash code final int prime = 31; int result = 17; result = prime * result + from; result = prime * result + playerIdx; result = prime * result + to; cachedHashCode = result; } //-------------------------------------------------------------------- @Override public int playerIdx() { return playerIdx; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int lastFrom() { return -1; } @Override public int lastTo() { return -1; } //-------------------------------------------------------------------- @Override public int hashCode() { return cachedHashCode; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ProactiveFeaturesKey)) return false; final ProactiveFeaturesKey other = (ProactiveFeaturesKey) obj; return (playerIdx == other.playerIdx && from == other.from && to == other.to); } @Override public String toString() { return "[ProactiveFeaturesKey: " + playerIdx + ", " + from + ", " + to + "]"; } //-------------------------------------------------------------------- } //------------------------------------------------------------------------- /** * Small class for objects used as keys in HashMaps related to reactive * features. * * @author Dennis Soemers */ public static class ReactiveFeaturesKey implements MoveFeaturesKey { //-------------------------------------------------------------------- /** Player index */ private int playerIdx = -1; /** Last from-position */ private int lastFrom = -1; /** Last to-position */ private int lastTo = -1; /** from-position */ private int from = -1; /** to-position */ private int to = -1; /** Cached hash code */ private transient int cachedHashCode = -1; //-------------------------------------------------------------------- /** * Default constructor */ public ReactiveFeaturesKey() { // Do nothing } /** * Copy constructor * @param other */ public ReactiveFeaturesKey(final ReactiveFeaturesKey other) { resetData(other.playerIdx, other.lastFrom, other.lastTo, other.from, other.to); } //-------------------------------------------------------------------- /** * Resets the data in this object and recomputes cached hash code * @param p Player Index * @param lastF Last from * @param lastT last To * @param f From * @param t To */ public void resetData(final int p, final int lastF, final int lastT, final int f, final int t) { this.playerIdx = p; this.lastFrom = lastF; this.lastTo = lastT; this.from = f; this.to = t; // Create and cache hash code final int prime = 31; int result = 17; result = prime * result + from; result = prime * result + lastFrom; result = prime * result + lastTo; result = prime * result + playerIdx; result = prime * result + to; cachedHashCode = result; } //-------------------------------------------------------------------- @Override public int playerIdx() { return playerIdx; } @Override public int from() { return from; } @Override public int to() { return to; } @Override public int lastFrom() { return lastFrom; } @Override public int lastTo() { return lastTo; } //-------------------------------------------------------------------- @Override public int hashCode() { return cachedHashCode; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof ReactiveFeaturesKey)) return false; final ReactiveFeaturesKey other = (ReactiveFeaturesKey) obj; return (playerIdx == other.playerIdx && lastFrom == other.lastFrom && lastTo == other.lastTo && from == other.from && to == other.to); } @Override public String toString() { return "[ReactiveFeaturesKey: " + playerIdx + ", " + from + ", " + to + ", " + lastFrom + ", " + lastTo + "]"; } //-------------------------------------------------------------------- } //------------------------------------------------------------------------- }
21,144
23.644522
113
java
Ludii
Ludii-master/Features/src/features/feature_sets/LegacyFeatureSet.java
package features.feature_sets; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Stream; import features.Feature; import features.aspatial.AspatialFeature; import features.spatial.SpatialFeature; import features.spatial.Walk; import features.spatial.cache.ActiveFeaturesCache; import features.spatial.cache.footprints.BaseFootprint; import features.spatial.cache.footprints.FullFootprint; import features.spatial.instances.BitwiseTest; import features.spatial.instances.FeatureInstance; import features.spatial.instances.OneOfMustEmpty; import features.spatial.instances.OneOfMustWhat; import features.spatial.instances.OneOfMustWho; import game.Game; import gnu.trove.iterator.TIntIterator; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import main.collections.ChunkSet; import main.collections.FVector; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.trial.Trial; /** * NOTE: legacy version, old implementation based on intuition, should be retired in favour * of the more principled SPatterNet implementation. * * A collection of features which can be loaded/saved from/to files, can be instantiated for * any game, and has consistent indices per feature (which means it can be used in a consistent * manner in combination with a file of learned weights/parameters for example) * * @author Dennis Soemers */ public class LegacyFeatureSet extends BaseFeatureSet { //------------------------------------------------------------------------- /** * Reactive instances, indexed by: * player index, * last-from-pos * last-to-pos, * from-pos * to-pos * * When indexed according to all of the above, we're left with a forest * containing all relevant instances. */ protected HashMap<ReactiveFeaturesKey, FastFeatureInstanceNode[]> reactiveInstances; /** * Proactive instances, indexed by: * player index, * from-pos * to-pos * * When indexed according to all of the above, we're left with a forest * containing all relevant instances */ protected HashMap<ProactiveFeaturesKey, FastFeatureInstanceNode[]> proactiveInstances; /** * Reactive Features, indexed by: * player index, * last-from-pos * last-to-pos, * from-pos * to-pos * * When indexed according to all of the above, we're left with a forest * containing all relevant Features. */ protected HashMap<ReactiveFeaturesKey, FastFeaturesNode[]> reactiveFeatures; /** * Proactive Features, indexed by: * player index, * from-pos * to-pos * * When indexed according to all of the above, we're left with a forest * containing all relevant Features. */ protected HashMap<ProactiveFeaturesKey, FastFeaturesNode[]> proactiveFeatures; /** * Same as above, but only includes features with absolute weights that exceed the above * threshold. */ protected HashMap<ReactiveFeaturesKey, FastFeaturesNode[]> reactiveFeaturesThresholded; /** * Same as above, but only includes features with absolute weights that exceed the above * threshold. */ protected HashMap<ProactiveFeaturesKey, FastFeaturesNode[]> proactiveFeaturesThresholded; /** Cache with indices of active proactive features previously computed */ protected ActiveFeaturesCache activeProactiveFeaturesCache; //------------------------------------------------------------------------- /** * Construct feature set from lists of features * @param aspatialFeatures * @param spatialFeatures */ public LegacyFeatureSet(final List<AspatialFeature> aspatialFeatures, final List<SpatialFeature> spatialFeatures) { this.spatialFeatures = new SpatialFeature[spatialFeatures.size()]; for (int i = 0; i < this.spatialFeatures.length; ++i) { this.spatialFeatures[i] = spatialFeatures.get(i); this.spatialFeatures[i].setSpatialFeatureSetIndex(i); } this.aspatialFeatures = aspatialFeatures.toArray(new AspatialFeature[aspatialFeatures.size()]); reactiveInstances = null; proactiveInstances = null; reactiveFeatures = null; proactiveFeatures = null; reactiveFeaturesThresholded = null; proactiveFeaturesThresholded = null; } /** * Loads a feature set from a given filename * @param filename */ public LegacyFeatureSet(final String filename) { Feature[] tempFeatures; //System.out.println("loading feature set from " + filename); try (Stream<String> stream = Files.lines(Paths.get(filename))) { tempFeatures = stream.map(s -> Feature.fromString(s)).toArray(Feature[]::new); } catch (final IOException exception) { tempFeatures = null; exception.printStackTrace(); } final List<AspatialFeature> aspatialFeaturesList = new ArrayList<AspatialFeature>(); final List<SpatialFeature> spatialFeaturesList = new ArrayList<SpatialFeature>(); for (final Feature feature : tempFeatures) { if (feature instanceof AspatialFeature) { aspatialFeaturesList.add((AspatialFeature)feature); } else { ((SpatialFeature)feature).setSpatialFeatureSetIndex(spatialFeaturesList.size()); spatialFeaturesList.add((SpatialFeature)feature); } } this.aspatialFeatures = aspatialFeaturesList.toArray(new AspatialFeature[aspatialFeaturesList.size()]); this.spatialFeatures = spatialFeaturesList.toArray(new SpatialFeature[spatialFeaturesList.size()]); } //------------------------------------------------------------------------- @Override protected void instantiateFeatures(final int[] supportedPlayers) { activeProactiveFeaturesCache = new ActiveFeaturesCache(); // First we create ''WIP'' versions of these maps, with the slower // node class (necessary when the structure of the tree may still // change) Map<ReactiveFeaturesKey, List<FeatureInstanceNode>> reactiveInstancesWIP = new HashMap<ReactiveFeaturesKey, List<FeatureInstanceNode>>(); Map<ProactiveFeaturesKey, List<FeatureInstanceNode>> proactiveInstancesWIP = new HashMap<ProactiveFeaturesKey, List<FeatureInstanceNode>>(); // Create a dummy context because we need some context for // feature generation final Context featureGenContext = new Context(game.get(), new Trial(game.get())); final ProactiveFeaturesKey proactiveKey = new ProactiveFeaturesKey(); final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); for (int i = 0; i < supportedPlayers.length; ++i) { final int player = supportedPlayers[i]; for (final SpatialFeature feature : spatialFeatures) { final List<FeatureInstance> newInstances = feature.instantiateFeature ( game.get(), featureGenContext.state().containerStates()[0], player, -1, -1, -1, -1, -1 ); for (final FeatureInstance instance : newInstances) { final int lastFrom = instance.lastFrom(); final int lastTo = instance.lastTo(); final int from = instance.from(); final int to = instance.to(); if (lastFrom >= 0 || lastTo >= 0) // reactive feature { reactiveKey.resetData(player, lastFrom, lastTo, from, to); List<FeatureInstanceNode> instanceNodes = reactiveInstancesWIP.get(reactiveKey); if (instanceNodes == null) { instanceNodes = new ArrayList<FeatureInstanceNode>(1); reactiveInstancesWIP.put(new ReactiveFeaturesKey(reactiveKey), instanceNodes); } insertInstanceInForest(instance, instanceNodes); } else // proactive feature { proactiveKey.resetData(player, from, to); List<FeatureInstanceNode> instanceNodes = proactiveInstancesWIP.get(proactiveKey); if (instanceNodes == null) { instanceNodes = new ArrayList<FeatureInstanceNode>(1); proactiveInstancesWIP.put(new ProactiveFeaturesKey(proactiveKey), instanceNodes); } insertInstanceInForest(instance, instanceNodes); } } } } // simplify all our WIP forests simplifyInstanceForests(reactiveInstancesWIP, proactiveInstancesWIP); // now convert all our forests to variants with the more efficient // node class, and store them permanently reactiveInstances = new HashMap<ReactiveFeaturesKey, FastFeatureInstanceNode[]>( (int) Math.ceil(reactiveInstancesWIP.size() / 0.75f), 0.75f); for ( final Entry<ReactiveFeaturesKey, List<FeatureInstanceNode>> entry : reactiveInstancesWIP.entrySet() ) { final FastFeatureInstanceNode[] roots = new FastFeatureInstanceNode[entry.getValue().size()]; for (int i = 0; i < roots.length; ++i) { roots[i] = new FastFeatureInstanceNode(entry.getValue().get(i)); } reactiveInstances.put(entry.getKey(), roots); } proactiveInstances = new HashMap<ProactiveFeaturesKey, FastFeatureInstanceNode[]> ( (int) Math.ceil(proactiveInstancesWIP.size() / 0.75f), 0.75f ); for ( final Entry<ProactiveFeaturesKey, List<FeatureInstanceNode>> entry : proactiveInstancesWIP.entrySet() ) { final FastFeatureInstanceNode[] roots = new FastFeatureInstanceNode[entry.getValue().size()]; for (int i = 0; i < roots.length; ++i) { roots[i] = new FastFeatureInstanceNode(entry.getValue().get(i)); } proactiveInstances.put(entry.getKey(), roots); } // and also create the even more efficient forests for cases where // we only need to distinguish between features, rather than feature // instances reactiveFeatures = new HashMap<ReactiveFeaturesKey, FastFeaturesNode[]> ( (int) Math.ceil(reactiveInstances.size() / 0.75f), 0.75f ); for ( final Entry<ReactiveFeaturesKey, FastFeatureInstanceNode[]> entry : reactiveInstances.entrySet() ) { final FastFeaturesNode[] roots = new FastFeaturesNode[entry.getValue().length]; for (int i = 0; i < roots.length; ++i) { roots[i] = new FastFeaturesNode(entry.getValue()[i]); } reactiveFeatures.put(entry.getKey(), roots); } proactiveFeatures = new HashMap<ProactiveFeaturesKey, FastFeaturesNode[]> ( (int) Math.ceil(proactiveInstances.size() / 0.75f), 0.75f ); for ( final Entry<ProactiveFeaturesKey, FastFeatureInstanceNode[]> entry : proactiveInstances.entrySet() ) { final FastFeaturesNode[] roots = new FastFeaturesNode[entry.getValue().length]; for (int i = 0; i < roots.length; ++i) { roots[i] = new FastFeaturesNode(entry.getValue()[i]); } proactiveFeatures.put(entry.getKey(), roots); } // System.out.println("---"); // proactiveFeatures.get(new ProactiveFeaturesKey(1, -1, 0))[0].print(0); // System.out.println("---"); // finally, even more optimised forests where we remove nodes that // are irrelevant due to low feature weights reactiveFeaturesThresholded = new HashMap<ReactiveFeaturesKey, FastFeaturesNode[]> ( (int) Math.ceil(reactiveFeatures.size() / 0.75f), 0.75f ); for ( final Entry<ReactiveFeaturesKey, FastFeaturesNode[]> entry : reactiveFeatures.entrySet() ) { final List<FastFeaturesNode> roots = new ArrayList<FastFeaturesNode>(entry.getValue().length); for (final FastFeaturesNode node : entry.getValue()) { final FastFeaturesNode optimisedNode = FastFeaturesNode.thresholdedNode(node, spatialFeatureInitWeights); if (optimisedNode != null) roots.add(optimisedNode); } reactiveFeaturesThresholded.put(entry.getKey(), roots.toArray(new FastFeaturesNode[0])); } proactiveFeaturesThresholded = new HashMap<ProactiveFeaturesKey, FastFeaturesNode[]> ( (int) Math.ceil(proactiveFeatures.size() / 0.75f), 0.75f ); for ( final Entry<ProactiveFeaturesKey, FastFeaturesNode[]> entry : proactiveFeatures.entrySet() ) { final List<FastFeaturesNode> roots = new ArrayList<FastFeaturesNode>(entry.getValue().length); for (final FastFeaturesNode node : entry.getValue()) { final FastFeaturesNode optimisedNode = FastFeaturesNode.thresholdedNode(node, spatialFeatureInitWeights); if (optimisedNode != null) roots.add(optimisedNode); } proactiveFeaturesThresholded.put(entry.getKey(), roots.toArray(new FastFeaturesNode[0])); } } @Override public void closeCache() { activeProactiveFeaturesCache.close(); } //------------------------------------------------------------------------- @Override public TIntArrayList getActiveSpatialFeatureIndices ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player, final boolean thresholded ) { // a lot of code duplication with getActiveFeatureInstances() here, // but more efficient final boolean[] featuresActive = new boolean[spatialFeatures.length]; // try to get proactive features immediately from cache final TIntArrayList activeFeatureIndices; if (proactiveFeatures.size() > 0) { final int[] cachedActiveFeatureIndices; if (thresholded) cachedActiveFeatureIndices = activeProactiveFeaturesCache.getCachedActiveFeatures(this, state, from, to, player); else cachedActiveFeatureIndices = null; if (cachedActiveFeatureIndices != null) { // successfully retrieved from cache activeFeatureIndices = new TIntArrayList(cachedActiveFeatureIndices); //System.out.println("cache hit!"); } else { // did not retrieve from cache, so need to compute the proactive features first activeFeatureIndices = new TIntArrayList(); //System.out.println("cache miss!"); final List<FastFeaturesNode[]> featuresNodesToCheck = getFeaturesNodesToCheckProactive(state, from, to, thresholded); for (int i = 0; i < featuresNodesToCheck.size(); ++i) { final FastFeaturesNode[] nodesArray = featuresNodesToCheck.get(i); for (int j = 0; j < nodesArray.length; ++j) { final FastFeaturesNode node = nodesArray[j]; final BitwiseTest test = node.test; if (test.matches(state)) { final int[] featureIndices = node.activeFeatureIndices; for (int idx = 0; idx < featureIndices.length; ++idx) { featuresActive[featureIndices[idx]] = true; } // will also have to test all the children of our // current node featuresNodesToCheck.add(node.children); } } } // we'll want to cache these results as well for (int i = 0; i < featuresActive.length; ++i) { if (featuresActive[i]) { activeFeatureIndices.add(i); } } if (thresholded) activeProactiveFeaturesCache.cache(state, from, to, activeFeatureIndices.toArray(), player); // clear the featuresActive bools, we've already // added these to the activeFeatureIndices list Arrays.fill(featuresActive, false); } } else { activeFeatureIndices = new TIntArrayList(); } // now still need to compute the reactive features, which aren't cached final List<FastFeaturesNode[]> featuresNodesToCheck = getFeaturesNodesToCheckReactive(state, lastFrom, lastTo, from, to, thresholded); for (int i = 0; i < featuresNodesToCheck.size(); ++i) { final FastFeaturesNode[] nodesArray = featuresNodesToCheck.get(i); for (int j = 0; j < nodesArray.length; ++j) { final FastFeaturesNode node = nodesArray[j]; final BitwiseTest test = node.test; if (test.matches(state)) { final int[] featureIndices = node.activeFeatureIndices; for (int idx = 0; idx < featureIndices.length; ++idx) { featuresActive[featureIndices[idx]] = true; } // will also have to test all the children of our // current node featuresNodesToCheck.add(node.children); } } } for (int i = 0; i < featuresActive.length; ++i) { if (featuresActive[i]) { activeFeatureIndices.add(i); } } return activeFeatureIndices; } @Override public List<FeatureInstance> getActiveSpatialFeatureInstances ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player ) { final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(); final List<FastFeatureInstanceNode[]> instanceNodesToCheck = getInstanceNodesToCheck(state, lastFrom, lastTo, from, to, player); for (int i = 0; i < instanceNodesToCheck.size(); ++i) { final FastFeatureInstanceNode[] nodesArray = instanceNodesToCheck.get(i); for (int j = 0; j < nodesArray.length; ++j) { final FeatureInstance instance = nodesArray[j].featureInstance; if (instance.matches(state)) { activeInstances.add(instance); // will also have to test all the children of our // current node instanceNodesToCheck.add(nodesArray[j].children); } } } // if (activeInstances.size() == 0) // { // System.out.println("lastFrom = " + lastFrom); // System.out.println("lastTo = " + lastTo); // System.out.println("from = " + from); // System.out.println("to = " + to); // System.out.println("player = " + player); // System.out.println("instanceNodesToCheck.size() = " + instanceNodesToCheck.size()); // System.out.println("returning num active instances = " + activeInstances.size()); // } return activeInstances; } /** * @param context * @param lastFrom * @param lastTo * @param from * @param to * @param player * @param thresholded * * @return A list of all features that are active for a given state+action * pair (where action is defined by from and to positions) */ public List<SpatialFeature> getActiveFeatures ( final Context context, final int lastFrom, final int lastTo, final int from, final int to, final int player, final boolean thresholded ) { final TIntArrayList activeFeatureIndices = getActiveSpatialFeatureIndices(context.state(), lastFrom, lastTo, from, to, player, thresholded); final List<SpatialFeature> activeFeatures = new ArrayList<SpatialFeature>(activeFeatureIndices.size()); final TIntIterator it = activeFeatureIndices.iterator(); while (it.hasNext()) { activeFeatures.add(spatialFeatures[it.next()]); } return activeFeatures; } //------------------------------------------------------------------------- /** * Helper method to collect a list of all instance nodes to start with * when checking which instances match a given state+action pair * * We return a list of arrays rather than a flat list due to efficiency * (lets us work much more with raw arrays rather than a large and * frequently-growing ArrayList) * * @param state * @param lastFrom * @param lastTo * @param from * @param to * @param player * @return List of arrays of root nodes to start checking */ private List<FastFeatureInstanceNode[]> getInstanceNodesToCheck ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player ) { final List<FastFeatureInstanceNode[]> instanceNodesToCheck = new ArrayList<FastFeatureInstanceNode[]>(); final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; final int[] lastFroms = lastFrom >= 0 ? new int[]{-1, lastFrom} : new int[]{-1}; final int[] lastTos = lastTo >= 0 ? new int[]{-1, lastTo} : new int[]{-1}; final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); if (lastFrom >= 0 || lastTo >= 0) { for (int i = 0; i < lastFroms.length; ++i) { final int lastFromPos = lastFroms[i]; for (int j = 0; j < lastTos.length; ++j) { final int lastToPos = lastTos[j]; for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (lastToPos >= 0 || lastFromPos >= 0) { // Reactive instances reactiveKey.resetData(player, lastFromPos, lastToPos, fromPos, toPos); final FastFeatureInstanceNode[] nodes = reactiveInstances.get(reactiveKey); if (nodes != null) { instanceNodesToCheck.add(nodes); } } } } } } } final ProactiveFeaturesKey proactiveKey = new ProactiveFeaturesKey(); for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Proactive instances proactiveKey.resetData(player, fromPos, toPos); final FastFeatureInstanceNode[] nodes = proactiveInstances.get(proactiveKey); if (nodes != null) { instanceNodesToCheck.add(nodes); } } } } return instanceNodesToCheck; } //------------------------------------------------------------------------- /** * Helper method to collect a list of all Features nodes to start with * when checking which proactive Features match a given state+action pair * * We return a list of arrays rather than a flat list due to efficiency * (lets us work much more with raw arrays rather than a large and * frequently-growing ArrayList) * * @param state * @param from * @param to * @param thresholded * * @return List of arrays of root nodes to start checking */ private List<FastFeaturesNode[]> getFeaturesNodesToCheckProactive ( final State state, final int from, final int to, final boolean thresholded ) { final List<FastFeaturesNode[]> featuresNodesToCheck = new ArrayList<FastFeaturesNode[]>(); final int mover = state.mover(); final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; final HashMap<ProactiveFeaturesKey, FastFeaturesNode[]> featuresMap; if (thresholded) featuresMap = proactiveFeaturesThresholded; else featuresMap = proactiveFeatures; final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { key.resetData(mover, fromPos, toPos); final FastFeaturesNode[] nodes = featuresMap.get(key); if (nodes != null) { featuresNodesToCheck.add(nodes); } } } } return featuresNodesToCheck; } /** * Helper method to collect a list of all Features nodes to start with * when checking which reactive Features match a given state+action pair * * We return a list of arrays rather than a flat list due to efficiency * (lets us work much more with raw arrays rather than a large and * frequently-growing ArrayList) * * @param state * @param lastFrom * @param lastTo * @param from * @param to * @param thresholded * * @return List of arrays of root nodes to start checking */ private List<FastFeaturesNode[]> getFeaturesNodesToCheckReactive ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final boolean thresholded ) { final List<FastFeaturesNode[]> featuresNodesToCheck = new ArrayList<FastFeaturesNode[]>(); if (reactiveFeatures.isEmpty()) return featuresNodesToCheck; final HashMap<ReactiveFeaturesKey, FastFeaturesNode[]> featuresMap; if (thresholded) featuresMap = reactiveFeaturesThresholded; else featuresMap = reactiveFeatures; final int mover = state.mover(); if (from >= 0) { if (to >= 0) { if (lastFrom >= 0) { if (lastTo >= 0) { addFeaturesNodes(mover, lastFrom, lastTo, from, to, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, lastFrom, lastTo, -1, to, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, lastFrom, lastTo, from, -1, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, -1, lastTo, from, to, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, -1, lastTo, -1, to, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, -1, lastTo, from, -1, featuresMap, featuresNodesToCheck); } addFeaturesNodes(mover, lastFrom, -1, from, to, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, lastFrom, -1, -1, to, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, lastFrom, -1, from, -1, featuresMap, featuresNodesToCheck); } else { if (lastTo >= 0) { addFeaturesNodes(mover, -1, lastTo, from, to, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, -1, lastTo, -1, to, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, -1, lastTo, from, -1, featuresMap, featuresNodesToCheck); } } } else { if (lastFrom >= 0) { if (lastTo >= 0) { addFeaturesNodes(mover, lastFrom, lastTo, from, -1, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, -1, lastTo, from, -1, featuresMap, featuresNodesToCheck); } addFeaturesNodes(mover, lastFrom, -1, from, -1, featuresMap, featuresNodesToCheck); } else { if (lastTo >= 0) addFeaturesNodes(mover, -1, lastTo, from, -1, featuresMap, featuresNodesToCheck); } } } else { if (to >= 0) { if (lastFrom >= 0) { if (lastTo >= 0) { addFeaturesNodes(mover, lastFrom, lastTo, -1, to, featuresMap, featuresNodesToCheck); addFeaturesNodes(mover, -1, lastTo, -1, to, featuresMap, featuresNodesToCheck); } addFeaturesNodes(mover, lastFrom, -1, -1, to, featuresMap, featuresNodesToCheck); } else { if (lastTo >= 0) addFeaturesNodes(mover, -1, lastTo, -1, to, featuresMap, featuresNodesToCheck); } } } return featuresNodesToCheck; } /** * Helper method for collecting feature instances * * @param mover * @param lastFrom * @param lastTo * @param from * @param to * @param featuresMap * @param outFeaturesNodes */ private static void addFeaturesNodes ( final int mover, final int lastFrom, final int lastTo, final int from, final int to, final HashMap<ReactiveFeaturesKey, FastFeaturesNode[]> featuresMap, final List<FastFeaturesNode[]> outFeaturesNodes ) { final ReactiveFeaturesKey key = new ReactiveFeaturesKey(); key.resetData(mover, lastFrom, lastTo, from, to); final FastFeaturesNode[] nodes = featuresMap.get(key); if (nodes != null) outFeaturesNodes.add(nodes); } //------------------------------------------------------------------------- @Override public BaseFootprint generateFootprint ( final State state, final int from, final int to, final int player ) { final ContainerState container = state.containerStates()[0]; final ChunkSet footprintEmptyCells = container.emptyChunkSetCell() != null ? new ChunkSet(container.emptyChunkSetCell().chunkSize(), 1) : null; final ChunkSet footprintEmptyVertices = container.emptyChunkSetVertex() != null ? new ChunkSet(container.emptyChunkSetVertex().chunkSize(), 1) : null; final ChunkSet footprintEmptyEdges = container.emptyChunkSetEdge() != null ? new ChunkSet(container.emptyChunkSetEdge().chunkSize(), 1) : null; final ChunkSet footprintWhoCells = container.chunkSizeWhoCell() > 0 ? new ChunkSet(container.chunkSizeWhoCell(), 1) : null; final ChunkSet footprintWhoVertices = container.chunkSizeWhoVertex() > 0 ? new ChunkSet(container.chunkSizeWhoVertex(), 1) : null; final ChunkSet footprintWhoEdges = container.chunkSizeWhoEdge() > 0 ? new ChunkSet(container.chunkSizeWhoEdge(), 1) : null; final ChunkSet footprintWhatCells = container.chunkSizeWhatCell() > 0 ? new ChunkSet(container.chunkSizeWhatCell(), 1) : null; final ChunkSet footprintWhatVertices = container.chunkSizeWhatVertex() > 0 ? new ChunkSet(container.chunkSizeWhatVertex(), 1) : null; final ChunkSet footprintWhatEdges = container.chunkSizeWhatEdge() > 0 ? new ChunkSet(container.chunkSizeWhatEdge(), 1) : null; // the two -1s ensure we only get proactive feature instances here final List<FastFeatureInstanceNode[]> instanceNodes = getInstanceNodesToCheck(state, -1, -1, from, to, player); // loop through complete tree of instances, OR all the tests for (int i = 0; i < instanceNodes.size(); ++i) { final FastFeatureInstanceNode[] nodesArray = instanceNodes.get(i); for (int j = 0; j < nodesArray.length; ++j) { final FeatureInstance instance = nodesArray[j].featureInstance; if (instance.mustEmpty() != null) { switch (instance.graphElementType()) { case Cell: footprintEmptyCells.or(instance.mustEmpty()); break; case Vertex: footprintEmptyVertices.or(instance.mustEmpty()); break; case Edge: footprintEmptyEdges.or(instance.mustEmpty()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustNotEmpty() != null) { switch (instance.graphElementType()) { case Cell: footprintEmptyCells.or(instance.mustNotEmpty()); break; case Vertex: footprintEmptyVertices.or(instance.mustNotEmpty()); break; case Edge: footprintEmptyEdges.or(instance.mustNotEmpty()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustWhoMask() != null) { switch (instance.graphElementType()) { case Cell: footprintWhoCells.or(instance.mustWhoMask()); break; case Vertex: footprintWhoVertices.or(instance.mustWhoMask()); break; case Edge: footprintWhoEdges.or(instance.mustWhoMask()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustNotWhoMask() != null) { switch (instance.graphElementType()) { case Cell: footprintWhoCells.or(instance.mustNotWhoMask()); break; case Vertex: footprintWhoVertices.or(instance.mustNotWhoMask()); break; case Edge: footprintWhoEdges.or(instance.mustNotWhoMask()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustWhatMask() != null) { switch (instance.graphElementType()) { case Cell: footprintWhatCells.or(instance.mustWhatMask()); break; case Vertex: footprintWhatVertices.or(instance.mustWhatMask()); break; case Edge: footprintWhatEdges.or(instance.mustWhatMask()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustNotWhatMask() != null) { switch (instance.graphElementType()) { case Cell: footprintWhatCells.or(instance.mustNotWhatMask()); break; case Vertex: footprintWhatVertices.or(instance.mustNotWhatMask()); break; case Edge: footprintWhatEdges.or(instance.mustNotWhatMask()); break; //$CASES-OMITTED$ Hint default: break; } } // will also have to test all the children of our current node instanceNodes.add(nodesArray[j].children); } } return new FullFootprint ( footprintEmptyCells, footprintEmptyVertices, footprintEmptyEdges, footprintWhoCells, footprintWhoVertices, footprintWhoEdges, footprintWhatCells, footprintWhatVertices, footprintWhatEdges ); } //------------------------------------------------------------------------- /** * Attempts to create an expanded feature set which contains all of the current features, * plus one new feature by combining a pair of features from the given list of active instances * into a new feature. Will return null if no such pair can be found such that it results in a * really new feature. We only allow pairs of instances that have a shared anchor. * * @param activeFeatureInstances * @param combineMaxWeightedFeatures * If true, we will prioritise creating new pairs of features such that at least one * of them has the highest possible absolute weight in our linear function approximator * (i.e. we try to extend features that are already highly informative with additional * elements). If false, we'll select pairs of features randomly. * @param featureWeights * @return New Feature Set with one extra feature, or null if cannot be expanded */ public LegacyFeatureSet createExpandedFeatureSet ( final List<FeatureInstance> activeFeatureInstances, final boolean combineMaxWeightedFeatures, final FVector featureWeights ) { // generate all possible pairs of two different features (order does not matter) final int numActiveInstances = activeFeatureInstances.size(); final List<FeatureInstancePair> allPairs = new ArrayList<FeatureInstancePair>(); for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance firstInstance = activeFeatureInstances.get(i); for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance secondInstance = activeFeatureInstances.get(j); if (firstInstance.anchorSite() == secondInstance.anchorSite()) { allPairs.add(new FeatureInstancePair(firstInstance, secondInstance)); } } } if (combineMaxWeightedFeatures) { // sort feature pairs in increasing order of max(abs(weight(a), abs(weight(b)))) final FVector absWeights = featureWeights.copy(); absWeights.abs(); allPairs.sort(new Comparator<FeatureInstancePair>() { @Override public int compare(FeatureInstancePair o1, FeatureInstancePair o2) { final float score1 = Math.max( absWeights.get(o1.a.feature().spatialFeatureSetIndex()), absWeights.get(o1.b.feature().spatialFeatureSetIndex())); final float score2 = Math.max( absWeights.get(o2.a.feature().spatialFeatureSetIndex()), absWeights.get(o2.b.feature().spatialFeatureSetIndex())); if (score1 == score2) { return 0; } else if (score1 < score2) { return -1; } else { return 1; } } }); } else { // just shuffle them for random combining Collections.shuffle(allPairs); } // keep trying to combine pairs of features, until we find a new one or // until we have tried them all while (!allPairs.isEmpty()) { final FeatureInstancePair pair = allPairs.remove(allPairs.size() - 1); final LegacyFeatureSet newFeatureSet = createExpandedFeatureSet ( game.get(), SpatialFeature.combineFeatures ( game.get(), pair.a, pair.b ) ); if (newFeatureSet != null) { return newFeatureSet; } } // failed to construct a new feature set with a new feature return null; } @Override public LegacyFeatureSet createExpandedFeatureSet ( final Game targetGame, final SpatialFeature newFeature ) { boolean featureAlreadyExists = false; for (final SpatialFeature oldFeature : spatialFeatures) { if (newFeature.equals(oldFeature)) { featureAlreadyExists = true; break; } // also try all legal rotations of the generated feature, see // if any of those turn out to be equal to an old feature TFloatArrayList allowedRotations = newFeature.pattern().allowedRotations(); if (allowedRotations == null) { allowedRotations = new TFloatArrayList(Walk.allGameRotations(game.get())); } for (int i = 0; i < allowedRotations.size(); ++i) { final SpatialFeature rotatedCopy = newFeature.rotatedCopy(allowedRotations.getQuick(i)); if (rotatedCopy.equals(oldFeature)) { // TODO only break if for every possible anchor this works? featureAlreadyExists = true; break; } } } if (!featureAlreadyExists) { // create new feature set with this feature, and return it final List<SpatialFeature> newFeatureList = new ArrayList<SpatialFeature>(spatialFeatures.length + 1); // all old features... for (final SpatialFeature feature : spatialFeatures) { newFeatureList.add(feature); } // and our new feature newFeatureList.add(newFeature); return new LegacyFeatureSet(Arrays.asList(aspatialFeatures), newFeatureList); } return null; } //------------------------------------------------------------------------- /** * We'll simplify all of our forests of Feature Instances by: * 1) for every Feature Instance, removing all tests already included * in ancestor nodes * 2) collapsing deep sequences of instances that have no remaining tests * after the above simplification into a wide list of children for the * first ancestor that still has meaningful tests. * * @param reactiveInstancesWIP * @param proactiveInstancesWIP */ private static void simplifyInstanceForests ( final Map<ReactiveFeaturesKey, List<FeatureInstanceNode>> reactiveInstancesWIP, final Map<ProactiveFeaturesKey, List<FeatureInstanceNode>> proactiveInstancesWIP ) { final List<List<FeatureInstanceNode>> allForests = new ArrayList<List<FeatureInstanceNode>>(2); allForests.addAll(proactiveInstancesWIP.values()); allForests.addAll(reactiveInstancesWIP.values()); // System.out.println("---"); // proactiveInstancesWIP.get(new ProactiveFeaturesKey(1, 3, 2)).get(0).print(0); // System.out.println("---"); // System.out.println("---"); // reactiveInstancesWIP.get(new ReactiveFeaturesKey(1, -1, 45, 3, 0)).get(0).print(0); // System.out.println("---"); // for every forest... for (final List<FeatureInstanceNode> forest : allForests) { // for every tree... for (final FeatureInstanceNode root : forest) { // traverse entire tree; for every node, remove all tests // from all descendants of that node final List<FeatureInstanceNode> rootsToProcess = new ArrayList<FeatureInstanceNode>(); rootsToProcess.add(root); while (!rootsToProcess.isEmpty()) { final FeatureInstanceNode rootToProcess = rootsToProcess.remove(0); if (!rootToProcess.featureInstance.hasNoTests()) { //System.out.println("removing " + rootToProcess.featureInstance + " tests from all descendants..."); final List<FeatureInstanceNode> descendants = rootToProcess.collectDescendants(); for (final FeatureInstanceNode descendant : descendants) { //System.out.println("before removal: " + descendant.featureInstance); descendant.featureInstance.removeTests(rootToProcess.featureInstance); //System.out.println("after removal: " + descendant.featureInstance); } } // all children of current ''root'' become new ''roots'' rootsToProcess.addAll(rootToProcess.children); } // and now collapse long sequences of no-test-instances final List<FeatureInstanceNode> allNodes = root.collectDescendants(); for (final FeatureInstanceNode node : allNodes) { FeatureInstanceNode ancestor = node.parent; // find first ancestor with meaningful tests while (ancestor.featureInstance.hasNoTests()) { if (ancestor == root) { // can't go further up break; } else { //System.out.println(node.featureInstance + " skipping ancestor: " + ancestor.featureInstance); ancestor = ancestor.parent; } } if (ancestor != node.parent) { // need to change parent //System.out.println(node.featureInstance + " swapping parent to " + ancestor.featureInstance); // first remove ourselves from the current parent's // list of children node.parent.children.remove(node); // now add ourselves to the new ancestor's list // of children ancestor.children.add(node); // and change our parent reference node.parent = ancestor; } } } } // System.out.println("---"); // proactiveInstancesWIP.get(new ProactiveFeaturesKey(1, 3, 0)).get(0).print(0); // System.out.println("---"); // System.out.println("---"); // reactiveInstancesWIP.get(new ReactiveFeaturesKey(1, -1, 45, 3, 0)).get(0).print(0); // System.out.println("---"); } //------------------------------------------------------------------------- /** * Inserts the given Feature Instance into a forest defined by a list * of root nodes. May modify existing instances if the new instance * becomes an ancestor of them. * * @param instance * @param instanceNodes */ private static void insertInstanceInForest ( final FeatureInstance instance, final List<FeatureInstanceNode> instanceNodes ) { final FeatureInstanceNode parentNode = findDeepestParent(instance, instanceNodes); if (parentNode == null) { // need to add a new root for this feature instance instanceNodes.add(new FeatureInstanceNode(instance, null)); } else { // this instance will become a new child of parentNode final FeatureInstanceNode newNode = new FeatureInstanceNode(instance, parentNode); // see if our new instance generalises any instances that were // previously children of the parent we found; if so, our new // node becomes their parent instead for (int i = 0; i < parentNode.children.size(); /**/) { final FeatureInstanceNode child = parentNode.children.get(i); if (instance.generalises(child.featureInstance)) { // we generalise this child and should become its parent parentNode.children.remove(i); newNode.children.add(child); child.parent = newNode; } else { // didn't remove entry from list, so increment index ++i; } } // finally, add the new node to the parent's list of children parentNode.children.add(newNode); parentNode.children.trimToSize(); } } /** * Finds the deepest node in the forest defined by the given list of * root nodes which would be a valid parent for the given new instance. * * @param instance * @param instanceNodes * @return Deepest parent node for given new instance */ private static FeatureInstanceNode findDeepestParent ( final FeatureInstance instance, final List<FeatureInstanceNode> instanceNodes ) { FeatureInstanceNode deepestParent = null; int deepestParentDepthLevel = -1; int currDepthLevel = 0; List<FeatureInstanceNode> currDepthNodes = instanceNodes; List<FeatureInstanceNode> nextDepthNodes = new ArrayList<FeatureInstanceNode>(); while (!currDepthNodes.isEmpty()) { for (final FeatureInstanceNode node : currDepthNodes) { if (node.featureInstance.generalises(instance)) { // this node could be a parent if (currDepthLevel > deepestParentDepthLevel) { // don't have a parent at this depth level yet, // so pick this one for now deepestParent = node; deepestParentDepthLevel = currDepthLevel; } // see if any of our children still could lead to a deeper // parent nextDepthNodes.addAll(node.children); } } currDepthNodes = nextDepthNodes; nextDepthNodes = new ArrayList<FeatureInstanceNode>(); ++currDepthLevel; } return deepestParent; } //------------------------------------------------------------------------- /** * Prints complete tree of tests for proactive features. Useful for debugging * @param player * @param from * @param to */ public void printProactiveFeaturesTree(final int player, final int from, final int to) { System.out.println("---"); final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); key.resetData(player, from, to); proactiveFeatures.get(key)[0].print(0); System.out.println("---"); } //------------------------------------------------------------------------- /** * Wrapper class for a pair of feature instances * * @author Dennis Soemers */ private static class FeatureInstancePair { //-------------------------------------------------------------------- /** First instance */ protected final FeatureInstance a; /** Second instance */ protected final FeatureInstance b; //--------------------------------------------------------------------- /** * Constructor * @param a * @param b */ protected FeatureInstancePair ( final FeatureInstance a, final FeatureInstance b ) { this.a = a; this.b = b; } //--------------------------------------------------------------------- } //------------------------------------------------------------------------- /** * A node in a tree of related Feature Instances. Feature Instances * in a node of this type will no longer contain checks that are also * already performed by Feature Instances in ancestor nodes (parent, * grandparent, etc.) * * This class includes a reference to parent node, and stores children * in a resizable ArrayList, which makes it convenient for usage during * the feature instantiating process (when we're still building the tree) * * @author Dennis Soemers */ private static class FeatureInstanceNode { //-------------------------------------------------------------------- /** Our feature instance */ protected final FeatureInstance featureInstance; /** Child nodes */ protected final ArrayList<FeatureInstanceNode> children = new ArrayList<FeatureInstanceNode>(2); /** Parent node */ protected FeatureInstanceNode parent; //-------------------------------------------------------------------- /** * Constructor * @param featureInstance * @param parent */ public FeatureInstanceNode ( final FeatureInstance featureInstance, final FeatureInstanceNode parent ) { this.featureInstance = featureInstance; this.parent = parent; } //-------------------------------------------------------------------- /** * @return All descendants of this node (the entire subtree below it) */ public List<FeatureInstanceNode> collectDescendants() { final List<FeatureInstanceNode> result = new ArrayList<FeatureInstanceNode>(); final List<FeatureInstanceNode> nodesToCheck = new ArrayList<FeatureInstanceNode>(); nodesToCheck.addAll(children); while (!nodesToCheck.isEmpty()) { final FeatureInstanceNode node = nodesToCheck.remove(nodesToCheck.size() - 1); result.add(node); nodesToCheck.addAll(node.children); } return result; } //-------------------------------------------------------------------- /** * Prints the entire subtree rooted at this node. Useful for debugging. * @param depthLevel */ @SuppressWarnings("unused") // Please do NOT remove; frequently used for debugging! public void print(final int depthLevel) { for (int i = 0; i < depthLevel; ++i) { System.out.print("\t"); } System.out.println(featureInstance); for (final FeatureInstanceNode child : children) { child.print(depthLevel + 1); } } //-------------------------------------------------------------------- } //------------------------------------------------------------------------- /** * A very similar kind of node to the class above. This node class is * heavily optimised for speed, and should only be used after a tree * of Feature Instances has been completely built. * * It no longer contains a reference to the parent node, and stores * children in a fixed-size array. * * @author Dennis Soemers */ private static class FastFeatureInstanceNode { //-------------------------------------------------------------------- /** Our feature instance */ protected final FeatureInstance featureInstance; /** Child nodes */ protected final FastFeatureInstanceNode[] children; //-------------------------------------------------------------------- /** * Constructor * @param slowNode */ public FastFeatureInstanceNode(final FeatureInstanceNode slowNode) { this.featureInstance = slowNode.featureInstance; this.children = new FastFeatureInstanceNode[slowNode.children.size()]; for (int i = 0; i < children.length; ++i) { children[i] = new FastFeatureInstanceNode(slowNode.children.get(i)); } } //-------------------------------------------------------------------- } //------------------------------------------------------------------------- /** * Again a similar node to the above node types, but this time even more * optimised by only keeping track of lists of features that are active * if certain tests (still contained in Feature Instances) succeed. * * This node type allows for complete removal of zero-test instances, * instead letting their parent nodes immediately return multiple active * features. * * @author Dennis Soemers */ private static class FastFeaturesNode { //-------------------------------------------------------------------- /** Our bitwise test(s) to execute */ protected BitwiseTest test; /** Child nodes */ protected final FastFeaturesNode[] children; /** * Indices of features that are active if the tests of this * node's instance succeed. */ protected final int[] activeFeatureIndices; //-------------------------------------------------------------------- /** * Constructor * @param instanceNode */ public FastFeaturesNode(final FastFeatureInstanceNode instanceNode) { this.test = instanceNode.featureInstance; final FastFeatureInstanceNode[] instanceChildren = instanceNode.children; final List<FastFeaturesNode> childrenList = new ArrayList<FastFeaturesNode>(instanceChildren.length); final TIntArrayList featureIndicesList = new TIntArrayList(); // we'll definitely need the index of the instance contained // in the node featureIndicesList.add(instanceNode.featureInstance.feature().spatialFeatureSetIndex()); for (final FastFeatureInstanceNode instanceChild : instanceChildren) { final FeatureInstance instance = instanceChild.featureInstance; if (instance.hasNoTests()) { // this child does not need to exist anymore, just absorb // its feature index final int featureIdx = instance.feature().spatialFeatureSetIndex(); if (!featureIndicesList.contains(featureIdx)) { featureIndicesList.add(featureIdx); } } else { // the child has meaningful tests, so it should still exist childrenList.add(new FastFeaturesNode(instanceChild)); } } // this sorting is useful for the optimisation implemented in the // following lines of code for our parent node featureIndicesList.sort(); // try to merge children which all have the same list of active // features into a single child that performs multiple tests at // once final int numChildren = childrenList.size(); final boolean[] skipIndices = new boolean[numChildren]; for (int i = 0; i < numChildren; ++i) { if (skipIndices[i]) { continue; } final FastFeaturesNode child = childrenList.get(i); if (child.children.length == 0) { for (int j = i + 1; j < numChildren; ++j) { if (skipIndices[j]) continue; final FastFeaturesNode otherChild = childrenList.get(j); if (otherChild.children.length == 0) { if ( Arrays.equals ( child.activeFeatureIndices, otherChild.activeFeatureIndices ) ) { final BitwiseTest testA = child.test; final BitwiseTest testB = otherChild.test; assert (testA.graphElementType() == testB.graphElementType()); if ( testA.onlyRequiresSingleMustEmpty() && testB.onlyRequiresSingleMustEmpty() ) { // merge B's test into A's test if (testA instanceof FeatureInstance) { final FeatureInstance instanceA = (FeatureInstance) testA; final FeatureInstance instanceB = (FeatureInstance) testB; final ChunkSet combinedTest = instanceA.mustEmpty().clone(); combinedTest.or(instanceB.mustEmpty()); child.test = new OneOfMustEmpty(combinedTest, testA.graphElementType()); } else { final OneOfMustEmpty A = (OneOfMustEmpty) testA; if (testB instanceof FeatureInstance) { final FeatureInstance instanceB = (FeatureInstance) testB; A.mustEmpties().or(instanceB.mustEmpty()); child.test = new OneOfMustEmpty(A.mustEmpties(), testA.graphElementType()); } else { final OneOfMustEmpty B = (OneOfMustEmpty) testB; A.mustEmpties().or(B.mustEmpties()); child.test = new OneOfMustEmpty(A.mustEmpties(), testA.graphElementType()); } } skipIndices[j] = true; } else if ( testA.onlyRequiresSingleMustWho() && testB.onlyRequiresSingleMustWho() ) { // merge B's test into A's test if (testA instanceof FeatureInstance) { final FeatureInstance instanceA = (FeatureInstance) testA; final FeatureInstance instanceB = (FeatureInstance) testB; final ChunkSet whoA = instanceA.mustWho(); final ChunkSet whoMaskA = instanceA.mustWhoMask(); final ChunkSet whoB = instanceB.mustWho(); final ChunkSet whoMaskB = instanceB.mustWhoMask(); final ChunkSet combinedMask = whoMaskA.clone(); combinedMask.or(whoMaskB); if (whoMaskA.intersects(whoMaskB)) { final ChunkSet cloneB = whoB.clone(); cloneB.and(whoMaskB); if (!whoA.matches(combinedMask, cloneB)) { // conflicting tests, can't // merge these continue; } } final ChunkSet combinedWhos = whoA.clone(); combinedWhos.or(whoB); child.test = new OneOfMustWho(combinedWhos, combinedMask, testA.graphElementType()); } else { final OneOfMustWho A = (OneOfMustWho) testA; final ChunkSet whosA = A.mustWhos(); final ChunkSet whosMaskA = A.mustWhosMask(); if (testB instanceof FeatureInstance) { final FeatureInstance instanceB = (FeatureInstance) testB; final ChunkSet whoB = instanceB.mustWho(); final ChunkSet whoMaskB = instanceB.mustWhoMask(); if (whosMaskA.intersects(whoMaskB)) { if (!whosA.matches(whoMaskB, whoB)) { // conflicting tests, can't // merge these continue; } } whosA.or(whoB); whosMaskA.or(whoMaskB); child.test = new OneOfMustWho(whosA, whosMaskA, testA.graphElementType()); } else { final OneOfMustWho B = (OneOfMustWho) testB; final ChunkSet whosB = B.mustWhos(); final ChunkSet whosMaskB = B.mustWhosMask(); if (whosMaskA.intersects(whosMaskB)) { if (!whosA.matches(whosMaskB, whosB)) { // conflicting tests, can't // merge these continue; } if (!whosB.matches(whosMaskA, whosA)) { // conflicting tests, can't // merge these continue; } } whosA.or(whosB); whosMaskA.or(whosMaskB); child.test = new OneOfMustWho(whosA, whosMaskA, testA.graphElementType()); } } skipIndices[j] = true; } else if ( testA.onlyRequiresSingleMustWhat() && testB.onlyRequiresSingleMustWhat() ) { // merge B's test into A's test if (testA instanceof FeatureInstance) { final FeatureInstance instanceA = (FeatureInstance) testA; final FeatureInstance instanceB = (FeatureInstance) testB; final ChunkSet whatA = instanceA.mustWhat(); final ChunkSet whatMaskA = instanceA.mustWhatMask(); final ChunkSet whatB = instanceB.mustWhat(); final ChunkSet whatMaskB = instanceB.mustWhatMask(); final ChunkSet combinedMask = whatMaskA.clone(); combinedMask.or(whatMaskB); if (whatMaskA.intersects(whatMaskB)) { final ChunkSet cloneB = whatB.clone(); cloneB.and(whatMaskB); if (!whatA.matches(combinedMask, cloneB)) { // conflicting tests, can't // merge these continue; } } final ChunkSet combinedWhats = whatA.clone(); combinedWhats.or(whatB); child.test = new OneOfMustWhat(combinedWhats, combinedMask, testA.graphElementType()); } else { final OneOfMustWhat A = (OneOfMustWhat) testA; final ChunkSet whatsA = A.mustWhats(); final ChunkSet whatsMaskA = A.mustWhatsMask(); if (testB instanceof FeatureInstance) { final FeatureInstance instanceB = (FeatureInstance) testB; final ChunkSet whatB = instanceB.mustWhat(); final ChunkSet whatMaskB = instanceB.mustWhatMask(); if (whatsMaskA.intersects(whatMaskB)) { if (!whatsA.matches(whatMaskB, whatB)) { // conflicting tests, can't // merge these continue; } } whatsA.or(whatB); whatsMaskA.or(whatMaskB); child.test = new OneOfMustWhat(whatsA, whatsMaskA, testA.graphElementType()); } else { final OneOfMustWhat B = (OneOfMustWhat) testB; final ChunkSet whatsB = B.mustWhats(); final ChunkSet whatsMaskB = B.mustWhatsMask(); if (whatsMaskA.intersects(whatsMaskB)) { if (!whatsA.matches(whatsMaskB, whatsB)) { // conflicting tests, can't // merge these continue; } if (!whatsB.matches(whatsMaskA, whatsA)) { // conflicting tests, can't // merge these continue; } } whatsA.or(whatsB); whatsMaskA.or(whatsMaskB); child.test = new OneOfMustWhat(whatsA, whatsMaskA, testA.graphElementType()); } } skipIndices[j] = true; } } } } } } // create replacement list only containing children that haven't // been merged into another child final List<FastFeaturesNode> remainingChildren = new ArrayList<FastFeaturesNode>(); for (int i = 0; i < numChildren; ++i) { if (!skipIndices[i]) { remainingChildren.add(childrenList.get(i)); } } // convert lists to arrays children = new FastFeaturesNode[remainingChildren.size()]; remainingChildren.toArray(children); activeFeatureIndices = featureIndicesList.toArray(); } /** * Constructor * @param test * @param children * @param activeFeatureIndices */ private FastFeaturesNode ( final BitwiseTest test, final FastFeaturesNode[] children, final int[] activeFeatureIndices ) { this.test = test; this.children = children; this.activeFeatureIndices = activeFeatureIndices; } //-------------------------------------------------------------------- /** * Creates a copy of the given other subtree, with * features removed if their absolute weights in the * given weight vector do not exceed our threshold. * * @param other * @param weights null if we want to ignore thresholding * @return Constructed node, or null if no longer relevant after thresholding */ public static FastFeaturesNode thresholdedNode(final FastFeaturesNode other, final FVector weights) { final List<FastFeaturesNode> thresholdedChildren = new ArrayList<FastFeaturesNode>(other.children.length); for (final FastFeaturesNode child : other.children) { final FastFeaturesNode thresholdedChild = thresholdedNode(child, weights); if (thresholdedChild != null) thresholdedChildren.add(thresholdedChild); } final TIntArrayList thresholdedFeatures = new TIntArrayList(other.activeFeatureIndices.length); for (final int activeFeature : other.activeFeatureIndices) { if (weights == null || Math.abs(weights.get(activeFeature)) >= SPATIAL_FEATURE_WEIGHT_THRESHOLD) thresholdedFeatures.add(activeFeature); } if (thresholdedChildren.isEmpty() && thresholdedFeatures.isEmpty()) return null; return new FastFeaturesNode ( other.test, thresholdedChildren.toArray(new FastFeaturesNode[0]), thresholdedFeatures.toArray() ); } //-------------------------------------------------------------------- /** * Prints the entire subtree rooted at this node. Useful * for debugging. * @param depthLevel */ public void print(final int depthLevel) { for (int i = 0; i < depthLevel; ++i) { System.out.print("\t"); } System.out.println(this); for (final FastFeaturesNode child : children) { child.print(depthLevel + 1); } } @Override public String toString() { return String.format( "%s %s", test, Arrays.toString(activeFeatureIndices)); } //-------------------------------------------------------------------- } //------------------------------------------------------------------------- }
63,214
27.721036
117
java
Ludii
Ludii-master/Features/src/features/feature_sets/NaiveFeatureSet.java
package features.feature_sets; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.stream.Stream; import features.Feature; import features.aspatial.AspatialFeature; import features.spatial.SpatialFeature; import features.spatial.Walk; import features.spatial.cache.ActiveFeaturesCache; import features.spatial.cache.footprints.BaseFootprint; import features.spatial.cache.footprints.FullFootprint; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.iterator.TIntIterator; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import main.collections.ChunkSet; import main.collections.FVector; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.trial.Trial; /** * A naive implementation of a feature set, which does instantiate features, * but simply evaluates all of them for every move. * * @author Dennis Soemers */ public class NaiveFeatureSet extends BaseFeatureSet { //------------------------------------------------------------------------- /** * Reactive instances, indexed by: * player index, * last-from-pos * last-to-pos, * from-pos * to-pos */ protected HashMap<ReactiveFeaturesKey, List<FeatureInstance>> reactiveInstances; /** * Proactive instances, indexed by: * player index, * from-pos * to-pos */ protected HashMap<ProactiveFeaturesKey, List<FeatureInstance>> proactiveInstances; /** * Reactive Features, indexed by: * player index, * last-from-pos * last-to-pos, * from-pos * to-pos */ protected HashMap<ReactiveFeaturesKey, List<FeatureInstance>[]> reactiveFeatures; /** * Proactive Features, indexed by: * player index, * from-pos * to-pos */ protected HashMap<ProactiveFeaturesKey, List<FeatureInstance>[]> proactiveFeatures; /** * Same as above, but only includes features with absolute weights that exceed the above * threshold. */ protected HashMap<ReactiveFeaturesKey, List<FeatureInstance>[]> reactiveFeaturesThresholded; /** * Same as above, but only includes features with absolute weights that exceed the above * threshold. */ protected HashMap<ProactiveFeaturesKey, List<FeatureInstance>[]> proactiveFeaturesThresholded; /** Cache with indices of active proactive features previously computed */ protected ActiveFeaturesCache activeProactiveFeaturesCache; //------------------------------------------------------------------------- /** * Construct feature set from lists of features * @param aspatialFeatures * @param spatialFeatures */ public NaiveFeatureSet(final List<AspatialFeature> aspatialFeatures, final List<SpatialFeature> spatialFeatures) { this.spatialFeatures = new SpatialFeature[spatialFeatures.size()]; for (int i = 0; i < this.spatialFeatures.length; ++i) { this.spatialFeatures[i] = spatialFeatures.get(i); this.spatialFeatures[i].setSpatialFeatureSetIndex(i); } this.aspatialFeatures = aspatialFeatures.toArray(new AspatialFeature[aspatialFeatures.size()]); reactiveInstances = null; proactiveInstances = null; reactiveFeatures = null; proactiveFeatures = null; reactiveFeaturesThresholded = null; proactiveFeaturesThresholded = null; } /** * Loads a feature set from a given filename * @param filename */ public NaiveFeatureSet(final String filename) { Feature[] tempFeatures; //System.out.println("loading feature set from " + filename); try (Stream<String> stream = Files.lines(Paths.get(filename))) { tempFeatures = stream.map(s -> Feature.fromString(s)).toArray(Feature[]::new); } catch (final IOException exception) { tempFeatures = null; exception.printStackTrace(); } final List<AspatialFeature> aspatialFeaturesList = new ArrayList<AspatialFeature>(); final List<SpatialFeature> spatialFeaturesList = new ArrayList<SpatialFeature>(); for (final Feature feature : tempFeatures) { if (feature instanceof AspatialFeature) { aspatialFeaturesList.add((AspatialFeature)feature); } else { ((SpatialFeature)feature).setSpatialFeatureSetIndex(spatialFeaturesList.size()); spatialFeaturesList.add((SpatialFeature)feature); } } this.aspatialFeatures = aspatialFeaturesList.toArray(new AspatialFeature[aspatialFeaturesList.size()]); this.spatialFeatures = spatialFeaturesList.toArray(new SpatialFeature[spatialFeaturesList.size()]); } //------------------------------------------------------------------------- @SuppressWarnings("unchecked") @Override protected void instantiateFeatures(final int[] supportedPlayers) { activeProactiveFeaturesCache = new ActiveFeaturesCache(); reactiveInstances = new HashMap<ReactiveFeaturesKey, List<FeatureInstance>>(); proactiveInstances = new HashMap<ProactiveFeaturesKey, List<FeatureInstance>>(); // Create a dummy context because we need some context for // feature generation final Context featureGenContext = new Context(game.get(), new Trial(game.get())); final ProactiveFeaturesKey proactiveKey = new ProactiveFeaturesKey(); final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); for (int i = 0; i < supportedPlayers.length; ++i) { final int player = supportedPlayers[i]; for (final SpatialFeature feature : spatialFeatures) { final List<FeatureInstance> newInstances = feature.instantiateFeature ( game.get(), featureGenContext.state().containerStates()[0], player, -1, -1, -1, -1, -1 ); for (final FeatureInstance instance : newInstances) { final int lastFrom = instance.lastFrom(); final int lastTo = instance.lastTo(); final int from = instance.from(); final int to = instance.to(); if (lastFrom >= 0 || lastTo >= 0) // reactive feature { reactiveKey.resetData(player, lastFrom, lastTo, from, to); List<FeatureInstance> instances = reactiveInstances.get(reactiveKey); if (instances == null) { instances = new ArrayList<FeatureInstance>(1); reactiveInstances.put(new ReactiveFeaturesKey(reactiveKey), instances); } instances.add(instance); } else // proactive feature { proactiveKey.resetData(player, from, to); List<FeatureInstance> instances = proactiveInstances.get(proactiveKey); if (instances == null) { instances = new ArrayList<FeatureInstance>(1); proactiveInstances.put(new ProactiveFeaturesKey(proactiveKey), instances); } instances.add(instance); } } } } reactiveFeatures = new HashMap<ReactiveFeaturesKey, List<FeatureInstance>[]>(); reactiveFeaturesThresholded = new HashMap<ReactiveFeaturesKey, List<FeatureInstance>[]>(); for (final Entry<ReactiveFeaturesKey, List<FeatureInstance>> entry : reactiveInstances.entrySet()) { final List<FeatureInstance>[] unthresholdedInstanceLists = new List[spatialFeatures.length]; for (int i = 0; i < unthresholdedInstanceLists.length; ++i) { unthresholdedInstanceLists[i] = new ArrayList<FeatureInstance>(); } for (final FeatureInstance instance : entry.getValue()) { unthresholdedInstanceLists[instance.feature().spatialFeatureSetIndex()].add(instance); } reactiveFeatures.put(entry.getKey(), unthresholdedInstanceLists); final List<FeatureInstance>[] thresholdedInstanceLists = new List[spatialFeatures.length]; for (int i = 0; i < thresholdedInstanceLists.length; ++i) { thresholdedInstanceLists[i] = new ArrayList<FeatureInstance>(); } for (final FeatureInstance instance : entry.getValue()) { final int featureIdx = instance.feature().spatialFeatureSetIndex(); if (spatialFeatureInitWeights == null || Math.abs(spatialFeatureInitWeights.get(featureIdx)) >= SPATIAL_FEATURE_WEIGHT_THRESHOLD) { thresholdedInstanceLists[featureIdx].add(instance); } } reactiveFeaturesThresholded.put(entry.getKey(), thresholdedInstanceLists); } proactiveFeatures = new HashMap<ProactiveFeaturesKey, List<FeatureInstance>[]>(); proactiveFeaturesThresholded = new HashMap<ProactiveFeaturesKey, List<FeatureInstance>[]>(); for (final Entry<ProactiveFeaturesKey, List<FeatureInstance>> entry : proactiveInstances.entrySet()) { final List<FeatureInstance>[] unthresholdedInstanceLists = new List[spatialFeatures.length]; for (int i = 0; i < unthresholdedInstanceLists.length; ++i) { unthresholdedInstanceLists[i] = new ArrayList<FeatureInstance>(); } for (final FeatureInstance instance : entry.getValue()) { unthresholdedInstanceLists[instance.feature().spatialFeatureSetIndex()].add(instance); } proactiveFeatures.put(entry.getKey(), unthresholdedInstanceLists); final List<FeatureInstance>[] thresholdedInstanceLists = new List[spatialFeatures.length]; for (int i = 0; i < thresholdedInstanceLists.length; ++i) { thresholdedInstanceLists[i] = new ArrayList<FeatureInstance>(); } for (final FeatureInstance instance : entry.getValue()) { final int featureIdx = instance.feature().spatialFeatureSetIndex(); if (spatialFeatureInitWeights == null || Math.abs(spatialFeatureInitWeights.get(featureIdx)) >= SPATIAL_FEATURE_WEIGHT_THRESHOLD) { thresholdedInstanceLists[featureIdx].add(instance); } } proactiveFeaturesThresholded.put(entry.getKey(), thresholdedInstanceLists); } } @Override public void closeCache() { activeProactiveFeaturesCache.close(); } //------------------------------------------------------------------------- @Override public TIntArrayList getActiveSpatialFeatureIndices ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player, final boolean thresholded ) { final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; final int[] lastFroms = lastFrom >= 0 ? new int[]{-1, lastFrom} : new int[]{-1}; final int[] lastTos = lastTo >= 0 ? new int[]{-1, lastTo} : new int[]{-1}; final TIntArrayList activeFeatureIndices; if (proactiveFeatures.size() > 0) { final int[] cachedActiveFeatureIndices; if (thresholded) cachedActiveFeatureIndices = activeProactiveFeaturesCache.getCachedActiveFeatures(this, state, from, to, player); else cachedActiveFeatureIndices = null; if (cachedActiveFeatureIndices != null) { // successfully retrieved from cache activeFeatureIndices = new TIntArrayList(cachedActiveFeatureIndices); //System.out.println("cache hit!"); } else { // Did not retrieve from cache, so need to compute the proactive features first activeFeatureIndices = new TIntArrayList(); //System.out.println("cache miss!"); final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Proactive instances key.resetData(player, fromPos, toPos); final List<FeatureInstance>[] instanceLists; if (thresholded) instanceLists = proactiveFeaturesThresholded.get(key); else instanceLists = proactiveFeatures.get(key); if (instanceLists != null) { for (int i = 0; i < instanceLists.length; ++i) { for (final FeatureInstance instance : instanceLists[i]) { if (instance.matches(state)) { activeFeatureIndices.add(i); break; } } } } } } } if (thresholded) activeProactiveFeaturesCache.cache(state, from, to, activeFeatureIndices.toArray(), player); } } else { activeFeatureIndices = new TIntArrayList(); } // Now still need to compute the reactive features, which aren't cached final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); if (lastFrom >= 0 || lastTo >= 0) { for (int i = 0; i < lastFroms.length; ++i) { final int lastFromPos = lastFroms[i]; for (int j = 0; j < lastTos.length; ++j) { final int lastToPos = lastTos[j]; for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (lastToPos >= 0 || lastFromPos >= 0) { // Reactive instances final List<FeatureInstance>[] instanceLists; reactiveKey.resetData(player, lastFromPos, lastToPos, fromPos, toPos); if (thresholded) instanceLists = reactiveFeaturesThresholded.get(reactiveKey); else instanceLists = reactiveFeatures.get(reactiveKey); if (instanceLists != null) { for (int f = 0; f < instanceLists.length; ++f) { for (final FeatureInstance instance : instanceLists[f]) { if (instance.matches(state)) { activeFeatureIndices.add(f); break; } } } } } } } } } } return activeFeatureIndices; } @Override public List<FeatureInstance> getActiveSpatialFeatureInstances ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player ) { final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(); final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; final int[] lastFroms = lastFrom >= 0 ? new int[]{-1, lastFrom} : new int[]{-1}; final int[] lastTos = lastTo >= 0 ? new int[]{-1, lastTo} : new int[]{-1}; final ProactiveFeaturesKey proactiveKey = new ProactiveFeaturesKey(); for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Proactive instances proactiveKey.resetData(player, fromPos, toPos); final List<FeatureInstance>[] instanceLists = proactiveFeatures.get(proactiveKey); for (int i = 0; i < instanceLists.length; ++i) { for (final FeatureInstance instance : instanceLists[i]) { if (instance.matches(state)) { activeInstances.add(instance); } } } } } } final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); if (lastFrom >= 0 || lastTo >= 0) { for (int i = 0; i < lastFroms.length; ++i) { final int lastFromPos = lastFroms[i]; for (int j = 0; j < lastTos.length; ++j) { final int lastToPos = lastTos[j]; for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (lastToPos >= 0 || lastFromPos >= 0) { // Reactive instances reactiveKey.resetData(player, lastFromPos, lastToPos, fromPos, toPos); final List<FeatureInstance>[] instanceLists = reactiveFeatures.get(reactiveKey); if (instanceLists != null) { for (int f = 0; f < instanceLists.length; ++f) { for (final FeatureInstance instance : instanceLists[f]) { if (instance.matches(state)) { activeInstances.add(instance); } } } } } } } } } } // if (activeInstances.size() == 0) // { // System.out.println("lastFrom = " + lastFrom); // System.out.println("lastTo = " + lastTo); // System.out.println("from = " + from); // System.out.println("to = " + to); // System.out.println("player = " + player); // System.out.println("instanceNodesToCheck.size() = " + instanceNodesToCheck.size()); // System.out.println("returning num active instances = " + activeInstances.size()); // } return activeInstances; } /** * @param context * @param lastFrom * @param lastTo * @param from * @param to * @param player * @param thresholded * * @return A list of all features that are active for a given state+action * pair (where action is defined by from and to positions) */ public List<SpatialFeature> getActiveFeatures ( final Context context, final int lastFrom, final int lastTo, final int from, final int to, final int player, final boolean thresholded ) { final TIntArrayList activeFeatureIndices = getActiveSpatialFeatureIndices(context.state(), lastFrom, lastTo, from, to, player, thresholded); final List<SpatialFeature> activeFeatures = new ArrayList<SpatialFeature>(activeFeatureIndices.size()); final TIntIterator it = activeFeatureIndices.iterator(); while (it.hasNext()) { activeFeatures.add(spatialFeatures[it.next()]); } return activeFeatures; } //------------------------------------------------------------------------- @Override public BaseFootprint generateFootprint ( final State state, final int from, final int to, final int player ) { final ContainerState container = state.containerStates()[0]; final ChunkSet footprintEmptyCells = container.emptyChunkSetCell() != null ? new ChunkSet(container.emptyChunkSetCell().chunkSize(), 1) : null; final ChunkSet footprintEmptyVertices = container.emptyChunkSetVertex() != null ? new ChunkSet(container.emptyChunkSetVertex().chunkSize(), 1) : null; final ChunkSet footprintEmptyEdges = container.emptyChunkSetEdge() != null ? new ChunkSet(container.emptyChunkSetEdge().chunkSize(), 1) : null; final ChunkSet footprintWhoCells = container.chunkSizeWhoCell() > 0 ? new ChunkSet(container.chunkSizeWhoCell(), 1) : null; final ChunkSet footprintWhoVertices = container.chunkSizeWhoVertex() > 0 ? new ChunkSet(container.chunkSizeWhoVertex(), 1) : null; final ChunkSet footprintWhoEdges = container.chunkSizeWhoEdge() > 0 ? new ChunkSet(container.chunkSizeWhoEdge(), 1) : null; final ChunkSet footprintWhatCells = container.chunkSizeWhatCell() > 0 ? new ChunkSet(container.chunkSizeWhatCell(), 1) : null; final ChunkSet footprintWhatVertices = container.chunkSizeWhatVertex() > 0 ? new ChunkSet(container.chunkSizeWhatVertex(), 1) : null; final ChunkSet footprintWhatEdges = container.chunkSizeWhatEdge() > 0 ? new ChunkSet(container.chunkSizeWhatEdge(), 1) : null; final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; // Loop through all instances, OR all the tests final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Proactive instances key.resetData(player, fromPos, toPos); final List<FeatureInstance>[] instanceLists = proactiveFeatures.get(key); if (instanceLists != null) { for (int i = 0; i < instanceLists.length; ++i) { for (final FeatureInstance instance : instanceLists[i]) { if (instance.mustEmpty() != null) { switch (instance.graphElementType()) { case Cell: footprintEmptyCells.or(instance.mustEmpty()); break; case Vertex: footprintEmptyVertices.or(instance.mustEmpty()); break; case Edge: footprintEmptyEdges.or(instance.mustEmpty()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustNotEmpty() != null) { switch (instance.graphElementType()) { case Cell: footprintEmptyCells.or(instance.mustNotEmpty()); break; case Vertex: footprintEmptyVertices.or(instance.mustNotEmpty()); break; case Edge: footprintEmptyEdges.or(instance.mustNotEmpty()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustWhoMask() != null) { switch (instance.graphElementType()) { case Cell: footprintWhoCells.or(instance.mustWhoMask()); break; case Vertex: footprintWhoVertices.or(instance.mustWhoMask()); break; case Edge: footprintWhoEdges.or(instance.mustWhoMask()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustNotWhoMask() != null) { switch (instance.graphElementType()) { case Cell: footprintWhoCells.or(instance.mustNotWhoMask()); break; case Vertex: footprintWhoVertices.or(instance.mustNotWhoMask()); break; case Edge: footprintWhoEdges.or(instance.mustNotWhoMask()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustWhatMask() != null) { switch (instance.graphElementType()) { case Cell: footprintWhatCells.or(instance.mustWhatMask()); break; case Vertex: footprintWhatVertices.or(instance.mustWhatMask()); break; case Edge: footprintWhatEdges.or(instance.mustWhatMask()); break; //$CASES-OMITTED$ Hint default: break; } } if (instance.mustNotWhatMask() != null) { switch (instance.graphElementType()) { case Cell: footprintWhatCells.or(instance.mustNotWhatMask()); break; case Vertex: footprintWhatVertices.or(instance.mustNotWhatMask()); break; case Edge: footprintWhatEdges.or(instance.mustNotWhatMask()); break; //$CASES-OMITTED$ Hint default: break; } } } } } } } } return new FullFootprint ( footprintEmptyCells, footprintEmptyVertices, footprintEmptyEdges, footprintWhoCells, footprintWhoVertices, footprintWhoEdges, footprintWhatCells, footprintWhatVertices, footprintWhatEdges ); } //------------------------------------------------------------------------- /** * Attempts to create an expanded feature set which contains all of the current features, * plus one new feature by combining a pair of features from the given list of active instances * into a new feature. Will return null if no such pair can be found such that it results in a * really new feature. We only allow pairs of instances that have a shared anchor. * * @param activeFeatureInstances * @param combineMaxWeightedFeatures * If true, we will prioritise creating new pairs of features such that at least one * of them has the highest possible absolute weight in our linear function approximator * (i.e. we try to extend features that are already highly informative with additional * elements). If false, we'll select pairs of features randomly. * @param featureWeights * @return New Feature Set with one extra feature, or null if cannot be expanded */ public NaiveFeatureSet createExpandedFeatureSet ( final List<FeatureInstance> activeFeatureInstances, final boolean combineMaxWeightedFeatures, final FVector featureWeights ) { // generate all possible pairs of two different features (order does not matter) final int numActiveInstances = activeFeatureInstances.size(); final List<FeatureInstancePair> allPairs = new ArrayList<FeatureInstancePair>(); for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance firstInstance = activeFeatureInstances.get(i); for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance secondInstance = activeFeatureInstances.get(j); if (firstInstance.anchorSite() == secondInstance.anchorSite()) { allPairs.add(new FeatureInstancePair(firstInstance, secondInstance)); } } } if (combineMaxWeightedFeatures) { // sort feature pairs in increasing order of max(abs(weight(a), abs(weight(b)))) final FVector absWeights = featureWeights.copy(); absWeights.abs(); allPairs.sort(new Comparator<FeatureInstancePair>() { @Override public int compare(FeatureInstancePair o1, FeatureInstancePair o2) { final float score1 = Math.max( absWeights.get(o1.a.feature().spatialFeatureSetIndex()), absWeights.get(o1.b.feature().spatialFeatureSetIndex())); final float score2 = Math.max( absWeights.get(o2.a.feature().spatialFeatureSetIndex()), absWeights.get(o2.b.feature().spatialFeatureSetIndex())); if (score1 == score2) { return 0; } else if (score1 < score2) { return -1; } else { return 1; } } }); } else { // just shuffle them for random combining Collections.shuffle(allPairs); } // keep trying to combine pairs of features, until we find a new one or // until we have tried them all while (!allPairs.isEmpty()) { final FeatureInstancePair pair = allPairs.remove(allPairs.size() - 1); final NaiveFeatureSet newFeatureSet = createExpandedFeatureSet ( game.get(), SpatialFeature.combineFeatures ( game.get(), pair.a, pair.b ) ); if (newFeatureSet != null) { return newFeatureSet; } } // failed to construct a new feature set with a new feature return null; } @Override public NaiveFeatureSet createExpandedFeatureSet ( final Game targetGame, final SpatialFeature newFeature ) { boolean featureAlreadyExists = false; for (final SpatialFeature oldFeature : spatialFeatures) { if (newFeature.equals(oldFeature)) { featureAlreadyExists = true; break; } // also try all legal rotations of the generated feature, see // if any of those turn out to be equal to an old feature TFloatArrayList allowedRotations = newFeature.pattern().allowedRotations(); if (allowedRotations == null) { allowedRotations = new TFloatArrayList(Walk.allGameRotations(game.get())); } for (int i = 0; i < allowedRotations.size(); ++i) { final SpatialFeature rotatedCopy = newFeature.rotatedCopy(allowedRotations.getQuick(i)); if (rotatedCopy.equals(oldFeature)) { // TODO only break if for every possible anchor this works? featureAlreadyExists = true; break; } } } if (!featureAlreadyExists) { // create new feature set with this feature, and return it final List<SpatialFeature> newFeatureList = new ArrayList<SpatialFeature>(spatialFeatures.length + 1); // all old features... for (final SpatialFeature feature : spatialFeatures) { newFeatureList.add(feature); } // and our new feature newFeatureList.add(newFeature); return new NaiveFeatureSet(Arrays.asList(aspatialFeatures), newFeatureList); } return null; } //------------------------------------------------------------------------- /** * Wrapper class for a pair of feature instances * * @author Dennis Soemers */ private static class FeatureInstancePair { //-------------------------------------------------------------------- /** First instance */ protected final FeatureInstance a; /** Second instance */ protected final FeatureInstance b; //--------------------------------------------------------------------- /** * Constructor * @param a * @param b */ protected FeatureInstancePair ( final FeatureInstance a, final FeatureInstance b ) { this.a = a; this.b = b; } //--------------------------------------------------------------------- } //------------------------------------------------------------------------- }
28,940
27.597826
133
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/BipartiteGraphFeatureInstanceSet.java
package features.feature_sets.network; import java.util.ArrayList; import java.util.BitSet; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import features.spatial.instances.AtomicProposition; import features.spatial.instances.AtomicProposition.StateVectorTypes; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.list.array.TIntArrayList; /** * A bipartite graph representation of a feature instance set. We have one * group of nodes representing atomic propositions, and one group of nodes * representing all feature instances. * * @author Dennis Soemers */ public class BipartiteGraphFeatureInstanceSet { //------------------------------------------------------------------------- /** Proposition nodes stored as map, so we can easily avoid adding duplicates for same proposition */ protected final Map<AtomicProposition, PropositionNode> propositionNodes; /** Also need the same propositions stored in a list */ protected final List<PropositionNode> propositionNodesList; /** List of all feature instance nodes */ protected final List<FeatureInstanceNode> instanceNodes; //------------------------------------------------------------------------- /** * Constructor */ public BipartiteGraphFeatureInstanceSet() { propositionNodes = new HashMap<AtomicProposition, PropositionNode>(); propositionNodesList = new ArrayList<PropositionNode>(); instanceNodes = new ArrayList<FeatureInstanceNode>(); } //------------------------------------------------------------------------- /** * Inserts given instance into this set * @param instance */ public void insertInstance(final FeatureInstance instance) { final List<AtomicProposition> atomicPropositions = instance.generateAtomicPropositions(); final FeatureInstanceNode instanceNode = new FeatureInstanceNode(instanceNodes.size(), instance); instanceNodes.add(instanceNode); for (final AtomicProposition proposition : atomicPropositions) { PropositionNode propNode = propositionNodes.get(proposition); if (propNode == null) { propNode = new PropositionNode(propositionNodesList.size(), proposition); propositionNodesList.add(propNode); propositionNodes.put(proposition, propNode); } propNode.instances.add(instanceNode); instanceNode.propositions.add(propNode); } } //------------------------------------------------------------------------- /** * @return A PropFeatureInstanceSet representation of this feature set */ public PropFeatureInstanceSet toPropFeatureInstanceSet() { // The list of nodes we want to build up final List<PropNode> nodes = new ArrayList<PropNode>(); // Compute conjunctive clauses final BitSet[] conjunctiveClauses = computeConjunctiveClauses(); // Split clauses into Ungeneralised and Generalised sets // - Ungeneralised clauses are not generalised by any others, so they must for sure get at // least one of their propositions checked // - Generalised clauses are generalised by at least one other, so maybe it doesn't need to // get anything checked (if one of its generalisers already ends up getting disproven) List<BitSet> ungeneralised = new ArrayList<BitSet>(); List<BitSet> generalised = new ArrayList<BitSet>(); for (int i = 0; i < conjunctiveClauses.length; ++i) { final BitSet iProps = conjunctiveClauses[i]; if (iProps.isEmpty()) continue; // Skip this, don't need it in either set boolean isGeneralised = false; for (int j = 0; j < conjunctiveClauses.length; ++j) { if (i == j) continue; final BitSet jProps = conjunctiveClauses[j]; if (jProps.isEmpty()) continue; // Skip this, don't need it in either set if (iProps.equals(jProps)) continue; // If they're equal, don't count as generalised either way, just preserve both final BitSet jPropsCopy = ((BitSet)jProps.clone()); jPropsCopy.andNot(iProps); if (jPropsCopy.isEmpty()) { // j has no propositions that i doesn't, so j generalises i isGeneralised = true; break; } } if (isGeneralised) generalised.add(iProps); else ungeneralised.add(iProps); } // Loop until ungeneralised is depleted (which must mean that generalised is also depleted) while (!ungeneralised.isEmpty()) { // Generate bins of instances in ungeneralised based on the cardinalities of their clauses final List<List<BitSet>> ungeneralisedBins = new ArrayList<List<BitSet>>(); ungeneralisedBins.add(null); for (final BitSet clause : ungeneralised) { final int clauseLength = clause.cardinality(); while (ungeneralisedBins.size() <= clauseLength) { ungeneralisedBins.add(new ArrayList<BitSet>()); } ungeneralisedBins.get(clauseLength).add(clause); } // For every proposition, we want to know how often it shows up in generalised (as tie-breaker) final int[] generalisedPropCounts = new int[propositionNodesList.size()]; for (final BitSet props : generalised) { for (int i = props.nextSetBit(0); i >= 0; i = props.nextSetBit(i + 1)) { generalisedPropCounts[i]++; } } // Figure out which propositions to add in this round // We'll track this as both a list and a BitSet // List is used because order is important, // BitSet is used for efficient testing of already-covered clauses final TIntArrayList propsToAdd = new TIntArrayList(); final BitSet selectedProps = new BitSet(); // All propositions of clause length 1 must for sure be added for (final BitSet clause : ungeneralisedBins.get(1)) { final int propID = clause.nextSetBit(0); propsToAdd.add(propID); selectedProps.set(propID); } // From every other bin, select the proposition that: // - is not already selected // - occurs maximally often in uncovered clauses of that bin // - as tie-breaker, occurs maximally often in ungeneralised for (int l = 2; l < ungeneralisedBins.size(); ++l) { final BitSet candidateProps = new BitSet(); final int[] propOccurrences = new int[propositionNodesList.size()]; for (final BitSet clause : ungeneralisedBins.get(l)) { if (clause.intersects(selectedProps)) continue; // Already covered for (int i = clause.nextSetBit(0); i >= 0; i = clause.nextSetBit(i + 1)) { candidateProps.set(i); propOccurrences[i]++; } } if (!candidateProps.isEmpty()) { final TIntArrayList bestCandidates = new TIntArrayList(); int maxOccurrence = 0; for (int i = candidateProps.nextSetBit(0); i >= 0; i = candidateProps.nextSetBit(i + 1)) { if (propOccurrences[i] > maxOccurrence) { maxOccurrence = propOccurrences[i]; bestCandidates.clear(); bestCandidates.add(i); } else if (propOccurrences[i] == maxOccurrence) { bestCandidates.add(i); } } // Tie-breaker: most occurrences in generalised set int propToAdd = bestCandidates.getQuick(0); int maxGeneralisedOccurrences = generalisedPropCounts[propToAdd]; for (int i = 1; i < bestCandidates.size(); ++i) { final int propID = bestCandidates.getQuick(i); final int generalisedOccurrences = generalisedPropCounts[propID]; if (generalisedOccurrences > maxGeneralisedOccurrences) { maxGeneralisedOccurrences = generalisedOccurrences; propToAdd = propID; } } // Select proposition propsToAdd.add(propToAdd); selectedProps.set(propToAdd); } } // Add all the propositions we want to add. // IMPORTANT: do so in the order in which we selected them for (int i = 0; i < propsToAdd.size(); ++i) { final int propID = propsToAdd.getQuick(i); nodes.add(new PropNode(nodes.size(), propositionNodesList.get(propID).proposition)); } // Update clauses in ungeneralised set for (int i = ungeneralised.size() - 1; i >= 0; --i) { final BitSet clause = ungeneralised.get(i); clause.andNot(selectedProps); if (clause.isEmpty()) ungeneralised.remove(i); } // Update clauses in generalised set for (int i = generalised.size() - 1; i >= 0; --i) { final BitSet clause = generalised.get(i); clause.andNot(selectedProps); if (clause.isEmpty()) generalised.remove(i); } // Re-compute ungeneralised and generalised sets final List<BitSet> newUngeneralised = new ArrayList<BitSet>(); final List<BitSet> newGeneralised = new ArrayList<BitSet>(); // Gather all remaining clauses in a set first, to remove duplicates final Set<BitSet> allClausesSet = new HashSet<BitSet>(); allClausesSet.addAll(generalised); allClausesSet.addAll(ungeneralised); final BitSet[] allClauses = allClausesSet.toArray(new BitSet[allClausesSet.size()]); for (int i = 0; i < allClauses.length; ++i) { final BitSet iProps = allClauses[i]; if (iProps.isEmpty()) continue; // Skip this, don't need it in either set boolean isGeneralised = false; for (int j = 0; j < allClauses.length; ++j) { if (i == j) continue; final BitSet jProps = allClauses[j]; if (jProps.isEmpty()) continue; // Skip this, don't need it in either set final BitSet jPropsCopy = ((BitSet)jProps.clone()); jPropsCopy.andNot(iProps); if (jPropsCopy.isEmpty()) { // j has no propositions that i doesn't, so j generalises i isGeneralised = true; break; } } if (isGeneralised) newGeneralised.add(iProps); else newUngeneralised.add(iProps); } generalised = newGeneralised; ungeneralised = newUngeneralised; } // Tell every propnode which feature instances it should deactivate if false for (final PropNode propNode : nodes) { final List<FeatureInstanceNode> instances = propositionNodes.get(propNode.proposition()).instances; for (int i = instances.size() - 1; i >= 0; --i) { // Doing this in reverse order leads to better memory usage because we start with // the biggest index, which usually causes the dependentInstances bitset in the propNode // to get sized to precisely the correct size, rather than getting doubled several times // and overshooting propNode.setDependentInstance(instances.get(i).id); } } // Generate our array of feature instances final FeatureInstance[] featureInstances = new FeatureInstance[instanceNodes.size()]; for (int i = 0; i < instanceNodes.size(); ++i) { featureInstances[i] = instanceNodes.get(i).instance; } // And array of propnodes final PropNode[] propNodes = nodes.toArray(new PropNode[nodes.size()]); return new PropFeatureInstanceSet(featureInstances, propNodes); } //------------------------------------------------------------------------- /** * @param numFeatures * @param thresholdedFeatures Features that should be ignored because their abs weights are too low * @param game * @param perspectivePlayer * @return A SPatterNet representation of this feature set */ public SPatterNet toSPatterNet ( final int numFeatures, final BitSet thresholdedFeatures, final Game game, final int perspectivePlayer ) { // Our final, correctly-sorted list of atomic propositions in the order in which they // should be evaluated final List<AtomicProposition> propositions = new ArrayList<AtomicProposition>(); // Compute our conjunctions (one per feature instance) final List<BitSet> conjunctiveClauses = new ArrayList<BitSet>(); for (final BitSet bitset : computeConjunctiveClauses()) { conjunctiveClauses.add(bitset); } // Remember which features should auto-activate (due to 0-requirement instances) final BitSet autoActiveFeatures = new BitSet(); // Create list of instance nodes where we already filter some unnecessary ones out final List<FeatureInstanceNode> filteredInstanceNodes = new ArrayList<FeatureInstanceNode>(instanceNodes.size()); // First we add everything, afterwards we remove, because we need to synchronise also removing bitsets from // conjunctiveClauses filteredInstanceNodes.addAll(instanceNodes); for (int i = filteredInstanceNodes.size() - 1; i >= 0; --i) { final FeatureInstanceNode node = filteredInstanceNodes.get(i); final int featureIdx = node.instance.feature().spatialFeatureSetIndex(); if (thresholdedFeatures.get(featureIdx)) { // Should remove this instance because its feature is thresholded filteredInstanceNodes.remove(i); conjunctiveClauses.remove(i); } else if (conjunctiveClauses.get(i).isEmpty()) { // Should remove this instance because it has no requirements, and remember that feature // should auto-activate filteredInstanceNodes.remove(i); conjunctiveClauses.remove(i); autoActiveFeatures.set(featureIdx); } } // A second pass to remove any instance of auto-active features for (int i = filteredInstanceNodes.size() - 1; i >= 0; --i) { final FeatureInstanceNode node = filteredInstanceNodes.get(i); final int featureIdx = node.instance.feature().spatialFeatureSetIndex(); if (autoActiveFeatures.get(featureIdx)) { filteredInstanceNodes.remove(i); conjunctiveClauses.remove(i); } } // Also get rid of any feature instances that are generalised by other instances for the same feature for (int i = filteredInstanceNodes.size() - 1; i >= 0; --i) { final FeatureInstanceNode instanceNode = filteredInstanceNodes.get(i); final int featureIdx = instanceNode.instance.feature().spatialFeatureSetIndex(); for (int k = 0; k < filteredInstanceNodes.size(); ++k) { if (i != k) { final FeatureInstanceNode other = filteredInstanceNodes.get(k); if (other.instance.feature().spatialFeatureSetIndex() == featureIdx) { if (other.instance.generalises(instanceNode.instance)) { filteredInstanceNodes.remove(i); conjunctiveClauses.remove(i); break; } } } } } // First keep instances unsorted, but gather data here that we can use to sort afterwards final List<SortableFeatureInstance> sortableFeatureInstances = new ArrayList<SortableFeatureInstance>(); for (final FeatureInstanceNode node : filteredInstanceNodes) { sortableFeatureInstances.add(new SortableFeatureInstance(node.instance)); } // Compute our disjunctions (one per feature) final DisjunctiveClause[] disjunctions = new DisjunctiveClause[numFeatures]; for (int i = 0; i < numFeatures; ++i) { disjunctions[i] = new DisjunctiveClause(); } for (int i = 0; i < filteredInstanceNodes.size(); ++i) { final int featureIdx = filteredInstanceNodes.get(i).instance.feature().spatialFeatureSetIndex(); disjunctions[featureIdx].addConjunction(new Conjunction(conjunctiveClauses.get(i))); } // Compute which propositions are still relevant (maybe not all of them due to removals of feature instances) final BitSet relevantProps = new BitSet(propositionNodesList.size()); for (final DisjunctiveClause disjunction : disjunctions) { relevantProps.or(disjunction.usedPropositions()); } // For every proposition, compute which other propositions it should (dis)prove if found to be // true or false final BitSet[] proveIfTrue = new BitSet[propositionNodesList.size()]; final BitSet[] disproveIfTrue = new BitSet[propositionNodesList.size()]; final BitSet[] proveIfFalse = new BitSet[propositionNodesList.size()]; final BitSet[] disproveIfFalse = new BitSet[propositionNodesList.size()]; for (int i = 0; i < propositionNodesList.size(); ++i) { proveIfTrue[i] = new BitSet(); disproveIfTrue[i] = new BitSet(); proveIfFalse[i] = new BitSet(); disproveIfFalse[i] = new BitSet(); final AtomicProposition propI = propositionNodesList.get(i).proposition; for (int j = 0; j < propositionNodesList.size(); ++j) { if (i == j) continue; final AtomicProposition propJ = propositionNodesList.get(j).proposition; if (propI.provesIfTrue(propJ, game)) proveIfTrue[i].set(j); else if (propI.disprovesIfTrue(propJ, game)) disproveIfTrue[i].set(j); if (propI.provesIfFalse(propJ, game)) proveIfFalse[i].set(j); else if (propI.disprovesIfFalse(propJ, game)) disproveIfFalse[i].set(j); } } // Each of these lists should contain, at index i, all disjunctions with i assumed-proven conjunctions List<List<DisjunctiveClause>> ungeneralisedDisjunctions = new ArrayList<List<DisjunctiveClause>>(); List<List<DisjunctiveClause>> generalisedDisjunctions = new ArrayList<List<DisjunctiveClause>>(); // Start out putting everything in Generalised, and not yet assuming anything proven final List<DisjunctiveClause> zeroProvenDisjunctions = new ArrayList<DisjunctiveClause>(); for (final DisjunctiveClause clause : disjunctions) { // Remove conjunctions from the disjunction that are generalised by other conjunctions within the same disjunction clause.eliminateGeneralisedConjunctions(); // Only include clause if it's non-empty if (clause.length() > 0) zeroProvenDisjunctions.add(clause); } // Sort the disjunctions in increasing order of number of conjunctions; this will generally // let us more quickly fill up the ungeneralised set and hence discover generalisers more quickly zeroProvenDisjunctions.sort(new Comparator<DisjunctiveClause>() { @Override public int compare(final DisjunctiveClause o1, final DisjunctiveClause o2) { return o1.length() - o2.length(); } }); generalisedDisjunctions.add(zeroProvenDisjunctions); // Now compute which ones are ungeneralised for real UngeneralisedGeneralisedWrapper ungenGenWrapper = updateUngeneralisedGeneralised(ungeneralisedDisjunctions, generalisedDisjunctions); ungeneralisedDisjunctions = ungenGenWrapper.ungeneralisedDisjunctions; generalisedDisjunctions = ungenGenWrapper.generalisedDisjunctions; // We track picked propositions in both a list and a bitset. // List because order of picking is relevant, bitset for faster coverage tests final TIntArrayList pickedPropsList = new TIntArrayList(); final BitSet pickedPropsBitset = new BitSet(); // Mark any propositions that are irrelevant as "already picked", so we don't prioritise and pick them // anyway if they test for empty positions final BitSet irrelevantProps = (BitSet) relevantProps.clone(); irrelevantProps.flip(0, propositionNodesList.size()); pickedPropsBitset.or(irrelevantProps); // Keep going until every Ungeneralised_i list is empty (which must mean that all Generalised_X lists are also empty) int i = -1; while ((i = firstNonEmptyListIndex(ungeneralisedDisjunctions)) >= 0) { final List<DisjunctiveClause> ungeneralised_i = ungeneralisedDisjunctions.get(i); // Need to clear list of picked props, but bitset doesn't need to be cleared pickedPropsList.clear(); // For every disjunction in this ungeneralised_i set, we have to pick at least one conjunction // to cover by at least one proposition // // Finding the minimum set of propositions such that at least one conjunction from every // disjunction is covered is the Hitting Set problem: NP-hard // // A simple heuristic for simple greedy approaches for Set Cover is to pick whichever proposition // covers the largest number of disjunctions first. This is also similar to the "Max occurrences" // idea in the MOMS heuristic for SAT. // (and splitting in generalised/ungeneralised may be similar to eliminating dominated columns in // set cover?) // Create bins of disjunctions based on their length (= number of conjunctions) final List<List<DisjunctiveClause>> disjunctionBins = new ArrayList<List<DisjunctiveClause>>(); for (final DisjunctiveClause clause : ungeneralised_i) { final int clauseLength = clause.length(); while (disjunctionBins.size() <= clauseLength) { disjunctionBins.add(new ArrayList<DisjunctiveClause>()); } disjunctionBins.get(clauseLength).add(clause); } // We will start looking at disjunctions that have only a single conjunction; from each of these // we will for sure have to pick at least one proposition final List<DisjunctiveClause> singleConjList = disjunctionBins.get(1); // As an additional heuristic, we want to look at is-empty tests first // Sort in reverse order, since after this sorting we loop through it in reverse order // StringBuilder sb = new StringBuilder(); // for (final DisjunctiveClause dis : singleConjList) // { // sb.append(propositionNodesList.get(dis.conjunctions().get(0).toProve().nextSetBit(0)) + ", "); // } // System.out.println("before sort: " + sb.toString()); singleConjList.sort(new Comparator<DisjunctiveClause>() { @Override public int compare(final DisjunctiveClause o1, final DisjunctiveClause o2) { // We should only have a single conjunction per disjunction here final BitSet conj1BitSet = o1.conjunctions().get(0).toProve(); final BitSet conj2BitSet = o2.conjunctions().get(0).toProve(); int numEmptyChecks1 = 0; for (int j = conj1BitSet.nextSetBit(0); j >= 0; j = conj1BitSet.nextSetBit(j + 1)) { if (propositionNodesList.get(j).proposition.stateVectorType() == StateVectorTypes.Empty) ++numEmptyChecks1; } int numEmptyChecks2 = 0; for (int j = conj2BitSet.nextSetBit(0); j >= 0; j = conj2BitSet.nextSetBit(j + 1)) { if (propositionNodesList.get(j).proposition.stateVectorType() == StateVectorTypes.Empty) ++numEmptyChecks2; } return numEmptyChecks2 - numEmptyChecks1; } }); // sb = new StringBuilder(); // for (final DisjunctiveClause dis : singleConjList) // { // sb.append(propositionNodesList.get(dis.conjunctions().get(0).toProve().nextSetBit(0)) + ", "); // } // System.out.println("after sort: " + sb.toString()); // System.out.println(); // Within this bin of single-conjunction disjunctions, first add all the propositions of length-1 // conjunctions; these have to be picked for sure for (int j = singleConjList.size() - 1; j >= 0; --j) { final DisjunctiveClause disj = singleConjList.get(j); if (disj.usedPropositions().cardinality() == 1) { // Entire disjunction uses only a single proposition final int propID = disj.usedPropositions().nextSetBit(0); if (!pickedPropsBitset.get(propID)) { // Proposition not already picked, so pick it now pickProp(propID, pickedPropsList, pickedPropsBitset); } // Remove this disjunction, already handled it singleConjList.remove(j); } } // Any remaining disjunctions still have only 1 conjunction, but a conjunction with more than 1 prop // For any that are not already covered, we pick 1 proposition to add; as a heuristic, always pick // whichever proposition has the max occurrences for (int j = 0; j < singleConjList.size(); ++j) { final DisjunctiveClause disj = singleConjList.get(j); pickCoveringPropositions ( disj, pickedPropsList, pickedPropsBitset, singleConjList, j + 1, // First tie-breaker layer disjunctionBins, 2, // Second tie-breaker layer ungeneralisedDisjunctions, i + 1, // Third tie-breaker layer generalisedDisjunctions, 0, // Fourth tie-breaker layer proveIfTrue, disproveIfTrue, proveIfFalse, disproveIfFalse ); } // Now we need to go through bins of disjunctions that have 2 or more conjunctions each for (int j = 2; j < disjunctionBins.size(); ++j) { final List<DisjunctiveClause> bin = disjunctionBins.get(j); for (int k = 0; k < bin.size(); ++k) { final DisjunctiveClause disj = bin.get(k); pickCoveringPropositions ( disj, pickedPropsList, pickedPropsBitset, bin, k + 1, // First tie-breaker layer disjunctionBins, j + 1, // Second tie-breaker layer ungeneralisedDisjunctions, i + 1, // Third tie-breaker layer generalisedDisjunctions, 0, // Fourth tie-breaker layer proveIfTrue, disproveIfTrue, proveIfFalse, disproveIfFalse ); } } // Add all the propositions that we've decided need adding for (int j = 0; j < pickedPropsList.size(); ++j) { final int propID = pickedPropsList.getQuick(j); final AtomicProposition prop = propositionNodesList.get(propID).proposition; propositions.add(prop); } // Inform all disjunctions about propositions that are now assumed to be true for (int j = 0; j < ungeneralisedDisjunctions.size(); ++j) { final List<DisjunctiveClause> list = ungeneralisedDisjunctions.get(j); for (int k = 0; k < list.size(); ++k) { list.get(k).assumeTrue(pickedPropsBitset); } } for (int j = 0; j < generalisedDisjunctions.size(); ++j) { final List<DisjunctiveClause> list = generalisedDisjunctions.get(j); for (int k = 0; k < list.size(); ++k) { list.get(k).assumeTrue(pickedPropsBitset); } } // Update the Ungeneralised/Generalised split again ungenGenWrapper = updateUngeneralisedGeneralised(ungeneralisedDisjunctions, generalisedDisjunctions); ungeneralisedDisjunctions = ungenGenWrapper.ungeneralisedDisjunctions; generalisedDisjunctions = ungenGenWrapper.generalisedDisjunctions; } // Tell all the sortable feature instances which post-sorting propositions they use // We did not yet sort the sortable feature instances, so for now they're in the same // order as the filtered feature instance nodes for (int j = 0; j < filteredInstanceNodes.size(); ++j) { final FeatureInstanceNode instanceNode = filteredInstanceNodes.get(j); for (final PropositionNode propNode : instanceNode.propositions) { final int newPropID = propositions.indexOf(propNode.proposition); if (newPropID >= 0) sortableFeatureInstances.get(j).propIDs.set(newPropID); } } // Thresholded features should not auto-activate autoActiveFeatures.andNot(thresholdedFeatures); // Sort our sortable feature instances sortableFeatureInstances.sort(null); // Generate all the final arrays we need final FeatureInstance[] sortedFeatureInstances = new FeatureInstance[sortableFeatureInstances.size()]; final BitSet[] instancesPerProp = new BitSet[propositions.size()]; final BitSet[] instancesPerFeature = new BitSet[numFeatures]; final BitSet[] propsPerInstance = new BitSet[sortableFeatureInstances.size()]; for (int j = 0; j < propositions.size(); ++j) { instancesPerProp[j] = new BitSet(); } // Reverse loop for better memory usage in bitsets for (int j = sortableFeatureInstances.size() - 1; j >= 0; --j) { sortedFeatureInstances[j] = sortableFeatureInstances.get(j).featureInstance; final BitSet instanceProps = sortableFeatureInstances.get(j).propIDs; propsPerInstance[j] = (BitSet) instanceProps.clone(); for (int k = instanceProps.nextSetBit(0); k >= 0; k = instanceProps.nextSetBit(k + 1)) { instancesPerProp[k].set(j); } final int featureIdx = sortedFeatureInstances[j].feature().spatialFeatureSetIndex(); if (instancesPerFeature[featureIdx] == null) instancesPerFeature[featureIdx] = new BitSet(); instancesPerFeature[featureIdx].set(j); } final TIntArrayList autoActiveFeaturesList = new TIntArrayList(); for (int j = autoActiveFeatures.nextSetBit(0); j >= 0; j = autoActiveFeatures.nextSetBit(j + 1)) { autoActiveFeaturesList.add(j); } // Recompute all the proves/disproves if true/false relations, but now for the sorted // propositions, and only in the "forwards" direction final BitSet[] provesIfTruePerProp = new BitSet[propositions.size()]; final BitSet[] disprovesIfTruePerProp = new BitSet[propositions.size()]; final BitSet[] provesIfFalsePerProp = new BitSet[propositions.size()]; final BitSet[] disprovesIfFalsePerProp = new BitSet[propositions.size()]; for (int j = 0; j < propositions.size(); ++j) { provesIfTruePerProp[j] = new BitSet(); disprovesIfTruePerProp[j] = new BitSet(); provesIfFalsePerProp[j] = new BitSet(); disprovesIfFalsePerProp[j] = new BitSet(); final AtomicProposition propJ = propositions.get(j); for (int k = j + 1; k < propositions.size(); ++k) { final AtomicProposition propK = propositions.get(k); if (propJ.provesIfTrue(propK, game)) provesIfTruePerProp[j].set(k); else if (propJ.disprovesIfTrue(propK, game)) disprovesIfTruePerProp[j].set(k); if (propJ.provesIfFalse(propK, game)) provesIfFalsePerProp[j].set(k); else if (propJ.disprovesIfFalse(propK, game)) disprovesIfFalsePerProp[j].set(k); } } final int[] featureIndices = new int[sortedFeatureInstances.length]; for (int instanceIdx = 0; instanceIdx < featureIndices.length; ++instanceIdx) { featureIndices[instanceIdx] = sortedFeatureInstances[instanceIdx].feature().spatialFeatureSetIndex(); } return new SPatterNet ( featureIndices, propositions.toArray(new AtomicProposition[propositions.size()]), instancesPerProp, instancesPerFeature, propsPerInstance, autoActiveFeaturesList.toArray(), thresholdedFeatures, provesIfTruePerProp, disprovesIfTruePerProp, provesIfFalsePerProp, disprovesIfFalsePerProp ); } //------------------------------------------------------------------------- /** * Returns updated sets of ungeneralised and generalised disjunctions * @param ungeneralisedDisjunctions * @param generalisedDisjunctions * @return Updated sets */ private static UngeneralisedGeneralisedWrapper updateUngeneralisedGeneralised ( final List<List<DisjunctiveClause>> ungeneralisedDisjunctions, final List<List<DisjunctiveClause>> generalisedDisjunctions ) { final List<List<DisjunctiveClause>> newUngeneralisedDisjunctions = new ArrayList<List<DisjunctiveClause>>(); final List<List<DisjunctiveClause>> newGeneralisedDisjunctions = new ArrayList<List<DisjunctiveClause>>(); @SuppressWarnings("unchecked") final List<List<DisjunctiveClause>>[] lists = new List[]{ungeneralisedDisjunctions, generalisedDisjunctions}; // Loop through all disjunctions and put them in the correct place for (final List<List<DisjunctiveClause>> list : lists) { for (int i = 0; i < list.size(); ++i) { final List<DisjunctiveClause> list_i = list.get(i); // Do next loop in reverse order, more efficient due to removals for (int j = list_i.size() - 1; j >= 0; --j) { // Make sure index is still safe, because we may have multiple removals during search for generalisers if (j >= list_i.size()) { j = list_i.size(); continue; } final DisjunctiveClause disjunction = list_i.get(j); if (disjunction.length() > 0) // Can't discard this entirely { // Search for a generaliser of this disjunction final boolean hasGeneraliser = searchGeneraliser(disjunction, ungeneralisedDisjunctions, generalisedDisjunctions); // Insert in correct position based on whether or not we are generalised final int numAssumedTrue = disjunction.numAssumedTrue(); if (hasGeneraliser) { // Make sure list we want to go to actually exists while (newGeneralisedDisjunctions.size() <= numAssumedTrue) { newGeneralisedDisjunctions.add(new ArrayList<DisjunctiveClause>()); } newGeneralisedDisjunctions.get(numAssumedTrue).add(disjunction); } else { // Make sure list we want to go to actually exists while (newUngeneralisedDisjunctions.size() <= numAssumedTrue) { newUngeneralisedDisjunctions.add(new ArrayList<DisjunctiveClause>()); } newUngeneralisedDisjunctions.get(numAssumedTrue).add(disjunction); } } } } } return new UngeneralisedGeneralisedWrapper(newUngeneralisedDisjunctions, newGeneralisedDisjunctions); } /** * Searches for a disjunctive clause, among all the given clauses, that generalises the given clause. * * NOTE: this method may also decide to remove various duplicates as it detects them. * * @param clause * @param ungeneralisedDisjunctions * @param generalisedDisjunctions * @return True if we are generalised (by a non-equal clause) */ private static boolean searchGeneraliser ( final DisjunctiveClause clause, final List<List<DisjunctiveClause>> ungeneralisedDisjunctions, final List<List<DisjunctiveClause>> generalisedDisjunctions ) { @SuppressWarnings("unchecked") final List<List<DisjunctiveClause>>[] lists = new List[]{ungeneralisedDisjunctions, generalisedDisjunctions}; for (int i = 0; i < lists.length; ++i) { final List<List<DisjunctiveClause>> list_i = lists[i]; for (int j = 0; j < list_i.size(); ++j) { final List<DisjunctiveClause> list_j = list_i.get(j); for (int k = 0; k < list_j.size(); /**/) { final DisjunctiveClause other = list_j.get(k); if (other.generalises(clause)) { if (clause.generalises(other)) { // Generalise both ways around, so we're equal! if (clause.numAssumedTrue() > other.numAssumedTrue()) { // "steal" the num assumed true, such that we can keep clause clause.setNumAssumedTrue(other.numAssumedTrue()); } // Remove other, and continue loop without incrementing k list_j.remove(k); continue; } else { // Found a generaliser //System.out.println(other + " generalises " + clause); return true; } } // Need to increment index ++k; } } } return false; } /** * Picks a covering proposition from the given disjunction * * @param disjunction * @param pickedPropsList * @param pickedPropsBitset * @param firstTiebreakerList * @param firstTiebreakerIndex * @param secondTiebreakerLists * @param secondTiebreakerIndex * @param thirdTiebreakerLists * @param thirdTiebreakerIndex * @param fourthTiebreakerLists * @param fourthTiebreakerIndex * @param proveIfTrue * @param disproveIfTrue * @param proveIfFalse * @param disproveIfFalse */ private void pickCoveringPropositions ( final DisjunctiveClause disjunction, final TIntArrayList pickedPropsList, final BitSet pickedPropsBitset, final List<DisjunctiveClause> firstTiebreakerList, final int firstTiebreakerIndex, final List<List<DisjunctiveClause>> secondTiebreakerLists, final int secondTiebreakerIndex, final List<List<DisjunctiveClause>> thirdTiebreakerLists, final int thirdTiebreakerIndex, final List<List<DisjunctiveClause>> fourthTiebreakerLists, final int fourthTiebreakerIndex, final BitSet[] proveIfTrue, final BitSet[] disproveIfTrue, final BitSet[] proveIfFalse, final BitSet[] disproveIfFalse ) { final BitSet candidateProps = (BitSet) disjunction.usedPropositions().clone(); if (candidateProps.intersects(pickedPropsBitset)) return; // Already covered TIntArrayList maxIndices = maxScorePropIndices( candidateProps, disjunction, firstTiebreakerList, firstTiebreakerIndex, pickedPropsBitset, proveIfTrue, disproveIfTrue, proveIfFalse, disproveIfFalse); if (maxIndices.size() == 1) { // No more tie-breakers, pick the max pickProp(maxIndices.getQuick(0), pickedPropsList, pickedPropsBitset); return; } // Need to continue to second tie-breaker // But first, eliminate non-max candidates candidateProps.clear(); for (int i = 0; i < maxIndices.size(); ++i) { candidateProps.set(maxIndices.getQuick(i)); } // Same story as before, but with next list of clauses for tie-breaking for (int i = secondTiebreakerIndex; i < secondTiebreakerLists.size(); ++i) { maxIndices = maxScorePropIndices( candidateProps, null, secondTiebreakerLists.get(i), 0, pickedPropsBitset, proveIfTrue, disproveIfTrue, proveIfFalse, disproveIfFalse); if (maxIndices.size() == 1) { // No more tie-breakers, pick the max pickProp(maxIndices.getQuick(0), pickedPropsList, pickedPropsBitset); return; } // Eliminate non-max candidates and move on to next tie-breaker candidateProps.clear(); for (int j = 0; j < maxIndices.size(); ++j) { candidateProps.set(maxIndices.getQuick(j)); } } // Same story as before, but with next list of clauses for tie-breaking for (int i = thirdTiebreakerIndex; i < thirdTiebreakerLists.size(); ++i) { maxIndices = maxScorePropIndices( candidateProps, null, thirdTiebreakerLists.get(i), 0, pickedPropsBitset, proveIfTrue, disproveIfTrue, proveIfFalse, disproveIfFalse); if (maxIndices.size() == 1) { // No more tie-breakers, pick the max pickProp(maxIndices.getQuick(0), pickedPropsList, pickedPropsBitset); return; } // Eliminate non-max candidates and move on to next tie-breaker candidateProps.clear(); for (int j = 0; j < maxIndices.size(); ++j) { candidateProps.set(maxIndices.getQuick(j)); } } // Same story as before, but with next list of clauses for tie-breaking for (int i = fourthTiebreakerIndex; i < fourthTiebreakerLists.size(); ++i) { maxIndices = maxScorePropIndices( candidateProps, null, fourthTiebreakerLists.get(i), 0, pickedPropsBitset, proveIfTrue, disproveIfTrue, proveIfFalse, disproveIfFalse); if (maxIndices.size() == 1) { // No more tie-breakers, pick the max pickProp(maxIndices.getQuick(0), pickedPropsList, pickedPropsBitset); return; } // Eliminate non-max candidates and move on to next tie-breaker candidateProps.clear(); for (int j = 0; j < maxIndices.size(); ++j) { candidateProps.set(maxIndices.getQuick(j)); } } // No more tie-breakers, so let's just randomly pick one max index pickProp(maxIndices.getQuick(ThreadLocalRandom.current().nextInt(maxIndices.size())), pickedPropsList, pickedPropsBitset); } /** * Helper method to pick a proposition of a given ID: may additionally first * pick proposition with empty tests to prioritise them before other types of tests. * * @param propID * @param pickedPropsList * @param pickedPropsBitset */ private void pickProp(final int propID, final TIntArrayList pickedPropsList, final BitSet pickedPropsBitset) { pickedPropsBitset.set(propID); final AtomicProposition pickedProp = propositionNodesList.get(propID).proposition; if (pickedProp.stateVectorType() != StateVectorTypes.Empty) { // See if we have any empty tests for the same site that are not yet picked; if so, prioritise them final int site = pickedProp.testedSite(); for (int i = pickedPropsBitset.nextClearBit(0); i < propositionNodesList.size(); i = pickedPropsBitset.nextClearBit(i + 1)) { final AtomicProposition unpickedProp = propositionNodesList.get(i).proposition; if (unpickedProp.testedSite() == site && unpickedProp.stateVectorType() == StateVectorTypes.Empty) { // We want to pick this prop first pickedPropsBitset.set(i); pickedPropsList.add(i); } } } pickedPropsList.add(propID); } /** * @param candidateProps Candidate props * @param disjunction The disjunction from which we obtained candidate props (or null for tie-breaking) * @param clauses List of clauses from which to compute scores * @param startIdx Index in list to start at * @param coveredProps Propositions that are already covered * @param proveIfTrue * @param disproveIfTrue * @param proveIfFalse * @param disproveIfFalse * @return List of indices of all candidate props that obtain the max score */ private TIntArrayList maxScorePropIndices ( final BitSet candidateProps, final DisjunctiveClause disjunction, final List<DisjunctiveClause> clauses, final int startIdx, final BitSet coveredProps, final BitSet[] proveIfTrue, final BitSet[] disproveIfTrue, final BitSet[] proveIfFalse, final BitSet[] disproveIfFalse ) { final double[] propScores = new double[propositionNodesList.size()]; if (disjunction != null) { for (int candidateProp = candidateProps.nextSetBit(0); candidateProp >= 0; candidateProp = candidateProps.nextSetBit(candidateProp + 1)) { propScores[candidateProp] += propScoreForDisjunction(disjunction, candidateProp, proveIfTrue, disproveIfTrue, proveIfFalse, disproveIfFalse); } } for (int i = startIdx; i < clauses.size(); ++i) { final DisjunctiveClause dis = clauses.get(i); final BitSet disProps = dis.usedPropositions(); if (disProps.intersects(coveredProps)) continue; // Already covered, so skip it for (int candidateProp = candidateProps.nextSetBit(0); candidateProp >= 0; candidateProp = candidateProps.nextSetBit(candidateProp + 1)) { if (disProps.get(candidateProp)) { // This candidate proposition shows up in this disjunction, so add its score propScores[candidateProp] += propScoreForDisjunction(dis, candidateProp, proveIfTrue, disproveIfTrue, proveIfFalse, disproveIfFalse); } } } final TIntArrayList maxIndices = new TIntArrayList(); double maxScore = -1.0; for (int candidateProp = candidateProps.nextSetBit(0); candidateProp >= 0; candidateProp = candidateProps.nextSetBit(candidateProp + 1)) { //System.out.println("Prop = " + this.propositionNodesList.get(candidateProp).proposition); //System.out.println("Score = " + propScores[candidateProp]); if (propScores[candidateProp] > maxScore) { maxIndices.clear(); maxIndices.add(candidateProp); maxScore = propScores[candidateProp]; } else if (propScores[candidateProp] == maxScore) { maxIndices.add(candidateProp); } } //System.out.println(); return maxIndices; } /** * Implements the Jeroslow-Wang method for SAT (+ extra terms based on inferences between props) * * @param disjunction * @param prop * @param proveIfTrue * @param disproveIfTrue * @param proveIfFalse * @param disproveIfFalse * @return Heuristic score for proposition in given disjunction */ private static double propScoreForDisjunction ( final DisjunctiveClause disjunction, final int prop, final BitSet[] proveIfTrue, final BitSet[] disproveIfTrue, final BitSet[] proveIfFalse, final BitSet[] disproveIfFalse ) { double score = 0.0; for (final Conjunction conj : disjunction.conjunctions()) { final BitSet conjProps = conj.toProve(); if (conjProps.get(prop)) { score += Math.pow(2.0, -conj.length()); } else { final BitSet ifTrueOverlap = (BitSet) proveIfTrue[prop].clone(); ifTrueOverlap.or(disproveIfTrue[prop]); ifTrueOverlap.and(conjProps); final BitSet ifFalseOverlap = (BitSet) proveIfFalse[prop].clone(); ifFalseOverlap.or(disproveIfFalse[prop]); ifFalseOverlap.and(conjProps); score += (0.5 * ifTrueOverlap.cardinality() + 0.5 * ifFalseOverlap.cardinality()) * Math.pow(2.0, -conj.length()); } } return score; } //------------------------------------------------------------------------- /** * @return Computes array of conjunctive clauses, each represented as a bitset * with bits on for propositions included in clause; one clause per instance node. */ private BitSet[] computeConjunctiveClauses() { final BitSet[] conjunctiveClauses = new BitSet[instanceNodes.size()]; // For every feature instance, compute its conjunctive clause as a BitSet for (int i = 0; i < instanceNodes.size(); ++i) { final FeatureInstanceNode instanceNode = instanceNodes.get(i); final BitSet propIDs = new BitSet(this.propositionNodes.size()); for (final PropositionNode propNode : instanceNode.propositions) { propIDs.set(propNode.id); } conjunctiveClauses[i] = propIDs; } // Convert to array return conjunctiveClauses; } /** * @param lists * @return Index of first non-empty list in given list of lists, or -1 if all empty */ private static int firstNonEmptyListIndex(final List<List<DisjunctiveClause>> lists) { for (int i = 0; i < lists.size(); ++i) { if (!lists.get(i).isEmpty()) return i; } return -1; } //------------------------------------------------------------------------- /** * @param bitset * @return A nice string representation of the propositions described by given bitset. */ private String toPropsString(final BitSet bitset) { final StringBuilder sb = new StringBuilder(); sb.append("{"); for (int i = bitset.nextSetBit(0); i >= 0; i = bitset.nextSetBit(i + 1)) { if (sb.length() > 1) sb.append(", "); sb.append(this.propositionNodesList.get(i).proposition.toString()); } sb.append("}"); return sb.toString(); } /** * @param bitset * @return A nice string representation of the propositions used by a disjunction. */ @SuppressWarnings("unused") // Do NOT remove SuppressWarning: sometimes use this for debugging! private String toPropsString(final DisjunctiveClause disjunction) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < disjunction.conjunctions().size(); ++i) { sb.append("("); sb.append(toPropsString(disjunction.conjunctions().get(i).toProve())); sb.append(")"); if (i < disjunction.conjunctions().size() - 1) sb.append(" OR "); } return sb.toString(); } //------------------------------------------------------------------------- /** * Node for an atomic proposition * * @author Dennis Soemers */ public static class PropositionNode { /** Unique ID for this node */ protected final int id; /** The atomic proposition */ protected final AtomicProposition proposition; /** Nodes for feature instances that use this proposition */ protected final List<FeatureInstanceNode> instances = new ArrayList<FeatureInstanceNode>(); /** * Constructor * @param id * @param proposition */ public PropositionNode(final int id, final AtomicProposition proposition) { this.id = id; this.proposition = proposition; } @Override public String toString() { return "[PropNode " + id + ": " + proposition + "]"; } } /** * Node for a feature instance * * @author Dennis Soemers */ protected static class FeatureInstanceNode { /** Unique ID for this node */ protected final int id; /** The feature instance */ protected final FeatureInstance instance; /** Nodes for propositions used by this feature */ protected final List<PropositionNode> propositions = new ArrayList<PropositionNode>(); /** * Constructor * @param id * @param instance */ public FeatureInstanceNode(final int id, final FeatureInstance instance) { this.id = id; this.instance = instance; } } //------------------------------------------------------------------------- /** * Small wrapper around a split of disjunctive clauses into ungeneralised * and generalised (such that we can return them together from a single method) * * @author Dennis Soemers */ private static class UngeneralisedGeneralisedWrapper { public final List<List<DisjunctiveClause>> ungeneralisedDisjunctions; public final List<List<DisjunctiveClause>> generalisedDisjunctions; /** * Constructor * @param ungeneralisedDisjunctions * @param generalisedDisjunctions */ public UngeneralisedGeneralisedWrapper ( final List<List<DisjunctiveClause>> ungeneralisedDisjunctions, final List<List<DisjunctiveClause>> generalisedDisjunctions ) { this.ungeneralisedDisjunctions = ungeneralisedDisjunctions; this.generalisedDisjunctions = generalisedDisjunctions; } } //------------------------------------------------------------------------- /** * A wrapper around a feature instance with some data about propositions * that it requires, and the ability to sort a list of wrappers based * on that data. * * @author Dennis Soemers */ private static class SortableFeatureInstance implements Comparable<SortableFeatureInstance> { /** The feature instance */ public final FeatureInstance featureInstance; /** IDs of propositions (after sorting) that are required by this instance */ public final BitSet propIDs = new BitSet(); /** * Constructor * @param featureInstance */ public SortableFeatureInstance(final FeatureInstance featureInstance) { this.featureInstance = featureInstance; } @Override public int compareTo(final SortableFeatureInstance o) { int myRightmost = propIDs.length() - 1; int otherRightmost = o.propIDs.length() - 1; while (myRightmost == otherRightmost && myRightmost >= 0) { myRightmost = propIDs.previousSetBit(myRightmost - 1); otherRightmost = o.propIDs.previousSetBit(otherRightmost - 1); } if (myRightmost > otherRightmost) { // We should go after other return 1; } else if (myRightmost < otherRightmost) { // We should go before other return -1; } return 0; } } //------------------------------------------------------------------------- }
49,733
32.558704
145
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/Conjunction.java
package features.feature_sets.network; import java.util.BitSet; /** * Represents a conjunction of atomic propositions. Is mutable: we can modify * it by giving it propositions that we "assume to have been proven", which will * then be removed from the requirements * * @author Dennis Soemers */ public class Conjunction { //------------------------------------------------------------------------- /** IDs of atomic propositions that must be true */ private final BitSet mustTrue; /** Number of propositions that are to be proven */ private int length; //------------------------------------------------------------------------- /** * Constructor * @param mustTrue */ public Conjunction(final BitSet mustTrue) { this.mustTrue = mustTrue; length = mustTrue.cardinality(); } //------------------------------------------------------------------------- /** * Tells this conjunction to assume that proposition of given ID is true * (safe to also call on conjunctions that do not require this proposition at all) * @param id * @return True if and only if the given proposition was a requirement of this conjunction */ public boolean assumeTrue(final int id) { if (mustTrue.get(id)) { mustTrue.clear(id); --length; return true; } return false; } /** * @param other * @return True if, ignoring propositions that are already assumed to have been proven, * this conjunction generalises the given other conjunction. */ public boolean generalises(final Conjunction other) { if (length > other.length) return false; final BitSet otherToProve = other.toProve(); final BitSet toProve = (BitSet) mustTrue.clone(); toProve.andNot(otherToProve); return toProve.isEmpty(); } /** * @return Length of this conjunction: number of propositions remaining to be proven */ public int length() { return length; } /** * @return BitSet of IDs that must still be proven */ public BitSet toProve() { return mustTrue; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((mustTrue == null) ? 0 : mustTrue.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof Conjunction)) return false; final Conjunction other = (Conjunction) obj; return mustTrue.equals(other.mustTrue); } //------------------------------------------------------------------------- @Override public String toString() { return "[Conjunction: " + mustTrue + "]"; } //------------------------------------------------------------------------- }
2,765
21.672131
91
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/DisjunctiveClause.java
package features.feature_sets.network; import java.util.ArrayList; import java.util.BitSet; import java.util.List; /** * A disjunctive clause: a disjunction of one or more conjunctions. Is mutable: * we can modify it by giving it propositions that are assumed to have already * been proven, which will then be removed from conjunctions they appear in, * and fully-proven conjunctions will also be removed entirely from the * disjunctive clause! * * @author Dennis Soemers */ public class DisjunctiveClause { //------------------------------------------------------------------------- /** List of conjunctions, one of which must be true for this disjunction to be true */ private final List<Conjunction> conjunctions; /** Number of conjunctions that we assume to have already been proven */ private int numAssumedTrue = 0; // NOTE: field ignored in hashCode() and equals() /** BitSet of all propositions that show up anywhere in any of the conjunctions of this disjunction */ private final BitSet usedPropositions = new BitSet(); //------------------------------------------------------------------------- /** * Constructor */ public DisjunctiveClause() { this.conjunctions = new ArrayList<Conjunction>(); } //------------------------------------------------------------------------- /** * Adds the given conjunction to list of conjunctions that can prove this disjunction * @param conjunction */ public void addConjunction(final Conjunction conjunction) { conjunctions.add(conjunction); usedPropositions.or(conjunction.toProve()); } /** * Tells this disjunction to assume that proposition of given ID is true. Will propagate * to all conjunctions, and remove fully-proven conjunctions. * * @param id */ public void assumeTrue(final int id) { if (usedPropositions.get(id)) { for (final Conjunction conjunction : conjunctions) { if (conjunction.assumeTrue(id)) { if (conjunction.length() == 0) { conjunctions.remove(conjunction); ++numAssumedTrue; } } } usedPropositions.clear(id); } } /** * Tells this disjunction to assume that all propositions in given * BitSet are true. Will propagate to all conjunctions, and remove * fully-proven conjunctions. * * @param propositions */ public void assumeTrue(final BitSet propositions) { final BitSet intersection = (BitSet) propositions.clone(); intersection.and(usedPropositions); for (int id = intersection.nextSetBit(0); id >= 0; id = intersection.nextSetBit(id + 1)) { for (int i = conjunctions.size() - 1; i >= 0; --i) { final Conjunction conjunction = conjunctions.get(i); if (conjunction.assumeTrue(id)) { if (conjunction.length() == 0) { conjunctions.remove(i); ++numAssumedTrue; } } } } usedPropositions.andNot(intersection); } /** * @return Our list of conjunctions */ public List<Conjunction> conjunctions() { return conjunctions; } /** * Removes any conjunctions that are generalised by any other conjunctions * that are also in this disjunction. */ public void eliminateGeneralisedConjunctions() { final int oldSize = conjunctions.size(); for (int i = 0; i < conjunctions.size(); ++i) { final Conjunction iConj = conjunctions.get(i); for (int j = conjunctions.size() - 1; j > i; --j) { final Conjunction jConj = conjunctions.get(j); if (iConj.generalises(jConj)) conjunctions.remove(j); } } if (conjunctions.size() != oldSize) { // We've removed some conjunctions, should recompute usedPropositions to be safe usedPropositions.clear(); for (final Conjunction conj : conjunctions) { usedPropositions.or(conj.toProve()); } } } /** * @param other * @return True if and only if this disjunctive clause generalises the given * other disjunctive clause. */ public boolean generalises(final DisjunctiveClause other) { outer: for (final Conjunction otherConj : other.conjunctions) { for (final Conjunction myConj : conjunctions) { if (myConj.generalises(otherConj)) continue outer; } return false; } return !other.conjunctions.isEmpty(); } /** * @return Number of conjunctions (excluding ones already assumed to be true) */ public int length() { return conjunctions.size(); } /** * @return Number of conjunctions that we assume to have been fully proven */ public int numAssumedTrue() { return numAssumedTrue; } /** * Sets the number of conjunctions that are assumed to have already been fully proven. * Can be used when "merging" disjunctions that have become "equal" after making some * assumptions of proven conjunctions. * @param num */ public void setNumAssumedTrue(final int num) { this.numAssumedTrue = num; } /** * @return Bitset of all propositions that show up in any conjunctions in this disjunction */ public BitSet usedPropositions() { return usedPropositions; } //------------------------------------------------------------------------- @Override public String toString() { return "[Disjunction: " + conjunctions + "]"; } //------------------------------------------------------------------------- }
5,303
23.555556
103
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/FeaturePropNode.java
package features.feature_sets.network; import java.util.BitSet; import features.spatial.instances.AtomicProposition; import other.state.State; /** * A feature prop node in the FeaturePropSet representation * * @author Dennis Soemers */ public class FeaturePropNode { //------------------------------------------------------------------------- /** Unique index of this node in array */ protected final int index; /** Atomic proposition which must be true for this node to be true */ protected final AtomicProposition proposition; /** Bitset of feature indices to deactivate if this node is false */ protected final BitSet dependentFeatures = new BitSet(); //------------------------------------------------------------------------- /** * Constructor * @param index * @param proposition */ public FeaturePropNode(final int index, final AtomicProposition proposition) { this.index = index; this.proposition = proposition; } //------------------------------------------------------------------------- /** * Evaluate the given state. * @param state * @param activeNodes Bitset of nodes that are still active. * @param activeFeatures Bitset of feature indices that are active. */ public void eval(final State state, final BitSet activeNodes, final BitSet activeFeatures) { if (activeFeatures.intersects(dependentFeatures)) // if false, might as well not check anything { if (!proposition.matches(state)) // Requirement not satisfied activeFeatures.andNot(dependentFeatures); } } //------------------------------------------------------------------------- /** * Mark a feature ID that we should set to false if our proposition is false * @param featureID */ public void setDependentFeature(final int featureID) { dependentFeatures.set(featureID); } /** * @return Our proposition */ public AtomicProposition proposition() { return proposition; } //------------------------------------------------------------------------- }
2,026
24.658228
98
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/JITSPatterNetFeatureSet.java
package features.feature_sets.network; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; import features.Feature; import features.aspatial.AspatialFeature; import features.feature_sets.BaseFeatureSet; import features.spatial.RelativeFeature; import features.spatial.SpatialFeature; import features.spatial.Walk; import features.spatial.cache.ActiveFeaturesCache; import features.spatial.cache.footprints.BaseFootprint; import features.spatial.instances.AtomicProposition; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import main.collections.ArrayUtils; import main.collections.FastTIntArrayList; import other.context.Context; import other.move.Move; import other.state.State; import other.state.container.ContainerState; import other.trial.Trial; /** * Implementation of Feature Set based on SPatterNets, with JIT (Just-In-Time) * construction of the SPatterNets * * NOTE: for better JIT behaviour, we assume that every feature has either * the to or the from position as anchor * * @author Dennis Soemers */ public class JITSPatterNetFeatureSet extends BaseFeatureSet { //------------------------------------------------------------------------- /** * If this is set to true, we allow for the use of a Feature Set cache that * recognises when we try to load exactly the same feature set and returns * the same object instead of constructing a new one. * * Note that it is not necessarily always safe to do this, for instance because * we call instantiateFeatures() on a feature set whenever an AI that uses it * gets initialised, and we do not want this to happen while (e.g., in a different * thread) the feature set is being actively used by a different AI. * * In cases where we can be sure that it is safe (like some highly controlled * experiments / training runs), this can save us a lot of memory (and maybe * even slightly improve performance due to more re-usable JIT behaviour). */ public static boolean ALLOW_FEATURE_SET_CACHE = false; /** Cache of feature set objects */ protected static final Map<FeatureLists, JITSPatterNetFeatureSet> featureSetsCache = new ConcurrentHashMap<FeatureLists, JITSPatterNetFeatureSet>(); //------------------------------------------------------------------------- /** JIT map (mix of proactive and reactive keys) */ protected JITMap jitMap; /** Cache with indices of active proactive features previously computed */ protected ActiveFeaturesCache activeProactiveFeaturesCache; /** Bitset of features that should be thresholded based on their absolute weights */ protected BitSet thresholdedFeatures = null; //------------------------------------------------------------------------- /** * Clear the entire cache of feature set objects. */ public static void clearFeatureSetCache() { featureSetsCache.clear(); } /** * Construct feature set from list of features * @param features */ public static JITSPatterNetFeatureSet construct(final List<Feature> features) { final List<AspatialFeature> aspatials = new ArrayList<AspatialFeature>(); final List<SpatialFeature> spatials = new ArrayList<SpatialFeature>(); for (final Feature f : features) { if (f instanceof AspatialFeature) aspatials.add((AspatialFeature) f); else spatials.add((SpatialFeature) f); } return construct(aspatials, spatials); } /** * Construct feature set from lists of features * @param aspatialFeatures * @param spatialFeatures */ public static JITSPatterNetFeatureSet construct(final List<AspatialFeature> aspatialFeatures, final List<SpatialFeature> spatialFeatures) { if (ALLOW_FEATURE_SET_CACHE) { final FeatureLists key = new FeatureLists(aspatialFeatures, spatialFeatures); final JITSPatterNetFeatureSet cached = featureSetsCache.get(key); if (cached != null) return cached; final JITSPatterNetFeatureSet newSet = new JITSPatterNetFeatureSet(aspatialFeatures, spatialFeatures); featureSetsCache.put(key, newSet); return newSet; } return new JITSPatterNetFeatureSet(aspatialFeatures, spatialFeatures); } /** * Loads a feature set from a given filename * @param filename */ public static JITSPatterNetFeatureSet construct(final String filename) { Feature[] tempFeatures; //System.out.println("loading feature set from " + filename); try (Stream<String> stream = Files.lines(Paths.get(filename))) { tempFeatures = stream.map(s -> Feature.fromString(s)).toArray(Feature[]::new); } catch (final IOException exception) { tempFeatures = null; exception.printStackTrace(); } final List<AspatialFeature> aspatialFeaturesList = new ArrayList<AspatialFeature>(); final List<SpatialFeature> spatialFeaturesList = new ArrayList<SpatialFeature>(); for (final Feature feature : tempFeatures) { if (feature instanceof AspatialFeature) { aspatialFeaturesList.add((AspatialFeature)feature); } else { ((SpatialFeature)feature).setSpatialFeatureSetIndex(spatialFeaturesList.size()); spatialFeaturesList.add((SpatialFeature)feature); } } return construct(aspatialFeaturesList, spatialFeaturesList); } /** * Construct feature set from lists of features * @param aspatialFeatures * @param spatialFeatures */ private JITSPatterNetFeatureSet(final List<AspatialFeature> aspatialFeatures, final List<SpatialFeature> spatialFeatures) { this.spatialFeatures = new SpatialFeature[spatialFeatures.size()]; for (int i = 0; i < this.spatialFeatures.length; ++i) { this.spatialFeatures[i] = spatialFeatures.get(i); this.spatialFeatures[i].setSpatialFeatureSetIndex(i); } this.aspatialFeatures = aspatialFeatures.toArray(new AspatialFeature[aspatialFeatures.size()]); jitMap = null; } //------------------------------------------------------------------------- @Override protected void instantiateFeatures(final int[] supportedPlayers) { activeProactiveFeaturesCache = new ActiveFeaturesCache(); // Collect features that should be ignored when running in thresholded mode thresholdedFeatures = new BitSet(); if (spatialFeatureInitWeights != null) { // Doing following loop in reverse order ensures that thresholdedFeatures bitset size // does not grow larger than necessary for (int i = spatialFeatures.length - 1; i >= 0; --i) { if (Math.abs(spatialFeatureInitWeights.get(i)) < SPATIAL_FEATURE_WEIGHT_THRESHOLD) thresholdedFeatures.set(i); } } jitMap = new JITMap(); // We'll use a dummy context to kickstart our JIT compilation on some real moves final Context jitContext = new Context(game.get(), new Trial(game.get())); // We'll do 3 random (partial, very short) trials for (int i = 0; i < 3; ++i) { game.get().start(jitContext); // We'll do 5 moves max per trial for (int j = 0; j < 10; ++j) { if (jitContext.trial().over()) break; for (final Move move : game.get().moves(jitContext).moves()) { final int mover = move.mover(); if (ArrayUtils.contains(supportedPlayers, mover)) { final boolean thresholding = (spatialFeatureInitWeights != null); this.computeFeatureVector(jitContext, move, thresholding); // This lets us do JIT instantiation } } jitContext.model().startNewStep(jitContext, null, 0.1); } } } @Override public void closeCache() { activeProactiveFeaturesCache.close(); } //------------------------------------------------------------------------- @Override public TIntArrayList getActiveSpatialFeatureIndices ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player, final boolean thresholded ) { final FastTIntArrayList featureIndices = new FastTIntArrayList(this.getNumSpatialFeatures()); // System.out.println("lastFrom = " + lastFrom); // System.out.println("lastTo = " + lastTo); // System.out.println("from = " + from); // System.out.println("to = " + to); // System.out.println("player = " + player); // final List<FeatureInstance> instances = getActiveFeatureInstances(state, lastFrom, lastTo, from, to, player); // for (final FeatureInstance instance : instances) // { // if (!featureIndices.contains(instance.feature().featureSetIndex())) // featureIndices.add(instance.feature().featureSetIndex()); // } final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; final int[] lastFroms = lastFrom >= 0 ? new int[]{-1, lastFrom} : new int[]{-1}; final int[] lastTos = lastTo >= 0 ? new int[]{-1, lastTo} : new int[]{-1}; final int[] cachedActiveFeatureIndices; if (thresholded) cachedActiveFeatureIndices = activeProactiveFeaturesCache.getCachedActiveFeatures(this, state, from, to, player); else cachedActiveFeatureIndices = null; if (cachedActiveFeatureIndices != null) { // Successfully retrieved from cache featureIndices.add(cachedActiveFeatureIndices); //System.out.println("cache hit!"); } else { final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Proactive instances key.resetData(player, fromPos, toPos); final SPatterNet set = thresholded ? jitMap.spatterNetThresholded(key, state) : jitMap.spatterNet(key, state); if (set != null) featureIndices.addAll(set.getActiveFeatures(state)); } } } if (thresholded && !featureIndices.isEmpty()) activeProactiveFeaturesCache.cache(state, from, to, featureIndices.toArray(), player); } final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); for (int i = 0; i < lastFroms.length; ++i) { final int lastFromPos = lastFroms[i]; for (int j = 0; j < lastTos.length; ++j) { final int lastToPos = lastTos[j]; if (lastToPos >= 0 || lastFromPos >= 0) { for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Reactive instances reactiveKey.resetData(player, lastFromPos, lastToPos, fromPos, toPos); final SPatterNet set = jitMap.spatterNet(reactiveKey, state); if (set != null) featureIndices.addAll(set.getActiveFeatures(state)); } } } } } } return featureIndices; } @Override public List<FeatureInstance> getActiveSpatialFeatureInstances ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player ) { final List<FeatureInstance> instances = new ArrayList<FeatureInstance>(); final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; final int[] lastFroms = lastFrom >= 0 ? new int[]{-1, lastFrom} : new int[]{-1}; final int[] lastTos = lastTo >= 0 ? new int[]{-1, lastTo} : new int[]{-1}; final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Proactive instances key.resetData(player, fromPos, toPos); final PropFeatureInstanceSet set = jitMap.propFeatureInstanceSet(key, state); if (set != null) instances.addAll(set.getActiveInstances(state)); } } } final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); for (int i = 0; i < lastFroms.length; ++i) { final int lastFromPos = lastFroms[i]; for (int j = 0; j < lastTos.length; ++j) { final int lastToPos = lastTos[j]; if (lastToPos >= 0 || lastFromPos >= 0) { for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Reactive instances reactiveKey.resetData(player, lastFromPos, lastToPos, fromPos, toPos); final PropFeatureInstanceSet set = jitMap.propFeatureInstanceSet(reactiveKey, state); if (set != null) instances.addAll(set.getActiveInstances(state)); } } } } } } return instances; } //------------------------------------------------------------------------- @Override public BaseFootprint generateFootprint ( final State state, final int from, final int to, final int player ) { final ContainerState container = state.containerStates()[0]; // NOTE: only using caching with thresholding final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); key.resetData(player, from, to); SPatterNet set = jitMap.spatterNetThresholded(key, state); if (set == null) { set = new SPatterNet ( new int[0], new AtomicProposition[0], new BitSet[0], new BitSet[0], new BitSet[0], new int[0], new BitSet(), new BitSet[0], new BitSet[0], new BitSet[0], new BitSet[0] ); } final BaseFootprint footprint = set.generateFootprint(container); if (from >= 0) { // Also add footprints for from alone, and for to alone key.resetData(player, from, -1); set = jitMap.spatterNetThresholded(key, state); if (set != null) footprint.union(set.generateFootprint(container)); key.resetData(player, -1, to); set = jitMap.spatterNetThresholded(key, state); if (set != null) footprint.union(set.generateFootprint(container)); } return footprint; } //------------------------------------------------------------------------- @Override public JITSPatterNetFeatureSet createExpandedFeatureSet ( final Game targetGame, final SpatialFeature newFeature ) { boolean featureAlreadyExists = false; for (final SpatialFeature oldFeature : spatialFeatures) { if (newFeature.equals(oldFeature)) { featureAlreadyExists = true; break; } // also try all legal rotations of the generated feature, see // if any of those turn out to be equal to an old feature TFloatArrayList allowedRotations = newFeature.pattern().allowedRotations(); if (allowedRotations == null) { allowedRotations = new TFloatArrayList(Walk.allGameRotations(targetGame)); } for (int i = 0; i < allowedRotations.size(); ++i) { final SpatialFeature rotatedCopy = newFeature.rotatedCopy(allowedRotations.getQuick(i)); if (rotatedCopy.equals(oldFeature)) { // TODO only break if for every possible anchor this works? featureAlreadyExists = true; break; } } } if (!featureAlreadyExists) { // create new feature set with this feature, and return it final List<SpatialFeature> newFeatureList = new ArrayList<SpatialFeature>(spatialFeatures.length + 1); // all old features... for (final SpatialFeature feature : spatialFeatures) { newFeatureList.add(feature); } // and our new feature newFeatureList.add(newFeature); return new JITSPatterNetFeatureSet(Arrays.asList(aspatialFeatures), newFeatureList); } return null; } //------------------------------------------------------------------------- /** * Wrapper around a collection of maps from keys (reactive or proactive) to SPatterNets * or PropFeatureInstanceSets. * * @author Dennis Soemers */ private class JITMap { /** Map to prop-feature-instance-set representation */ private final Map<MoveFeaturesKey, PropFeatureInstanceSet> propInstanceSetMap; /** Map to SPatterNet representation (without thresholding) */ private final Map<MoveFeaturesKey, SPatterNet> spatterNetMap; /** Map to SPatterNet representation (thresholded) */ private final Map<MoveFeaturesKey, SPatterNet> spatterNetMapThresholded; /** * Constructor */ public JITMap() { this.propInstanceSetMap = new ConcurrentHashMap<MoveFeaturesKey, PropFeatureInstanceSet>(); this.spatterNetMap = new ConcurrentHashMap<MoveFeaturesKey, SPatterNet>(); this.spatterNetMapThresholded = new ConcurrentHashMap<MoveFeaturesKey, SPatterNet>(); } /** * @param key * @param state * @return PropFeatureInstanceSet for given key */ public PropFeatureInstanceSet propFeatureInstanceSet(final MoveFeaturesKey key, final State state) { PropFeatureInstanceSet set = propInstanceSetMap.get(key); final boolean isKeyReactive = (key.lastFrom() >= 0 || key.lastTo() >= 0); if (set == null && !isKeyReactive) // NOTE: we assume that proactive features are always computed before reactive ones { // JIT: instantiate net for this key final BipartiteGraphFeatureInstanceSet proactiveBipartiteGraph = new BipartiteGraphFeatureInstanceSet(); final Map<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> reactiveGraphs = new HashMap<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet>(); for (final SpatialFeature feature : JITSPatterNetFeatureSet.this.spatialFeatures()) { final RelativeFeature relFeature = (RelativeFeature)feature; final List<FeatureInstance> newInstances = new ArrayList<FeatureInstance>(); if ( key.from() >= 0 && relFeature.fromPosition() != null && ((key.to() >= 0) == (relFeature.toPosition() != null)) ) { // Try instantiating with from as anchor newInstances.addAll ( feature.instantiateFeature ( JITSPatterNetFeatureSet.this.gameRef().get(), state.containerStates()[0], state.mover(), key.from(), key.from(), key.to(), -1, -1 ) ); } if ( key.to() >= 0 && relFeature.toPosition() != null && ((key.from() >= 0) == (relFeature.fromPosition() != null)) ) { // Try instantiating with to as anchor newInstances.addAll ( feature.instantiateFeature ( JITSPatterNetFeatureSet.this.gameRef().get(), state.containerStates()[0], state.mover(), key.to(), key.from(), key.to(), -1, -1 ) ); } if (feature.isReactive()) { // Can have different instances for different reactive keys final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); for (final FeatureInstance instance : newInstances) { reactiveKey.resetData(key.playerIdx(), instance.lastFrom(), instance.lastTo(), key.from(), key.to()); BipartiteGraphFeatureInstanceSet bipartite = reactiveGraphs.get(reactiveKey); if (bipartite == null) { bipartite = new BipartiteGraphFeatureInstanceSet(); reactiveGraphs.put(new ReactiveFeaturesKey(reactiveKey), bipartite); } bipartite.insertInstance(instance); } } else { // Just collect them all in the bipartite graph for proactive features for (final FeatureInstance instance : newInstances) { proactiveBipartiteGraph.insertInstance(instance); } } } for (final Entry<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> entry : reactiveGraphs.entrySet()) { propInstanceSetMap.put ( entry.getKey(), entry.getValue().toPropFeatureInstanceSet() ); } set = proactiveBipartiteGraph.toPropFeatureInstanceSet(); propInstanceSetMap.put(new ProactiveFeaturesKey((ProactiveFeaturesKey)key), set); } return set; } /** * @param key * @param state * @return SPatterNet for given key */ public SPatterNet spatterNet(final MoveFeaturesKey key, final State state) { SPatterNet net = spatterNetMap.get(key); final boolean isKeyReactive = (key.lastFrom() >= 0 || key.lastTo() >= 0); if (net == null && !isKeyReactive) // NOTE: we assume that proactive features are always computed before reactive ones { // JIT: instantiate net for this key final BipartiteGraphFeatureInstanceSet proactiveBipartiteGraph = new BipartiteGraphFeatureInstanceSet(); final Map<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> reactiveGraphs = new HashMap<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet>(); for (final SpatialFeature feature : JITSPatterNetFeatureSet.this.spatialFeatures()) { final RelativeFeature relFeature = (RelativeFeature)feature; final List<FeatureInstance> newInstances = new ArrayList<FeatureInstance>(); if ( key.from() >= 0 && relFeature.fromPosition() != null && ((key.to() >= 0) == (relFeature.toPosition() != null)) ) { // Try instantiating with from as anchor newInstances.addAll ( feature.instantiateFeature ( JITSPatterNetFeatureSet.this.gameRef().get(), state.containerStates()[0], state.mover(), key.from(), key.from(), key.to(), -1, -1 ) ); } if ( key.to() >= 0 && relFeature.toPosition() != null && ((key.from() >= 0) == (relFeature.fromPosition() != null)) ) { // Try instantiating with to as anchor newInstances.addAll ( feature.instantiateFeature ( JITSPatterNetFeatureSet.this.gameRef().get(), state.containerStates()[0], state.mover(), key.to(), key.from(), key.to(), -1, -1 ) ); } if (feature.isReactive()) { // Can have different instances for different reactive keys final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); for (final FeatureInstance instance : newInstances) { reactiveKey.resetData(key.playerIdx(), instance.lastFrom(), instance.lastTo(), key.from(), key.to()); BipartiteGraphFeatureInstanceSet bipartite = reactiveGraphs.get(reactiveKey); if (bipartite == null) { bipartite = new BipartiteGraphFeatureInstanceSet(); reactiveGraphs.put(new ReactiveFeaturesKey(reactiveKey), bipartite); } bipartite.insertInstance(instance); } } else { // Just collect them all in the bipartite graph for proactive features for (final FeatureInstance instance : newInstances) { proactiveBipartiteGraph.insertInstance(instance); } } } for (final Entry<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> entry : reactiveGraphs.entrySet()) { spatterNetMap.put ( entry.getKey(), entry.getValue().toSPatterNet(getNumSpatialFeatures(), new BitSet(), gameRef().get(), key.playerIdx()) ); } if (isKeyReactive) { net = spatterNetMap.get(key); } else { net = proactiveBipartiteGraph.toSPatterNet(getNumSpatialFeatures(), new BitSet(), gameRef().get(), key.playerIdx()); spatterNetMap.put(new ProactiveFeaturesKey((ProactiveFeaturesKey)key), net); } } return net; } /** * @param key * @param state * @return SPatterNet (with thresholding) for given key */ public SPatterNet spatterNetThresholded(final MoveFeaturesKey key, final State state) { SPatterNet net = spatterNetMapThresholded.get(key); final boolean isKeyReactive = (key.lastFrom() >= 0 || key.lastTo() >= 0); if (net == null && !isKeyReactive) // NOTE: we assume that proactive features are always computed before reactive ones { // JIT: instantiate net for this key final BipartiteGraphFeatureInstanceSet proactiveBipartiteGraph = new BipartiteGraphFeatureInstanceSet(); final Map<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> reactiveGraphs = new HashMap<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet>(); for (final SpatialFeature feature : JITSPatterNetFeatureSet.this.spatialFeatures()) { final RelativeFeature relFeature = (RelativeFeature)feature; final List<FeatureInstance> newInstances = new ArrayList<FeatureInstance>(); if ( key.from() >= 0 && relFeature.fromPosition() != null && ((key.to() >= 0) == (relFeature.toPosition() != null)) ) { // Try instantiating with from as anchor newInstances.addAll ( feature.instantiateFeature ( JITSPatterNetFeatureSet.this.gameRef().get(), state.containerStates()[0], state.mover(), key.from(), key.from(), key.to(), -1, -1 ) ); } if ( key.to() >= 0 && relFeature.toPosition() != null && ((key.from() >= 0) == (relFeature.fromPosition() != null)) ) { // Try instantiating with to as anchor newInstances.addAll ( feature.instantiateFeature ( JITSPatterNetFeatureSet.this.gameRef().get(), state.containerStates()[0], state.mover(), key.to(), key.from(), key.to(), -1, -1 ) ); } if (feature.isReactive()) { // Can have different instances for different reactive keys final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); for (final FeatureInstance instance : newInstances) { reactiveKey.resetData(key.playerIdx(), instance.lastFrom(), instance.lastTo(), key.from(), key.to()); BipartiteGraphFeatureInstanceSet bipartite = reactiveGraphs.get(reactiveKey); if (bipartite == null) { bipartite = new BipartiteGraphFeatureInstanceSet(); reactiveGraphs.put(new ReactiveFeaturesKey(reactiveKey), bipartite); } bipartite.insertInstance(instance); } } else { // Just collect them all in the bipartite graph for proactive features for (final FeatureInstance instance : newInstances) { proactiveBipartiteGraph.insertInstance(instance); } } } for (final Entry<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> entry : reactiveGraphs.entrySet()) { spatterNetMap.put ( entry.getKey(), entry.getValue().toSPatterNet(getNumSpatialFeatures(), new BitSet(), gameRef().get(), key.playerIdx()) ); } if (isKeyReactive) { net = spatterNetMapThresholded.get(key); } else { net = proactiveBipartiteGraph.toSPatterNet(getNumSpatialFeatures(), thresholdedFeatures, gameRef().get(), key.playerIdx()); spatterNetMapThresholded.put(new ProactiveFeaturesKey((ProactiveFeaturesKey)key), net); } } return net; } /** * @return Map of SPatterNets */ public Map<MoveFeaturesKey, SPatterNet> spatterNetMap() { return spatterNetMap; } /** * @return Map of SPatterNets (thresholded) */ public Map<MoveFeaturesKey, SPatterNet> spatterNetMapThresholded() { return spatterNetMapThresholded; } } //------------------------------------------------------------------------- /** * @return Map of SPatterNets for reactive as well as proactive features */ public Map<MoveFeaturesKey, SPatterNet> spatterNetMap() { return jitMap.spatterNetMap(); } /** * @return Map of SPatterNets for reactive as well as proactive features (thresholded) */ public Map<MoveFeaturesKey, SPatterNet> spatterNetMapThresholded() { return jitMap.spatterNetMapThresholded(); } //------------------------------------------------------------------------- /** * Wrapper around a list of aspatial features and a list of spatial features. * * @author Dennis Soemers */ private static class FeatureLists { /** List of aspatial features */ protected final List<AspatialFeature> aspatialFeatures; /** List of spatial features */ protected final List<SpatialFeature> spatialFeatures; /** * Constructor * @param aspatialFeatures * @param spatialFeatures */ public FeatureLists(final List<AspatialFeature> aspatialFeatures, final List<SpatialFeature> spatialFeatures) { this.aspatialFeatures = aspatialFeatures; this.spatialFeatures = spatialFeatures; } @Override public int hashCode() { return Objects.hash(aspatialFeatures, spatialFeatures); } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof FeatureLists)) return false; final FeatureLists other = (FeatureLists) obj; return Objects.equals(aspatialFeatures, other.aspatialFeatures) && Objects.equals(spatialFeatures, other.spatialFeatures); } } //------------------------------------------------------------------------- }
29,758
27.450287
138
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/PropFeatureInstanceSet.java
package features.feature_sets.network; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import features.spatial.instances.FeatureInstance; import other.state.State; /** * A set of propositions and feature instances. * * @author Dennis Soemers */ public class PropFeatureInstanceSet { //------------------------------------------------------------------------- /** Array of feature instances */ protected final FeatureInstance[] featureInstances; /** Array of PropNodes */ protected final PropNode[] propNodes; //------------------------------------------------------------------------- /** * Constructor * @param featureInstances * @param propNodes */ public PropFeatureInstanceSet(final FeatureInstance[] featureInstances, final PropNode[] propNodes) { this.featureInstances = featureInstances; this.propNodes = propNodes; } //------------------------------------------------------------------------- /** * @param state * @return List of active instances for given state */ public List<FeatureInstance> getActiveInstances(final State state) { final List<FeatureInstance> active = new ArrayList<FeatureInstance>(); final BitSet activeNodes = new BitSet(propNodes.length); activeNodes.set(0, propNodes.length); final BitSet activeInstances = new BitSet(featureInstances.length); activeInstances.set(0, featureInstances.length); for (int i = activeNodes.nextSetBit(0); i >= 0; i = activeNodes.nextSetBit(i + 1)) { propNodes[i].eval(state, activeNodes, activeInstances); } for (int i = activeInstances.nextSetBit(0); i >= 0; i = activeInstances.nextSetBit(i + 1)) { active.add(featureInstances[i]); } return active; } //------------------------------------------------------------------------- }
1,823
24.690141
100
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/PropNode.java
package features.feature_sets.network; import java.util.BitSet; import features.spatial.instances.AtomicProposition; import other.state.State; /** * A prop node in the PropFeatureInstanceSet representation. * * @author Dennis Soemers */ public class PropNode { //------------------------------------------------------------------------- /** Unique index of this node in array */ protected final int index; /** Atomic proposition which must be true for this node to be true */ protected final AtomicProposition proposition; /** Bitset of instances to deactivate if this node is false */ protected final BitSet dependentInstances = new BitSet(); //------------------------------------------------------------------------- /** * Constructor * @param index * @param proposition */ public PropNode(final int index, final AtomicProposition proposition) { this.index = index; this.proposition = proposition; } //------------------------------------------------------------------------- /** * Evaluate the given state. * @param state * @param activeNodes Bitset of nodes that are still active. * @param activeInstances Bitset of feature instances that are active. */ public void eval(final State state, final BitSet activeNodes, final BitSet activeInstances) { if (activeInstances.intersects(dependentInstances)) // if false, might as well not check anything { if (!proposition.matches(state)) // Requirement not satisfied activeInstances.andNot(dependentInstances); } } //------------------------------------------------------------------------- /** * Mark an instance ID that we should set to false if our proposition is false * @param instanceID */ public void setDependentInstance(final int instanceID) { dependentInstances.set(instanceID); } /** * @return Our proposition */ public AtomicProposition proposition() { return proposition; } //------------------------------------------------------------------------- }
2,024
24.632911
100
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/SPatterNet.java
package features.feature_sets.network; import java.util.Arrays; import java.util.BitSet; import features.spatial.cache.footprints.BaseFootprint; import features.spatial.cache.footprints.FullFootprint; import features.spatial.instances.AtomicProposition; import main.collections.ChunkSet; import main.collections.FastTIntArrayList; import other.state.State; import other.state.container.ContainerState; /** * A set of propositions which can (dis)prove feature instances, which * in turn can prove features, with propositions and instances implicitly * arranged in a network (but using flat arrays for improved cache locality) * * @author Dennis Soemers */ public class SPatterNet { //------------------------------------------------------------------------- /** Array of feature indices, appropriately sorted, such that we can index it by feature instance indices */ protected final int[] featureIndices; /** Array of propositions to test */ protected final AtomicProposition[] propositions; /** For every proposition, a bitset of feature instances that depend on that proposition */ protected final BitSet[] instancesPerProp; /** * For every feature, a bitset containing the instances for that feature. * NOTE: subtract featureOffset for correct indexing */ protected final BitSet[] instancesPerFeature; /** Minimum feature index for which we have more than 0 instances */ protected final int featureOffset; /** For every feature instance, an array of the propositions required for that feature instance */ protected final int[][] propsPerInstance; /** Array of feature indices that are always active */ protected final int[] autoActiveFeatures; /** For every proposition, if it's true, an array of other propositions that are then proven */ protected final int[][] provesPropsIfTruePerProp; /** For every proposition, if it's true, a bitset of instances that are then deactivated (either disproven, or features already proven) */ protected final BitSet[] deactivateInstancesIfTrue; /** For every proposition, if it's false, an array of other propositions that are then proven */ protected final int[][] provesPropsIfFalsePerProp; /** For every proposition, if it's false, a bitset of instances that are then deactivated (either disproven, or features already proven) */ protected final BitSet[] deactivateInstancesIfFalse; /** Bitset with a 1 entry for every single proposition */ protected final boolean[] ALL_PROPS_ACTIVE; /** Bitset with a 1 entry for every single instance, except those for features that are always active */ protected final BitSet INIT_INSTANCES_ACTIVE; //------------------------------------------------------------------------- /** * Constructor * @param featureIndices * @param propositions * @param dependentFeatureInstances * @param instancesPerFeature * @param propsPerInstance * @param autoActiveFeatures * @param thresholdedFeatures * @param provesPropsIfTruePerProp * @param disprovesPropsIfTruePerProp * @param provesPropsIfFalsePerProp * @param disprovesPropsIfFalsePerProp */ public SPatterNet ( final int[] featureIndices, final AtomicProposition[] propositions, final BitSet[] dependentFeatureInstances, final BitSet[] instancesPerFeature, final BitSet[] propsPerInstance, final int[] autoActiveFeatures, final BitSet thresholdedFeatures, final BitSet[] provesPropsIfTruePerProp, final BitSet[] disprovesPropsIfTruePerProp, final BitSet[] provesPropsIfFalsePerProp, final BitSet[] disprovesPropsIfFalsePerProp ) { // System.out.println(); // for (int i = 0; i < propositions.length; ++i) // { // System.out.println("Prop " + i + " = " + propositions[i]); // } // System.out.println(); this.featureIndices = featureIndices; int firstValidFeatureIdx = -1; for (int i = 0; i < instancesPerFeature.length; ++i) { if (instancesPerFeature[i] != null) { firstValidFeatureIdx = i; break; } } if (firstValidFeatureIdx < 0) { this.featureOffset = 0; this.instancesPerFeature = new BitSet[0]; } else { this.featureOffset = firstValidFeatureIdx; int lastValidFeatureIdx = -1; for (int i = instancesPerFeature.length - 1; i >= firstValidFeatureIdx; --i) { if (instancesPerFeature[i] != null) { lastValidFeatureIdx = i; break; } } this.instancesPerFeature = new BitSet[lastValidFeatureIdx - firstValidFeatureIdx + 1]; for (int i = 0; i < this.instancesPerFeature.length; ++i) { this.instancesPerFeature[i] = instancesPerFeature[i + featureOffset]; } } this.propositions = propositions; this.instancesPerProp = dependentFeatureInstances; this.autoActiveFeatures = autoActiveFeatures; this.provesPropsIfTruePerProp = new int[provesPropsIfTruePerProp.length][]; for (int i = 0; i < provesPropsIfTruePerProp.length; ++i) { this.provesPropsIfTruePerProp[i] = new int[provesPropsIfTruePerProp[i].cardinality()]; int k = 0; for (int j = provesPropsIfTruePerProp[i].nextSetBit(0); j >= 0; j = provesPropsIfTruePerProp[i].nextSetBit(j + 1)) { this.provesPropsIfTruePerProp[i][k++] = j; } } this.provesPropsIfFalsePerProp = new int[provesPropsIfFalsePerProp.length][]; for (int i = 0; i < provesPropsIfFalsePerProp.length; ++i) { this.provesPropsIfFalsePerProp[i] = new int[provesPropsIfFalsePerProp[i].cardinality()]; int k = 0; for (int j = provesPropsIfFalsePerProp[i].nextSetBit(0); j >= 0; j = provesPropsIfFalsePerProp[i].nextSetBit(j + 1)) { this.provesPropsIfFalsePerProp[i][k++] = j; } } this.deactivateInstancesIfTrue = new BitSet[disprovesPropsIfTruePerProp.length]; for (int i = 0; i < deactivateInstancesIfTrue.length; ++i) { final BitSet deactivate = new BitSet(); for (int j = disprovesPropsIfTruePerProp[i].nextSetBit(0); j >= 0; j = disprovesPropsIfTruePerProp[i].nextSetBit(j + 1)) { deactivate.or(instancesPerProp[j]); } // Useless clone, but it also trims to size which is nice to reduce memory usage deactivateInstancesIfTrue[i] = (BitSet) deactivate.clone(); } this.deactivateInstancesIfFalse = new BitSet[disprovesPropsIfFalsePerProp.length]; for (int i = 0; i < deactivateInstancesIfFalse.length; ++i) { final BitSet deactivate = new BitSet(); for (int j = disprovesPropsIfFalsePerProp[i].nextSetBit(0); j >= 0; j = disprovesPropsIfFalsePerProp[i].nextSetBit(j + 1)) { deactivate.or(instancesPerProp[j]); } // Also incorporate any instances that require the proposition itself as disprove-if-false instances deactivate.or(instancesPerProp[i]); // Useless clone, but it also trims to size which is nice to reduce memory usage deactivateInstancesIfFalse[i] = (BitSet) deactivate.clone(); } ALL_PROPS_ACTIVE = new boolean[propositions.length]; Arrays.fill(ALL_PROPS_ACTIVE, true); INIT_INSTANCES_ACTIVE = new BitSet(featureIndices.length); INIT_INSTANCES_ACTIVE.set(0, featureIndices.length); // TODO following two little loops should be unnecessary, all those instances should already be gone for (final int feature : autoActiveFeatures) { assert (instancesPerFeature[feature] == null || instancesPerFeature[feature].isEmpty()); //INIT_INSTANCES_ACTIVE.andNot(instancesPerFeature[feature]); } for (int i = thresholdedFeatures.nextSetBit(0); i >= 0; i = thresholdedFeatures.nextSetBit(i + 1)) { assert (instancesPerFeature[i] == null || instancesPerFeature[i].isEmpty()); //INIT_INSTANCES_ACTIVE.andNot(instancesPerFeature[i]); } // Remove propositions for instances if those propositions also appear in earlier propositions, // and those other instances are guaranteed to get checked before the later instances. // // An earlier instance is guaranteed to get checked before a later instance if the earlier instance // is the first instance of its feature // // The tracking of active props already would avoid re-evaluating these props, but this optimisation // step removes even more overhead by removing the bits altogether final BitSet firstInstancesOfFeature = new BitSet(featureIndices.length); final boolean[] featuresObserved = new boolean[instancesPerFeature.length]; for (int i = 0; i < featureIndices.length; ++i) { final int featureIdx = featureIndices[i]; if (!featuresObserved[featureIdx]) { firstInstancesOfFeature.set(i); featuresObserved[featureIdx] = true; final BitSet instanceProps = propsPerInstance[i]; for (int j = i + 1; j < featureIndices.length; ++j) { if (featureIndices[j] == featureIdx) propsPerInstance[j].andNot(instanceProps); } } } this.propsPerInstance = new int[propsPerInstance.length][]; for (int i = 0; i < propsPerInstance.length; ++i) { this.propsPerInstance[i] = new int[propsPerInstance[i].cardinality()]; int k = 0; for (int j = propsPerInstance[i].nextSetBit(0); j >= 0; j = propsPerInstance[i].nextSetBit(j + 1)) { this.propsPerInstance[i][k++] = j; } } // TODO keeping the following "optimisation" in, but it never actually seems to trigger // maybe this is provably unnecessary??? // // For every proposition i, collect all propositions that we know for sure must be true // if that proposition gets evaluated as true (resp. false), i.e.: // // 1) earlier propositions that cannot themselves be deactivated and, if they were false, // would deactivate all instances that check proposition i, and // 2) later propositions that get directly proven by i being true (resp. false) // // Any instances that are fully covered by that collection of propositions (+ i if true) // will for sure also be true, which means their features must for sure be true and we can // skip their other instances, i.e. deactivate them. // // The instance(s) that can potentially get proven by a proposition i through this mechanism // will be marked "immune" and cannot get deactivated again through the same mechanism (proving // a different instance of the same feature) by a later proposition j > i. This is because // we want to avoid having to track which features are already "proven" (but not yet included // because their single remaining instance still needs to be visited), and also want to avoid // explicitly checking for duplicate features final BitSet immuneInstances = new BitSet(featureIndices.length); // A prop is undeactivatable if at least one of its instances is undeactivatable, // so we should track that for instances, and if it's the first instance of its feature final BitSet undeactivatableInstances = new BitSet(featureIndices.length); for (final BitSet bitset : deactivateInstancesIfTrue) { undeactivatableInstances.or(bitset); } for (final BitSet bitset : deactivateInstancesIfFalse) { undeactivatableInstances.or(bitset); } undeactivatableInstances.flip(0, featureIndices.length); undeactivatableInstances.and(firstInstancesOfFeature); for (int i = 0; i < propositions.length; ++i) { // Collect propositions that must be true because, if they were false, // they would deactivate every single instance that uses proposition i final BitSet mustTrueProps = new BitSet(propositions.length); for (int j = 0; j < i; ++j) { // Can only include prop j if prop j is undeactivatable, i.e. if it has at least one // undeactivatable instance final BitSet jInstances = (BitSet) instancesPerProp[j].clone(); jInstances.and(undeactivatableInstances); if (jInstances.isEmpty()) continue; final BitSet jDeactivatesIfFalse = deactivateInstancesIfFalse[j]; final BitSet iInstances = (BitSet) instancesPerProp[i].clone(); iInstances.andNot(jDeactivatesIfFalse); if (iInstances.isEmpty()) { // i would never get checked if j were false, so j must be true if i gets checked mustTrueProps.set(j); } } for (int j = 0; j < featureIndices.length; ++j) { // First the case where we assume that i evaluates to false BitSet jProps = (BitSet) propsPerInstance[j].clone(); jProps.andNot(mustTrueProps); jProps.andNot(provesPropsIfFalsePerProp[i]); if (jProps.isEmpty()) { // Instance j must for sure be true if prop i gets checked and evaluates to false // we'll deactivate all other instances of this feature (except immune ones) // // j will become immune immuneInstances.set(j); final BitSet deactivateInstances = (BitSet) instancesPerFeature[featureIndices[j]].clone(); deactivateInstances.andNot(immuneInstances); // deactivateInstances.andNot(deactivateInstancesIfFalse[i]); // deactivateInstances.andNot(INIT_INSTANCES_ACTIVE); deactivateInstancesIfFalse[i].or(deactivateInstances); // for (int k = deactivateInstances.nextSetBit(0); k >= 0; k = deactivateInstances.nextSetBit(k + 1)) // { // System.out.println(featureInstances[i] + " deactivates " + featureInstances[k] + " if false."); // } // More instances have become deactivatable... undeactivatableInstances.andNot(deactivateInstances); } // Now the case where we assume that i evaluates to true jProps = (BitSet) propsPerInstance[j].clone(); jProps.andNot(mustTrueProps); jProps.andNot(provesPropsIfTruePerProp[i]); jProps.clear(i); if (jProps.isEmpty()) { // Instance j must for sure be true if prop i gets checked and evaluates to true // we'll deactivate all other instances of this feature (except immune ones) // // j will become immune immuneInstances.set(j); final BitSet deactivateInstances = (BitSet) instancesPerFeature[featureIndices[j]].clone(); deactivateInstances.andNot(immuneInstances); // deactivateInstances.andNot(deactivateInstancesIfTrue[i]); // deactivateInstances.andNot(INIT_INSTANCES_ACTIVE); deactivateInstancesIfTrue[i].or(deactivateInstances); // for (int k = deactivateInstances.nextSetBit(0); k >= 0; k = deactivateInstances.nextSetBit(k + 1)) // { // System.out.println(featureInstances[i] + " deactivates " + featureInstances[k] + " if true."); // } // More instances have become deactivatable... undeactivatableInstances.andNot(deactivateInstances); } } } } //------------------------------------------------------------------------- /** * @param state * @return List of active instances for given state */ public FastTIntArrayList getActiveFeatures(final State state) { final FastTIntArrayList activeFeatures = new FastTIntArrayList(instancesPerFeature.length + autoActiveFeatures.length); activeFeatures.add(autoActiveFeatures); final boolean[] activeProps = ALL_PROPS_ACTIVE.clone(); final BitSet activeInstances = (BitSet) INIT_INSTANCES_ACTIVE.clone(); //System.out.println(); //System.out.println("Auto-active features: " + Arrays.toString(autoActiveFeatures)); outer: for ( int instanceToCheck = activeInstances.nextSetBit(0); instanceToCheck >= 0; instanceToCheck = activeInstances.nextSetBit(instanceToCheck + 1)) { final int[] instanceProps = propsPerInstance[instanceToCheck]; //System.out.println("Checking feature instance " + instanceToCheck + ": " + featureInstances[instanceToCheck]); //System.out.println("instance props = " + Arrays.toString(instanceProps)); // Keep checking props for this instance in order for (int i = 0; i < instanceProps.length; ++i) { final int propID = instanceProps[i]; if (!activeProps[propID]) continue; // Prop already known to be true // We're checking propID now, so mark it as inactive activeProps[propID] = false; //System.out.println("evaluating prop " + propID + ": " + propositions[propID]); // Check the proposition if (!propositions[propID].matches(state)) { // Proposition is false //System.out.println("evaluated to false!"); // Prove other propositions that get proven by this one being false; simply switch them // off in the list of active props for (final int j : provesPropsIfFalsePerProp[propID]) { activeProps[j] = false; } // Disprove propositions that get disproven by this one being false; switch off any instances // that require them // And at the same time, also deactivate instances of features that get auto-proven activeInstances.andNot(deactivateInstancesIfFalse[propID]); // No point in continuing with props for this instance, instance is false anyway continue outer; } else { // Proposition is true //System.out.println("evaluated to true"); // Prove other propositions that get proven by this one being true; simply switch them // off in the list of active props for (final int j : provesPropsIfTruePerProp[propID]) { activeProps[j] = false; } // Disprove propositions that get disproven by this one being true; switch off any // instances that require them // And at the same time, also deactivate instances of features that get auto-proven activeInstances.andNot(deactivateInstancesIfTrue[propID]); } } // If we reach this point, the feature instance (and hence the feature) is active final int newActiveFeature = featureIndices[instanceToCheck]; activeFeatures.add(newActiveFeature); // This also means that we can skip any remaining instances for the same feature activeInstances.andNot(instancesPerFeature[newActiveFeature - featureOffset]); } //System.out.println(); return activeFeatures; } //------------------------------------------------------------------------- /** * @param containerState * @return Footprint of the state members that may be tested by this set. */ public BaseFootprint generateFootprint(final ContainerState containerState) { final ChunkSet footprintEmptyCells = containerState.emptyChunkSetCell() != null ? new ChunkSet(containerState.emptyChunkSetCell().chunkSize(), 1) : null; final ChunkSet footprintEmptyVertices = containerState.emptyChunkSetVertex() != null ? new ChunkSet(containerState.emptyChunkSetVertex().chunkSize(), 1) : null; final ChunkSet footprintEmptyEdges = containerState.emptyChunkSetEdge() != null ? new ChunkSet(containerState.emptyChunkSetEdge().chunkSize(), 1) : null; final ChunkSet footprintWhoCells = containerState.chunkSizeWhoCell() > 0 ? new ChunkSet(containerState.chunkSizeWhoCell(), 1) : null; final ChunkSet footprintWhoVertices = containerState.chunkSizeWhoVertex() > 0 ? new ChunkSet(containerState.chunkSizeWhoVertex(), 1) : null; final ChunkSet footprintWhoEdges = containerState.chunkSizeWhoEdge() > 0 ? new ChunkSet(containerState.chunkSizeWhoEdge(), 1) : null; final ChunkSet footprintWhatCells = containerState.chunkSizeWhatCell() > 0 ? new ChunkSet(containerState.chunkSizeWhatCell(), 1) : null; final ChunkSet footprintWhatVertices = containerState.chunkSizeWhatVertex() > 0 ? new ChunkSet(containerState.chunkSizeWhatVertex(), 1) : null; final ChunkSet footprintWhatEdges = containerState.chunkSizeWhatEdge() > 0 ? new ChunkSet(containerState.chunkSizeWhatEdge(), 1) : null; for (final AtomicProposition prop : propositions) { switch (prop.graphElementType()) { case Cell: switch (prop.stateVectorType()) { case Empty: prop.addMaskTo(footprintEmptyCells); break; case Who: prop.addMaskTo(footprintWhoCells); break; case What: prop.addMaskTo(footprintWhatCells); break; } break; case Edge: switch (prop.stateVectorType()) { case Empty: prop.addMaskTo(footprintEmptyEdges); break; case Who: prop.addMaskTo(footprintWhoEdges); break; case What: prop.addMaskTo(footprintWhatEdges); break; } break; case Vertex: switch (prop.stateVectorType()) { case Empty: prop.addMaskTo(footprintEmptyVertices); break; case Who: prop.addMaskTo(footprintWhoVertices); break; case What: prop.addMaskTo(footprintWhatVertices); break; } break; } } return new FullFootprint ( footprintEmptyCells, footprintEmptyVertices, footprintEmptyEdges, footprintWhoCells, footprintWhoVertices, footprintWhoEdges, footprintWhatCells, footprintWhatVertices, footprintWhatEdges ); } //------------------------------------------------------------------------- /** * @return Number of propositions in this SPatterNet */ public int numPropositions() { return propositions.length; } //------------------------------------------------------------------------- }
21,026
34.518581
140
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/SPatterNetFeatureSet.java
package features.feature_sets.network; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Stream; import features.Feature; import features.aspatial.AspatialFeature; import features.feature_sets.BaseFeatureSet; import features.spatial.SpatialFeature; import features.spatial.Walk; import features.spatial.cache.ActiveFeaturesCache; import features.spatial.cache.footprints.BaseFootprint; import features.spatial.instances.AtomicProposition; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import main.collections.FastTIntArrayList; import other.context.Context; import other.state.State; import other.state.container.ContainerState; import other.trial.Trial; /** * Implementation of Feature Set based on SPatterNets * * @author Dennis Soemers */ public class SPatterNetFeatureSet extends BaseFeatureSet { //------------------------------------------------------------------------- /** * Reactive instance sets, indexed by: * player index, * last-from-pos * last-to-pos, * from-pos * to-pos * * When indexed according to all of the above, we're left with a feature instance set. */ protected HashMap<ReactiveFeaturesKey, PropFeatureInstanceSet> reactiveInstances; /** * Proactive instances, indexed by: * player index, * from-pos * to-pos * * When indexed according to all of the above, we're left with a feature instance set. */ protected HashMap<ProactiveFeaturesKey, PropFeatureInstanceSet> proactiveInstances; /** * Reactive features, indexed by: * player index, * last-from-pos * last-to-pos, * from-pos * to-pos * * When indexed according to all of the above, we're left with a feature set. */ protected HashMap<ReactiveFeaturesKey, SPatterNet> reactiveFeatures; /** * Proactive features, indexed by: * player index, * from-pos * to-pos * * When indexed according to all of the above, we're left with a feature set. */ protected HashMap<ProactiveFeaturesKey, SPatterNet> proactiveFeatures; /** * Same as reactive features above, but only retaining features with absolute * weights that exceed the threshold defined by BaseFeatureSet. */ protected HashMap<ReactiveFeaturesKey, SPatterNet> reactiveFeaturesThresholded; /** * Same as proactive features above, but only retaining features with absolute * weights that exceed the threshold defined by BaseFeatureSet. */ protected HashMap<ProactiveFeaturesKey, SPatterNet> proactiveFeaturesThresholded; /** Cache with indices of active proactive features previously computed */ protected ActiveFeaturesCache activeProactiveFeaturesCache; //------------------------------------------------------------------------- /** * Construct feature set from lists of features * @param aspatialFeatures * @param spatialFeatures */ public SPatterNetFeatureSet(final List<AspatialFeature> aspatialFeatures, final List<SpatialFeature> spatialFeatures) { this.spatialFeatures = new SpatialFeature[spatialFeatures.size()]; for (int i = 0; i < this.spatialFeatures.length; ++i) { this.spatialFeatures[i] = spatialFeatures.get(i); this.spatialFeatures[i].setSpatialFeatureSetIndex(i); } this.aspatialFeatures = aspatialFeatures.toArray(new AspatialFeature[aspatialFeatures.size()]); reactiveInstances = null; proactiveInstances = null; reactiveFeatures = null; proactiveFeatures = null; reactiveFeaturesThresholded = null; proactiveFeaturesThresholded = null; } /** * Loads a feature set from a given filename * @param filename */ public SPatterNetFeatureSet(final String filename) { final List<AspatialFeature> aspatialFeaturesList = new ArrayList<AspatialFeature>(); final List<SpatialFeature> spatialFeaturesList = new ArrayList<SpatialFeature>(); Feature[] tempFeatures; //System.out.println("loading feature set from " + filename); try (Stream<String> stream = Files.lines(Paths.get(filename))) { tempFeatures = stream.map(s -> Feature.fromString(s)).toArray(Feature[]::new); for (final Feature feature : tempFeatures) { if (feature instanceof AspatialFeature) { aspatialFeaturesList.add((AspatialFeature)feature); } else { ((SpatialFeature)feature).setSpatialFeatureSetIndex(spatialFeaturesList.size()); spatialFeaturesList.add((SpatialFeature)feature); } } } catch (final IOException exception) { tempFeatures = null; exception.printStackTrace(); } this.aspatialFeatures = aspatialFeaturesList.toArray(new AspatialFeature[aspatialFeaturesList.size()]); this.spatialFeatures = spatialFeaturesList.toArray(new SpatialFeature[spatialFeaturesList.size()]); } //------------------------------------------------------------------------- @Override protected void instantiateFeatures(final int[] supportedPlayers) { activeProactiveFeaturesCache = new ActiveFeaturesCache(); // Start out creating feature (instance) sets represented as bipartite graphs Map<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> reactiveInstancesSet = new HashMap<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet>(); Map<ProactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> proactiveInstancesSet = new HashMap<ProactiveFeaturesKey, BipartiteGraphFeatureInstanceSet>(); // Create a dummy context because we need some context for // feature generation final Context featureGenContext = new Context(game.get(), new Trial(game.get())); // Collect features that should be ignored when running in thresholded mode final BitSet thresholdedFeatures = new BitSet(); if (spatialFeatureInitWeights != null) { // Doing following loop in reverse order ensures that thresholdedFeatures bitset size // does not grow larger than necessary for (int i = spatialFeatures.length - 1; i >= 0; --i) { if (Math.abs(spatialFeatureInitWeights.get(i)) < SPATIAL_FEATURE_WEIGHT_THRESHOLD) thresholdedFeatures.set(i); } } final ProactiveFeaturesKey proactiveKey = new ProactiveFeaturesKey(); final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); for (int i = 0; i < supportedPlayers.length; ++i) { final int player = supportedPlayers[i]; for (final SpatialFeature feature : spatialFeatures) { final List<FeatureInstance> newInstances = feature.instantiateFeature ( game.get(), featureGenContext.state().containerStates()[0], player, -1, -1, -1, -1, -1 ); for (final FeatureInstance instance : newInstances) { final int lastFrom = instance.lastFrom(); final int lastTo = instance.lastTo(); final int from = instance.from(); final int to = instance.to(); if (lastFrom >= 0 || lastTo >= 0) // Reactive feature { reactiveKey.resetData(player, lastFrom, lastTo, from, to); BipartiteGraphFeatureInstanceSet instancesSet = reactiveInstancesSet.get(reactiveKey); if (instancesSet == null) { instancesSet = new BipartiteGraphFeatureInstanceSet(); reactiveInstancesSet.put(new ReactiveFeaturesKey(reactiveKey), instancesSet); } instancesSet.insertInstance(instance); } else // Proactive feature { proactiveKey.resetData(player, from, to); BipartiteGraphFeatureInstanceSet instancesSet = proactiveInstancesSet.get(proactiveKey); if (instancesSet == null) { instancesSet = new BipartiteGraphFeatureInstanceSet(); proactiveInstancesSet.put(new ProactiveFeaturesKey(proactiveKey), instancesSet); } instancesSet.insertInstance(instance); } } } } reactiveInstances = new HashMap<ReactiveFeaturesKey, PropFeatureInstanceSet>(); reactiveFeatures = new HashMap<ReactiveFeaturesKey, SPatterNet>(); reactiveFeaturesThresholded = new HashMap<ReactiveFeaturesKey, SPatterNet>(); for (final Entry<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> entry : reactiveInstancesSet.entrySet()) { reactiveInstances.put(entry.getKey(), entry.getValue().toPropFeatureInstanceSet()); reactiveFeatures.put(entry.getKey(), entry.getValue().toSPatterNet(getNumSpatialFeatures(), new BitSet(), game.get(), entry.getKey().playerIdx())); reactiveFeaturesThresholded.put(entry.getKey(), entry.getValue().toSPatterNet(getNumSpatialFeatures(), thresholdedFeatures, game.get(), entry.getKey().playerIdx())); } proactiveInstances = new HashMap<ProactiveFeaturesKey, PropFeatureInstanceSet>(); proactiveFeatures = new HashMap<ProactiveFeaturesKey, SPatterNet>(); proactiveFeaturesThresholded = new HashMap<ProactiveFeaturesKey, SPatterNet>(); for (final Entry<ProactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> entry : proactiveInstancesSet.entrySet()) { proactiveInstances.put(entry.getKey(), entry.getValue().toPropFeatureInstanceSet()); proactiveFeatures.put(entry.getKey(), entry.getValue().toSPatterNet(getNumSpatialFeatures(), new BitSet(), game.get(), entry.getKey().playerIdx())); proactiveFeaturesThresholded.put(entry.getKey(), entry.getValue().toSPatterNet(getNumSpatialFeatures(), thresholdedFeatures, game.get(), entry.getKey().playerIdx())); } } @Override public void closeCache() { activeProactiveFeaturesCache.close(); } //------------------------------------------------------------------------- @Override public TIntArrayList getActiveSpatialFeatureIndices ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player, final boolean thresholded ) { final HashMap<ReactiveFeaturesKey, SPatterNet> reactiveFeaturesMap; final HashMap<ProactiveFeaturesKey, SPatterNet> proactiveFeaturesMap; if (thresholded) { reactiveFeaturesMap = reactiveFeaturesThresholded; proactiveFeaturesMap = proactiveFeaturesThresholded; } else { reactiveFeaturesMap = reactiveFeatures; proactiveFeaturesMap = proactiveFeatures; } final FastTIntArrayList featureIndices = new FastTIntArrayList(this.getNumSpatialFeatures()); // System.out.println("lastFrom = " + lastFrom); // System.out.println("lastTo = " + lastTo); // System.out.println("from = " + from); // System.out.println("to = " + to); // System.out.println("player = " + player); // final List<FeatureInstance> instances = getActiveFeatureInstances(state, lastFrom, lastTo, from, to, player); // for (final FeatureInstance instance : instances) // { // if (!featureIndices.contains(instance.feature().featureSetIndex())) // featureIndices.add(instance.feature().featureSetIndex()); // } final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; final int[] lastFroms = lastFrom >= 0 ? new int[]{-1, lastFrom} : new int[]{-1}; final int[] lastTos = lastTo >= 0 ? new int[]{-1, lastTo} : new int[]{-1}; if (!proactiveFeaturesMap.isEmpty()) { final int[] cachedActiveFeatureIndices; if (thresholded) cachedActiveFeatureIndices = activeProactiveFeaturesCache.getCachedActiveFeatures(this, state, from, to, player); else cachedActiveFeatureIndices = null; if (cachedActiveFeatureIndices != null) { // Successfully retrieved from cache featureIndices.add(cachedActiveFeatureIndices); //System.out.println("cache hit!"); } else { final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Proactive instances key.resetData(player, fromPos, toPos); final SPatterNet set = proactiveFeaturesMap.get(key); if (set != null) featureIndices.addAll(set.getActiveFeatures(state)); } } } if (thresholded && !featureIndices.isEmpty()) activeProactiveFeaturesCache.cache(state, from, to, featureIndices.toArray(), player); } } if (!reactiveFeatures.isEmpty()) { final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); if (lastFrom >= 0 || lastTo >= 0) { for (int i = 0; i < lastFroms.length; ++i) { final int lastFromPos = lastFroms[i]; for (int j = 0; j < lastTos.length; ++j) { final int lastToPos = lastTos[j]; if (lastToPos >= 0 || lastFromPos >= 0) { for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Reactive instances reactiveKey.resetData(player, lastFromPos, lastToPos, fromPos, toPos); final SPatterNet set = reactiveFeaturesMap.get(reactiveKey); if (set != null) featureIndices.addAll(set.getActiveFeatures(state)); } } } } } } } } return featureIndices; } @Override public List<FeatureInstance> getActiveSpatialFeatureInstances ( final State state, final int lastFrom, final int lastTo, final int from, final int to, final int player ) { final List<FeatureInstance> instances = new ArrayList<FeatureInstance>(); final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; final int[] lastFroms = lastFrom >= 0 ? new int[]{-1, lastFrom} : new int[]{-1}; final int[] lastTos = lastTo >= 0 ? new int[]{-1, lastTo} : new int[]{-1}; final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); for (int i = 0; i < lastFroms.length; ++i) { final int lastFromPos = lastFroms[i]; for (int j = 0; j < lastTos.length; ++j) { final int lastToPos = lastTos[j]; if (lastToPos >= 0 || lastFromPos >= 0) { for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Reactive instances reactiveKey.resetData(player, lastFromPos, lastToPos, fromPos, toPos); final PropFeatureInstanceSet set = reactiveInstances.get(reactiveKey); if (set != null) instances.addAll(set.getActiveInstances(state)); } } } } } } final ProactiveFeaturesKey proactiveKey = new ProactiveFeaturesKey(); for (int k = 0; k < froms.length; ++k) { final int fromPos = froms[k]; for (int l = 0; l < tos.length; ++l) { final int toPos = tos[l]; if (toPos >= 0 || fromPos >= 0) { // Proactive instances proactiveKey.resetData(player, fromPos, toPos); final PropFeatureInstanceSet set = proactiveInstances.get(proactiveKey); if (set != null) instances.addAll(set.getActiveInstances(state)); } } } return instances; } //------------------------------------------------------------------------- @Override public BaseFootprint generateFootprint ( final State state, final int from, final int to, final int player ) { final ContainerState container = state.containerStates()[0]; // NOTE: only using caching with thresholding final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); key.resetData(player, from, to); SPatterNet set = proactiveFeaturesThresholded.get(key); if (set == null) { set = new SPatterNet ( new int[0], new AtomicProposition[0], new BitSet[0], new BitSet[0], new BitSet[0], new int[0], new BitSet(), new BitSet[0], new BitSet[0], new BitSet[0], new BitSet[0] ); } final BaseFootprint footprint = set.generateFootprint(container); if (from >= 0) { // Also add footprints for from alone, and for to alone key.resetData(player, from, -1); set = proactiveFeaturesThresholded.get(key); if (set != null) footprint.union(set.generateFootprint(container)); key.resetData(player, -1, to); set = proactiveFeaturesThresholded.get(key); if (set != null) footprint.union(set.generateFootprint(container)); } return footprint; } //------------------------------------------------------------------------- @Override public SPatterNetFeatureSet createExpandedFeatureSet ( final Game targetGame, final SpatialFeature newFeature ) { boolean featureAlreadyExists = false; for (final SpatialFeature oldFeature : spatialFeatures) { if (newFeature.equals(oldFeature)) { featureAlreadyExists = true; break; } // also try all legal rotations of the generated feature, see // if any of those turn out to be equal to an old feature TFloatArrayList allowedRotations = newFeature.pattern().allowedRotations(); if (allowedRotations == null) { allowedRotations = new TFloatArrayList(Walk.allGameRotations(targetGame)); } for (int i = 0; i < allowedRotations.size(); ++i) { final SpatialFeature rotatedCopy = newFeature.rotatedCopy(allowedRotations.getQuick(i)); if (rotatedCopy.equals(oldFeature)) { // TODO only break if for every possible anchor this works? featureAlreadyExists = true; break; } } } if (!featureAlreadyExists) { // create new feature set with this feature, and return it final List<SpatialFeature> newFeatureList = new ArrayList<SpatialFeature>(spatialFeatures.length + 1); // all old features... for (final SpatialFeature feature : spatialFeatures) { newFeatureList.add(feature); } // and our new feature newFeatureList.add(newFeature); return new SPatterNetFeatureSet(Arrays.asList(aspatialFeatures), newFeatureList); } return null; } //------------------------------------------------------------------------- /** * @return Map of SPatterNets for reactive features */ public HashMap<ReactiveFeaturesKey, SPatterNet> reactiveFeatures() { return reactiveFeatures; } /** * @return Map of SPatterNets for reactive features (thresholded) */ public HashMap<ReactiveFeaturesKey, SPatterNet> reactiveFeaturesThresholded() { return reactiveFeaturesThresholded; } /** * @return Map of SPatterNets for proactive features */ public HashMap<ProactiveFeaturesKey, SPatterNet> proactiveFeatures() { return proactiveFeatures; } /** * @return Map of SPatterNets for proactive features (thresholded) */ public HashMap<ProactiveFeaturesKey, SPatterNet> proactiveFeaturesThresholded() { return proactiveFeaturesThresholded; } //------------------------------------------------------------------------- }
19,315
28.762712
169
java
Ludii
Ludii-master/Features/src/features/feature_sets/network/decision_tree/JITSPatterNetFeatureSetDecisionTree.java
package features.feature_sets.network.decision_tree; /** * A Decision-Tree variant of the JIT SPAtterNet Feature Set. Only computes active * features as necessary when following the branches of a Decision or Regression tree. * * @author Dennis Soemers */ public class JITSPatterNetFeatureSetDecisionTree { // //------------------------------------------------------------------------- // // /** Cache of feature set objects */ // protected static final Map<FeatureLists, JITSPatterNetFeatureSetDecisionTree> featureSetsCache = // new ConcurrentHashMap<FeatureLists, JITSPatterNetFeatureSetDecisionTree>(); // // //------------------------------------------------------------------------- // // /** JIT map (mix of proactive and reactive keys) */ // protected JITMap jitMap; // // //------------------------------------------------------------------------- // // /** // * Clear the entire cache of feature set objects. // */ // public static void clearFeatureSetCache() // { // featureSetsCache.clear(); // } // // /** // * Construct feature set from lists of features // * @param aspatialFeatures // * @param spatialFeatures // */ // public static JITSPatterNetFeatureSetDecisionTree construct(final List<AspatialFeature> aspatialFeatures, final List<SpatialFeature> spatialFeatures) // { // if (JITSPatterNetFeatureSet.ALLOW_FEATURE_SET_CACHE) // { // final FeatureLists key = new FeatureLists(aspatialFeatures, spatialFeatures); // final JITSPatterNetFeatureSetDecisionTree cached = featureSetsCache.get(key); // // if (cached != null) // return cached; // // final JITSPatterNetFeatureSetDecisionTree newSet = new JITSPatterNetFeatureSetDecisionTree(aspatialFeatures, spatialFeatures); // featureSetsCache.put(key, newSet); // return newSet; // } // // return new JITSPatterNetFeatureSetDecisionTree(aspatialFeatures, spatialFeatures); // } // //// /** //// * Loads a feature set from a given filename //// * @param filename //// */ //// public static JITSPatterNetFeatureSetDecisionTree construct(final String filename) //// { //// Feature[] tempFeatures; //// //// //System.out.println("loading feature set from " + filename); //// try (Stream<String> stream = Files.lines(Paths.get(filename))) //// { //// tempFeatures = stream.map(s -> Feature.fromString(s)).toArray(Feature[]::new); //// } //// catch (final IOException exception) //// { //// tempFeatures = null; //// exception.printStackTrace(); //// } //// //// final List<AspatialFeature> aspatialFeaturesList = new ArrayList<AspatialFeature>(); //// final List<SpatialFeature> spatialFeaturesList = new ArrayList<SpatialFeature>(); //// //// for (final Feature feature : tempFeatures) //// { //// if (feature instanceof AspatialFeature) //// { //// aspatialFeaturesList.add((AspatialFeature)feature); //// } //// else //// { //// ((SpatialFeature)feature).setSpatialFeatureSetIndex(spatialFeaturesList.size()); //// spatialFeaturesList.add((SpatialFeature)feature); //// } //// } //// //// return construct(aspatialFeaturesList, spatialFeaturesList); //// } // // /** // * Construct feature set from lists of features // * @param aspatialFeatures // * @param spatialFeatures // */ // private JITSPatterNetFeatureSetDecisionTree(final List<AspatialFeature> aspatialFeatures, final List<SpatialFeature> spatialFeatures) // { // this.spatialFeatures = new SpatialFeature[spatialFeatures.size()]; // // for (int i = 0; i < this.spatialFeatures.length; ++i) // { // this.spatialFeatures[i] = spatialFeatures.get(i); // this.spatialFeatures[i].setSpatialFeatureSetIndex(i); // } // // this.aspatialFeatures = aspatialFeatures.toArray(new AspatialFeature[aspatialFeatures.size()]); // // jitMap = null; // } // // //------------------------------------------------------------------------- // // @Override // protected void instantiateFeatures(final int[] supportedPlayers) // { // activeProactiveFeaturesCache = new ActiveFeaturesCache(); // // // Collect features that should be ignored when running in thresholded mode // thresholdedFeatures = new BitSet(); // if (spatialFeatureInitWeights != null) // { // // Doing following loop in reverse order ensures that thresholdedFeatures bitset size // // does not grow larger than necessary // for (int i = spatialFeatures.length - 1; i >= 0; --i) // { // if (Math.abs(spatialFeatureInitWeights.get(i)) < SPATIAL_FEATURE_WEIGHT_THRESHOLD) // thresholdedFeatures.set(i); // } // } // // jitMap = new JITMap(); // // // We'll use a dummy context to kickstart our JIT compilation on some real moves // final Context jitContext = new Context(game.get(), new Trial(game.get())); // // // We'll do 3 random (partial, very short) trials // for (int i = 0; i < 3; ++i) // { // game.get().start(jitContext); // // // We'll do 5 moves max per trial // for (int j = 0; j < 10; ++j) // { // if (jitContext.trial().over()) // break; // // for (final Move move : game.get().moves(jitContext).moves()) // { // final int mover = move.mover(); // if (ArrayUtils.contains(supportedPlayers, mover)) // { // final boolean thresholding = (spatialFeatureInitWeights != null); // this.computeFeatureVector(jitContext, move, thresholding); // This lets us do JIT instantiation // } // } // // jitContext.model().startNewStep(jitContext, null, 0.1); // } // } // } // // //------------------------------------------------------------------------- // // @Override // public TIntArrayList getActiveSpatialFeatureIndices // ( // final State state, // final int lastFrom, // final int lastTo, // final int from, // final int to, // final int player, // final boolean thresholded // ) // { // final FastTIntArrayList featureIndices = new FastTIntArrayList(this.getNumSpatialFeatures()); // //// System.out.println("lastFrom = " + lastFrom); //// System.out.println("lastTo = " + lastTo); //// System.out.println("from = " + from); //// System.out.println("to = " + to); //// System.out.println("player = " + player); //// final List<FeatureInstance> instances = getActiveFeatureInstances(state, lastFrom, lastTo, from, to, player); //// for (final FeatureInstance instance : instances) //// { //// if (!featureIndices.contains(instance.feature().featureSetIndex())) //// featureIndices.add(instance.feature().featureSetIndex()); //// } // // final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; // final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; // final int[] lastFroms = lastFrom >= 0 ? new int[]{-1, lastFrom} : new int[]{-1}; // final int[] lastTos = lastTo >= 0 ? new int[]{-1, lastTo} : new int[]{-1}; // // final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); // for (int k = 0; k < froms.length; ++k) // { // final int fromPos = froms[k]; // // for (int l = 0; l < tos.length; ++l) // { // final int toPos = tos[l]; // // if (toPos >= 0 || fromPos >= 0) // { // // Proactive instances // key.resetData(player, fromPos, toPos); // final SPatterNet set = thresholded ? jitMap.spatterNetThresholded(key, state) : jitMap.spatterNet(key, state); // // if (set != null) // featureIndices.addAll(set.getActiveFeatures(state)); // } // } // } // // final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); // // for (int i = 0; i < lastFroms.length; ++i) // { // final int lastFromPos = lastFroms[i]; // // for (int j = 0; j < lastTos.length; ++j) // { // final int lastToPos = lastTos[j]; // // if (lastToPos >= 0 || lastFromPos >= 0) // { // for (int k = 0; k < froms.length; ++k) // { // final int fromPos = froms[k]; // // for (int l = 0; l < tos.length; ++l) // { // final int toPos = tos[l]; // // if (toPos >= 0 || fromPos >= 0) // { // // Reactive instances // reactiveKey.resetData(player, lastFromPos, lastToPos, fromPos, toPos); // final SPatterNet set = jitMap.spatterNet(reactiveKey, state); // // if (set != null) // featureIndices.addAll(set.getActiveFeatures(state)); // } // } // } // } // } // } // // return featureIndices; // } // // @Override // public List<FeatureInstance> getActiveSpatialFeatureInstances // ( // final State state, // final int lastFrom, // final int lastTo, // final int from, // final int to, // final int player // ) // { // final List<FeatureInstance> instances = new ArrayList<FeatureInstance>(); // // final int[] froms = from >= 0 ? new int[]{-1, from} : new int[]{-1}; // final int[] tos = to >= 0 ? new int[]{-1, to} : new int[]{-1}; // final int[] lastFroms = lastFrom >= 0 ? new int[]{-1, lastFrom} : new int[]{-1}; // final int[] lastTos = lastTo >= 0 ? new int[]{-1, lastTo} : new int[]{-1}; // // final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); // for (int k = 0; k < froms.length; ++k) // { // final int fromPos = froms[k]; // // for (int l = 0; l < tos.length; ++l) // { // final int toPos = tos[l]; // // if (toPos >= 0 || fromPos >= 0) // { // // Proactive instances // key.resetData(player, fromPos, toPos); // // final PropFeatureInstanceSet set = jitMap.propFeatureInstanceSet(key, state); // // if (set != null) // instances.addAll(set.getActiveInstances(state)); // } // } // } // // final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); // // for (int i = 0; i < lastFroms.length; ++i) // { // final int lastFromPos = lastFroms[i]; // // for (int j = 0; j < lastTos.length; ++j) // { // final int lastToPos = lastTos[j]; // // if (lastToPos >= 0 || lastFromPos >= 0) // { // for (int k = 0; k < froms.length; ++k) // { // final int fromPos = froms[k]; // // for (int l = 0; l < tos.length; ++l) // { // final int toPos = tos[l]; // // if (toPos >= 0 || fromPos >= 0) // { // // Reactive instances // reactiveKey.resetData(player, lastFromPos, lastToPos, fromPos, toPos); // final PropFeatureInstanceSet set = jitMap.propFeatureInstanceSet(reactiveKey, state); // // if (set != null) // instances.addAll(set.getActiveInstances(state)); // } // } // } // } // } // } // // return instances; // } // // //------------------------------------------------------------------------- // // /** // * Wrapper around a collection of maps from keys (reactive or proactive) to SPatterNets // * or PropFeatureInstanceSets. // * // * @author Dennis Soemers // */ // private class JITMap // { // // /** Map to prop-feature-instance-set representation */ // private final Map<MoveFeaturesKey, PropFeatureInstanceSet> propInstanceSetMap; // // /** Map to SPatterNet representation (without thresholding) */ // private final Map<MoveFeaturesKey, SPatterNet> spatterNetMap; // // /** // * Constructor // */ // public JITMap() // { // this.propInstanceSetMap = new ConcurrentHashMap<MoveFeaturesKey, PropFeatureInstanceSet>(); // this.spatterNetMap = new ConcurrentHashMap<MoveFeaturesKey, SPatterNet>(); // } // // /** // * @param key // * @param state // * @return PropFeatureInstanceSet for given key // */ // public PropFeatureInstanceSet propFeatureInstanceSet(final MoveFeaturesKey key, final State state) // { // PropFeatureInstanceSet set = propInstanceSetMap.get(key); // // final boolean isKeyReactive = (key.lastFrom() >= 0 || key.lastTo() >= 0); // // if (set == null && !isKeyReactive) // NOTE: we assume that proactive features are always computed before reactive ones // { // // JIT: instantiate net for this key // final BipartiteGraphFeatureInstanceSet proactiveBipartiteGraph = new BipartiteGraphFeatureInstanceSet(); // final Map<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> reactiveGraphs = // new HashMap<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet>(); // // for (final SpatialFeature feature : JITSPatterNetFeatureSetDecisionTree.this.spatialFeatures()) // { // final RelativeFeature relFeature = (RelativeFeature)feature; // // final List<FeatureInstance> newInstances = new ArrayList<FeatureInstance>(); // // if // ( // key.from() >= 0 // && // relFeature.fromPosition() != null // && // ((key.to() >= 0) == (relFeature.toPosition() != null)) // ) // { // // Try instantiating with from as anchor // newInstances.addAll // ( // feature.instantiateFeature // ( // JITSPatterNetFeatureSetDecisionTree.this.gameRef().get(), // state.containerStates()[0], // state.mover(), // key.from(), // key.from(), // key.to(), // -1, // -1 // ) // ); // } // // if // ( // key.to() >= 0 // && // relFeature.toPosition() != null // && // ((key.from() >= 0) == (relFeature.fromPosition() != null)) // ) // { // // Try instantiating with to as anchor // newInstances.addAll // ( // feature.instantiateFeature // ( // JITSPatterNetFeatureSetDecisionTree.this.gameRef().get(), // state.containerStates()[0], // state.mover(), // key.to(), // key.from(), // key.to(), // -1, // -1 // ) // ); // } // // if (feature.isReactive()) // { // // Can have different instances for different reactive keys // final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); // // for (final FeatureInstance instance : newInstances) // { // reactiveKey.resetData(key.playerIdx(), instance.lastFrom(), instance.lastTo(), key.from(), key.to()); // BipartiteGraphFeatureInstanceSet bipartite = reactiveGraphs.get(reactiveKey); // // if (bipartite == null) // { // bipartite = new BipartiteGraphFeatureInstanceSet(); // reactiveGraphs.put(new ReactiveFeaturesKey(reactiveKey), bipartite); // } // // bipartite.insertInstance(instance); // } // } // else // { // // Just collect them all in the bipartite graph for proactive features // for (final FeatureInstance instance : newInstances) // { // proactiveBipartiteGraph.insertInstance(instance); // } // } // } // // for (final Entry<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> entry : reactiveGraphs.entrySet()) // { // propInstanceSetMap.put // ( // entry.getKey(), // entry.getValue().toPropFeatureInstanceSet() // ); // } // // set = proactiveBipartiteGraph.toPropFeatureInstanceSet(); // propInstanceSetMap.put(new ProactiveFeaturesKey((ProactiveFeaturesKey)key), set); // } // // return set; // } // // /** // * @param key // * @param state // * @return SPatterNet for given key // */ // public SPatterNet spatterNet(final MoveFeaturesKey key, final State state) // { // SPatterNet net = spatterNetMap.get(key); // // final boolean isKeyReactive = (key.lastFrom() >= 0 || key.lastTo() >= 0); // // if (net == null && !isKeyReactive) // NOTE: we assume that proactive features are always computed before reactive ones // { // // JIT: instantiate net for this key // final BipartiteGraphFeatureInstanceSet proactiveBipartiteGraph = new BipartiteGraphFeatureInstanceSet(); // final Map<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> reactiveGraphs = // new HashMap<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet>(); // // for (final SpatialFeature feature : JITSPatterNetFeatureSetDecisionTree.this.spatialFeatures()) // { // final RelativeFeature relFeature = (RelativeFeature)feature; // // final List<FeatureInstance> newInstances = new ArrayList<FeatureInstance>(); // // if // ( // key.from() >= 0 // && // relFeature.fromPosition() != null // && // ((key.to() >= 0) == (relFeature.toPosition() != null)) // ) // { // // Try instantiating with from as anchor // newInstances.addAll // ( // feature.instantiateFeature // ( // JITSPatterNetFeatureSetDecisionTree.this.gameRef().get(), // state.containerStates()[0], // state.mover(), // key.from(), // key.from(), // key.to(), // -1, // -1 // ) // ); // } // // if // ( // key.to() >= 0 // && // relFeature.toPosition() != null // && // ((key.from() >= 0) == (relFeature.fromPosition() != null)) // ) // { // // Try instantiating with to as anchor // newInstances.addAll // ( // feature.instantiateFeature // ( // JITSPatterNetFeatureSetDecisionTree.this.gameRef().get(), // state.containerStates()[0], // state.mover(), // key.to(), // key.from(), // key.to(), // -1, // -1 // ) // ); // } // // if (feature.isReactive()) // { // // Can have different instances for different reactive keys // final ReactiveFeaturesKey reactiveKey = new ReactiveFeaturesKey(); // // for (final FeatureInstance instance : newInstances) // { // reactiveKey.resetData(key.playerIdx(), instance.lastFrom(), instance.lastTo(), key.from(), key.to()); // BipartiteGraphFeatureInstanceSet bipartite = reactiveGraphs.get(reactiveKey); // // if (bipartite == null) // { // bipartite = new BipartiteGraphFeatureInstanceSet(); // reactiveGraphs.put(new ReactiveFeaturesKey(reactiveKey), bipartite); // } // // bipartite.insertInstance(instance); // } // } // else // { // // Just collect them all in the bipartite graph for proactive features // for (final FeatureInstance instance : newInstances) // { // proactiveBipartiteGraph.insertInstance(instance); // } // } // } // // for (final Entry<ReactiveFeaturesKey, BipartiteGraphFeatureInstanceSet> entry : reactiveGraphs.entrySet()) // { // spatterNetMap.put // ( // entry.getKey(), // entry.getValue().toSPatterNet(getNumSpatialFeatures(), new BitSet(), gameRef().get(), key.playerIdx()) // ); // } // // net = proactiveBipartiteGraph.toSPatterNet(getNumSpatialFeatures(), new BitSet(), gameRef().get(), key.playerIdx()); // spatterNetMap.put(new ProactiveFeaturesKey((ProactiveFeaturesKey)key), net); // } // // return net; // } // } // // //------------------------------------------------------------------------- // // /** // * Wrapper around a list of aspatial features and a list of spatial features. // * // * @author Dennis Soemers // */ // private static class FeatureLists // { // /** List of aspatial features */ // protected final List<AspatialFeature> aspatialFeatures; // /** List of spatial features */ // protected final List<SpatialFeature> spatialFeatures; // // /** // * Constructor // * @param aspatialFeatures // * @param spatialFeatures // */ // public FeatureLists(final List<AspatialFeature> aspatialFeatures, final List<SpatialFeature> spatialFeatures) // { // this.aspatialFeatures = aspatialFeatures; // this.spatialFeatures = spatialFeatures; // } // // @Override // public int hashCode() // { // return Objects.hash(aspatialFeatures, spatialFeatures); // } // // @Override // public boolean equals(final Object obj) // { // if (this == obj) // return true; // if (!(obj instanceof FeatureLists)) // return false; // final FeatureLists other = (FeatureLists) obj; // return Objects.equals(aspatialFeatures, other.aspatialFeatures) // && Objects.equals(spatialFeatures, other.spatialFeatures); // } // } // // //------------------------------------------------------------------------- }
20,113
29.897081
152
java
Ludii
Ludii-master/Features/src/features/generation/AtomicFeatureGenerator.java
package features.generation; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; import features.aspatial.AspatialFeature; import features.aspatial.InterceptFeature; import features.aspatial.PassMoveFeature; import features.aspatial.SwapMoveFeature; import features.spatial.AbsoluteFeature; import features.spatial.Pattern; import features.spatial.RelativeFeature; import features.spatial.SpatialFeature; import features.spatial.Walk; import features.spatial.elements.FeatureElement; import features.spatial.elements.FeatureElement.ElementType; import features.spatial.elements.RelativeFeatureElement; import game.Game; import game.equipment.component.Component; import game.equipment.other.Regions; import game.types.state.GameType; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; /** * Generates "atomic" features for a game. We say that a spatial feature is atomic if * and only if it consists of exactly 0 or 1 restrictions (Walk + element type) * * The maximum size any Walk is allowed to have can be specified on * instantiation of the generator * * Any relevant aspatial features are also included. * * @author Dennis Soemers */ public class AtomicFeatureGenerator { //------------------------------------------------------------------------- /** Reference to our game */ protected final Game game; /** Generated aspatial features */ protected final List<AspatialFeature> aspatialFeatures; /** Generated spatial features */ protected final List<SpatialFeature> spatialFeatures; //------------------------------------------------------------------------- /** * Constructor * @param game * @param maxWalkSize Maximum size of walks generated for atomic features * @param maxStraightWalkSize Maximum size of straight-line walks for * atomic features. These straight-line walks may be longer than * non-straight-line walks, which are subject to the standard maxWalkSize * restriction. */ public AtomicFeatureGenerator ( final Game game, final int maxWalkSize, final int maxStraightWalkSize ) { this.game = game; // First generate spatial features spatialFeatures = SpatialFeature.simplifySpatialFeaturesList(game, generateFeatures(maxWalkSize, maxStraightWalkSize)); spatialFeatures.sort(new Comparator<SpatialFeature>() { @Override public int compare(final SpatialFeature o1, final SpatialFeature o2) { final FeatureElement[] els1 = o1.pattern().featureElements(); final FeatureElement[] els2 = o2.pattern().featureElements(); if (els1.length < els2.length) { return -1; } else if (els1.length > els2.length) { return 1; } else { int sumWalkLengths1 = 0; int sumWalkLengths2 = 0; for (final FeatureElement el : els1) { if (el instanceof RelativeFeatureElement) { sumWalkLengths1 += ((RelativeFeatureElement) el).walk().steps().size(); } } for (final FeatureElement el : els2) { if (el instanceof RelativeFeatureElement) { sumWalkLengths2 += ((RelativeFeatureElement) el).walk().steps().size(); } } return sumWalkLengths1 - sumWalkLengths2; } } }); aspatialFeatures = new ArrayList<AspatialFeature>(); // Intercept feature always considered relevant aspatialFeatures.add(InterceptFeature.instance()); // Pass feature always considered relevant aspatialFeatures.add(PassMoveFeature.instance()); // Swap feature only relevant if game uses swap rule if ((game.gameFlags() & GameType.UsesSwapRule) != 0L) aspatialFeatures.add(SwapMoveFeature.instance()); } //------------------------------------------------------------------------- /** * @return Generated aspatial features */ public List<AspatialFeature> getAspatialFeatures() { return aspatialFeatures; } /** * @return Generated spatial features */ public List<SpatialFeature> getSpatialFeatures() { return spatialFeatures; } //------------------------------------------------------------------------- /** * Generates new features with additional walks up to the given max size. * * @param maxSize * @param maxStraightWalkSize * @return */ private List<SpatialFeature> generateFeatures(final int maxSize, final int maxStraightWalkSize) { //final MoveFeatures moveFeaturesGenerator = new MoveFeatures(game); //final List<Feature> moveFeatures = moveFeaturesGenerator.features(); //final Set<Feature> generatedFeatures = new HashSet<Feature>(16384); //generatedFeatures.addAll(moveFeatures); final List<SpatialFeature> emptyFeatures = new ArrayList<SpatialFeature>(); emptyFeatures.add(new RelativeFeature(new Pattern(), new Walk(), null)); if ((game.gameFlags() & GameType.UsesFromPositions) != 0L) emptyFeatures.add(new RelativeFeature(new Pattern(), null, new Walk())); final Set<SpatialFeature> generatedFeatures = new HashSet<SpatialFeature>(16384); generatedFeatures.addAll(emptyFeatures); final TIntArrayList connectivities = game.board().topology().trueOrthoConnectivities(game); final TFloatArrayList allGameRotations = new TFloatArrayList(Walk.allGameRotations(game)); final EnumSet<ElementType> elementTypes = FeatureGenerationUtils.usefulElementTypes(game); elementTypes.add(ElementType.LastFrom); elementTypes.add(ElementType.LastTo); for (int walkSize = 0; walkSize <= maxStraightWalkSize; ++walkSize) { final List<Walk> allWalks = generateAllWalks(walkSize, maxSize, allGameRotations); // for every base feature, create new versions with all possible // additions of a Walk of length walkSize for (final SpatialFeature baseFeature : emptyFeatures) { final Pattern basePattern = baseFeature.pattern(); // we'll always add exactly one Walk for (final Walk walk : allWalks) { // for every element type... for (final ElementType elementType : elementTypes) { final TIntArrayList itemIndices = new TIntArrayList(); if (elementType == ElementType.Item) { final Component[] components = game.equipment().components(); for (int i = 1; i < components.length; ++i) { if (components[i] != null) { itemIndices.add(i); } } } else if (elementType == ElementType.IsPos) { System.err.println("WARNING: not yet including position indices in AtomicFeatureGenerator.generateFeatures()"); } else if (elementType == ElementType.Connectivity) { itemIndices.addAll(connectivities); } else if (elementType == ElementType.RegionProximity) { if (walkSize > 0) // RegionProximity test on anchor is useless { // Only include regions for which we actually have distance tables final Regions[] regions = game.equipment().regions(); for (int i = 0; i < regions.length; ++i) { if (game.distancesToRegions()[i] != null) itemIndices.add(i); } } } else if (elementType == ElementType.LineOfSightOrth || elementType == ElementType.LineOfSightDiag) { final Component[] components = game.equipment().components(); for (int i = 1; i < components.length; ++i) { if (components[i] != null) { itemIndices.add(i); } } } else { itemIndices.add(-1); } // normal tests and NOT-tests for (final boolean not : new boolean[] {false, true}) { // for every item / position index... for (int idx = 0; idx < itemIndices.size(); ++idx) { // create a new version of the pattern where we add the // current walk + the current element type final Pattern newPattern = new Pattern(baseFeature.pattern()); if (elementType != ElementType.LastFrom && elementType != ElementType.LastTo) { newPattern.addElement ( new RelativeFeatureElement(elementType, not, new Walk(walk), itemIndices.getQuick(idx)) ); } // make sure it's actually a consistent pattern if (newPattern.isConsistent()) { // remove elements that appear with same walk multiple times newPattern.removeRedundancies(); // make sure that we're still meaningfully // different from base pattern after removing // redundancies if ( !newPattern.equals(basePattern) || elementType != ElementType.LastFrom || elementType != ElementType.LastTo ) { final SpatialFeature newFeature; if (baseFeature instanceof AbsoluteFeature) { final AbsoluteFeature absBase = (AbsoluteFeature) baseFeature; newFeature = new AbsoluteFeature ( newPattern, absBase.toPosition(), absBase.fromPosition() ); } else { final Walk lastTo = (elementType == ElementType.LastTo) ? new Walk(walk) : null; final Walk lastFrom = (elementType == ElementType.LastFrom) ? new Walk(walk) : null; final RelativeFeature relBase = (RelativeFeature) baseFeature; newFeature = new RelativeFeature ( newPattern, relBase.toPosition() != null ? new Walk(relBase.toPosition()) : null, relBase.fromPosition() != null ? new Walk(relBase.fromPosition()) : null, lastTo, lastFrom ); } // try to eliminate duplicates under rotation // and/or reflection newFeature.normalise(game); // remove elements that appear with // same walk multiple times newFeature.pattern().removeRedundancies(); generatedFeatures.add(newFeature); } } } } } } } } return new ArrayList<SpatialFeature>(generatedFeatures); } /** * @param walkSize * @param maxWalkSize * @param allGameRotations * @return A list of all possible walks of the given size. * Returns a list containing just null for walkSize < 0 */ private static List<Walk> generateAllWalks ( final int walkSize, final int maxWalkSize, final TFloatArrayList allGameRotations ) { if (walkSize < 0) { final List<Walk> walks = new ArrayList<Walk>(1); walks.add(null); return walks; } List<Walk> allWalks = Arrays.asList(new Walk()); int currWalkLengths = 0; while (currWalkLengths < walkSize) { final List<Walk> allWalksReplacement = new ArrayList<Walk>(allWalks.size() * 4); for (final Walk walk : allWalks) { for (int i = 0; i < allGameRotations.size(); ++i) { final float rot = allGameRotations.getQuick(i); if (rot == 0.f || currWalkLengths == 0 || walkSize <= maxWalkSize) { // only straight-line walks are allowed to exceed maxWalkSize if (rot != 0.5f || currWalkLengths == 0) { // rotating by 0.5 is never useful // (except as very first step) final Walk newWalk = new Walk(walk); newWalk.steps().add(rot); allWalksReplacement.add(newWalk); } } } } ++currWalkLengths; allWalks = allWalksReplacement; } return allWalks; } //------------------------------------------------------------------------- }
11,767
28.717172
121
java
Ludii
Ludii-master/Features/src/features/generation/FeatureGenerationUtils.java
package features.generation; import java.util.EnumSet; import java.util.List; import features.spatial.elements.FeatureElement.ElementType; import game.Game; import game.equipment.component.Component; import game.equipment.other.Regions; import game.util.directions.DirectionFacing; import game.util.directions.RelativeDirection; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import other.context.Context; /** * Utility methods for feature generation * * @author Dennis Soemers and cambolbro */ public class FeatureGenerationUtils { //------------------------------------------------------------------------- private FeatureGenerationUtils() { // should not be used } //------------------------------------------------------------------------- /** * Generates walks that are likely to correspond to the given direction choice, * with optional restrictions imposed by Piece facing (if facing != null). * * The two "out" lists should be empty, and will be populated by this method. * * In possibly ambiguous cases, this method will generate relatively "safe", * highly general features that will almost surely cover the real legal moves, * as well as some more specific features that are likely to correspond more * closely with movement rules, but also may in some games fail to capture * all legal moves. * * @param game * @param dirnChoice * @param facing * @param outAllowedRotations Will be populated with lists of permitted rotations * (null if no restriction on rotations) * @param outWalks Will be populated with lists, each of which is a Walk * (null if we want a feature with unrestricted from-pos) */ public static void generateWalksForDirnChoice ( final Game game, final RelativeDirection dirnChoice, final DirectionFacing facing, final List<TFloatArrayList> outAllowedRotations, final List<TFloatArrayList> outWalks ) { // final Tiling tiling = game.board().tiling(); // final DirectionType[] supportedDirectionTypes = tiling.getSupportedDirectionTypes(); // final DirectionType[] supportedOrthDirectionTypes = tiling.getSupportedOrthogonalDirectionTypes(); // // final boolean allDirsOrth = Arrays.equals(supportedDirectionTypes, supportedOrthDirectionTypes); // // final int[] directionIndices; // if (facing != null) // { // directionIndices = tiling.getChosenDirectionIndices(facing, dirnChoice); // } // else // { // directionIndices = tiling.getChosenDirectionIndices(facing, dirnChoice); // } // // boolean allDirectionsAllowed = true; // for (final DirectionType dirType : supportedDirectionTypes) // { // boolean foundIt = false; // // for (int i = 0; i < directionIndices.length; ++i) // { // if (directionIndices[i] == dirType.index()) // { // foundIt = true; // break; // } // } // // if (!foundIt) // { // allDirectionsAllowed = false; // break; // } // } // // if (allDirsOrth) // { // // this means that we're in a situation where all connections are orthogonal // // for example, this could be a hexagonal tiling // if (allDirectionsAllowed) // { // // easiest case; all we need is a single-step walk, all rotations allowed // outAllowedRotations.add(null); // outWalks.add(TFloatArrayList.wrap(0.f)); // } // else // { // // difficult case; for now, we'll just separately generate a walk without any // // allowed rotations per direction index // // // // later on we probably could handle some more special cases with some support // // for rotations, if that turns out to be useful // System.err.println( // "Note: FeatureGenerationutils.generateWalksForDirnChoice() " // + "returning no-rot walks!"); // // for (final int directionIndex : directionIndices) // { // int orthDirTypeIdx = -1; // // for (int i = 0; i < supportedOrthDirectionTypes.length; ++i) // { // if (supportedOrthDirectionTypes[i].index() == directionIndex) // { // orthDirTypeIdx = i; // break; // } // } // // if (orthDirTypeIdx == -1) // { // System.err.println( // "Error in FeatureGenerationutils.generateWalksForDirnChoice(): " // + "orthDirTypeIdx == -1"); // } // else // { // outAllowedRotations.add(TFloatArrayList.wrap(0.f)); // outWalks.add(TFloatArrayList.wrap( // (float) orthDirTypeIdx / (float) supportedOrthDirectionTypes.length)); // } // } // } // } // else // { // // this means that we're in a situation where some connections are not orthogonal // // for example, this could be a square tiling / chessboard, where diagonals exist // // // // in this case, we'll have to start out with some a general feature just to // // make sure we don't miss out on any legal moves in strange boards // outAllowedRotations.add(null); // outWalks.add(null); // // // try to generate good orthogonal-move features if necessary // boolean orthDirAllowed = false; // // for (int i = 0; i < directionIndices.length; ++i) // { // boolean foundIt = false; // // for (final DirectionType dirType : supportedOrthDirectionTypes) // { // if (dirType.index() == directionIndices[i]) // { // foundIt = true; // break; // } // } // // if (foundIt) // { // orthDirAllowed = true; // break; // } // } // // if (orthDirAllowed) // { // outAllowedRotations.add(null); // outWalks.add(TFloatArrayList.wrap(0.f)); // } // // // try to generate good diagonal-move features if necessary // boolean nonOrthDirAllowed = false; // // for (int i = 0; i < directionIndices.length; ++i) // { // boolean foundIt = false; // // for (final DirectionType dirType : supportedOrthDirectionTypes) // { // if (dirType.index() == directionIndices[i]) // { // foundIt = true; // break; // } // } // // if (!foundIt) // { // nonOrthDirAllowed = true; // break; // } // } // // // we'll create all-rotations-allowed walks of {0.f, 0.25}. // // these should specifically cover diagonal movements in many games // // (e.g. games with square tilings). In some strange boards they may // // fail, but then we still have the more general walks above as back-up. // if (nonOrthDirAllowed) // { // outAllowedRotations.add(null); // outWalks.add(TFloatArrayList.wrap(0.f, 0.25f)); // } // } } /** * @param game * @param context * @param elementType * @param site * @param itemIndex * @return Whether or not the given elementType is applicable to the given site in the given context */ public static boolean testElementTypeInState ( final Game game, final Context context, final ElementType elementType, final int site, final int itemIndex ) { // if (site == -1) // { // return elementType == ElementType.Off; // } // else // { // final ContainerState cs = context.trial().state().containerStates()[0]; // // if (elementType == ElementType.Empty) // { // return cs.whoCell(site) == 0; // } // else if (elementType == ElementType.Friend) // { // return cs.whoCell(site) == context.trial().state().mover(); // } // else if (elementType == ElementType.Enemy) // { // return cs.whoCell(site) != context.trial().state().mover() && cs.whoCell(site) != 0; // } // else if (elementType == ElementType.Off) // { // return false; // } // else if (elementType == ElementType.Any) // { // return true; // } // else if (elementType == ElementType.P1) // { // return cs.whoCell(site) == 1; // } // else if (elementType == ElementType.P2) // { // return cs.whoCell(site) == 2; // } // else if (elementType == ElementType.Item) // { // return cs.whatCell(site) == itemIndex; // } // else if (elementType == ElementType.IsPos) // { // return site == itemIndex; // } // else // { // System.err.println( // "FeatureGenerationUtils.testElementTypeInState cannot handle: " + elementType); // return false; // } // } return false; } //------------------------------------------------------------------------- /** * @param game * @return A set of all feature element types that may be useful in the given game */ public static EnumSet<ElementType> usefulElementTypes(final Game game) { final EnumSet<ElementType> elementTypes = EnumSet.of(ElementType.Empty, ElementType.Friend, ElementType.Off); if (game.players().count() > 1) { elementTypes.add(ElementType.Enemy); } final Component[] components = game.equipment().components(); // if (components.length > 1) // >1 instead of >=1 because we have dummy entry of null at index 0 // { // elementTypes.add(ElementType.LineOfSightOrth); // elementTypes.add(ElementType.LineOfSightDiag); // } final int[] componentsPerPlayer = new int[game.players().count() + 1]; for (final Component component : components) { if (component != null && component.owner() <= game.players().count()) { componentsPerPlayer[component.owner()]++; } } if (componentsPerPlayer[0] > 1) { elementTypes.add(ElementType.Item); } else { for (int i = 1; i < componentsPerPlayer.length; ++i) { if (componentsPerPlayer[i] > 1) { elementTypes.add(ElementType.Item); } } } final TIntArrayList connectivities = game.board().topology().trueOrthoConnectivities(game); if (connectivities.size() > 1) { // We have different graph elements with different connectivity numbers elementTypes.add(ElementType.Connectivity); } if (game.distancesToRegions() != null) { final Regions[] regions = game.equipment().regions(); if (regions.length > 0) { for (int i = 0; i < regions.length; ++i) { if (game.distancesToRegions()[i] != null) { // We have at least one region with meaningful distances, so RegionProximity is relevant elementTypes.add(ElementType.RegionProximity); break; } } } } return elementTypes; } //------------------------------------------------------------------------- }
10,268
26.754054
111
java
Ludii
Ludii-master/Features/src/features/spatial/AbsoluteFeature.java
package features.spatial; import java.util.List; import java.util.Set; import features.spatial.elements.FeatureElement; import features.spatial.elements.RelativeFeatureElement; import game.Game; import gnu.trove.list.array.TFloatArrayList; /** * In an Absolute Feature, the Action-to-play is implied by * absolute "from" and "to" positions (sometimes only a "to" position) * * @author Dennis Soemers */ public class AbsoluteFeature extends SpatialFeature { //------------------------------------------------------------------------- /** Position we want to move to */ protected final int toPosition; /** * Position we want to move from (-1 in cases where there is no from * position, or where it's not restricted) */ protected final int fromPosition; /** Position that was moved to last (-1 for proactive features) */ protected final int lastToPosition; /** * Position that was last moved from (-1 for proactive features and in * cases where we don't care about restricting from-positions) */ protected final int lastFromPosition; //------------------------------------------------------------------------- /** * Constructor * @param pattern * @param toPosition * @param fromPosition */ public AbsoluteFeature ( final Pattern pattern, final int toPosition, final int fromPosition ) { this.pattern = pattern; this.toPosition = toPosition; this.fromPosition = fromPosition; this.lastToPosition = -1; this.lastFromPosition = -1; } /** * Copy constructor * @param other */ public AbsoluteFeature(final AbsoluteFeature other) { this.pattern = new Pattern(other.pattern); this.toPosition = other.toPosition; this.fromPosition = other.fromPosition; this.lastToPosition = other.lastToPosition; this.lastFromPosition = other.lastFromPosition; // this.comment = new String(other.comment); } /** * Constructor from string * @param string */ public AbsoluteFeature(final String string) { final String[] parts = string.split(":"); // need these because we're not allowed to assign value to final // members inside a loop int toPos = -1; int fromPos = -1; int lastToPos = -1; int lastFromPos = -1; for (String part : parts) { if (part.startsWith("last_to=<")) { part = part.substring( "last_to=<".length(), part.length() - ">".length()); lastToPos = Integer.parseInt(part); } else if (part.startsWith("last_from=<")) { part = part.substring( "last_from=<".length(), part.length() - ">".length()); lastFromPos = Integer.parseInt(part); } else if (part.startsWith("to=<")) { part = part.substring( "to=<".length(), part.length() - ">".length()); toPos = Integer.parseInt(part); } else if (part.startsWith("from=<")) { part = part.substring( "from=<".length(), part.length() - ">".length()); fromPos = Integer.parseInt(part); } else if (part.startsWith("pat=<")) { part = part.substring( "pat=<".length(), part.length() - ">".length()); pattern = new Pattern(part); } else if (part.startsWith("comment=\"")) { part = part.substring( "comment=\"".length(), part.length() - "\"".length()); // comment = part; } } toPosition = toPos; fromPosition = fromPos; lastToPosition = lastToPos; lastFromPosition = lastFromPos; } //------------------------------------------------------------------------- /** * @return Absolute to-position */ public int toPosition() { return toPosition; } /** * @return Absolute from-position */ public int fromPosition() { return fromPosition; } /** * @return Absolute last-to position */ public int lastToPosition() { return lastToPosition; } /** * @return Absolute last-from position */ public int lastFromPosition() { return lastFromPosition; } //------------------------------------------------------------------------- @Override public SpatialFeature rotatedCopy(final float rotation) { final AbsoluteFeature copy = new AbsoluteFeature(this); for (final FeatureElement element : copy.pattern().featureElements()) { if (element instanceof RelativeFeatureElement) { final RelativeFeatureElement rel = (RelativeFeatureElement) element; if (rel.walk().steps().size() > 0) { rel.walk().steps().setQuick( 0, rel.walk().steps().getQuick(0) + rotation); } } } return copy; } @Override public SpatialFeature reflectedCopy() { final AbsoluteFeature copy = new AbsoluteFeature(this); for (final FeatureElement element : copy.pattern().featureElements()) { if (element instanceof RelativeFeatureElement) { final RelativeFeatureElement rel = (RelativeFeatureElement) element; final TFloatArrayList steps = rel.walk().steps(); for (int i = 0; i < steps.size(); ++i) { steps.setQuick(i, steps.getQuick(i) * -1); } } } return copy; } @Override public boolean generalises(final SpatialFeature other) { if (!(other instanceof AbsoluteFeature)) { return false; } final AbsoluteFeature otherFeature = (AbsoluteFeature) other; return (toPosition == otherFeature.toPosition && fromPosition == otherFeature.fromPosition && lastToPosition == otherFeature.lastToPosition && lastFromPosition == otherFeature.lastFromPosition && pattern.generalises(otherFeature.pattern)); } //------------------------------------------------------------------------- @Override public List<SpatialFeature> generateGeneralisers(final Game game, final Set<RotRefInvariantFeature> generalisers, final int numRecursions) { System.err.println("ERRROR: AbsoluteFeature::generateGeneralisers(Game) not yet implemented!"); return null; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + fromPosition; result = prime * result + toPosition; result = prime * result + lastFromPosition; result = prime * result + lastToPosition; return result; } @Override public boolean equals(final Object other) { if (! super.equals(other)) return false; if (!(other instanceof AbsoluteFeature)) return false; final AbsoluteFeature otherFeature = (AbsoluteFeature) other; return toPosition == otherFeature.toPosition && fromPosition == otherFeature.fromPosition && lastToPosition == otherFeature.lastToPosition && lastFromPosition == otherFeature.lastFromPosition; } @Override public boolean equalsIgnoreRotRef(final SpatialFeature other) { if (! super.equalsIgnoreRotRef(other)) return false; if (!(other instanceof AbsoluteFeature)) return false; final AbsoluteFeature otherFeature = (AbsoluteFeature) other; return toPosition == otherFeature.toPosition && fromPosition == otherFeature.fromPosition && lastToPosition == otherFeature.lastToPosition && lastFromPosition == otherFeature.lastFromPosition; } @Override public int hashCodeIgnoreRotRef() { final int prime = 31; int result = super.hashCodeIgnoreRotRef(); result = prime * result + fromPosition; result = prime * result + toPosition; result = prime * result + lastFromPosition; result = prime * result + lastToPosition; return result; } //------------------------------------------------------------------------- @Override public String toString() { String str = String.format("pat=<%s>", pattern); if (toPosition != -1) { str = String.format("to=<%s>:%s", Integer.valueOf(toPosition), str); } if (fromPosition != -1) { str = String.format("from=<%s>:%s", Integer.valueOf(fromPosition), str); } if (lastToPosition != -1) { str = String.format("last_to=<%s>:%s", Integer.valueOf(lastToPosition), str); } if (lastFromPosition != -1) { str = String.format("last_from=<%s>:%s", Integer.valueOf(lastFromPosition), str); } // if (comment.length() > 0) // { // str = String.format("%s:comment=\"%s\"", str, comment); // } return "abs:" + str; } //------------------------------------------------------------------------- @Override public String generateTikzCode(final Game game) { return "TO DO"; } //------------------------------------------------------------------------- }
8,482
22.963277
139
java
Ludii
Ludii-master/Features/src/features/spatial/FeatureUtils.java
package features.spatial; import other.move.Move; /** * Some utility methods related to features * * @author Dennis Soemers */ public class FeatureUtils { //------------------------------------------------------------------------- /** * Private constructor, should not use */ private FeatureUtils() { // should not instantiate } //------------------------------------------------------------------------- /** * @param move * @return Extracts a from-position from an action */ public static int fromPos(final Move move) { if (move == null || move.isPass()) { return -1; } int fromPos = move.fromNonDecision(); if (fromPos == move.toNonDecision()) { fromPos = -1; } return fromPos; } /** * @param move * @return Extracts a to-position from an action */ public static int toPos(final Move move) { if (move == null || move.isPass()) { return -1; } return move.toNonDecision(); } //------------------------------------------------------------------------- }
1,045
15.603175
76
java
Ludii
Ludii-master/Features/src/features/spatial/Pattern.java
package features.spatial; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import features.spatial.elements.AbsoluteFeatureElement; import features.spatial.elements.FeatureElement; import features.spatial.elements.RelativeFeatureElement; import features.spatial.graph_search.Path; import gnu.trove.list.array.TFloatArrayList; import main.collections.ArrayUtils; /** * A local, lightweight Pattern, for Features<br> * * @author Dennis Soemers and cambolbro */ public class Pattern { //------------------------------------------------------------------------- /** Array of elements (positions + Element Types) that define this pattern. */ protected FeatureElement[] featureElements; /** * List of complete Pattern rotations that are allowed */ protected TFloatArrayList allowedRotations = null; /** Whether we allow reflection (true by default) */ protected boolean allowsReflection = true; /** If set to true, the pattern will automatically be rotated to match the mover's direction */ protected boolean matchMoverDirection = false; //------------------------------------------------------------------------- /** * Constructor */ public Pattern() { featureElements = new FeatureElement[0]; } /** * Constructor * @param elements */ public Pattern(final FeatureElement... elements) { featureElements = Arrays.copyOf(elements, elements.length); } /** * Copy constructor * @param other */ public Pattern(final Pattern other) { featureElements = new FeatureElement[other.featureElements.length]; for (int i = 0; i < featureElements.length; ++i) { featureElements[i] = FeatureElement.copy(other.featureElements[i]); } allowedRotations = other.allowedRotations; } /** * Constructs pattern from string * @param string */ public Pattern(final String string) { int currIdx = 0; // move through the entire string // Default enable reflection and rotations if not specified allowsReflection = true; allowedRotations = null; while (currIdx < string.length()) { if (string.startsWith("refl=true,", currIdx)) { allowsReflection = true; currIdx += "refl=true,".length(); // skip ahead } else if (string.startsWith("refl=false,", currIdx)) { allowsReflection = false; currIdx += "refl=false,".length(); // skip ahead } else if (string.startsWith("rots=", currIdx)) { if (string.startsWith("rots=all,", currIdx)) { allowedRotations = null; currIdx += "rots=all,".length(); // skip ahead } else // legal rotations are written as an array, got some work to do { final int rotsListEnd = string.indexOf("]", currIdx); // the following substring includes "rots=[" at the beginning, and "]," at the end String rotsListSubstring = string.substring(currIdx, rotsListEnd + 2); // already move currIdx ahead based on this substring currIdx += rotsListSubstring.length(); // get rid of the unnecessary parts in beginning and end rotsListSubstring = rotsListSubstring.substring("rots=[".length(), rotsListSubstring.length() - "],".length()); // now we can split on "," final String[] rotElements = rotsListSubstring.split(","); allowedRotations = new TFloatArrayList(rotElements.length); for (final String rotElement : rotElements) { allowedRotations.add(Float.parseFloat(rotElement)); } } } else if (string.startsWith("els=", currIdx)) { final int elsListEnd = string.indexOf("]", currIdx); // the following substring includes "els=[" at the beginning, and "]" at the end String elsListSubstring = string.substring(currIdx, elsListEnd + 1); // already move currIdx ahead based on this substring currIdx += elsListSubstring.length(); // get rid of the unnecessary parts in beginning and end elsListSubstring = elsListSubstring.substring("els=[".length(), elsListSubstring.length() - "]".length()); // we don't split on commas, because commas are used both for separating elements AND for // separating steps in a Walk inside the elements // // our first element starts immediately at index 0, and ends when we see a closing curly brace: } // then, we expect a comma and a second element to start after that, etc. final List<String> elements = new ArrayList<String>(); int elsIdx = 0; String elementString = ""; while (elsIdx < elsListSubstring.length()) { final char nextChar = elsListSubstring.charAt(elsIdx); elementString += Character.toString(nextChar); if (nextChar == '}') // finished this element { elements.add(elementString.trim()); elementString = ""; // start creating a new element string elsIdx += 2; // increment by 2 because we expect to see an extra comma which can be skipped } else { elsIdx += 1; } } final List<FeatureElement> list = new ArrayList<FeatureElement>(elements.size()); for (final String element : elements) { list.add(FeatureElement.fromString(element)); } featureElements = list.toArray(new FeatureElement[list.size()]); } else { System.err.println("Error in Pattern(String) constructor: don't know how to handle: " + string.substring(currIdx)); } } } //------------------------------------------------------------------------- /** * @param patterns * @return A new list of patterns where duplicates from the given list are removed. * Whenever there are multiple patterns in the list such that one is strictly a generalization * of the other, the most general pattern will be kept and the more specific one removed. */ public static List<Pattern> deduplicate(List<Pattern> patterns) { final List<Pattern> newPatterns = new ArrayList<Pattern>(patterns.size()); for (final Pattern pattern : patterns) { boolean shouldAdd = true; for (int i = 0; i < newPatterns.size(); /**/) { final Pattern otherPattern = newPatterns.get(i); if (pattern.equals(otherPattern)) { shouldAdd = false; break; } else if (pattern.generalises(otherPattern)) { newPatterns.remove(i); // pattern is more general than otherPattern, so remove otherPattern again } else { ++i; } } if (shouldAdd) { newPatterns.add(pattern); } } return newPatterns; } /** * @param p1 * @param p2 * @return The given two patterns merged into a single one */ public static Pattern merge(final Pattern p1, final Pattern p2) { final FeatureElement[] mergedElements = new FeatureElement[p1.featureElements.length + p2.featureElements.length]; for (int i = 0; i < p1.featureElements.length; ++i) { mergedElements[i] = FeatureElement.copy(p1.featureElements[i]); } for (int i = 0; i < p2.featureElements.length; ++i) { mergedElements[i + p1.featureElements.length] = FeatureElement.copy(p2.featureElements[i]); } final Pattern merged = new Pattern(mergedElements); return merged.allowRotations(p1.allowedRotations).allowRotations(p2.allowedRotations); } //------------------------------------------------------------------------ /** * Adds given new element to this pattern * @param newElement */ public void addElement(final FeatureElement newElement) { final FeatureElement[] temp = Arrays.copyOf(featureElements, featureElements.length + 1); temp[temp.length - 1] = newElement; featureElements = temp; } /** * Sets array of feature elements * @param elements */ public void setFeatureElements(final FeatureElement... elements) { this.featureElements = elements; } /** * @return Array of all feature elements in this pattern */ public FeatureElement[] featureElements() { return featureElements; } /** * Moves all relative elements currently in the pattern one additional step away from * the reference point of the pattern. This additional step is prepended, so * the additional step becomes the first step of every Walk * * @param direction */ public void prependStep(final int direction) { for (final FeatureElement element : featureElements) { if (element instanceof RelativeFeatureElement) { ((RelativeFeatureElement) element).walk().prependStep(direction); } else { System.err.println("Warning: trying to prepend a step to an Absolute Feature Element!"); } } } /** * Prepends all steps of the given walk to all relative elements in this pattern * @param walk */ public void prependWalk(final Walk walk) { for (final FeatureElement featureElement : featureElements) { if (featureElement instanceof RelativeFeatureElement) { final RelativeFeatureElement relativeFeatureEl = (RelativeFeatureElement) featureElement; relativeFeatureEl.walk().prependWalk(walk); } } } /** * Prepends all steps of the given walk to all relative elements in this pattern. * Additionally applies a correction to the first steps of any existing walks, * to make sure that they still continue moving in the same direction they * would have without prepending the new walk. * * @param walk * @param path The path we followed when walking the prepended walk * @param rotToRevert Already-applied rotation which should be reverted * @param refToRevert Already-applied reflection which should be reverted */ public void prependWalkWithCorrection ( final Walk walk, final Path path, final float rotToRevert, final int refToRevert ) { for (final FeatureElement featureElement : featureElements) { if (featureElement instanceof RelativeFeatureElement) { final RelativeFeatureElement relativeFeatureEl = (RelativeFeatureElement) featureElement; relativeFeatureEl.walk().prependWalkWithCorrection(walk, path, rotToRevert, refToRevert); } } } //------------------------------------------------------------------------- /** * Set list of allowed rotations. If the list of allowed rotations was already previously specified, * we will use the intersection of the lists of allowed rotations * * @param allowed * @return this AtomicPattern object */ public Pattern allowRotations(final TFloatArrayList allowed) { if (this.allowedRotations == null) { this.allowedRotations = allowed; } else { this.allowedRotations.retainAll(allowed); } return this; } /** * @param flag Whether or not the Pattern should allow reflection. * @return this Pattern object */ public Pattern allowReflection(final boolean flag) { allowsReflection = flag; return this; } /** * Makes the Pattern auto-rotate to match the mover's direction * @return this Pattern object */ public Pattern matchMoverDirection() { matchMoverDirection = true; return this; } //------------------------------------------------------------------------- /** * @return List of allowed rotations for this pattern */ public TFloatArrayList allowedRotations() { return allowedRotations; } /** * @return Whether we allow reflection of this pattern */ public boolean allowsReflection() { return allowsReflection; } /** * @return Whether the pattern should be rotated to match mover's direction */ public boolean matchesMoverDirection() { return matchMoverDirection; } /** * Sets the list of allowed rotations to the given new list * @param allowedRotations */ public void setAllowedRotations(final TFloatArrayList allowedRotations) { this.allowedRotations = allowedRotations; } //------------------------------------------------------------------------- /** * Applies the given reflection to the complete Pattern. Note that this * modifies the pattern itself! * @param reflection */ public void applyReflection(final int reflection) { if (reflection == 1) { // guess we're doing nothing at all return; } for (final FeatureElement element : featureElements) { if (element instanceof RelativeFeatureElement) { final RelativeFeatureElement rel = (RelativeFeatureElement) element; final TFloatArrayList steps = rel.walk().steps(); for (int i = 0; i < steps.size(); ++i) { steps.setQuick(i, steps.getQuick(i) * reflection); } } } } /** * Applies the given rotation to the complete Pattern. Note that this * modifies the pattern itself! * @param rotation */ public void applyRotation(final float rotation) { for (final FeatureElement element : featureElements) { if (element instanceof RelativeFeatureElement) { final RelativeFeatureElement rel = (RelativeFeatureElement) element; final TFloatArrayList steps = rel.walk().steps(); if (steps.size() > 0) { steps.setQuick(0, steps.getQuick(0) + rotation); } } } } //------------------------------------------------------------------------- /** * We are consistent if, for any pair of feature elements with the same position * (either equal relative Walk or equal absolute position), the elements are either * equal or one of them generalizes the other. * * @return Whether we are consistent */ public boolean isConsistent() { final List<AbsoluteFeatureElement> checkedAbsolutes = new ArrayList<AbsoluteFeatureElement>(); final List<RelativeFeatureElement> checkedRelatives = new ArrayList<RelativeFeatureElement>(); for (final FeatureElement element : featureElements) { if (element instanceof AbsoluteFeatureElement) { final AbsoluteFeatureElement abs = (AbsoluteFeatureElement) element; for (final AbsoluteFeatureElement other : checkedAbsolutes) { if (abs.position() == other.position()) // same positions, so need compatible elements { if (!(abs.equals(other) || abs.isCompatibleWith(other) || abs.generalises(other) || other.generalises(abs))) { return false; } } } checkedAbsolutes.add(abs); } else { final RelativeFeatureElement rel = (RelativeFeatureElement) element; for (final RelativeFeatureElement other : checkedRelatives) { if (rel.walk().equals(other.walk())) // equal Walks, so need compatible elements { if (!(rel.equals(other) || rel.isCompatibleWith(other) || rel.generalises(other) || other.generalises(rel))) { return false; } } } checkedRelatives.add(rel); } } return true; } //------------------------------------------------------------------------- /** * We generalise the other pattern if and only if the following conditions hold: <br> &emsp; * - For every element that we have, there is one in the other pattern that is at least as restrictive <br> &emsp; * - For at least one feature element in the other Pattern, we are strictly less restrictive (otherwise we just equal) <br> &emsp; * <br> * Our list of allowed rotations can also be viewed as "feature elements" in the list of conditions above * * @param other * @return Whether could generalise. */ public boolean generalises(final Pattern other) { boolean foundStrictGeneralisation = false; for (final FeatureElement featureElement : featureElements()) { boolean foundGeneralisation = false; for (final FeatureElement otherElement : other.featureElements()) { if (featureElement.generalises(otherElement)) // found an element that we strictly generalise { foundStrictGeneralisation = true; foundGeneralisation = true; break; } else if (featureElement.equals(otherElement)) // found an element that we equal (non-strict generalisation) { foundGeneralisation = true; break; } } if (!foundGeneralisation) { return false; } } if (other.allowedRotations == null) // other allows ALL rotations { if (allowedRotations != null) // we don't, so we're more restrictive { return false; } } else if (allowedRotations == null) // we allow ALL rotations, and other doesn't, so we have a strict generalisation here { foundStrictGeneralisation = true; } else { for (int i = 0; i < other.allowedRotations().size(); ++i) { final float allowedRotation = other.allowedRotations().getQuick(i); if (!allowedRotations.contains(allowedRotation)) // other allows a rotation that we don't { return false; } } // we have strict generalisation if we allow more rotations than other foundStrictGeneralisation = (allowedRotations.size() > other.allowedRotations().size()); } return foundStrictGeneralisation; } //------------------------------------------------------------------------- /** * Whenever we have multiple elements specifying the same place (either relatively using Walks, * or using absolute positions): * - If they are equal, we keep just one of them, * - If one generalises the other, we keep the most specific one * * If neither of the two conditions above applies, we probably have an inconsistency, * which we won't resolve here. */ public void removeRedundancies() { final List<FeatureElement> newFeatureElements = new ArrayList<FeatureElement>(featureElements.length); for (final FeatureElement element : featureElements) { boolean shouldAdd = true; if (element instanceof AbsoluteFeatureElement) { final AbsoluteFeatureElement abs = (AbsoluteFeatureElement) element; for (int i = 0; i < newFeatureElements.size(); ++i) { final FeatureElement alreadyAdded = newFeatureElements.get(i); if (alreadyAdded instanceof AbsoluteFeatureElement) { final AbsoluteFeatureElement other = (AbsoluteFeatureElement) alreadyAdded; if (abs.position() == other.position()) // same positions { if (abs.equals(other)) // already have this one, no need to add { shouldAdd = false; break; } else if (abs.generalises(other)) // have something more specific, so no need to add { shouldAdd = false; break; } else if (other.generalises(abs)) // have something more general, so we should replace that { newFeatureElements.set(i, abs); // just already added by replacement, so no need to add again shouldAdd = false; break; } } } } } else { final RelativeFeatureElement rel = (RelativeFeatureElement) element; for (int i = 0; i < newFeatureElements.size(); ++i) { final FeatureElement alreadyAdded = newFeatureElements.get(i); if (alreadyAdded instanceof RelativeFeatureElement) { final RelativeFeatureElement other = (RelativeFeatureElement) alreadyAdded; if (rel.walk().equals(other.walk())) // equal walks { if (rel.equals(other)) // already have this one, no need to add { shouldAdd = false; break; } else if (rel.generalises(other)) // have something more specific, so no need to add { shouldAdd = false; break; } else if (other.generalises(rel)) // have something more general, so we should replace that { newFeatureElements.set(i, rel); // just already added by replacement, so no need to add again shouldAdd = false; break; } } } } } if (shouldAdd) { newFeatureElements.add(element); } } featureElements = newFeatureElements.toArray(new FeatureElement[newFeatureElements.size()]); } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; // NOTE: we have custom equals() implementation which makes the order // of allowed rotations and featureElements lists not matter. Our // hashCode() implementation should therefore also be invariant to // order in those lists if (allowedRotations == null) { result = prime * result; } else { int allowedRotsHash = 0; for (int i = 0; i < allowedRotations.size(); ++i) { // XORing them all means order does not matter allowedRotsHash ^= 41 * Float.floatToIntBits(allowedRotations.getQuick(i)); } // adding prime inside brackets because that would also happen // in ArrayList.hashCode() result = prime * result + (prime + allowedRotsHash); } result = prime * result + (allowsReflection ? 1231 : 1237); if (featureElements == null) { result = prime * result; } else { int featureElementsHash = 0; for (final FeatureElement element : featureElements) { // XORing them all means order does not matter featureElementsHash ^= 37 * element.hashCode(); } // adding prime inside brackets because that would also happen in // ArrayList.hashCode() result = prime * result + (prime + featureElementsHash); } result = prime * result + (matchMoverDirection ? 1231 : 1237); return result; } @Override public boolean equals(final Object other) { if (!(other instanceof Pattern)) return false; final Pattern otherPattern = (Pattern) other; // For every feature element, we also need it to be present in other, // and vice versa if (featureElements.length != otherPattern.featureElements.length) return false; for (final FeatureElement element : featureElements) { if (!ArrayUtils.contains(otherPattern.featureElements, element)) return false; } // for (final FeatureElement element : otherPattern.featureElements()) // { // if (!featureElements.contains(element)) // { // return false; // } // } if (otherPattern.allowedRotations == null) { return allowedRotations == null; } else if (allowedRotations == null) { return false; } else { if (allowedRotations.size() != otherPattern.allowedRotations.size()) return false; for (int i = 0; i < otherPattern.allowedRotations().size(); ++i) { if (!allowedRotations.contains(otherPattern.allowedRotations().getQuick(i))) return false; } } return allowsReflection == otherPattern.allowsReflection; } //------------------------------------------------------------------------- /** * equals() method that ignores restrictions on rotation / reflection * * @param other * @return True if, ignoring rotation / reflection, the patterns are equal */ public boolean equalsIgnoreRotRef(final Pattern other) { // for every feature element, we also need it to be present in other, // and vice versa if (featureElements.length != other.featureElements.length) { return false; } for (final FeatureElement element : featureElements) { if (!ArrayUtils.contains(other.featureElements, element)) { return false; } } for (final FeatureElement element : other.featureElements()) { if (!ArrayUtils.contains(featureElements, element)) { return false; } } return allowsReflection == other.allowsReflection; } /** * hashCode() method that ignores restrictions on rotation / reflection * * @return Hash code. */ public int hashCodeIgnoreRotRef() { final int prime = 31; int result = 1; if (featureElements == null) { result = prime * result; } else { int featureElementsHash = 0; for (final FeatureElement element : featureElements) { // XORing them all means order does not matter featureElementsHash ^= element.hashCode(); } // adding prime inside brackets because that would also happen in // ArrayList.hashCode() result = prime * result + (prime + featureElementsHash); } result = prime * result + (matchMoverDirection ? 1231 : 1237); return result; } //------------------------------------------------------------------------- @Override public String toString() { String str = ""; if (!allowsReflection) str += "refl=false,"; String rotsStr; if (allowedRotations != null) { rotsStr = "["; for (int i = 0; i < allowedRotations.size(); ++i) { rotsStr += allowedRotations.getQuick(i); if (i < allowedRotations.size() - 1) { rotsStr += ","; } } rotsStr += "]"; } else { rotsStr = "all"; } if (allowedRotations != null) str += String.format("rots=%s,", rotsStr); str += String.format("els=%s", Arrays.toString(featureElements)); return str; } //------------------------------------------------------------------------- }
24,735
26.0931
133
java
Ludii
Ludii-master/Features/src/features/spatial/RelativeFeature.java
package features.spatial; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import features.spatial.elements.FeatureElement; import features.spatial.elements.RelativeFeatureElement; import game.Game; import gnu.trove.list.array.TFloatArrayList; import main.Constants; import main.math.Point2D; /** * In a Relative Feature, the Action-to-play is implied by * relative "from" and "to" Walks (sometimes only a "to" Walk) * * @author Dennis Soemers */ public class RelativeFeature extends SpatialFeature { //------------------------------------------------------------------------- /** Relative position that we want to move to */ protected final Walk toPosition; /** * Relative position that we want to move from (null in cases where * there is no from position, or where it's not restricted) */ protected final Walk fromPosition; /** * Relative position that was moved to last * (null for proactive features) */ protected final Walk lastToPosition; /** * Relative position that was last moved from (null for proactive features * and in cases where we don't care about restricting from-positions) */ protected final Walk lastFromPosition; //------------------------------------------------------------------------- /** * Constructor * @param pattern * @param toPosition * @param fromPosition */ public RelativeFeature ( final Pattern pattern, final Walk toPosition, final Walk fromPosition ) { this.pattern = pattern; this.toPosition = toPosition; this.fromPosition = fromPosition; this.lastToPosition = null; this.lastFromPosition = null; } /** * Constructor * @param pattern * @param toPosition * @param fromPosition * @param lastToPosition * @param lastFromPosition */ public RelativeFeature ( final Pattern pattern, final Walk toPosition, final Walk fromPosition, final Walk lastToPosition, final Walk lastFromPosition ) { this.pattern = pattern; this.toPosition = toPosition; this.fromPosition = fromPosition; this.lastToPosition = lastToPosition; this.lastFromPosition = lastFromPosition; } /** * Copy constructor * @param other */ public RelativeFeature(final RelativeFeature other) { this.pattern = new Pattern(other.pattern); this.toPosition = other.toPosition == null ? null : new Walk(other.toPosition); this.fromPosition = other.fromPosition == null ? null : new Walk(other.fromPosition); this.lastToPosition = other.lastToPosition == null ? null : new Walk(other.lastToPosition); this.lastFromPosition = other.lastFromPosition == null ? null : new Walk(other.lastFromPosition); // this.comment = new String(other.comment); } /** * Constructor from string * @param string */ public RelativeFeature(final String string) { final String[] parts = string.split(":"); // need these because we're not allowed to assign value to // final members inside a loop Walk toPos = null; Walk fromPos = null; Walk lastToPos = null; Walk lastFromPos = null; for (String part : parts) { if (part.startsWith("last_to=<")) { part = part.substring( "last_to=<".length(), part.length() - ">".length()); lastToPos = new Walk(part); } else if (part.startsWith("last_from=<")) { part = part.substring( "last_from=<".length(), part.length() - ">".length()); lastFromPos = new Walk(part); } else if (part.startsWith("to=<")) { part = part.substring( "to=<".length(), part.length() - ">".length()); toPos = new Walk(part); } else if (part.startsWith("from=<")) { part = part.substring( "from=<".length(), part.length() - ">".length()); fromPos = new Walk(part); } else if (part.startsWith("pat=<")) { part = part.substring( "pat=<".length(), part.length() - ">".length()); pattern = new Pattern(part); } else if (part.startsWith("comment=\"")) { part = part.substring( "comment=\"".length(), part.length() - "\"".length()); // comment = part; } } toPosition = toPos; fromPosition = fromPos; lastToPosition = lastToPos; lastFromPosition = lastFromPos; } //------------------------------------------------------------------------- /** * @return Relative to-position */ public Walk toPosition() { return toPosition; } /** * @return Relative from-position */ public Walk fromPosition() { return fromPosition; } /** * @return Relative last-to position */ public Walk lastToPosition() { return lastToPosition; } /** * @return Relative last-from position */ public Walk lastFromPosition() { return lastFromPosition; } @Override public boolean isReactive() { return lastToPosition != null || lastFromPosition != null; } //------------------------------------------------------------------------- @Override public SpatialFeature rotatedCopy(final float rotation) { final RelativeFeature copy = new RelativeFeature(this); if (copy.toPosition != null) { if (copy.toPosition().steps().size() > 0) { copy.toPosition().steps().setQuick( 0, copy.toPosition().steps().getQuick(0) + rotation); } } if (copy.fromPosition != null) { if (copy.fromPosition().steps().size() > 0) { copy.fromPosition().steps().setQuick( 0, copy.fromPosition().steps().getQuick(0) + rotation); } } if (copy.lastToPosition != null) { if (copy.lastToPosition().steps().size() > 0) { copy.lastToPosition().steps().setQuick( 0, copy.lastToPosition().steps().getQuick(0) + rotation); } } if (copy.lastFromPosition != null) { if (copy.lastFromPosition().steps().size() > 0) { copy.lastFromPosition().steps().setQuick( 0, copy.lastFromPosition().steps().getQuick(0) + rotation); } } for (final FeatureElement element : copy.pattern().featureElements()) { if (element instanceof RelativeFeatureElement) { final RelativeFeatureElement rel = (RelativeFeatureElement) element; if (rel.walk().steps().size() > 0) { rel.walk().steps().setQuick( 0, rel.walk().steps().getQuick(0) + rotation); } } } return copy; } @Override public SpatialFeature reflectedCopy() { final RelativeFeature copy = new RelativeFeature(this); if (copy.toPosition != null) { final TFloatArrayList steps = copy.toPosition.steps(); for (int i = 0; i < steps.size(); ++i) { steps.setQuick(i, steps.getQuick(i) * -1); } } if (copy.fromPosition != null) { final TFloatArrayList steps = copy.fromPosition.steps(); for (int i = 1; i < steps.size(); ++i) { steps.setQuick(i, steps.getQuick(i) * -1); } } if (copy.lastToPosition != null) { final TFloatArrayList steps = copy.lastToPosition.steps(); for (int i = 1; i < steps.size(); ++i) { steps.setQuick(i, steps.getQuick(i) * -1); } } if (copy.lastFromPosition != null) { final TFloatArrayList steps = copy.lastFromPosition.steps(); for (int i = 1; i < steps.size(); ++i) { steps.setQuick(i, steps.getQuick(i) * -1); } } for (final FeatureElement element : copy.pattern().featureElements()) { if (element instanceof RelativeFeatureElement) { final RelativeFeatureElement rel = (RelativeFeatureElement) element; final TFloatArrayList steps = rel.walk().steps(); for (int i = 1; i < steps.size(); ++i) { steps.setQuick(i, steps.getQuick(i) * -1); } } } return copy; } @Override public boolean generalises(final SpatialFeature other) { if (!(other instanceof RelativeFeature)) { return false; } final RelativeFeature otherFeature = (RelativeFeature) other; boolean foundStrictGeneralization = false; if (toPosition != null) { if (!(toPosition.equals(otherFeature.toPosition))) { return false; } } else if (otherFeature.toPosition == null) { return false; } if (fromPosition != null) { if (!(fromPosition.equals(otherFeature.fromPosition))) { return false; } } else if (otherFeature.fromPosition == null) { return false; } if (lastToPosition != null) { if (!(lastToPosition.equals(otherFeature.lastToPosition))) { return false; } } else if (otherFeature.lastToPosition == null) { return false; } if (lastFromPosition != null) { if (!(lastFromPosition.equals(otherFeature.lastFromPosition))) { return false; } } else if (otherFeature.lastFromPosition == null) { return false; } if (pattern.generalises(otherFeature.pattern)) { foundStrictGeneralization = true; } else if (!(pattern.equals(otherFeature.pattern))) { return false; } return foundStrictGeneralization; } //------------------------------------------------------------------------- @Override public List<SpatialFeature> generateGeneralisers ( final Game game, final Set<RotRefInvariantFeature> generalisers, final int numRecursions ) { if (toPosition != null && fromPosition != null) { // We can generalise by removing either the to- or the from-specifier addGeneraliser ( new RelativeFeature ( new Pattern(pattern), new Walk(toPosition), null, lastToPosition == null ? null : new Walk(lastToPosition), lastFromPosition == null ? null : new Walk(lastFromPosition) ), game, generalisers, numRecursions ); addGeneraliser ( new RelativeFeature ( new Pattern(pattern), null, new Walk(fromPosition), lastToPosition == null ? null : new Walk(lastToPosition), lastFromPosition == null ? null : new Walk(lastFromPosition) ), game, generalisers, numRecursions ); } if (lastToPosition != null) { // We can generalise by removing last-to requirement addGeneraliser ( new RelativeFeature ( new Pattern(pattern), toPosition == null ? null : new Walk(toPosition), fromPosition == null ? null : new Walk(fromPosition), null, lastFromPosition == null ? null : new Walk(lastFromPosition) ), game, generalisers, numRecursions ); } if (lastFromPosition != null) { // We can generalise by removing last-to requirement addGeneraliser ( new RelativeFeature ( new Pattern(pattern), toPosition == null ? null : new Walk(toPosition), fromPosition == null ? null : new Walk(fromPosition), lastToPosition == null ? null : new Walk(lastToPosition), null ), game, generalisers, numRecursions ); } final FeatureElement[] patternElements = pattern.featureElements(); for (int i = 0; i < patternElements.length; ++i) { // We can generalise by removing the ith element of the pattern final FeatureElement[] newElements = new FeatureElement[patternElements.length - 1]; int nextIdx = 0; for (int j = 0; j < patternElements.length; ++j) { if (j != i) newElements[nextIdx++] = FeatureElement.copy(patternElements[j]); } final RelativeFeature newFeature = new RelativeFeature ( new Pattern(newElements), toPosition == null ? null : new Walk(toPosition), fromPosition == null ? null : new Walk(fromPosition), lastToPosition == null ? null : new Walk(lastToPosition), lastFromPosition == null ? null : new Walk(lastFromPosition) ); newFeature.pattern().setAllowedRotations(pattern.allowedRotations()); addGeneraliser(newFeature, game, generalisers, numRecursions); } final List<SpatialFeature> outList = new ArrayList<SpatialFeature>(generalisers.size()); for (final RotRefInvariantFeature f : generalisers) { outList.add(f.feature()); } return outList; } /** * Helper method to add generaliser for given game to given set of generalisers. * May not add it if it's equivalent to another feature already in the list. * * @param generaliser * @param game * @param generalisers * @param numRecursions */ private static void addGeneraliser ( final RelativeFeature generaliser, final Game game, final Set<RotRefInvariantFeature> generalisers, final int numRecursions ) { generaliser.normalise(game); if (generalisers.add(new RotRefInvariantFeature(generaliser))) { if (numRecursions > 0) { // Also add generalisers of the generaliser generaliser.generateGeneralisers(game, generalisers, numRecursions - 1); } } } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((fromPosition == null) ? 0 : fromPosition.hashCode()); result = prime * result + ((toPosition == null) ? 0 : toPosition.hashCode()); result = prime * result + ((lastFromPosition == null) ? 0 : lastFromPosition.hashCode()); result = prime * result + ((lastToPosition == null) ? 0 : lastToPosition.hashCode()); return result; } @Override public boolean equals(final Object other) { if (!super.equals(other)) return false; if (!(other instanceof RelativeFeature)) return false; final RelativeFeature otherFeature = (RelativeFeature) other; // the extra == checks are because positions may be null, which is // fine if they are null for both features return ( toPosition == otherFeature.toPosition || ( toPosition != null && toPosition.equals(otherFeature.toPosition) ) ) && ( fromPosition == otherFeature.fromPosition || ( fromPosition != null && fromPosition.equals(otherFeature.fromPosition) ) ) && ( lastToPosition == otherFeature.lastToPosition || ( lastToPosition != null && lastToPosition.equals(otherFeature.lastToPosition) ) ) && ( lastFromPosition == otherFeature.lastFromPosition || ( lastFromPosition != null && lastFromPosition.equals(otherFeature.lastFromPosition) ) ); } @Override public boolean equalsIgnoreRotRef(final SpatialFeature other) { if (! super.equalsIgnoreRotRef(other)) return false; if (!(other instanceof RelativeFeature)) return false; final RelativeFeature otherFeature = (RelativeFeature) other; // the extra == checks are because positions may be null, which is // fine if they are null for both features return ( toPosition == otherFeature.toPosition || ( toPosition != null && toPosition.equals(otherFeature.toPosition) ) ) && ( fromPosition == otherFeature.fromPosition || ( fromPosition != null && fromPosition.equals(otherFeature.fromPosition) ) ) && ( lastToPosition == otherFeature.lastToPosition || ( lastToPosition != null && lastToPosition.equals(otherFeature.lastToPosition) ) ) && ( lastFromPosition == otherFeature.lastFromPosition || ( lastFromPosition != null && lastFromPosition.equals(otherFeature.lastFromPosition) ) ); } @Override public int hashCodeIgnoreRotRef() { final int prime = 31; int result = super.hashCodeIgnoreRotRef(); result = prime * result + ((fromPosition == null) ? 0 : fromPosition.hashCode()); result = prime * result + ((toPosition == null) ? 0 : toPosition.hashCode()); result = prime * result + ((lastFromPosition == null) ? 0 : lastFromPosition.hashCode()); result = prime * result + ((lastToPosition == null) ? 0 : lastToPosition.hashCode()); return result; } //------------------------------------------------------------------------- @Override public String toString() { String str = String.format("pat=<%s>", pattern); if (toPosition != null) { str = String.format("to=<%s>:%s", toPosition, str); } if (fromPosition != null) { str = String.format("from=<%s>:%s", fromPosition, str); } if (lastToPosition != null) { str = String.format("last_to=<%s>:%s", lastToPosition, str); } if (lastFromPosition != null) { str = String.format("last_from=<%s>:%s", lastFromPosition, str); } // if (comment.length() > 0) // { // str = String.format("%s:comment=\"%s\"", str, comment); // } return "rel:" + str; } //------------------------------------------------------------------------- @Override public String generateTikzCode(final Game game) { final Map<TFloatArrayList, List<String>> stringsPerWalk = new HashMap<TFloatArrayList, List<String>>(); // Anchor stringsPerWalk.put(new TFloatArrayList(), new ArrayList<String>()); stringsPerWalk.get(new TFloatArrayList()).add(""); if (toPosition != null) { final TFloatArrayList key = toPosition.steps(); List<String> strings = stringsPerWalk.get(key); if (strings == null) { strings = new ArrayList<String>(); stringsPerWalk.put(key, strings); } strings.add("To"); } if (fromPosition != null) { final TFloatArrayList key = fromPosition.steps(); List<String> strings = stringsPerWalk.get(key); if (strings == null) { strings = new ArrayList<String>(); stringsPerWalk.put(key, strings); } strings.add("From"); } if (lastToPosition != null) { final TFloatArrayList key = lastToPosition.steps(); List<String> strings = stringsPerWalk.get(key); if (strings == null) { strings = new ArrayList<String>(); stringsPerWalk.put(key, strings); } strings.add("Last To"); } if (lastFromPosition != null) { final TFloatArrayList key = lastFromPosition.steps(); List<String> strings = stringsPerWalk.get(key); if (strings == null) { strings = new ArrayList<String>(); stringsPerWalk.put(key, strings); } strings.add("Last From"); } for (final FeatureElement el : pattern.featureElements()) { final TFloatArrayList key = ((RelativeFeatureElement)el).walk().steps(); List<String> strings = stringsPerWalk.get(key); if (strings == null) { strings = new ArrayList<String>(); stringsPerWalk.put(key, strings); } strings.add((el.not() ? "!" : "") + el.type().label + (el.itemIndex() >= 0 ? String.valueOf(el.itemIndex()) : "")); } final StringBuilder sb = new StringBuilder(); final List<Point2D> points = new ArrayList<Point2D>(); final List<String> labels = new ArrayList<String>(); final List<List<String>> stringsPerPoint = new ArrayList<List<String>>(); final Map<List<String>, String> connections = new HashMap<List<String>, String>(); // Start with node for anchor sb.append("\\node[ellipse, draw, align=center] (Anchor) at (0,0) {"); final List<String> anchorStrings = stringsPerWalk.get(new TFloatArrayList()); while (anchorStrings.remove("")) { /** Keep going */ } // for (int i = 0; i < anchorStrings.size(); ++i) // { // if (i > 0) // sb.append("\\\\"); // sb.append(anchorStrings.get(i)); // } sb.append("{POINT_STRINGS_" + points.size() + "}"); sb.append("}; \n"); points.add(new Point2D(0.0, 0.0)); labels.add("(Anchor)"); stringsPerPoint.add(anchorStrings); final double STEP_SIZE = 2.0; int nextLabelIdx = 1; for (final Entry<TFloatArrayList, List<String>> entry : stringsPerWalk.entrySet()) { final TFloatArrayList walk = entry.getKey(); String currLabel = "(Anchor)"; double x = 0.0; double y = 0.0; double currTheta = 0.5 * Math.PI; final TFloatArrayList partialWalk = new TFloatArrayList(); for (int i = 0; i < walk.size(); ++i) { final float step = walk.getQuick(i); partialWalk.add(step); currTheta -= step * 2.0 * Math.PI; x += STEP_SIZE * Math.cos(currTheta); y += STEP_SIZE * Math.sin(currTheta); final Point2D currPoint = new Point2D(x, y); String nextLabel = null; List<String> pointStrings = null; for (int j = 0; j < points.size(); ++j) { if (points.get(j).equalsApprox(currPoint, Constants.EPSILON)) { nextLabel = labels.get(j); pointStrings = stringsPerPoint.get(j); break; } } if (nextLabel == null) { nextLabel = "(N" + (nextLabelIdx++) + ")"; // Need to draw a node for this partial walk // final StringBuilder nodeText = new StringBuilder(); // final List<String> walkStrings = stringsPerWalk.get(partialWalk); // // if (walkStrings != null) // { // while (walkStrings.remove("")) { /** Keep going */ } // for (int j = 0; j < walkStrings.size(); ++j) // { // if (j > 0) // nodeText.append("\\\\"); // nodeText.append(walkStrings.get(j)); // } // } sb.append("\\node[ellipse, draw, align=center] " + nextLabel + " at (" + x + ", " + y + ") {{POINT_STRINGS_" + points.size() + "}}; \n"); points.add(currPoint); labels.add(nextLabel); pointStrings = new ArrayList<String>(); stringsPerPoint.add(pointStrings); } final List<String> walkStrings = stringsPerWalk.get(partialWalk); if (walkStrings != null) { while (walkStrings.remove("")) { /** Keep going */ } for (final String walkString : walkStrings) { if (!pointStrings.contains(walkString)) pointStrings.add(walkString); } } connections.put(Arrays.asList(new String[] {currLabel, nextLabel}), "$" + new DecimalFormat("#.##").format(step) + "$"); currLabel = nextLabel; } } for (final Entry<List<String>, String> connection : connections.entrySet()) { sb.append("\\path[->,draw] " + connection.getKey().get(0) + " edge node {" + connection.getValue() + "} " + connection.getKey().get(1) + "; \n"); } String returnStr = sb.toString(); for (int i = 0; i < points.size(); ++i) { final StringBuilder replaceStr = new StringBuilder(); for (int j = 0; j < stringsPerPoint.get(i).size(); ++j) { if (j > 0) replaceStr.append("\\\\"); replaceStr.append(stringsPerPoint.get(i).get(j)); } returnStr = returnStr.replaceFirst ( java.util.regex.Pattern.quote("{POINT_STRINGS_" + i + "}"), java.util.regex.Matcher.quoteReplacement(replaceStr.toString()) ); } returnStr = returnStr.replaceAll ( java.util.regex.Pattern.quote("#"), java.util.regex.Matcher.quoteReplacement("\\#") ); return returnStr; } //------------------------------------------------------------------------- }
23,016
22.951093
148
java
Ludii
Ludii-master/Features/src/features/spatial/SpatialFeature.java
package features.spatial; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import features.Feature; import features.spatial.elements.AbsoluteFeatureElement; import features.spatial.elements.FeatureElement; import features.spatial.elements.FeatureElement.ElementType; import features.spatial.elements.RelativeFeatureElement; import features.spatial.graph_search.GraphSearch; import features.spatial.graph_search.Path; import features.spatial.instances.FeatureInstance; import game.Game; import game.types.board.SiteType; import game.util.directions.AbsoluteDirection; import game.util.graph.GraphElement; import game.util.graph.Radial; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TFloatIntMap; import gnu.trove.map.hash.TFloatIntHashMap; import other.state.container.ContainerState; import other.topology.Topology; import other.topology.TopologyElement; /** * Geometric features contain a Pattern that can be matched to parts of the board, and * some description of an action to play. * * @author Dennis Soemers */ public abstract class SpatialFeature extends Feature { //------------------------------------------------------------------------- /** Different types of BitSets we may want to compare against. */ public static enum BitSetTypes { /** Empty ChunkSet */ Empty, /** Who ChunkSet */ Who, /** What ChunkSet */ What, /** If we don't want to do anything */ None; } //------------------------------------------------------------------------- /** The feature's pattern */ protected Pattern pattern; /** The graph element type this feature applies to. Tries to auto-detect for game if null */ protected SiteType graphElementType = null; /** * Feature Sets will set this index to be the index that the feature has inside * its Feature Set This member is not really a "part" of the feature, and is * therefore not used in methods such as equals() and hashCode(). */ protected int spatialFeatureSetIndex = -1; // /** Optional comment */ // protected String comment = ""; //------------------------------------------------------------------------- /** * @return The feature's pattern */ public Pattern pattern() { return pattern; } //------------------------------------------------------------------------- /** * @return Index in our feature set */ public int spatialFeatureSetIndex() { return spatialFeatureSetIndex; } /** * Sets index in our feature set * @param newIdx */ public void setSpatialFeatureSetIndex(final int newIdx) { spatialFeatureSetIndex = newIdx; } /** * @return Is this a reactive feature (with specifiers for last-from * and/or last-to position)? */ @SuppressWarnings("static-method") public boolean isReactive() { return false; } //------------------------------------------------------------------------- /** * @param rotation * @return Copy of this feature with the given rotation applied */ public abstract SpatialFeature rotatedCopy(final float rotation); /** * @return Copy of this feature, with reflection applied */ public abstract SpatialFeature reflectedCopy(); /** * @param other * @return True if we generalise the given other feature */ public abstract boolean generalises(final SpatialFeature other); //------------------------------------------------------------------------- /** * Creates all possible instances for this feature * * @param game * @param container * @param player Player for whom to create the feature instance * @param anchorConstraint Constraint on anchor position (-1 if no constraint) * @param fromPosConstraint Constraint on absolute from-position (-1 if no constraint) * @param toPosConstraint Constraint on absolute to-position (-1 if no constraint) * @param lastFromConstraint Constraint on absolute last-from-position (-1 if no constraint) * @param lastToConstraint Constraint on absolute last-to-position (-1 if no constraint) * @return List of possible feature instances */ public final List<FeatureInstance> instantiateFeature ( final Game game, final ContainerState container, final int player, final int anchorConstraint, final int fromPosConstraint, final int toPosConstraint, final int lastFromConstraint, final int lastToConstraint ) { final Topology topology = game.board().topology(); final SiteType instanceType; if (graphElementType != null) instanceType = graphElementType; else if (game.board().defaultSite() == SiteType.Vertex) instanceType = SiteType.Vertex; else instanceType = SiteType.Cell; final List<FeatureInstance> instances = new ArrayList<FeatureInstance>(); final int[] reflections = pattern.allowsReflection() ? new int[]{ 1, -1 } : new int[]{ 1 }; // for every site, we want to try creating feature instances with that site as // anchor position final List<? extends TopologyElement> sites = game.graphPlayElements(); boolean moreSitesRelevant = true; int siteIdx = (anchorConstraint >= 0) ? anchorConstraint : 0; for (/** */; siteIdx < sites.size(); ++siteIdx) { if (anchorConstraint >= 0 && anchorConstraint != siteIdx) break; final TopologyElement anchorSite = sites.get(siteIdx); if (anchorSite.sortedOrthos().length == 0) continue; // No point in using this as an anchor TFloatArrayList rots = pattern.allowedRotations(); if (rots == null) rots = Walk.rotationsForNumOrthos(anchorSite.sortedOrthos().length); if (rots.size() == 0) System.err.println("Warning: rots.size() == 0 in Feature.instantiateFeature()"); // test all allowed multipliers due to reflection for (final int reflectionMult : reflections) { boolean moreReflectionsRelevant = false; // test every rotation for (int rotIdx = 0; rotIdx < rots.size(); ++rotIdx) { boolean moreRotationsRelevant = false; final float rot = rots.get(rotIdx); boolean allElementsAbsolute = true; // first compute instances with resolved action positions final List<FeatureInstance> instancesWithActions = new ArrayList<FeatureInstance>(1); final FeatureInstance baseInstance = new FeatureInstance(this, siteIdx, reflectionMult, rot, instanceType); if (this instanceof AbsoluteFeature) { // this case is easy, actions specified in terms of absolute positions final AbsoluteFeature absThis = (AbsoluteFeature) this; if (toPosConstraint < 0 || toPosConstraint == absThis.toPosition) { if (fromPosConstraint < 0 || fromPosConstraint == absThis.fromPosition) { baseInstance.setAction(absThis.toPosition, absThis.fromPosition); baseInstance.setLastAction(absThis.lastToPosition, absThis.lastFromPosition); instancesWithActions.add(baseInstance); } } } else { // this is the hard case, we'll have to follow along any non-null Walks // like the Walks above, these can split up again in cells with odd edge counts final RelativeFeature relThis = (RelativeFeature) this; final Walk toWalk = relThis.toPosition; final Walk fromWalk = relThis.fromPosition; final Walk lastToWalk = relThis.lastToPosition; final Walk lastFromWalk = relThis.lastFromPosition; // need to walk the last-to-Walk TIntArrayList possibleLastToPositions; if (lastToWalk == null) { possibleLastToPositions = TIntArrayList.wrap(-1); } else { possibleLastToPositions = lastToWalk.resolveWalk(game, anchorSite, rot, reflectionMult); final TFloatArrayList steps = lastToWalk.steps(); if (steps.size() > 0) { // we actually do have a meaningful Walk, // so rotations will change things moreRotationsRelevant = true; // reflections become relevant if we // have non-0, non-0.5 turns if (!moreReflectionsRelevant) { for (int step = 0; step < steps.size(); ++step) { final float turn = steps.getQuick(step); if (turn != 0.f && turn != 0.5f && turn != -0.5f) { moreReflectionsRelevant = true; } } } } } for (int lastToPosIdx = 0; lastToPosIdx < possibleLastToPositions.size(); ++lastToPosIdx) { final int lastToPos = possibleLastToPositions.getQuick(lastToPosIdx); if ( (lastToWalk == null || lastToPos >= 0) && (lastToConstraint < 0 || lastToPos < 0 || lastToPos == lastToConstraint) ) { // need to walk the last-from-Walk TIntArrayList possibleLastFromPositions; if (lastFromWalk == null) { possibleLastFromPositions = TIntArrayList.wrap(-1); } else { possibleLastFromPositions = lastFromWalk.resolveWalk(game, anchorSite, rot, reflectionMult); final TFloatArrayList steps = lastFromWalk.steps(); if (steps.size() > 0) { // we actually do have a meaningful // Walk, so rotations will change things moreRotationsRelevant = true; // reflections become relevant if we // have non-0, non-0.5 turns if (!moreReflectionsRelevant) { for (int step = 0; step < steps.size(); ++step) { final float turn = steps.getQuick(step); if (turn != 0.f && turn != 0.5f && turn != -0.5f) { moreReflectionsRelevant = true; } } } } } for (int lastFromPosIdx = 0; lastFromPosIdx < possibleLastFromPositions.size(); ++lastFromPosIdx) { final int lastFromPos = possibleLastFromPositions.getQuick(lastFromPosIdx); if ( (lastFromWalk == null || lastFromPos >= 0) && (lastFromConstraint < 0 || lastFromPos < 0 || lastFromPos == lastFromConstraint) ) { // need to walk the to-Walk TIntArrayList possibleToPositions; if (toWalk == null) { possibleToPositions = TIntArrayList.wrap(-1); } else { possibleToPositions = toWalk.resolveWalk(game, anchorSite, rot, reflectionMult); final TFloatArrayList steps = toWalk.steps(); if (steps.size() > 0) { // we actually do have a // meaningful Walk, so rotations // will change things moreRotationsRelevant = true; // reflections become relevant // if we have non-0, // non-0.5 turns if (!moreReflectionsRelevant) { for (int step = 0; step < steps.size(); ++step) { final float turn = steps.getQuick(step); if (turn != 0.f && turn != 0.5f && turn != -0.5f) { moreReflectionsRelevant = true; } } } } } for (int toPosIdx = 0; toPosIdx < possibleToPositions.size(); ++toPosIdx) { final int toPos = possibleToPositions.getQuick(toPosIdx); if (toPos == -1 && toWalk != null) continue; if (toPosConstraint >= 0 && toPos >= 0 && toPosConstraint != toPos) continue; // need to walk the from-Walk TIntArrayList possibleFromPositions; if (fromWalk == null) { possibleFromPositions = TIntArrayList.wrap(-1); } else { possibleFromPositions = fromWalk.resolveWalk( game, anchorSite, rot, reflectionMult); final TFloatArrayList steps = fromWalk.steps(); if (steps.size() > 0) { // we actually do have a meaningful Walk, // so rotations will change things moreRotationsRelevant = true; // reflections become relevant if we // have non-0, non-0.5 turns if (!moreReflectionsRelevant) { for (int step = 0; step < steps.size(); ++step) { final float turn = steps.getQuick(step); if (turn != 0.f && turn != 0.5f && turn != -0.5f) { moreReflectionsRelevant = true; } } } } } for (int fromPosIdx = 0; fromPosIdx < possibleFromPositions.size(); ++fromPosIdx) { final int fromPos = possibleFromPositions.getQuick(fromPosIdx); if (fromPos == -1 && fromWalk != null) continue; if (fromPosConstraint >= 0 && fromPos >= 0 && fromPosConstraint != fromPos) continue; final FeatureInstance newInstance = new FeatureInstance(baseInstance); newInstance.setAction(toPos, fromPos); newInstance.setLastAction(lastToPos, lastFromPos); instancesWithActions.add(newInstance); } } } } } } } // try to make the pattern fit // // we'll usually just be creating a single new instance here, but on boards // with cells with odd numbers of edges (e.g. triangular cells), every step of // a Walk (except for the first step) can get split up into two different // positions. List<FeatureInstance> instancesWithElements = new ArrayList<FeatureInstance>(instancesWithActions); for (final FeatureElement element : pattern.featureElements()) { final List<FeatureInstance> replaceNewInstances = new ArrayList<FeatureInstance>(instancesWithElements.size()); if (element instanceof RelativeFeatureElement) allElementsAbsolute = false; for (final FeatureInstance instance : instancesWithElements) // usually just size 1 { // first determine where we're testing for something TIntArrayList testSites = new TIntArrayList(1); // usually just a single site if (element instanceof AbsoluteFeatureElement) { final AbsoluteFeatureElement absElement = (AbsoluteFeatureElement) element; testSites.add(absElement.position()); } else { final RelativeFeatureElement relElement = (RelativeFeatureElement) element; // need to walk the Walk testSites = relElement.walk().resolveWalk(game, anchorSite, rot, reflectionMult); final TFloatArrayList steps = relElement.walk().steps(); if (steps.size() > 0) { // we actually do have a meaningful Walk, // so rotations will change things moreRotationsRelevant = true; // reflections become relevant if we // have non-0, non-0.5 turns if (!moreReflectionsRelevant) { for (int step = 0; step < steps.size(); ++step) { final float turn = steps.getQuick(step); if (turn != 0.f && turn != 0.5f && turn != -0.5f) { moreReflectionsRelevant = true; } } } } } // for every possible site that our Walk might be specifying, check the type for (int testSiteIdx = 0; testSiteIdx < testSites.size(); ++testSiteIdx) { final int testSite = testSites.getQuick(testSiteIdx); final ElementType type = element.type(); if (type == ElementType.Empty) // entry in "empty" BitSet must (not) be on { if (testSite >= 0) { final FeatureInstance newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.Empty, testSite, !element.not())) { replaceNewInstances.add(newInstance); } } else if (element.not()) // off board is also not empty { final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } } else if (type == ElementType.Friend) // entry in "who" BitSetS must (not) equal the player { if (testSite >= 0) { final FeatureInstance newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.Who, testSite, !element.not(), player)) { replaceNewInstances.add(newInstance); } } else if (element.not()) // off board is also not a friend { final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } } else if (type == ElementType.Enemy) { if (element.not()) { // we'll have to split up into an // off-board detector, // an empty detector, // and a friend detector if (testSite < 0) { // off-board already detected, // no more test needed final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } else { if (game.players().count() == 2) { // SPECIAL CASE: in 2-player // games, we can just directly // test for not-enemy final FeatureInstance newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.Who, testSite, false, player == 1 ? 2 : 1)) { replaceNewInstances.add(newInstance); } } else { // more than two players, so // need separate checks for // empty and friend FeatureInstance newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.Empty, testSite, true)) { replaceNewInstances.add(newInstance); } newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.Who, testSite, true, player)) { replaceNewInstances.add(newInstance); } } } } else if (testSite >= 0) { if (game.players().count() == 2) { // SPECIAL case: in 2-player // games, we can just test for // enemy directly final FeatureInstance newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.Who, testSite, true, player == 1 ? 2 : 1)) { replaceNewInstances.add(newInstance); } } else { // game with more than 2 players; // need an instance that tests for // not-empty as well as not-player final FeatureInstance newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.Empty, testSite, false)) { if (newInstance.addTest(container, BitSetTypes.Who, testSite, false, player)) { replaceNewInstances.add(newInstance); } } } } } else if (type == ElementType.Off) { if (testSite < 0 != element.not()) { // already performed our off-board check final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } } else if (type == ElementType.Any) { // anything is fine final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } else if (type == ElementType.P1) { if (testSite >= 0) { final FeatureInstance newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.Who, testSite, !element.not(), 1)) { replaceNewInstances.add(newInstance); } } else if (element.not()) // off board is also not player 1 { final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } } else if (type == ElementType.P2) { if (testSite >= 0) { final FeatureInstance newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.Who, testSite, !element.not(), 2)) { replaceNewInstances.add(newInstance); } } else if (element.not()) // off board is also not player 2 { final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } } else if (type == ElementType.Item) { if (testSite >= 0) { final FeatureInstance newInstance = new FeatureInstance(instance); if (newInstance.addTest(container, BitSetTypes.What, testSite, !element.not(), element.itemIndex())) { replaceNewInstances.add(newInstance); } } else if (element.not()) // off board is also not an item { final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } } else if (type == ElementType.IsPos) { if ((testSite == element.itemIndex()) != element.not()) // test has already succeeded! { final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } // else the test has already failed! } else if (type == ElementType.Connectivity) { if (testSite >= 0 && (sites.get(testSite).sortedOrthos().length == element.itemIndex())) { // Test succeeds if we either have or do not have the correct connectivity // (depending on element's not-flag) if ((sites.get(testSite).sortedOrthos().length == element.itemIndex()) != element.not()) { final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } } } else if (type == ElementType.RegionProximity) { // Test succeeds if we're (not) closer to specific region than the anchor position // (which is at index siteIdx) // Either test will always fail for off-board positions if (testSite >= 0) { final int[] distances = game.distancesToRegions()[element.itemIndex()]; final int anchorDist = distances[siteIdx]; final int testSiteDist = distances[testSite]; if ((anchorDist > testSiteDist) != element.not()) { // Test passed final FeatureInstance newInstance = new FeatureInstance(instance); newInstance.addInitTimeElement(element); replaceNewInstances.add(newInstance); } } } else if (type == ElementType.LineOfSightOrth) { if (!element.not()) { // We want a specific piece in orthogonal LOS if (testSite >= 0) { // There's lots of new instances we can create here, for every orth. radial: // - An instance that just directly wants a piece of given type next to us // - An instance that first wants one empty site, and then a piece // - An instance that first wants two empty sites, and then a piece // - etc... final TIntArrayList runningMustEmptiesList = new TIntArrayList(); for (final Radial radial : topology.trajectories().radials(instanceType, testSite, AbsoluteDirection.Orthogonal)) { final GraphElement[] steps = radial.steps(); for (int stepIdx = 1; stepIdx < steps.length; ++stepIdx) { // Create a feature instance with piece at stepIdx, and everything else leading up to it empty final FeatureInstance newInstance = new FeatureInstance(instance); boolean failure = (!newInstance.addTest(container, BitSetTypes.What, steps[stepIdx].id(), true, element.itemIndex())); for (int emptyStepIdx = 0; emptyStepIdx < runningMustEmptiesList.size(); ++emptyStepIdx) { // See if we can successfully add next must-empty requirement failure = ( failure || ( !newInstance.addTest ( container, BitSetTypes.Empty, runningMustEmptiesList.getQuick(emptyStepIdx), true ) ) ); } if (!failure) replaceNewInstances.add(newInstance); // All other instances we add will have this step as must-empty runningMustEmptiesList.add(steps[stepIdx].id()); } } } } else { // We do NOT want a specific piece type in orthogonal LOS if (testSite >= 0) { // There's lots of new instances we can create here, for every orth. radial: // - An instance that just directly wants not empty and not given piece next to us // - An instance that first wants one empty site, and then not empty and not given piece // - An instance that first wants two empty sites, and then not empty and not given piece // - etc... final TIntArrayList runningMustEmptiesList = new TIntArrayList(); for (final Radial radial : topology.trajectories().radials(instanceType, testSite, AbsoluteDirection.Orthogonal)) { final GraphElement[] steps = radial.steps(); for (int stepIdx = 1; stepIdx < steps.length; ++stepIdx) { // Create a feature instance with not empty and not given piece at stepIdx, // and everything else leading up to it empty final FeatureInstance newInstance = new FeatureInstance(instance); boolean failure = (!newInstance.addTest(container, BitSetTypes.What, steps[stepIdx].id(), false, element.itemIndex())); failure = failure || (!newInstance.addTest(container, BitSetTypes.Empty, steps[stepIdx].id(), false)); for (int emptyStepIdx = 0; emptyStepIdx < runningMustEmptiesList.size(); ++emptyStepIdx) { // See if we can successfully add next must-empty requirement failure = ( failure || ( !newInstance.addTest ( container, BitSetTypes.Empty, runningMustEmptiesList.getQuick(emptyStepIdx), true ) ) ); } if (!failure) replaceNewInstances.add(newInstance); // All other instances we add will have this step as must-empty runningMustEmptiesList.add(steps[stepIdx].id()); } } } } } else if (type == ElementType.LineOfSightDiag) { if (!element.not()) { // We want a specific piece in diagonal LOS if (testSite >= 0) { // There's lots of new instances we can create here, for every orth. radial: // - An instance that just directly wants a piece of given type next to us // - An instance that first wants one empty site, and then a piece // - An instance that first wants two empty sites, and then a piece // - etc... final TIntArrayList runningMustEmptiesList = new TIntArrayList(); for (final Radial radial : topology.trajectories().radials(instanceType, testSite, AbsoluteDirection.Diagonal)) { final GraphElement[] steps = radial.steps(); for (int stepIdx = 1; stepIdx < steps.length; ++stepIdx) { // Create a feature instance with piece at stepIdx, and everything else leading up to it empty final FeatureInstance newInstance = new FeatureInstance(instance); boolean failure = (!newInstance.addTest(container, BitSetTypes.What, steps[stepIdx].id(), true, element.itemIndex())); for (int emptyStepIdx = 0; emptyStepIdx < runningMustEmptiesList.size(); ++emptyStepIdx) { // See if we can successfully add next must-empty requirement failure = ( failure || ( !newInstance.addTest ( container, BitSetTypes.Empty, runningMustEmptiesList.getQuick(emptyStepIdx), true ) ) ); } if (!failure) replaceNewInstances.add(newInstance); // All other instances we add will have this step as must-empty runningMustEmptiesList.add(steps[stepIdx].id()); } } } } else { // We do NOT want a specific piece type in diagonal LOS if (testSite >= 0) { // There's lots of new instances we can create here, for every orth. radial: // - An instance that just directly wants not empty and not given piece next to us // - An instance that first wants one empty site, and then not empty and not given piece // - An instance that first wants two empty sites, and then not empty and not given piece // - etc... final TIntArrayList runningMustEmptiesList = new TIntArrayList(); for (final Radial radial : topology.trajectories().radials(instanceType, testSite, AbsoluteDirection.Diagonal)) { final GraphElement[] steps = radial.steps(); for (int stepIdx = 1; stepIdx < steps.length; ++stepIdx) { // Create a feature instance with not empty and not given piece at stepIdx, // and everything else leading up to it empty final FeatureInstance newInstance = new FeatureInstance(instance); boolean failure = (!newInstance.addTest(container, BitSetTypes.What, steps[stepIdx].id(), false, element.itemIndex())); failure = failure || (!newInstance.addTest(container, BitSetTypes.Empty, steps[stepIdx].id(), false)); for (int emptyStepIdx = 0; emptyStepIdx < runningMustEmptiesList.size(); ++emptyStepIdx) { // See if we can successfully add next must-empty requirement failure = ( failure || ( !newInstance.addTest ( container, BitSetTypes.Empty, runningMustEmptiesList.getQuick(emptyStepIdx), true ) ) ); } if (!failure) replaceNewInstances.add(newInstance); // All other instances we add will have this step as must-empty runningMustEmptiesList.add(steps[stepIdx].id()); } } } } } else { System.err.println("Warning: Element Type " + type + " not supported by Feature.instantiateFeature()"); } } } instancesWithElements = replaceNewInstances; } if (allElementsAbsolute) { // only need to consider 1 possible rotation if all element positions are // absolute moreRotationsRelevant = false; if (this instanceof AbsoluteFeature) { // if actions are ALSO specified absolutely, we also don't need to consider more // sites moreSitesRelevant = false; } } instances.addAll(instancesWithElements); if (!moreRotationsRelevant) { break; } } if (!moreReflectionsRelevant) { break; } } if (!moreSitesRelevant) { break; } } return FeatureInstance.deduplicate(instances); } //------------------------------------------------------------------------- /** * This method expects to only be called with two features that are already * known to be compatible (e.g. because they have already successfully fired * together for a single state+action pair) * * @param game * @param a * @param b * @return A new feature constructed by combining the features of instances a * and b */ public static SpatialFeature combineFeatures(final Game game, final FeatureInstance a, final FeatureInstance b) { final SpatialFeature featureA = a.feature(); final SpatialFeature featureB = b.feature(); final Pattern patternA = featureA.pattern(); final Pattern patternB = featureB.pattern(); // If a and b have different anchors, we can only preserve region-proximity requirements // from one of the two instances, because they are relative to the anchor. boolean bHasRegionProxim = false; if (a.anchorSite() != b.anchorSite()) { for (final FeatureElement elemB : patternB.featureElements()) { if (elemB.type() == ElementType.RegionProximity) { bHasRegionProxim = true; boolean aHasRegionProxim = false; for (final FeatureElement elemA : patternA.featureElements()) { if (elemA.type() == ElementType.RegionProximity) { aHasRegionProxim = true; break; } } if (!aHasRegionProxim) { // Instead of proceeding (and discarding region proxim from B), we'll just flip A and B return combineFeatures(game, b, a); } break; } } } // Compute extra rotation we should apply to pattern B final float requiredBRotation = b.reflection() * b.rotation() - a.reflection() * a.rotation(); //System.out.println("requiredBRotation = " + requiredBRotation); // Create modified copies of Patterns and last-from / last-to walks final Pattern modifiedPatternA = new Pattern(patternA); modifiedPatternA.applyReflection(a.reflection()); final Pattern modifiedPatternB = new Pattern(patternB); if (bHasRegionProxim) { // B has Region Proximity tests, and A must also have some (because otherwise we // would have flipped A and B around), and anchors are different (otherwise we wouldn't // have checked whether or not B has Region Proximity tests). // // We can only preserve those from A, so we should discard any in pattern B final List<FeatureElement> newElementsList = new ArrayList<FeatureElement>(modifiedPatternB.featureElements().length); for (final FeatureElement el : modifiedPatternB.featureElements()) newElementsList.add(el); for (int i = newElementsList.size() - 1; i >= 0; --i) { if (newElementsList.get(i).type() == ElementType.RegionProximity) newElementsList.remove(i); } modifiedPatternB.setFeatureElements(newElementsList.toArray(new FeatureElement[newElementsList.size()])); } modifiedPatternB.applyReflection(b.reflection()); modifiedPatternB.applyRotation(requiredBRotation); final List<? extends TopologyElement> sites = game.graphPlayElements(); final Path anchorsPath; final Walk anchorsWalk; if (a.anchorSite() != b.anchorSite()) { anchorsPath = GraphSearch.shortestPathTo ( game, sites.get(a.anchorSite()), sites.get(b.anchorSite()) ); // A temporary solution to avoid issues in graphs with multiple disconnected // subgraphs. TODO find a better permanent fix if (anchorsPath == null) { return a.feature().rotatedCopy(0.f); } anchorsWalk = anchorsPath.walk(); //System.out.println("anchors walk = " + anchorsWalk); //anchorsWalk.applyReflection(b.reflection()); anchorsWalk.applyRotation(-a.rotation() * a.reflection()); modifiedPatternB.prependWalkWithCorrection(anchorsWalk, anchorsPath, a.rotation(), a.reflection()); //System.out.println("corrected anchors walk = " + anchorsWalk); } else { anchorsPath = null; anchorsWalk = null; } final Pattern newPattern = Pattern.merge(modifiedPatternA, modifiedPatternB); if (featureA instanceof AbsoluteFeature && featureB instanceof AbsoluteFeature) { final AbsoluteFeature absA = (AbsoluteFeature) featureA; final AbsoluteFeature absB = (AbsoluteFeature) featureB; final AbsoluteFeature newFeature = new AbsoluteFeature(newPattern, Math.max(absA.toPosition, absB.toPosition), Math.max(absA.fromPosition, absB.fromPosition)); newFeature.normalise(game); newFeature.pattern().removeRedundancies(); if (!newFeature.pattern().isConsistent()) { System.err.println("Generated inconsistent pattern: " + newPattern); System.err.println("active feature A = " + featureA); System.err.println("rot A = " + a.rotation()); System.err.println("ref A = " + a.reflection()); System.err.println("anchor A = " + a.anchorSite()); System.err.println("active feature B = " + featureB); System.err.println("rot B = " + b.rotation()); System.err.println("ref B = " + b.reflection()); System.err.println("anchor B = " + b.anchorSite()); } return newFeature; } else if (featureA instanceof RelativeFeature && featureB instanceof RelativeFeature) { final RelativeFeature relA = (RelativeFeature) featureA; final RelativeFeature relB = (RelativeFeature) featureB; Walk newToPosition = null; if (relA.toPosition() != null) { newToPosition = new Walk(relA.toPosition()); newToPosition.applyReflection(a.reflection()); } else if (relB.toPosition() != null) { newToPosition = new Walk(relB.toPosition()); newToPosition.applyReflection(b.reflection()); newToPosition.applyRotation(requiredBRotation); if (anchorsWalk != null) newToPosition.prependWalkWithCorrection(anchorsWalk, anchorsPath, a.rotation(), a.reflection()); } Walk newFromPosition = null; if (relA.fromPosition() != null) { newFromPosition = new Walk(relA.fromPosition()); newFromPosition.applyReflection(a.reflection()); } else if (relB.fromPosition() != null) { newFromPosition = new Walk(relB.fromPosition()); newFromPosition.applyReflection(b.reflection()); newFromPosition.applyRotation(requiredBRotation); if (anchorsWalk != null) newFromPosition.prependWalkWithCorrection(anchorsWalk, anchorsPath, a.rotation(), a.reflection()); } Walk newLastFromPosition = null; if (relA.lastFromPosition() != null) { newLastFromPosition = new Walk(relA.lastFromPosition()); newLastFromPosition.applyReflection(a.reflection()); } else if (relB.lastFromPosition() != null) { newLastFromPosition = new Walk(relB.lastFromPosition()); newLastFromPosition.applyReflection(b.reflection()); newLastFromPosition.applyRotation(requiredBRotation); if (anchorsWalk != null) newLastFromPosition.prependWalkWithCorrection(anchorsWalk, anchorsPath, a.rotation(), a.reflection()); } Walk newLastToPosition = null; if (relA.lastToPosition() != null) { newLastToPosition = new Walk(relA.lastToPosition()); newLastToPosition.applyReflection(a.reflection()); } else if (relB.lastToPosition() != null) { newLastToPosition = new Walk(relB.lastToPosition()); newLastToPosition.applyReflection(b.reflection()); newLastToPosition.applyRotation(requiredBRotation); if (anchorsWalk != null) newLastToPosition.prependWalkWithCorrection(anchorsWalk, anchorsPath, a.rotation(), a.reflection()); } if (featureA.graphElementType != featureB.graphElementType) { System.err.println("WARNING: combining two features for different graph element types!"); } final RelativeFeature newFeature = new RelativeFeature ( newPattern, newToPosition, newFromPosition, newLastToPosition, newLastFromPosition ); newFeature.graphElementType = featureA.graphElementType; newFeature.pattern().removeRedundancies(); //System.out.println("pre-normalise = " + newFeature); newFeature.normalise(game); //System.out.println("post-normalise = " + newFeature); newFeature.pattern().removeRedundancies(); if (!newFeature.pattern().isConsistent()) { System.err.println("Generated inconsistent pattern: " + newPattern); System.err.println("active feature A = " + featureA); System.err.println("rot A = " + a.rotation()); System.err.println("ref A = " + a.reflection()); System.err.println("anchor A = " + a.anchorSite()); System.err.println("active feature B = " + featureB); System.err.println("rot B = " + b.rotation()); System.err.println("ref B = " + b.reflection()); System.err.println("anchor B = " + b.anchorSite()); } //System.out.println("constructed " + newFeature + " from " + a + " and " + b); return newFeature; } else { // TODO need to think of how we want to combine absolute // with relative features } // this should never happen System.err.println("WARNING: Feature.combineFeatures() returning null!"); return null; } //------------------------------------------------------------------------- /** * Simplifies the Feature, by: * 1) Getting the first turn of as many Walks as * possible down to 0.0 * 2) Making all turns positive if they were originally all * negative. * 3) Making sure any turns that are very close to one of the game's * rotations are set to precisely that rotation (for example, some of the * modifications described above can result in turns of 0.49999997 due to * floating point inaccuracies, which should instead be set to 0.5). * 4) Preferring small turns in opposite direction over large turns. * 5) Ensuring all turns are in [-1.0, 1.0]. * 6) Setting any turns of -0.5 to +0.5, and turns of -0.0 to +0.0. * * The first modification will only be done for features that allow all * rotations, and the second will only be done for patterns that allow * reflection. * * After these modifications, the originals can still be re-obtained through * rotation and/or reflection. * * @param game */ public void normalise(final Game game) { final float[] allGameRotations = Walk.allGameRotations(game); // if the absolute difference between a turn in a Walk and one of the // game's legal rotations is less than this tolerance level, we treat // them as equal // // for example, on a hexagonal grid the tolerance level will be about // (1/6) / 100 = 0.16666667 / 100 ~= 0.0016666667 final float turnEqualTolerance = (allGameRotations[1] - allGameRotations[0]) / 100.f; // let's first make sure our allowedRotations array has clean floating // point numbers final TFloatArrayList allowedRotations = pattern.allowedRotations(); if (allowedRotations != null) { for (int i = 0; i < allowedRotations.size(); ++i) { final float allowedRot = allowedRotations.getQuick(i); for (int j = 0; j < allGameRotations.length; ++j) { if (Math.abs(allowedRot - allGameRotations[j]) < turnEqualTolerance) { // this can only be close to 0.f if allowedRot is // positive, or if both are already approx. equal to 0.f allowedRotations.setQuick(i, allGameRotations[j]); break; } else if (Math.abs(allGameRotations[j] + allowedRot) < turnEqualTolerance) { // this can only be close to 0.f if allowedRot is // negative, or if both are already approx. equal to 0.f allowedRotations.setQuick(i, -allGameRotations[j]); break; } } } } // Collect all the lists of steps we want to look at / modify (can handle them all as a single big batch) final List<TFloatArrayList> stepsLists = new ArrayList<TFloatArrayList>(pattern.featureElements().length + 4); if (this instanceof RelativeFeature) { for (final FeatureElement featureElement : pattern.featureElements()) { stepsLists.add(((RelativeFeatureElement) featureElement).walk().steps); } final RelativeFeature relFeature = (RelativeFeature) this; for ( final Walk walk : new Walk[] { relFeature.fromPosition, relFeature.toPosition, relFeature.lastFromPosition, relFeature.lastToPosition } ) { if (walk != null) stepsLists.add(walk.steps); } } // Make sure we don't have any steps outside of [-1.0, 1.0] for (final TFloatArrayList steps : stepsLists) { for (int i = 0; i < steps.size(); ++i) { float turn = steps.getQuick(i); while (turn < -1.f) turn += 1.f; while (turn > 1.f) turn -= 1.f; steps.setQuick(i, turn); } } if (allowedRotations == null || Arrays.equals(allowedRotations.toArray(), allGameRotations)) { // All rotations are allowed // Find the most common turn among the first steps of all Walks // with length > 0 float mostCommonTurn = Float.MAX_VALUE; int numOccurrences = 0; final TFloatIntMap occurrencesMap = new TFloatIntHashMap(); for (final TFloatArrayList steps : stepsLists) { if (steps.size() > 0) { final float turn = steps.getQuick(0); final int newOccurrences = occurrencesMap.adjustOrPutValue(turn, 1, 1); if (newOccurrences > numOccurrences) { numOccurrences = newOccurrences; mostCommonTurn = turn; } else if (newOccurrences == numOccurrences) { // Prioritise small turns in case of tie mostCommonTurn = Math.min(mostCommonTurn, turn); } } } if (mostCommonTurn != 0.f) { // Now subtract that most common turn from the first step of // every walk for (final TFloatArrayList steps : stepsLists) { if (steps.size() > 0) { steps.setQuick(0, steps.getQuick(0) - mostCommonTurn); } } } } // Prefer small turns in opposite direction over large turns for (final TFloatArrayList steps : stepsLists) { for (int i = 0; i < steps.size(); ++i) { final float step = steps.getQuick(i); if (step > 0.5f) { steps.setQuick(i, step - 1.f); } else if (step < -0.5f) { steps.setQuick(i, step + 1.f); } } } if (pattern.allowsReflection()) { // Reflection is allowed // first figure out if we have any positive turns boolean havePositiveTurns = false; for (final TFloatArrayList steps : stepsLists) { for (int i = 0; i < steps.size(); ++i) { if (steps.getQuick(i) > 0.f) { havePositiveTurns = true; break; } } if (havePositiveTurns) { break; } } // if we didn't find any, we can multiply all the turns // by -1 (and reflection can later turn this back for us) if (!havePositiveTurns) { for (final TFloatArrayList steps : stepsLists) { for (int i = 0; i < steps.size(); ++i) { steps.setQuick(i, steps.getQuick(i) * -1.f); } } } } // Make sure floating point math didn't mess anything up with the turn // values if possible, we prefer them to PRECISELY match the perfect // fractions given by the game's possible rotations, because the // floating point numbers are used in hashCode() and equals() methods // // here, we'll also set any turns of -0.f to 0.f (don't like negative 0) for (final TFloatArrayList steps : stepsLists) { for (int i = 0; i < steps.size(); ++i) { final float turn = steps.getQuick(i); if (turn == -0.f) { steps.setQuick(i, 0.f); } else { for (int j = 0; j < allGameRotations.length; ++j) { if (Math.abs(turn - allGameRotations[j]) < turnEqualTolerance) { // this can only be close to 0.f if turn is positive, // or if both are already approx. equal to 0.f steps.setQuick(i, allGameRotations[j]); break; } else if (Math.abs(allGameRotations[j] + turn) < turnEqualTolerance) { // this can only be close to 0.f if turn is negative, // or if both are already approx. equal to 0.f steps.setQuick(i, -allGameRotations[j]); break; } } } } } } //------------------------------------------------------------------------- /** * @param features * @return Copy of given list of features, with duplicates removed */ public static List<SpatialFeature> deduplicate(final List<SpatialFeature> features) { // TODO doing this with a set is almost always going to be faster final List<SpatialFeature> deduplicated = new ArrayList<SpatialFeature>(features.size()); for (final SpatialFeature feature : features) { boolean foundDuplicate = false; for (final SpatialFeature alreadyAdded : deduplicated) { if (alreadyAdded.equals(feature)) { // System.out.println("removing " + feature + " (equal to " + alreadyAdded + // ")"); foundDuplicate = true; break; } } if (!foundDuplicate) { deduplicated.add(feature); } } return deduplicated; } //------------------------------------------------------------------------- /** * @param game The game for which we're generating features (passed such that * we can normalise) * @param generalisers The set in which we'll collect the generated generalisers * @param numRecursions Number of recursive calls we're still allowed to do * @return List of new spatial features that generalise (in a game-independent * manner, i.e. having strictly fewer elements in patterns or action-specifiers) * this feature. */ public abstract List<SpatialFeature> generateGeneralisers ( final Game game, final Set<RotRefInvariantFeature> generalisers, final int numRecursions ); //------------------------------------------------------------------------- // /** // * @return The feature's comment // */ // public String comment() // { // return comment; // } // // /** // * @param newComment New comment for the feature // * @return this Feature object (after modification) // */ // public SpatialFeature setComment(final String newComment) // { // comment = newComment; // return this; // } /** * @return This feature's graph element type */ public SiteType graphElementType() { return graphElementType; } //------------------------------------------------------------------------- @Override public boolean equals(final Object other) { if (!(other instanceof SpatialFeature)) return false; final SpatialFeature otherFeature = (SpatialFeature) other; return pattern.equals(otherFeature.pattern); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((pattern == null) ? 0 : pattern.hashCode()); return result; } //------------------------------------------------------------------------- /** * equals() function that ignores restrictions on rotation / reflection in * pattern. * * @param other * @return Result of test. */ public boolean equalsIgnoreRotRef(final SpatialFeature other) { return pattern.equalsIgnoreRotRef(other.pattern); } /** * hashCode() function that ignores restrictions on rotation / reflection in * pattern. * * @return Hash code. */ public int hashCodeIgnoreRotRef() { final int prime = 31; int result = 1; result = prime * result + ((pattern == null) ? 0 : pattern.hashCodeIgnoreRotRef()); return result; } //------------------------------------------------------------------------- /** * Simplifies the given list of spatial features by: * * 1) If there are two different features (which may not yet allow * reflection), such that they would become equal if one of them were * reflected; keeps only one of them (with reflection allowed). * * 2) If there are two different features (which may not yet allow all * rotations), such that they would become equal if one of them were * rotated by a certain amount; keeps only one of them (with the required * rotation allowed) * * @param featuresIn */ public static List<SpatialFeature> simplifySpatialFeaturesList(final Game game, final List<SpatialFeature> featuresIn) { final List<SpatialFeature> simplified = new ArrayList<SpatialFeature>(featuresIn.size()); final Map<Object, RotRefInvariantFeature> featuresToKeep = new HashMap<Object, RotRefInvariantFeature>(); final TFloatArrayList rotations = new TFloatArrayList(Walk.allGameRotations(game)); final boolean[] reflections = {true, false}; for (final SpatialFeature feature : featuresIn) { boolean shouldAddFeature = true; for (int i = 0; i < rotations.size(); ++i) { final float rotation = rotations.get(i); for (int j = 0; j < reflections.length; ++j) { final boolean reflect = reflections[j]; SpatialFeature rotatedFeature = feature.rotatedCopy(rotation); if (reflect) { rotatedFeature = rotatedFeature.reflectedCopy(); } rotatedFeature.normalise(game); final RotRefInvariantFeature wrapped = new RotRefInvariantFeature(rotatedFeature); if (featuresToKeep.containsKey(wrapped)) { shouldAddFeature = false; final SpatialFeature keepFeature = featuresToKeep.remove(wrapped).feature(); // make sure the feature that we decide to keep also // allows for the necessary rotation final float requiredRot = rotation == 0.f ? 0.f : 1.f - rotation; if (keepFeature.pattern().allowedRotations() != null) { if (!keepFeature.pattern().allowedRotations().contains(requiredRot)) { final TFloatArrayList allowedRotations = new TFloatArrayList(); allowedRotations.addAll ( keepFeature.pattern().allowedRotations() ); allowedRotations.add(requiredRot); keepFeature.pattern().setAllowedRotations(allowedRotations); keepFeature.pattern().allowedRotations().sort(); keepFeature.normalise(game); } } final RotRefInvariantFeature wrappedKeep = new RotRefInvariantFeature(keepFeature); featuresToKeep.put(wrappedKeep, wrappedKeep); /*System.out.println("using " + keepFeature + " instead of " + feature);*/ break; } } if (!shouldAddFeature) { break; } } if (shouldAddFeature) { final RotRefInvariantFeature wrapped = new RotRefInvariantFeature(feature); featuresToKeep.put(wrapped, wrapped); } } for (final RotRefInvariantFeature feature : featuresToKeep.values()) { simplified.add(feature.feature()); } return simplified; } //------------------------------------------------------------------------- /** * Wrapper around a feature, with equals() and hashCode() functions that * ignore rotation / reflection permissions in feature/pattern. * * @author Dennis Soemers */ public static class RotRefInvariantFeature { /** Wrapped Feature */ protected SpatialFeature feature; /** * Constructor * @param feature */ public RotRefInvariantFeature(final SpatialFeature feature) { this.feature = feature; } /** * @return The wrapped feature */ public SpatialFeature feature() { return feature; } @Override public boolean equals(final Object other) { if (!(other instanceof RotRefInvariantFeature)) { return false; } return feature.equalsIgnoreRotRef(((RotRefInvariantFeature) other).feature); } @Override public int hashCode() { return feature.hashCodeIgnoreRotRef(); } } //------------------------------------------------------------------------- }
57,574
31.528249
124
java
Ludii
Ludii-master/Features/src/features/spatial/Walk.java
package features.spatial; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import features.spatial.graph_search.Path; import game.Game; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import main.StringRoutines; import other.topology.TopologyElement; /** * A relative position specified by a sequence of turns to take whilst * walking<br> * <br> * In regular mode, every number indicates the fraction of possible clockwise * turns to make <br> * relative to the previous direction before taking another step. For example: * [0, 0.25, 0, -0.5] means: <br> * - 0 turns, walk once (straight ahead) <br> * - 1/4th of the possible turns clockwise (e.g. one turn on a square cell), * walk once, <br> * - 0 additional turns, so continue in the direction given by our previous * turns <br> * - half of the possible turns counter-clockwise (e.g. turning backwards), walk * once <br> * * @author Dennis Soemers and cambolbro */ public class Walk { //------------------------------------------------------------------------- /** Weak reference to last game for which we computed allGameRotations */ private static volatile WeakReference<Game> cachedGame = new WeakReference<Game>(null); /** Cached list of all game rotations */ private static volatile float[] cachedAllGameRotations = new float[0]; //------------------------------------------------------------------------- /** Relative turns to make for every step */ protected final TFloatArrayList steps; //------------------------------------------------------------------------- /** * Constructor */ public Walk() { this.steps = new TFloatArrayList(1); } /** * Constructor * @param steps */ public Walk(final float... steps) { this.steps = TFloatArrayList.wrap(steps); } /** * Constructor * @param steps */ public Walk(final TFloatArrayList steps) { this.steps = new TFloatArrayList(steps); } /** * Constructor * @param other */ public Walk(final Walk other) { this.steps = new TFloatArrayList(other.steps()); } /** * Constructor * @param string */ public Walk(final String string) { final String walkString = string.substring("{".length(), string.length() - "}".length()); if (walkString.length() > 0) { final String[] stepStrings = walkString.split(","); steps = new TFloatArrayList(stepStrings.length); for (final String stepString : stepStrings) { final String s = stepString.trim(); if (s.contains("/")) { final String[] parts = s.split(Pattern.quote("/")); steps.add((float) Integer.parseInt(parts[0]) / (float) Integer.parseInt(parts[1])); } else { steps.add(Float.parseFloat(stepString.trim())); } } } else { steps = new TFloatArrayList(0); } } //------------------------------------------------------------------------- /** * Applies given reflection multiplier to this Walk * @param reflection */ public void applyReflection(final int reflection) { if (reflection == 1) { // guess we're doing nothing at all return; } assert (reflection == -1); for (int i = 0; i < steps.size(); ++i) { steps.setQuick(i, steps.getQuick(i) * reflection); } } /** * Applies given rotation to this walk * @param rotation */ public void applyRotation(final float rotation) { if (steps.size() > 0) { steps.setQuick(0, steps.getQuick(0) + rotation); } } /** * Adds all steps from the given walk to the end of this walk * @param walk */ public void appendWalk(final Walk walk) { steps.add(walk.steps().toArray()); } /** * Adds a step corresponding to the given direction to the beginning of the Walk * * @param step */ public void prependStep(final float step) { steps.insert(0, step); } /** * Adds all steps from the given walk to the beginning of this Walk * @param walk */ public void prependWalk(final Walk walk) { steps.insert(0, walk.steps().toArray()); } /** * Prepends all steps of the given walk to this walk. * Additionally applies a correction to the first step (if it exists) of this walk, * to make sure that it still continues moving in the same direction that it * would have without prepending the new walk. * * @param walk * @param path The path we followed when walking the prepended walk * @param rotToRevert Already-applied rotation which should be reverted * @param refToRevert Already-applied reflection which should be reverted */ public void prependWalkWithCorrection ( final Walk walk, final Path path, final float rotToRevert, final int refToRevert ) { if (walk.steps.size() == 0) return; if (steps.size() > 0) { final TopologyElement endSite = path.destination(); final TopologyElement penultimateSite = path.sites().get(path.sites().size() - 2); // TODO code duplication with resolveWalk() // compute the directions that count as "continuing straight ahead" // (will be only one in the case of cells with even number of edges, but two otherwise) final TIntArrayList contDirs = new TIntArrayList(2); final TopologyElement[] sortedOrthos = endSite.sortedOrthos(); int fromDir = -1; for (int orthIdx = 0; orthIdx < sortedOrthos.length; ++orthIdx) { if ( sortedOrthos[orthIdx] != null && sortedOrthos[orthIdx].index() == penultimateSite.index() ) { fromDir = orthIdx; break; } } if (fromDir == -1) { System.err.println("Warning! Walk.prependWalkWithCorrection() could not find fromDir!"); } if (sortedOrthos.length % 2 == 0) { contDirs.add(fromDir + sortedOrthos.length / 2); } else { contDirs.add(fromDir + sortedOrthos.length / 2); //contDirs.add(fromDir + 1 + sortedOrthos.length / 2); } final float toSubtract = (contDirs.getQuick(0) / (float) sortedOrthos.length) - rotToRevert * refToRevert; // TODO now just assuming we get a single contDir // System.out.println(); // System.out.println("prepended walk = " + walk); // System.out.println("old code would have subtracted: " + walk.steps().sum()); // System.out.println("new code subtracts: " + toSubtract); // System.out.println("steps.getQuick(0) = " + steps.getQuick(0)); // System.out.println("num orthos = " + sortedOrthos.length); // System.out.println("contDir = " + contDirs.getQuick(0)); // System.out.println("fromDir = " + fromDir); // System.out.println("start = " + path.start()); // System.out.println("end = " + path.destination()); steps.setQuick(0, steps.getQuick(0) - toSubtract); } steps.insert(0, walk.steps().toArray()); } //------------------------------------------------------------------------- /** * @return Reference to this Walk's list of steps */ public TFloatArrayList steps() { return steps; } //------------------------------------------------------------------------- /** * Resolves this Walk * @param game Game in which we're resolving a Walk * @param startSite Vertex to start walking from * @param rotModifier Additional rotation to apply to the complete Walk * @param reflectionMult Reflection multiplier * @return Indices of all possible vertices this Walk can end up in * (may be many if we're walking through cells with odd numbers of edges where turns can be ambiguous). */ public TIntArrayList resolveWalk ( final Game game, final TopologyElement startSite, final float rotModifier, final int reflectionMult ) { // System.out.println(); // System.out.println("resolving walk: " + this); // System.out.println("starting at vertex: " + startVertex); // System.out.println("rotModifier = " + rotModifier); // System.out.println("reflectionMult = " + reflectionMult); final TIntArrayList results = new TIntArrayList(1); if (steps.size() > 0) { final TopologyElement[] sortedOrthos = startSite.sortedOrthos(); final TIntArrayList connectionIndices = new TIntArrayList(2); // apply rotation to first step, // rest of the Walk will then auto-rotate float connectionIdxFloat = ((steps.get(0) + rotModifier) * reflectionMult) * sortedOrthos.length; float connectionIdxFractionalPart = connectionIdxFloat - (int) connectionIdxFloat; if ( Math.abs(0.5f - connectionIdxFractionalPart) < 0.02f || Math.abs(0.5f + connectionIdxFractionalPart) < 0.02f ) { // we're (almost) exactly halfway between two integer indices, so we'll use both connectionIndices.add((int) Math.floor(connectionIdxFloat)); //connectionIndices.add((int) Math.ceil(connectionIdxFloat)); } else // not almost exactly halfway, so just round and use a single integer index { connectionIndices.add(Math.round(connectionIdxFloat)); } boolean wentOffBoard = false; for (int c = 0; c < connectionIndices.size(); ++c) { TopologyElement prevSite = startSite; int connectionIdx = connectionIndices.getQuick(c); //System.out.println("connectionIdx = " + connectionIdx); // wrap around... (thanks https://stackoverflow.com/a/4412200/6735980) connectionIdx = (connectionIdx % sortedOrthos.length + sortedOrthos.length) % sortedOrthos.length; TopologyElement nextSite = sortedOrthos[connectionIdx]; //System.out.println("nextSite = " + nextSite); List<TopologyElement> nextSites = Arrays.asList(nextSite); List<TopologyElement> prevSites = Arrays.asList(prevSite); for (int step = 1; step < steps.size(); ++step) { // apply step to all possible "next vertices" //System.out.println("step = " + step); final List<TopologyElement> newNextSites = new ArrayList<TopologyElement>(nextSites.size()); final List<TopologyElement> newPrevSites = new ArrayList<TopologyElement>(nextSites.size()); for (int i = 0; i < nextSites.size(); ++i) { prevSite = prevSites.get(i); nextSite = nextSites.get(i); //System.out.println("prevVertex = " + prevVertex); //System.out.println("nextVertex = " + nextVertex); if (nextSite == null) { //System.out.println("went off board"); wentOffBoard = true; } else { // compute the directions that count as "continuing straight ahead" // (will be only one in the case of cells with even number of edges, but two otherwise) final TIntArrayList contDirs = new TIntArrayList(2); final TopologyElement[] nextSortedOrthos = nextSite.sortedOrthos(); //System.out.println("sorted orthos of " + nextSite + " = " + Arrays.toString(nextSortedOrthos)); int fromDir = -1; for (int nextOrthIdx = 0; nextOrthIdx < nextSortedOrthos.length; ++nextOrthIdx) { if ( nextSortedOrthos[nextOrthIdx] != null && nextSortedOrthos[nextOrthIdx].index() == prevSite.index() ) { fromDir = nextOrthIdx; break; } } if (fromDir == -1) { System.err.println("Warning! Walk.resolveWalk() could not find fromDir!"); } if (nextSortedOrthos.length % 2 == 0) { contDirs.add(fromDir + nextSortedOrthos.length / 2); } else { contDirs.add(fromDir + nextSortedOrthos.length / 2); //contDirs.add(fromDir + 1 + nextSortedOrthos.length / 2); } // for each of these "continue directions", we apply the next rotation // specified in the Walk and move on for (int contDirIdx = 0; contDirIdx < contDirs.size(); ++contDirIdx) { final int contDir = contDirs.getQuick(contDirIdx); final TIntArrayList nextConnectionIndices = new TIntArrayList(2); connectionIdxFloat = contDir + (steps.get(step) * reflectionMult) * nextSortedOrthos.length; connectionIdxFractionalPart = connectionIdxFloat - (int) connectionIdxFloat; if ( Math.abs(0.5f - connectionIdxFractionalPart) < 0.02f || Math.abs(0.5f + connectionIdxFractionalPart) < 0.02f ) { // we're (almost) exactly halfway between two integer indices, so we'll use both nextConnectionIndices.add((int) Math.floor(connectionIdxFloat)); //nextConnectionIndices.add((int) Math.ceil(connectionIdxFloat)); } else // not almost exactly halfway, so just round and use a single integer index { nextConnectionIndices.add(Math.round(connectionIdxFloat)); } for (int n = 0; n < nextConnectionIndices.size(); ++n) { // wrap around... connectionIdx = (nextConnectionIndices.getQuick(n) % nextSortedOrthos.length + nextSortedOrthos.length) % nextSortedOrthos.length; final TopologyElement newNextSite = nextSortedOrthos[connectionIdx]; //System.out.println("newNextSite = " + newNextSite); newPrevSites.add(nextSite); newNextSites.add(newNextSite); } } } } nextSites = newNextSites; prevSites = newPrevSites; } // add all destinations reached by the Walk(s) for (final TopologyElement destination : nextSites) { if (destination == null) { wentOffBoard = true; } else { results.add(destination.index()); } } } if (wentOffBoard) { results.add(-1); } } else // no real Walk, so just testing on the site's pos { results.add(startSite.index()); } return results; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; // We very often have values of 0.f in steps, and otherwise also very often // permutations of the same values. // The standard hashCode() implementation of TFloatArrayList produces lots // of collisions for these types of lists, so we roll our own implementation for (int i = 0; i < steps.size(); ++i) { result = prime * result + Float.floatToIntBits((steps.getQuick(i) + 1.f) * 663608941.737f); } result = prime * result + ((steps == null) ? 0 : steps.hashCode()); return result; } @Override public boolean equals(final Object other) { if (!(other instanceof Walk)) return false; return steps.equals(((Walk) other).steps()); } //------------------------------------------------------------------------- /** * @param game * @return Array of all possible sensible rotations for the given game's board */ public static float[] allGameRotations(final Game game) { if (cachedGame.get() == game) return cachedAllGameRotations; final TIntArrayList connectivities = game.board().topology().trueOrthoConnectivities(game); final TFloatArrayList rotations = new TFloatArrayList(); for (int i = connectivities.size() - 1; i >= 0; --i) { final int connectivity = connectivities.getQuick(i); if (connectivity == 0) continue; boolean alreadyHandled = false; for (int j = i + 1; j < connectivities.size(); ++j) { if (connectivities.getQuick(j) % connectivity == 0) { // All rotations that this connectivity would generate have // already been generated by another (larger) connectivity number alreadyHandled = true; break; } } if (!alreadyHandled) { final TFloatArrayList newRots = rotationsForNumOrthos(connectivity); // Just double-checking that we don't add any duplicates for (int j = 0; j < newRots.size(); ++j) { if (!rotations.contains(newRots.getQuick(j))) rotations.add(newRots.getQuick(j)); } } } cachedAllGameRotations = rotations.toArray(); cachedGame = new WeakReference<Game>(game); return cachedAllGameRotations; } /** * @param numOrthos * @return List of all possible rotations for cell with given number of * orthogonals. */ public static TFloatArrayList rotationsForNumOrthos(final int numOrthos) { final TFloatArrayList allowedRotations = new TFloatArrayList(); for (int i = 0; i < numOrthos; ++i) { allowedRotations.add((float) i / (float) numOrthos); } return allowedRotations; } //------------------------------------------------------------------------- @Override public String toString() { String str = ""; for (int i = 0; i < steps.size(); ++i) { str += StringRoutines.floatToFraction(steps.get(i), 20); if (i < steps.size() - 1) { str += ","; } } return String.format("{%s}", str); } //------------------------------------------------------------------------- }
16,945
27.38526
109
java
Ludii
Ludii-master/Features/src/features/spatial/cache/ActiveFeaturesCache.java
package features.spatial.cache; import java.util.HashMap; import java.util.Map; import features.feature_sets.BaseFeatureSet; import features.feature_sets.BaseFeatureSet.ProactiveFeaturesKey; import features.spatial.cache.footprints.BaseFootprint; import main.collections.ChunkSet; import other.state.State; import other.state.container.ContainerState; /** * Given a list containing player index, from-pos, and to-pos as key, this cache * can look up a cached list of active features that were active the last time * that same index was used to compute a list of active features. * * Given a current game state, the cache will first use the key-specific * footprint of the complete Feature Set to ensure that all parts of the game * state covered by the footprint are still identical to how they were when the * active features were computed and stored in the cache. The active features * will only be returned if all parts of the game state covered by the footprint * are indeed still identical. * * Note that the cache is not linked to any specific Trial or Context, or even * to any specific full match of a game being played. Generally, we expect the * majority of the cache to remain valid throughout a single playout, with small * parts becoming invalid during a playout, and most of the cache having turned * invalid when we move on to the next playout. However, it is possible that * some parts of the cache remain valid over many different playouts (e.g. parts * of a board that trained policies are very unlikely to make moves in). * * We keep a separate cache per Thread (using ThreadLocal), to make sure that * different playouts running in different Threads do not invalidate each * others' caches. * * * @author Dennis Soemers */ public class ActiveFeaturesCache { //------------------------------------------------------------------------- /** Our caches (one per thread) */ protected final ThreadLocal<Map<ProactiveFeaturesKey, CachedDataFootprint>> threadLocalCache; //------------------------------------------------------------------------- /** * Constructor */ public ActiveFeaturesCache() { threadLocalCache = new ThreadLocal<Map<ProactiveFeaturesKey, CachedDataFootprint>>() { @Override protected Map<ProactiveFeaturesKey, CachedDataFootprint> initialValue() { return new HashMap<ProactiveFeaturesKey, CachedDataFootprint>(); } }; } //------------------------------------------------------------------------- /** * Stores the given list of active feature indices in the cache, for the * given state, from-, and to-positions * * @param state * @param from * @param to * @param activeFeaturesToCache * @param player */ public void cache ( final State state, final int from, final int to, final int[] activeFeaturesToCache, final int player ) { final ContainerState container = state.containerStates()[0]; final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); key.resetData(player, from, to); final Map<ProactiveFeaturesKey, CachedDataFootprint> map = threadLocalCache.get(); final CachedDataFootprint pair = map.get(key); final BaseFootprint footprint = pair.footprint; final ChunkSet maskedEmptyCells; if (container.emptyChunkSetCell() != null && footprint.emptyCell() != null) { maskedEmptyCells = container.emptyChunkSetCell().clone(); maskedEmptyCells.and(footprint.emptyCell()); } else { maskedEmptyCells = null; } final ChunkSet maskedEmptyVertices; if (container.emptyChunkSetVertex() != null && footprint.emptyVertex() != null) { maskedEmptyVertices = container.emptyChunkSetVertex().clone(); maskedEmptyVertices.and(footprint.emptyVertex()); } else { maskedEmptyVertices = null; } final ChunkSet maskedEmptyEdges; if (container.emptyChunkSetEdge() != null && footprint.emptyEdge() != null) { maskedEmptyEdges = container.emptyChunkSetEdge().clone(); maskedEmptyEdges.and(footprint.emptyEdge()); } else { maskedEmptyEdges = null; } final ChunkSet maskedWhoCells = container.cloneWhoCell(); if (maskedWhoCells != null && footprint.whoCell() != null) maskedWhoCells.and(footprint.whoCell()); final ChunkSet maskedWhoVertices = container.cloneWhoVertex(); if (maskedWhoVertices != null && footprint.whoVertex() != null) maskedWhoVertices.and(footprint.whoVertex()); final ChunkSet maskedWhoEdges = container.cloneWhoEdge(); if (maskedWhoEdges != null && footprint.whoEdge() != null) maskedWhoEdges.and(footprint.whoEdge()); final ChunkSet maskedWhatCells = container.cloneWhatCell(); if (maskedWhatCells != null && footprint.whatCell() != null) maskedWhatCells.and(footprint.whatCell()); final ChunkSet maskedWhatVertices = container.cloneWhatVertex(); if (maskedWhatVertices != null && footprint.whatVertex() != null) maskedWhatVertices.and(footprint.whatVertex()); final ChunkSet maskedWhatEdges = container.cloneWhatEdge(); if (maskedWhatEdges != null && footprint.whatEdge() != null) maskedWhatEdges.and(footprint.whatEdge()); final BaseCachedData data = new FullCachedData( activeFeaturesToCache, maskedEmptyCells, maskedEmptyVertices, maskedEmptyEdges, maskedWhoCells, maskedWhoVertices, maskedWhoEdges, maskedWhatCells, maskedWhatVertices, maskedWhatEdges); map.put(key, new CachedDataFootprint(data, footprint)); } /** * @param featureSet * @param state * @param from * @param to * @param player * @return Cached list of indices of active features, or null if not in cache or if entry * in cache is invalid. */ public int[] getCachedActiveFeatures ( final BaseFeatureSet featureSet, final State state, final int from, final int to, final int player ) { final ProactiveFeaturesKey key = new ProactiveFeaturesKey(); key.resetData(player, from, to); final Map<ProactiveFeaturesKey, CachedDataFootprint> map = threadLocalCache.get(); final CachedDataFootprint pair = map.get(key); if (pair == null) { // we need to compute and store footprint final BaseFootprint footprint = featureSet.generateFootprint(state, from, to, player); map.put(key, new CachedDataFootprint(null, footprint)); } else { final BaseCachedData cachedData = pair.data; if (cachedData != null) { // we cached something, gotta make sure it's still valid final ContainerState container = state.containerStates()[0]; final BaseFootprint footprint = pair.footprint; //System.out.println("footprint empty = " + footprint.empty()); //System.out.println("old empty state = " + cachedData.emptyState); //System.out.println("new empty state = " + container.empty().bitSet()); if (cachedData.isDataValid(container, footprint)) return cachedData.cachedActiveFeatureIndices(); } } // no cached data, so return null //System.out.println("key not in cache at all"); return null; } //------------------------------------------------------------------------- /** * Cleans up any memory used by this cache (only for calling thread) */ public void close() { threadLocalCache.remove(); } //------------------------------------------------------------------------- /** * Wrapper, around CachedData + a Footprint for the same key in HashMaps. * * @author Dennis Soemers */ private class CachedDataFootprint { /** Data we want to cache (active features, old state vectors) */ public final BaseCachedData data; /** Footprint for the same key */ public final BaseFootprint footprint; /** * Constructor * @param data * @param footprint */ public CachedDataFootprint(final BaseCachedData data, final BaseFootprint footprint) { this.data = data; this.footprint = footprint; } } //------------------------------------------------------------------------- }
7,965
29.521073
94
java
Ludii
Ludii-master/Features/src/features/spatial/cache/BaseCachedData.java
package features.spatial.cache; import features.spatial.cache.footprints.BaseFootprint; import other.state.container.ContainerState; /** * Abstract class for data cached in active-feature-caches * * @author Dennis Soemers */ public abstract class BaseCachedData { //------------------------------------------------------------------------- /** Active features as previously computed and stored in cache */ protected final int[] activeFeatureIndices; //------------------------------------------------------------------------- /** * Constructor * @param activeFeatureIndices */ public BaseCachedData(final int[] activeFeatureIndices) { this.activeFeatureIndices = activeFeatureIndices; } //------------------------------------------------------------------------- /** * @return Array of active feature indices as previously cached */ public final int[] cachedActiveFeatureIndices() { return activeFeatureIndices; } /** * @param containerState * @param footprint * @return Is this cached data still valid for the given container state and footprint? */ public abstract boolean isDataValid(final ContainerState containerState, final BaseFootprint footprint); //------------------------------------------------------------------------- }
1,295
24.92
105
java
Ludii
Ludii-master/Features/src/features/spatial/cache/FullCachedData.java
package features.spatial.cache; import features.spatial.cache.footprints.BaseFootprint; import main.collections.ChunkSet; import other.state.container.ContainerState; /** * A full version of cached data with support for any mix of cell/edge/vertex * * @author Dennis Soemers */ public class FullCachedData extends BaseCachedData { //------------------------------------------------------------------------- /** * masked "empty" ChunkSet in the game state for which we last cached active * features (for cells) */ protected final ChunkSet emptyStateCells; /** * masked "empty" ChunkSet in the game state for which we last cached active * features (for vertices) */ protected final ChunkSet emptyStateVertices; /** * masked "empty" ChunkSet in the game state for which we last cached active * features (for edges) */ protected final ChunkSet emptyStateEdges; /** * masked "who" ChunkSet in the game state for which we last cached active * features (for cells) */ protected final ChunkSet whoStateCells; /** * masked "who" ChunkSet in the game state for which we last cached active * features (for vertices) */ protected final ChunkSet whoStateVertices; /** * masked "who" ChunkSet in the game state for which we last cached active * features (for edges) */ protected final ChunkSet whoStateEdges; /** * masked "what" ChunkSet in the game state for which we last cached active * features (for cells) */ protected final ChunkSet whatStateCells; /** * masked "what" ChunkSet in the game state for which we last cached active * features (for vertices) */ protected final ChunkSet whatStateVertices; /** * masked "what" ChunkSet in the game state for which we last cached active * features (for edges) */ protected final ChunkSet whatStateEdges; //------------------------------------------------------------------------- /** * Constructor * * @param activeFeatureIndices * @param emptyStateCells * @param emptyStateVertices * @param emptyStateEdges * @param whoStateCells * @param whoStateVertices * @param whoStateEdges * @param whatStateCells * @param whatStateVertices * @param whatStateEdges */ public FullCachedData ( final int[] activeFeatureIndices, final ChunkSet emptyStateCells, final ChunkSet emptyStateVertices, final ChunkSet emptyStateEdges, final ChunkSet whoStateCells, final ChunkSet whoStateVertices, final ChunkSet whoStateEdges, final ChunkSet whatStateCells, final ChunkSet whatStateVertices, final ChunkSet whatStateEdges ) { super(activeFeatureIndices); this.emptyStateCells = emptyStateCells; this.emptyStateVertices = emptyStateVertices; this.emptyStateEdges = emptyStateEdges; this.whoStateCells = whoStateCells; this.whoStateVertices = whoStateVertices; this.whoStateEdges = whoStateEdges; this.whatStateCells = whatStateCells; this.whatStateVertices = whatStateVertices; this.whatStateEdges = whatStateEdges; } //------------------------------------------------------------------------- @Override public boolean isDataValid(final ContainerState containerState, final BaseFootprint footprint) { if ( footprint.emptyCell() != null && !containerState.emptyChunkSetCell().matches(footprint.emptyCell(), emptyStateCells) ) { // part of "empty" state for Cells covered by footprint no longer matches, data invalid return false; } else if ( footprint.emptyVertex() != null && !containerState.emptyChunkSetVertex().matches(footprint.emptyVertex(), emptyStateVertices) ) { // part of "empty" state for Vertices covered by footprint no longer matches, data invalid return false; } else if ( footprint.emptyEdge() != null && !containerState.emptyChunkSetEdge().matches(footprint.emptyEdge(), emptyStateEdges) ) { // part of "empty" state for Edges covered by footprint no longer matches, data invalid return false; } else if ( footprint.whoCell() != null && !containerState.matchesWhoCell(footprint.whoCell(), whoStateCells) ) { // part of "who" state for Cells covered by footprint no longer matches, data invalid return false; } else if ( footprint.whoVertex() != null && !containerState.matchesWhoVertex(footprint.whoVertex(), whoStateVertices) ) { // part of "who" state for Vertices covered by footprint no longer matches, data invalid return false; } else if ( footprint.whoEdge() != null && !containerState.matchesWhoEdge(footprint.whoEdge(), whoStateEdges) ) { // part of "who" state for Edges covered by footprint no longer matches, data invalid return false; } else if ( footprint.whatCell() != null && !containerState.matchesWhatCell(footprint.whatCell(), whatStateCells) ) { // part of "what" state for Cells covered by footprint no longer matches, data invalid return false; } else if ( footprint.whatVertex() != null && !containerState.matchesWhatVertex(footprint.whatVertex(), whatStateVertices) ) { // part of "what" state for Vertices covered by footprint no longer matches, data invalid return false; } else if ( footprint.whatEdge() != null && !containerState.matchesWhatEdge(footprint.whatEdge(), whatStateEdges) ) { // part of "what" state for Edges covered by footprint no longer matches, data invalid return false; } return true; } //------------------------------------------------------------------------- }
5,554
25.966019
95
java
Ludii
Ludii-master/Features/src/features/spatial/cache/footprints/BaseFootprint.java
package features.spatial.cache.footprints; import main.collections.ChunkSet; /** * Wrapper class for masks that represent the key-specific (specific to * player index / from-pos / to-pos) footprint of a complete Feature Set. * * @author Dennis Soemers */ public abstract class BaseFootprint { //------------------------------------------------------------------------- /** * @return Footprint on "empty" ChunkSet for cells */ public abstract ChunkSet emptyCell(); /** * @return Footprint on "empty" ChunkSet for vertices */ public abstract ChunkSet emptyVertex(); /** * @return Footprint on "empty" ChunkSet for edges */ public abstract ChunkSet emptyEdge(); /** * @return Footprint on "who" ChunkSet for cells */ public abstract ChunkSet whoCell(); /** * @return Footprint on "who" ChunkSet for vertices */ public abstract ChunkSet whoVertex(); /** * @return Footprint on "who" ChunkSet for edges */ public abstract ChunkSet whoEdge(); /** * @return Footprint on "what" ChunkSet for cells */ public abstract ChunkSet whatCell(); /** * @return Footprint on "what" ChunkSet for vertices */ public abstract ChunkSet whatVertex(); /** * @return Footprint on "what" ChunkSet for edges */ public abstract ChunkSet whatEdge(); //------------------------------------------------------------------------- /** * Adds the given other footprint to this one * @param other */ public void union(final BaseFootprint other) { if (other.emptyCell() != null) emptyCell().or(other.emptyCell()); if (other.emptyVertex() != null) emptyVertex().or(other.emptyVertex()); if (other.emptyEdge() != null) emptyEdge().or(other.emptyEdge()); if (other.whoCell() != null) whoCell().or(other.whoCell()); if (other.whoVertex() != null) whoVertex().or(other.whoVertex()); if (other.whoEdge() != null) whoEdge().or(other.whoEdge()); if (other.whatCell() != null) whatCell().or(other.whatCell()); if (other.whatVertex() != null) whatVertex().or(other.whatVertex()); if (other.whatEdge() != null) whatEdge().or(other.whatEdge()); } //------------------------------------------------------------------------- }
2,229
22.723404
76
java
Ludii
Ludii-master/Features/src/features/spatial/cache/footprints/FullFootprint.java
package features.spatial.cache.footprints; import main.collections.ChunkSet; /** * Footprint implementation with support for a mix of cell/vertex/edge stuff. * * @author Dennis Soemers */ public class FullFootprint extends BaseFootprint { //------------------------------------------------------------------------- /** Mask for all chunks that we run at least one "empty" cell test on */ protected final ChunkSet emptyCell; /** Mask for all chunks that we run at least one "empty" vertex test on */ protected final ChunkSet emptyVertex; /** Mask for all chunks that we run at least one "empty" edge test on */ protected final ChunkSet emptyEdge; /** Mask for all chunks that we run at least one "who" cell test on */ protected final ChunkSet whoCell; /** Mask for all chunks that we run at least one "who" vertex test on */ protected final ChunkSet whoVertex; /** Mask for all chunks that we run at least one "who" edge test on */ protected final ChunkSet whoEdge; /** Mask for all chunks that we run at least one "what" cell test on */ protected final ChunkSet whatCell; /** Mask for all chunks that we run at least one "what" vertex test on */ protected final ChunkSet whatVertex; /** Mask for all chunks that we run at least one "what" edge test on */ protected final ChunkSet whatEdge; //------------------------------------------------------------------------- /** * Constructor * @param emptyCell * @param emptyVertex * @param emptyEdge * @param whoCell * @param whoVertex * @param whoEdge * @param whatCell * @param whatVertex * @param whatEdge */ public FullFootprint ( final ChunkSet emptyCell, final ChunkSet emptyVertex, final ChunkSet emptyEdge, final ChunkSet whoCell, final ChunkSet whoVertex, final ChunkSet whoEdge, final ChunkSet whatCell, final ChunkSet whatVertex, final ChunkSet whatEdge ) { this.emptyCell = emptyCell; this.emptyVertex = emptyVertex; this.emptyEdge = emptyEdge; this.whoCell = whoCell; this.whoVertex = whoVertex; this.whoEdge = whoEdge; this.whatCell = whatCell; this.whatVertex = whatVertex; this.whatEdge = whatEdge; } //------------------------------------------------------------------------- @Override public ChunkSet emptyCell() { return emptyCell; } @Override public ChunkSet emptyVertex() { return emptyVertex; } @Override public ChunkSet emptyEdge() { return emptyEdge; } @Override public ChunkSet whoCell() { return whoCell; } @Override public ChunkSet whoVertex() { return whoVertex; } @Override public ChunkSet whoEdge() { return whoEdge; } @Override public ChunkSet whatCell() { return whatCell; } @Override public ChunkSet whatVertex() { return whatVertex; } @Override public ChunkSet whatEdge() { return whatEdge; } //------------------------------------------------------------------------- }
2,937
21.090226
77
java
Ludii
Ludii-master/Features/src/features/spatial/elements/AbsoluteFeatureElement.java
package features.spatial.elements; /** * Absolute Feature Element; a single element of a (state-action) feature, * where positions are specified in an absolute manner. * * @author Dennis Soemers */ public class AbsoluteFeatureElement extends FeatureElement { //------------------------------------------------------------------------- /** */ protected ElementType type = null; /** Set to true to negate any element-type-based test */ protected boolean not = false; /** Absolute position */ protected int position; /** Index of Item to check for in cases where type == ElementType.Item */ protected final int itemIndex; //------------------------------------------------------------------------- /** * Constructor. * @param type * @param position */ public AbsoluteFeatureElement(final ElementType type, final int position) { this.type = type; this.position = position; this.itemIndex = -1; } /** * Constructor. * @param type * @param not * @param position */ public AbsoluteFeatureElement(final ElementType type, final boolean not, final int position) { this.type = type; this.not = not; this.position = position; this.itemIndex = -1; } /** * Constructor. * @param type * @param position * @param itemIndex */ public AbsoluteFeatureElement(final ElementType type, final int position, final int itemIndex) { this.type = type; this.position = position; this.itemIndex = itemIndex; } /** * Constructor. * @param type * @param not * @param position * @param itemIndex */ public AbsoluteFeatureElement(final ElementType type, final boolean not, final int position, final int itemIndex) { this.type = type; this.not = not; this.position = position; this.itemIndex = itemIndex; } /** * Copy constructor. * @param other */ public AbsoluteFeatureElement(final AbsoluteFeatureElement other) { type = other.type; not = other.not; position = other.position; itemIndex = other.itemIndex; } /** * Constructor from String * @param string */ public AbsoluteFeatureElement(final String string) { final int startPosStringIdx = string.indexOf("{"); String typeString = string.substring(0, startPosStringIdx); String posString = string.substring(startPosStringIdx); if (typeString.startsWith("!")) { not = true; typeString = typeString.substring("!".length()); } int iIdx = -1; for (final ElementType elType : ElementType.values()) { if (typeString.startsWith(elType.label)) { type = elType; if (typeString.length() > elType.label.length()) { iIdx = Integer.parseInt(typeString.substring(elType.label.length())); } break; } } itemIndex = iIdx; posString = posString.substring("{abs-".length(), posString.length() - "}".length()); position = Integer.parseInt(posString); } //------------------------------------------------------------------------- @Override public ElementType type() { return type; } @Override public void setType(final ElementType type) { this.type = type; } @Override public void negate() { not = true; } @Override public boolean not() { return not; } /** * @return The position */ public int position() { return position; } @Override public int itemIndex() { return itemIndex; } @Override public boolean isAbsolute() { return true; } @Override public boolean isRelative() { return false; } //------------------------------------------------------------------------- @Override public boolean generalises(final FeatureElement other) { // absolute will never generalise relative if (other instanceof RelativeFeatureElement) { return false; } final AbsoluteFeatureElement otherElement = (AbsoluteFeatureElement) other; // absolute can only generalise another absolute if the positions are equal if (position == otherElement.position) { // and then we'll still need strict generalization from the type + not-flag test return FeatureElement.testTypeGeneralisation(type, not, otherElement.type, otherElement.not).strictlyGeneralises; } return false; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + itemIndex; result = prime * result + (not ? 1231 : 1237); result = prime * result + position; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(final Object other) { if (!(other instanceof AbsoluteFeatureElement)) { return false; } AbsoluteFeatureElement otherElement = (AbsoluteFeatureElement) other; return (type == otherElement.type && not == otherElement.not && position == otherElement.position && itemIndex == otherElement.itemIndex); } //------------------------------------------------------------------------- @Override public String toString() { String str = type().label; if (type == ElementType.Item || type == ElementType.IsPos || type == ElementType.Connectivity) { str += itemIndex; } if (not) { str = "!" + str; } str += String.format("{abs-%s}", Integer.valueOf(position)); return str; } //------------------------------------------------------------------------- }
5,347
19.490421
116
java
Ludii
Ludii-master/Features/src/features/spatial/elements/FeatureElement.java
package features.spatial.elements; /** * Abstract class for an element (for example, "empty", or "friend", or "any", etc.) that can be located * in a single site in a feature/pattern, which is specified relatively using a Walk. * * @author Dennis Soemers * */ public abstract class FeatureElement { //------------------------------------------------------------------------- /** Element types. */ public static enum ElementType { /** */ Empty("Empty", "-"), /** */ Friend("Friend", "f"), /** */ Enemy("Enemy", "e"), // NOTE: not supporting "Next" because we can't easily pre-generate instances that directly check for a context-dependent value /** Next player will be equal to Enemy in most games (exception: games where X may have more than 1 turn before Y has a single turn) */ //Next("Next", "n"), /** */ Off("Off", "#"), /** */ Any("Any", "*"), /** */ P1("P1", "1"), /** */ P2("P2", "2"), /** Index for a specific item */ Item("Item", "I"), /** Check if a position specified relatively evaluates to a specific (absolute) position */ IsPos("IsPos", "pos"), /** Check if a position specified relatively has number of connections = N */ Connectivity("Connectivity", "N"), /** Check if a position specified relatively is closer to a specific Region than the anchor position */ RegionProximity("RegionProximity", "R"), /** Check if a specific piece type is in orthogonal line-of-sight */ LineOfSightOrth("LineOfSightOrth", "LOSO"), /** Check if a specific piece type is in diagonal line-of-sight */ LineOfSightDiag("LineOfSightDiag", "LOSD"), // The following two are only used as "dummies" in Atomic Feature Generation, not inside actual features /** Only for use in atomic feature generation, not in real features */ LastFrom("LastFrom", "last_from"), /** Only for use in atomic feature generation, not in real features */ LastTo("LastTo", "last_to") ; /** Full name. */ public String name; /** Short label. */ public String label; //--------------------------------- /** * Constructor. * @param name * @param label */ ElementType(final String name, final String label) { this.name = name; this.label = label; } } //------------------------------------------------------------------------- /** * @param other * @return A deep copy of the given Feature Element */ public static FeatureElement copy(final FeatureElement other) { if (other instanceof AbsoluteFeatureElement) return new AbsoluteFeatureElement((AbsoluteFeatureElement) other); else if (other instanceof RelativeFeatureElement) return new RelativeFeatureElement((RelativeFeatureElement) other); else return null; } /** * @param string * @return New Feature Element constructed from string */ public static FeatureElement fromString(final String string) { if (string.contains("abs-")) return new AbsoluteFeatureElement(string); else return new RelativeFeatureElement(string); } //------------------------------------------------------------------------- /** * @param other * @return Whether this element strictly generalises the other one */ public abstract boolean generalises(final FeatureElement other); /** * @return Feature Element type */ public abstract ElementType type(); /** * Sets the element type. * @param type */ public abstract void setType(final ElementType type); /** * Mark that we do NOT want this element type to occur */ public abstract void negate(); /** * @return True if we're a negated element */ public abstract boolean not(); /** * @return True if this is an absolute feature */ public abstract boolean isAbsolute(); /** * @return True if this is a relative feature */ public abstract boolean isRelative(); /** * Most elements don't need a specific item index, but those of type "Item" or "IsPos" do * @return Item index for elements of type Item, or position for type IsPos */ public abstract int itemIndex(); //------------------------------------------------------------------------- /** * @param other * @return True if this feature element is compatible with the given other element * in same position. */ public final boolean isCompatibleWith(final FeatureElement other) { final ElementType myType = type(); final ElementType otherType = other.type(); if (myType == otherType && itemIndex() == other.itemIndex()) { return (not() == other.not()); } if (!not() && !other.not()) // neither negated { switch (myType) { case Empty: switch (otherType) { case Any: case IsPos: case Connectivity: case RegionProximity: case LineOfSightOrth: case LineOfSightDiag: return true; //$CASES-OMITTED$ default: return false; } case Friend: switch (otherType) { case Any: case P1: case P2: case Item: case IsPos: case Connectivity: case RegionProximity: case LineOfSightOrth: case LineOfSightDiag: return true; //$CASES-OMITTED$ default: return false; } case Enemy: switch (otherType) { case Any: case P1: case P2: case Item: case IsPos: case Connectivity: case RegionProximity: case LineOfSightOrth: case LineOfSightDiag: return true; //$CASES-OMITTED$ default: return false; } case Off: return false; case Any: return (otherType != ElementType.Off); case P1: switch (otherType) { case Any: case Friend: case Enemy: case P2: case Item: case IsPos: case Connectivity: case RegionProximity: case LineOfSightOrth: case LineOfSightDiag: return true; //$CASES-OMITTED$ default: return false; } case P2: switch (otherType) { case Any: case Friend: case Enemy: case P1: case Item: case IsPos: case Connectivity: case RegionProximity: case LineOfSightOrth: case LineOfSightDiag: return true; //$CASES-OMITTED$ default: return false; } case Item: switch (otherType) { case Any: case Friend: case Enemy: case P1: case P2: case IsPos: case Connectivity: case RegionProximity: case LineOfSightOrth: case LineOfSightDiag: return true; //$CASES-OMITTED$ default: return false; } case IsPos: switch (otherType) { case Any: case Friend: case Enemy: case P1: case P2: case Item: case Connectivity: case RegionProximity: case LineOfSightOrth: case LineOfSightDiag: return true; //$CASES-OMITTED$ default: return false; } case Connectivity: return (otherType != ElementType.Off); case RegionProximity: return (otherType != ElementType.Off); case LineOfSightOrth: return (otherType != ElementType.Off); case LineOfSightDiag: return (otherType != ElementType.Off); //$CASES-OMITTED$ default: System.err.println("Unrecognised element type: " + myType); throw new UnsupportedOperationException(); } } else if (not() && other.not()) // both negated { switch (myType) { case Empty: return (otherType != ElementType.Any); case Friend: return true; case Enemy: return true; case Off: return (otherType != ElementType.Any); case Any: return (otherType != ElementType.Off); case P1: return true; case P2: return true; case Item: return true; case IsPos: return true; case Connectivity: return (otherType != ElementType.Any); case RegionProximity: return (otherType != ElementType.Any); case LineOfSightOrth: return true; case LineOfSightDiag: return true; //$CASES-OMITTED$ default: System.err.println("Unrecognised element type: " + myType); throw new UnsupportedOperationException(); } } else if (not() && !other.not()) // we negated, other not negated { switch (myType) { case Empty: return true; case Friend: return true; case Enemy: return true; case Off: return true; case Any: return (otherType == ElementType.Off); case P1: return true; case P2: return true; case Item: return true; case IsPos: return true; case Connectivity: return (otherType != ElementType.Off); case RegionProximity: return (otherType != ElementType.Off); case LineOfSightOrth: return true; case LineOfSightDiag: return true; //$CASES-OMITTED$ default: System.err.println("Unrecognised element type: " + myType); throw new UnsupportedOperationException(); } } else // we not negated, other negated { return other.isCompatibleWith(this); } } //------------------------------------------------------------------------- /** * A pair of booleans that we can return when testing for generalisation between * two pairs of Element Type + not-flag. The first result will inform us about generalisation, * and the second about strict generalisation (excluding equality). * * @author Dennis Soemers */ public static class TypeGeneralisationResult { /** Whether we generalise (or are equal) */ public boolean generalises; /** Whether we strictly generalise (no equality) */ public boolean strictlyGeneralises; /** * Constructor * @param generalises * @param strictlyGeneralises */ public TypeGeneralisationResult(final boolean generalises, final boolean strictlyGeneralises) { this.generalises = generalises; this.strictlyGeneralises = strictlyGeneralises; } } /** * Tells us whether an element with the first type and first not-flag may generalise * (both strictly and not strictly) a different element with the second type and not-flag * (does not yet test for walks/positions). * * @param firstType * @param firstNot * @param secondType * @param secondNot * @return Result. */ public static TypeGeneralisationResult testTypeGeneralisation ( final ElementType firstType, final boolean firstNot, final ElementType secondType, final boolean secondNot ) { if (firstNot && !secondNot) { //----------------------------------------------------------------- // We have a "not" modifier and the other element doesn't //----------------------------------------------------------------- switch (firstType) { case Empty: // "not empty" fails to generalise "empty", "off board", "item" (which may test for empty with itemIndex = 0), // "is pos", and "connectivity" if ( secondType == ElementType.Empty || secondType == ElementType.Off || secondType == ElementType.Item || secondType == ElementType.IsPos || secondType == ElementType.Connectivity || secondType == ElementType.RegionProximity || secondType == ElementType.LineOfSightOrth || secondType == ElementType.LineOfSightDiag ) { return new TypeGeneralisationResult(false, false); } else { return new TypeGeneralisationResult(true, true); } case Friend: // "not friend" generalises "empty", "enemy", and "off board" if ( secondType != ElementType.Empty && secondType != ElementType.Enemy && secondType != ElementType.Off ) { return new TypeGeneralisationResult(false, false); } else { return new TypeGeneralisationResult(true, true); } case Enemy: // "not enemy" generalises "empty", "friend", and "off board" if ( secondType != ElementType.Empty && secondType != ElementType.Friend && secondType != ElementType.Off ) { return new TypeGeneralisationResult(false, false); } else { return new TypeGeneralisationResult(true, true); } case Off: // "not off" only fails to generalise "any" and "off board" if (secondType == ElementType.Off || secondType == ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case Any: // "not any" can only equal "off board" (but not a strict generalisation) if (secondType != ElementType.Off) return new TypeGeneralisationResult(false, false); else break; case P1: // "not P1" generalises "empty", "off board", and "P2" if ( secondType != ElementType.Empty && secondType != ElementType.Off && secondType != ElementType.P2 ) { return new TypeGeneralisationResult(false, false); } else { return new TypeGeneralisationResult(true, true); } case P2: // "not P2" generalises "empty", "off board", and "P1" if ( secondType != ElementType.Empty && secondType != ElementType.Off && secondType != ElementType.P1 ) { return new TypeGeneralisationResult(false, false); } else { return new TypeGeneralisationResult(true, true); } case Item: // "not item" only generalises "off board" if (secondType != ElementType.Off) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case IsPos: // "not is pos" doesn't generalise anything return new TypeGeneralisationResult(false, false); case Connectivity: // "not connectivity" doesn't generalise anything return new TypeGeneralisationResult(false, false); case RegionProximity: // "not closer than anchor to region" doesn't generalise anything return new TypeGeneralisationResult(false, false); case LineOfSightOrth: // "not in orthogonal line of sight" doesn't generalise anything return new TypeGeneralisationResult(false, false); case LineOfSightDiag: // "not in diagonal line of sight" doesn't generalise anything return new TypeGeneralisationResult(false, false); //$CASES-OMITTED$ default: System.err.println("Unrecognised element type: " + firstType); throw new UnsupportedOperationException(); } } else if (!firstNot && secondNot) { //----------------------------------------------------------------- // We do not have a "not" modifier and the other element does //----------------------------------------------------------------- if (firstType == ElementType.Off) // "off board" only equals "not any" (but not a strict generalisation) { if (secondType != ElementType.Any) { return new TypeGeneralisationResult(false, false); } } else // any other "X" doesn't generalise any "not Y" { return new TypeGeneralisationResult(false, false); } } else if (!firstNot && !secondNot) { //----------------------------------------------------------------- // Both elements have a "not" modifier //----------------------------------------------------------------- switch (firstType) { case Empty: // "not empty" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case Friend: // "not friend" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case Enemy: // "not enemy" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case Off: // "not off" only generalises "not empty" if (secondType != ElementType.Empty) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case Any: // "not any" can only equal "not any", but not generalise any other "not X" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else break; case P1: // "not P1" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case P2: // "not P2" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case Item: // "not Item" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case IsPos: // "not Is Pos" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case Connectivity: // "not connectivity" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case RegionProximity: // "not closer than anchor to region" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case LineOfSightOrth: // "not in orthogonal line of sight" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); case LineOfSightDiag: // "not in diagonal line of sight" only generalises "not any" if (secondType != ElementType.Any) return new TypeGeneralisationResult(false, false); else return new TypeGeneralisationResult(true, true); //$CASES-OMITTED$ default: System.err.println("Unrecognised element type: " + firstType); throw new UnsupportedOperationException(); } } else { //----------------------------------------------------------------- // Neither element has a "not" modifier //----------------------------------------------------------------- if (firstType != secondType) // only need to consider cases where the types are different, otherwise they're always equal { if (firstType != ElementType.Any) // anything other than "any" won't be a generalisation { return new TypeGeneralisationResult(false, false); } else { if (secondType != ElementType.Any) { return new TypeGeneralisationResult(true, true); } } } } return new TypeGeneralisationResult(true, false); } }
18,864
25.607898
137
java
Ludii
Ludii-master/Features/src/features/spatial/elements/RelativeFeatureElement.java
package features.spatial.elements; import features.spatial.Walk; /** * Feature Elements with positions specified relatively (through Walks) * * @author Dennis Soemers and cambolbro */ public class RelativeFeatureElement extends FeatureElement { //------------------------------------------------------------------------- /** */ protected ElementType type = null; /** Set to true to negate any element-type-based test */ protected boolean not = false; /** How do we end up in the site where we expect to see this from some reference point? */ protected Walk walk; /** Index of Item to check for in cases where type == ElementType.Item */ protected final int itemIndex; //------------------------------------------------------------------------- /** * Constructor. * @param type * @param walk */ public RelativeFeatureElement(final ElementType type, final Walk walk) { this(type, false, walk, -1); } /** * Constructor. * @param type * @param not * @param walk */ public RelativeFeatureElement ( final ElementType type, final boolean not, final Walk walk ) { this(type, not, walk, -1); } /** * Constructor. * @param type * @param walk * @param itemIndex */ public RelativeFeatureElement ( final ElementType type, final Walk walk, final int itemIndex ) { this(type, false, walk, itemIndex); } /** * Constructor. * @param type * @param not * @param walk * @param itemIndex */ public RelativeFeatureElement ( final ElementType type, final boolean not, final Walk walk, final int itemIndex ) { this.type = type; this.not = not; this.walk = walk; this.itemIndex = itemIndex; } /** * Copy constructor. * @param other */ public RelativeFeatureElement(final RelativeFeatureElement other) { type = other.type; not = other.not; walk = new Walk(other.walk()); itemIndex = other.itemIndex; } /** * Constructor from string * @param string */ public RelativeFeatureElement(final String string) { final int startWalkStringIdx = string.indexOf("{"); String typeString = string.substring(0, startWalkStringIdx); final String walkString = string.substring(startWalkStringIdx); if (typeString.startsWith("!")) { not = true; typeString = typeString.substring("!".length()); } int iIdx = -1; for (final ElementType elType : ElementType.values()) { if (typeString.startsWith(elType.label)) { type = elType; if (typeString.length() > elType.label.length()) { iIdx = Integer.parseInt( typeString.substring(elType.label.length())); } break; } } itemIndex = iIdx; walk = new Walk(walkString); } //------------------------------------------------------------------------- @Override public ElementType type() { return type; } @Override public void setType(final ElementType type) { this.type = type; } @Override public void negate() { not = true; } @Override public boolean not() { return not; } /** * @return The walk */ public Walk walk() { return walk; } @Override public int itemIndex() { return itemIndex; } @Override public boolean isAbsolute() { return false; } @Override public boolean isRelative() { return true; } //------------------------------------------------------------------------- @Override public boolean generalises(final FeatureElement other) { final TypeGeneralisationResult generalisationResult = FeatureElement.testTypeGeneralisation(type, not, other.type(), other.not()); if (!generalisationResult.generalises) { return false; } //--------------------------------------------------------------------- // We have compared types and not-modifiers, need to look at Walks now //--------------------------------------------------------------------- if (other instanceof AbsoluteFeatureElement) { // relative can only generalise absolute if we have no // restriction on relative positions return walk.steps().size() == 0; } final RelativeFeatureElement otherRel = (RelativeFeatureElement) other; return (generalisationResult.strictlyGeneralises && walk.equals(otherRel.walk())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + itemIndex; result = prime * result + (not ? 1231 : 1237); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((walk == null) ? 0 : walk.hashCode()); return result; } @Override public boolean equals(final Object other) { if (!(other instanceof RelativeFeatureElement)) return false; final RelativeFeatureElement otherElement = (RelativeFeatureElement) other; return (type == otherElement.type && not == otherElement.not && walk.equals(otherElement.walk()) && itemIndex == otherElement.itemIndex); } //------------------------------------------------------------------------- @Override public String toString() { String str = type().label; if ( type == ElementType.Item || type == ElementType.IsPos || type == ElementType.Connectivity || type == ElementType.RegionProximity || type == ElementType.LineOfSightOrth || type == ElementType.LineOfSightDiag ) { str += itemIndex; } if (not) { str = "!" + str; } str += walk; return str; } //------------------------------------------------------------------------- }
5,532
18.620567
91
java
Ludii
Ludii-master/Features/src/features/spatial/graph_search/GraphSearch.java
package features.spatial.graph_search; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import features.spatial.Walk; import game.Game; import gnu.trove.list.array.TFloatArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import other.topology.TopologyElement; /** * Some useful graph search algorithms. These are intended to be used specifically * with features (e.g. for finding / constructing features), so they follow similar * rules as the Walks in features do (e.g. no diagonal connections, allow connections * to off-board "locations", ...) * * @author Dennis Soemers */ public class GraphSearch { //------------------------------------------------------------------------- /** * Constructor */ private GraphSearch() { // no need to instantiate } //------------------------------------------------------------------------- /** * Implemented using uniform-cost search, we don't really have meaningful * costs or heuristics for Dijkstra's or A* * * @param game * @param startSite * @param destination * @return Shortest path from startSite to destination */ public static Path shortestPathTo(final Game game, final TopologyElement startSite, final TopologyElement destination) { final TIntSet alreadyVisited = new TIntHashSet(); final Queue<Path> fringe = new ArrayDeque<Path>(); List<TopologyElement> pathSites = new ArrayList<TopologyElement>(); pathSites.add(startSite); fringe.add(new Path(pathSites, new Walk())); alreadyVisited.add(startSite.index()); final List<? extends TopologyElement> sites = game.graphPlayElements(); while (!fringe.isEmpty()) { final Path path = fringe.remove(); final TopologyElement pathEnd = path.destination(); final int numOrthos = pathEnd.sortedOrthos().length; final TFloatArrayList rotations = Walk.rotationsForNumOrthos(numOrthos); for (int i = 0; i < rotations.size(); ++i) { final float nextStep = rotations.getQuick(i); // create a new walk with this new step final Walk newWalk = new Walk(path.walk()); newWalk.steps().add(nextStep); // see where we would end up if we were to follow this walk final TIntArrayList destinations = newWalk.resolveWalk(game, startSite, 0.f, 1); if (destinations.size() != 1) { System.err.println("WARNING: GraphSearch.shortestPathTo() resolved " + "a walk with " + destinations.size() + " destinations!"); } final int endWalkIdx = destinations.getQuick(0); if (destination.index() == endWalkIdx) { // we're done pathSites = new ArrayList<TopologyElement>(path.sites); pathSites.add(destination); return new Path(pathSites, newWalk); } else if (endWalkIdx >= 0 && !alreadyVisited.contains(endWalkIdx)) { // new path for fringe alreadyVisited.add(endWalkIdx); pathSites = new ArrayList<TopologyElement>(path.sites); pathSites.add(sites.get(endWalkIdx)); fringe.add(new Path(pathSites, newWalk)); } } } //System.out.println("startVertex = " + startVertex); //System.out.println("destination = " + destination); return null; } //------------------------------------------------------------------------- }
3,367
29.342342
119
java
Ludii
Ludii-master/Features/src/features/spatial/graph_search/Path.java
package features.spatial.graph_search; import java.util.List; import features.spatial.Walk; import other.topology.TopologyElement; /** * A Path used in graph search algorithms for features. A path consists of a * starting site, a destination site (may be null for off-board, or may be * the same as the start vertex for a 0-length path), and a Walk that moves from * the start to the destination. * * @author Dennis Soemers */ public class Path { //------------------------------------------------------------------------- /** List of sites on this path */ protected final List<TopologyElement> sites; /** */ protected final Walk walk; //------------------------------------------------------------------------- /** * Constructor * @param sites * @param walk */ public Path(final List<TopologyElement> sites, final Walk walk) { this.sites = sites; this.walk = walk; } //------------------------------------------------------------------------- /** * @return Destination Vertex */ public TopologyElement destination() { return sites.get(sites.size() - 1); } /** * @return Start vertex */ public TopologyElement start() { return sites.get(0); } /** * @return All sites on the path */ public List<TopologyElement> sites() { return sites; } /** * @return The Walk */ public Walk walk() { return walk; } //------------------------------------------------------------------------- }
1,476
18.181818
80
java
Ludii
Ludii-master/Features/src/features/spatial/instances/AtomicProposition.java
package features.spatial.instances; import game.Game; import game.equipment.component.Component; import gnu.trove.list.array.TIntArrayList; import main.collections.ChunkSet; /** * An atomic proposition is a test that checks for only a single specific * value (either absent or present) in a single specific chunk of a single * data vector. * * @author Dennis Soemers */ public abstract class AtomicProposition implements BitwiseTest { //------------------------------------------------------------------------- /** * Types of state vectors that atomic propositions can apply to * * @author Dennis Soemers */ public enum StateVectorTypes { /** For propositions that check the Empty chunkset */ Empty, /** For propositions that check the Who chunkset */ Who, /** For propositions that check the What chunkset */ What } //------------------------------------------------------------------------- @Override public boolean hasNoTests() { return false; } /** * Add mask for bits checked by this proposition to given chunkset * @param chunkSet */ public abstract void addMaskTo(final ChunkSet chunkSet); /** * @return State vector type this atomic proposition applies to. */ public abstract StateVectorTypes stateVectorType(); /** * @return Which site does this proposition look at? */ public abstract int testedSite(); /** * @return What value do we expect to (not) see? */ public abstract int value(); /** * @return Do we expect to NOT see the value returned by value()? */ public abstract boolean negated(); //------------------------------------------------------------------------- /** * @param other * @param game * @return Does this proposition being true also prove the given other prop? */ public abstract boolean provesIfTrue(final AtomicProposition other, final Game game); /** * @param other * @param game * @return Does this proposition being true disprove the given other prop? */ public abstract boolean disprovesIfTrue(final AtomicProposition other, final Game game); /** * @param other * @param game * @return Does this proposition being false prove the given other prop? */ public abstract boolean provesIfFalse(final AtomicProposition other, final Game game); /** * @param other * @param game * @return Does this proposition being false disprove the given other prop? */ public abstract boolean disprovesIfFalse(final AtomicProposition other, final Game game); //------------------------------------------------------------------------- /** * @param game * @param player * @return List of component IDs owned by given player */ public static TIntArrayList ownedComponentIDs(final Game game, final int player) { final TIntArrayList owned = new TIntArrayList(); final Component[] components = game.equipment().components(); for (int i = 0; i < components.length; ++i) { final Component comp = components[i]; if (comp == null) continue; if (comp.owner() == player) owned.add(i); } return owned; } /** * @param game * @param compID * @return True if and only if, in the given game, the owner of given comp ID doesn't own any other components */ public static boolean ownerOnlyOwns(final Game game, final int compID) { final Component[] components = game.equipment().components(); final int owner = components[compID].owner(); for (int i = 0; i < components.length; ++i) { if (i == compID) continue; final Component comp = components[i]; if (comp == null) continue; if (comp.owner() == owner) return false; } return true; } /** * @param game * @param player * @param compID * @return True if and only if, in the given game, given player only owns the given component ID and no other components */ public static boolean playerOnlyOwns(final Game game, final int player, final int compID) { final Component[] components = game.equipment().components(); if (components[compID].owner() != player) return false; for (int i = 0; i < components.length; ++i) { if (i == compID) continue; final Component comp = components[i]; if (comp == null) continue; if (comp.owner() == player) return false; } return true; } //------------------------------------------------------------------------- }
4,424
23.447514
121
java
Ludii
Ludii-master/Features/src/features/spatial/instances/BitwiseTest.java
package features.spatial.instances; import game.types.board.SiteType; import other.state.State; /** * Interface for classes that can perform bitwise tests on game states. * * The primary class implementing this interface is the general Feature * Instance, but there are also some more specific subclasses that only * need a small part of the full Feature Instance functionality, and can * run their tests more efficiently. * * @author Dennis Soemers */ public interface BitwiseTest { //------------------------------------------------------------------------- /** * @param state * @return True if this test matches the given game state */ public boolean matches(final State state); //------------------------------------------------------------------------- /** * @return True if and only if this test automatically returns true */ public boolean hasNoTests(); /** * @return True if and only if this test only requires a single chunk to * be empty. */ public boolean onlyRequiresSingleMustEmpty(); /** * @return True if and only if this test only requires a single chunk to be * owned by a specific player. */ public boolean onlyRequiresSingleMustWho(); /** * @return True if and only if this test only requires a single chunk to * contain a specific component. */ public boolean onlyRequiresSingleMustWhat(); /** * @return GraphElementType that this test applies to */ public SiteType graphElementType(); //------------------------------------------------------------------------- }
1,566
25.116667
76
java
Ludii
Ludii-master/Features/src/features/spatial/instances/FeatureInstance.java
package features.spatial.instances; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import features.spatial.SpatialFeature; import features.spatial.SpatialFeature.BitSetTypes; import features.spatial.elements.FeatureElement; import game.types.board.SiteType; import gnu.trove.list.array.TIntArrayList; import main.Constants; import main.collections.ChunkSet; import main.math.BitTwiddling; import other.state.State; import other.state.container.ContainerState; //----------------------------------------------------------------------------- /** * A concrete instance of a feature (always in an absolute positions, and in * BitSet-representation for efficient detection). * * @author Dennis Soemers */ public final class FeatureInstance implements BitwiseTest { //------------------------------------------------------------------------- /** Reference to the feature of which this is an instance */ protected final SpatialFeature parentFeature; /** Index of the vertex used as anchor for this instance */ protected final int anchorSite; /** Reflection multiplier applied to parent feature for this instance */ protected final int reflection; /** Additional rotation applied to parent feature for this instance */ protected final float rotation; /** The graph element type this instance tests on */ protected final SiteType graphElementType; /** Elements that have already passed testing at init-time */ protected final List<FeatureElement> initTimeElements = new ArrayList<FeatureElement>(); //------------------------------------------------------------------------- /** Set bits must be empty in the game state */ protected ChunkSet mustEmpty; /** Set bits must be NOT empty in the game state */ protected ChunkSet mustNotEmpty; /** After masking the game state's "who" bits, it must equal these bits */ protected ChunkSet mustWho; /** Mask to apply to game state's "who" bits before testing */ protected ChunkSet mustWhoMask; /** * After masking the game state's "who" bits, it must NOT equal these bits */ protected ChunkSet mustNotWho; /** Mask to apply to game state's "who" bits before testing */ protected ChunkSet mustNotWhoMask; /** After masking the game state's "what" bits, it must equal these bits */ protected ChunkSet mustWhat; /** Mask to apply to game state's "what" bits before testing */ protected ChunkSet mustWhatMask; /** * After masking the game state's "what" bits, it must NOT equal these bits */ protected ChunkSet mustNotWhat; /** Mask to apply to game state's "what" bits before testing */ protected ChunkSet mustNotWhatMask; /** This will be True if all of the above ChunkSets are null */ protected transient boolean allRestrictionsNull; //------------------------------------------------------------------------- /** "to" position of action recommended by this feature instance */ protected int toPosition; /** "from" position of action recommended by this feature instance */ protected int fromPosition; /** "to" position of last action, which this feature instance reacts to */ protected int lastToPosition; /** "from" position of last action, which this feature instance reacts to */ protected int lastFromPosition; //------------------------------------------------------------------------- /** * Constructs new Feature Instance * @param parentFeature * @param anchorSite * @param reflection * @param rotation * @param graphElementType */ public FeatureInstance ( final SpatialFeature parentFeature, final int anchorSite, final int reflection, final float rotation, final SiteType graphElementType ) { this.parentFeature = parentFeature; this.anchorSite = anchorSite; this.reflection = reflection; this.rotation = rotation; this.graphElementType = graphElementType; mustEmpty = null; mustNotEmpty = null; mustWho = null; mustWhoMask = null; mustNotWho = null; mustNotWhoMask = null; mustWhat = null; mustWhatMask = null; mustNotWhat = null; mustNotWhatMask = null; allRestrictionsNull = true; toPosition = -1; fromPosition = -1; lastToPosition = -1; lastFromPosition = -1; } /** * Copy constructor * @param other */ public FeatureInstance(final FeatureInstance other) { this.parentFeature = other.parentFeature; this.anchorSite = other.anchorSite; this.reflection = other.reflection; this.rotation = other.rotation; this.graphElementType = other.graphElementType; mustEmpty = other.mustEmpty == null ? null : (ChunkSet) other.mustEmpty.clone(); mustNotEmpty = other.mustNotEmpty == null ? null : (ChunkSet) other.mustNotEmpty.clone(); mustWho = other.mustWho == null ? null : (ChunkSet) other.mustWho.clone(); mustWhoMask = other.mustWhoMask == null ? null : (ChunkSet) other.mustWhoMask.clone(); mustNotWho = other.mustNotWho == null ? null : (ChunkSet) other.mustNotWho.clone(); mustNotWhoMask = other.mustNotWhoMask == null ? null : (ChunkSet) other.mustNotWhoMask.clone(); mustWhat = other.mustWhat == null ? null : (ChunkSet) other.mustWhat.clone(); mustWhatMask = other.mustWhatMask == null ? null : (ChunkSet) other.mustWhatMask.clone(); mustNotWhat = other.mustNotWhat == null ? null : (ChunkSet) other.mustNotWhat.clone(); mustNotWhatMask = other.mustNotWhatMask == null ? null : (ChunkSet) other.mustNotWhatMask.clone(); allRestrictionsNull = other.allRestrictionsNull; toPosition = other.toPosition; fromPosition = other.fromPosition; lastToPosition = other.lastToPosition; lastFromPosition = other.lastFromPosition; initTimeElements.addAll(other.initTimeElements); } //------------------------------------------------------------------------- /** * Adds an element that has already been satisfied at init-time * @param element */ public void addInitTimeElement(final FeatureElement element) { initTimeElements.add(element); } /** * Adds a test without any particular value (testing for something like Empty, rather than something like * a specific Player or Item). * @param container * @param bitSetType * @param testSite * @param active * @return True if the test was successfully added, false if it would lead to inconsistencies */ public boolean addTest ( final ContainerState container, final BitSetTypes bitSetType, final int testSite, final boolean active ) { return addTest(container, bitSetType, testSite, active, -1); } /** * Adds a test to the feature instance * @param container * @param bitSetType * @param testSite * @param active * @param value * @return True if the test was successfully added, false if it would lead to inconsistencies */ public boolean addTest ( final ContainerState container, final BitSetTypes bitSetType, final int testSite, final boolean active, final int value ) { switch (bitSetType) { case Empty: if (active) { if (mustNotEmpty != null && mustNotEmpty.get(testSite)) return false; // inconsistency: we already require this site to be non-empty if (mustEmpty == null) { switch (graphElementType) { case Cell: mustEmpty = new ChunkSet(1, 1); break; case Vertex: mustEmpty = new ChunkSet(1, 1); break; case Edge: mustEmpty = new ChunkSet(1, 1); break; //$CASES-OMITTED$ Hint default: break; } } mustEmpty.set(testSite); allRestrictionsNull = false; } else { if (mustEmpty != null && mustEmpty.get(testSite)) return false; // inconsistency: we already require this site to be empty if (mustNotEmpty == null) { switch (graphElementType) { case Cell: mustNotEmpty = new ChunkSet(1, 1); break; case Vertex: mustNotEmpty = new ChunkSet(1, 1); break; case Edge: mustNotEmpty = new ChunkSet(1, 1); break; //$CASES-OMITTED$ Hint default: break; } } mustNotEmpty.set(testSite); allRestrictionsNull = false; } break; case Who: if (active) { if (mustWhoMask != null && mustWhoMask.getChunk(testSite) != 0) { // we already have who-requirements for this chunk // will only be fine if exactly the same value is already // required (redundant), otherwise it will be an // inconsistency which is not fine return (mustWho.getChunk(testSite) == value); } else if (mustNotWhoMask != null && mustNotWho.getChunk(testSite) == value) { // inconsistency: we already have a requirement that who // should specifically NOT be this value return false; } if (mustWho == null) { final int chunkSize; switch (graphElementType) { case Cell: chunkSize = container.chunkSizeWhoCell(); break; case Edge: chunkSize = container.chunkSizeWhoEdge(); break; case Vertex: chunkSize = container.chunkSizeWhoVertex(); break; //$CASES-OMITTED$ Hint default: chunkSize = Constants.UNDEFINED; break; } mustWho = new ChunkSet(chunkSize, 1); mustWhoMask = new ChunkSet(chunkSize, 1); } mustWho.setChunk(testSite, value); mustWhoMask.setChunk(testSite, BitTwiddling.maskI(mustWhoMask.chunkSize())); allRestrictionsNull = false; } else { if (mustNotWhoMask != null && mustNotWhoMask.getChunk(testSite) != 0) { // we already have not-who-requirements for this chunk // will only be fine if exactly the same value is already // not allowed (redundant), otherwise it will be an // inconsistency which is not fine return (mustNotWho.getChunk(testSite) == value); } else if (mustWhoMask != null && mustWho.getChunk(testSite) == value) { // inconsistency: we already have a requirement that who // should specifically be this value return false; } if (mustNotWho == null) { final int chunkSize; switch (graphElementType) { case Cell: chunkSize = container.chunkSizeWhoCell(); break; case Edge: chunkSize = container.chunkSizeWhoEdge(); break; case Vertex: chunkSize = container.chunkSizeWhoVertex(); break; //$CASES-OMITTED$ Hint default: chunkSize = Constants.UNDEFINED; break; } mustNotWho = new ChunkSet(chunkSize, 1); mustNotWhoMask = new ChunkSet(chunkSize, 1); } mustNotWho.setChunk(testSite, value); mustNotWhoMask.setChunk(testSite, BitTwiddling.maskI(mustNotWhoMask.chunkSize())); allRestrictionsNull = false; } break; case What: if (active) { if (mustWhatMask != null && mustWhatMask.getChunk(testSite) != 0) { // we already have what-requirements for this chunk // will only be fine if exactly the same value is already // required (redundant), otherwise it will be an // inconsistency which is not fine return (mustWhat.getChunk(testSite) == value); } else if ( mustNotWhatMask != null && mustNotWhat.getChunk(testSite) == value ) { // inconsistency: we already have a requirement that what // should specifically NOT be this value return false; } if (mustWhat == null) { final int chunkSize; switch (graphElementType) { case Cell: chunkSize = container.chunkSizeWhatCell(); break; case Edge: chunkSize = container.chunkSizeWhatEdge(); break; case Vertex: chunkSize = container.chunkSizeWhatVertex(); break; //$CASES-OMITTED$ Hint default: chunkSize = Constants.UNDEFINED; break; } mustWhat = new ChunkSet(chunkSize, 1); mustWhatMask = new ChunkSet(chunkSize, 1); } mustWhat.setChunk(testSite, value); mustWhatMask.setChunk(testSite, BitTwiddling.maskI(mustWhatMask.chunkSize())); allRestrictionsNull = false; } else { if (mustNotWhatMask != null && mustNotWhatMask.getChunk(testSite) != 0) { // we already have not-what-requirements for this chunk // will only be fine if exactly the same value is already // not allowed (redundant), otherwise it will be an // inconsistency which is not fine return (mustNotWhat.getChunk(testSite) == value); } else if (mustWhatMask != null && mustWhat.getChunk(testSite) == value) { // inconsistency: we already have a requirement that what // should specifically be this value return false; } if (mustNotWhat == null) { final int chunkSize; switch (graphElementType) { case Cell: chunkSize = container.chunkSizeWhatCell(); break; case Edge: chunkSize = container.chunkSizeWhatEdge(); break; case Vertex: chunkSize = container.chunkSizeWhatVertex(); break; //$CASES-OMITTED$ Hint default: chunkSize = Constants.UNDEFINED; break; } mustNotWhat = new ChunkSet(chunkSize, 1); mustNotWhatMask = new ChunkSet(chunkSize, 1); } mustNotWhat.setChunk(testSite, value); mustNotWhatMask.setChunk(testSite, BitTwiddling.maskI(mustNotWhatMask.chunkSize())); allRestrictionsNull = false; } break; //$CASES-OMITTED$ default: System.err.println("Warning: bitSetType " + bitSetType + " not supported by FeatureInstance.addTest()!"); return false; } return true; } //------------------------------------------------------------------------- /** * @param state * @return True if this feature instance is active in the given game state */ @Override public final boolean matches(final State state) { if (allRestrictionsNull) return true; final ContainerState container = state.containerStates()[0]; switch (graphElementType) { case Cell: if (mustEmpty != null) { if (!container.emptyChunkSetCell().matches(mustEmpty, mustEmpty)) return false; } if (mustNotEmpty != null) { if (container.emptyChunkSetCell().violatesNot(mustNotEmpty, mustNotEmpty)) return false; } if (mustWho != null) { if (!container.matchesWhoCell(mustWhoMask, mustWho)) return false; } if (mustNotWho != null) { if (container.violatesNotWhoCell(mustNotWhoMask, mustNotWho)) return false; } if (mustWhat != null) { if (!container.matchesWhatCell(mustWhatMask, mustWhat)) return false; } if (mustNotWhat != null) { if (container.violatesNotWhatCell(mustNotWhatMask, mustNotWhat)) return false; } break; case Vertex: if (mustEmpty != null) { if (!container.emptyChunkSetVertex().matches(mustEmpty, mustEmpty)) return false; } if (mustNotEmpty != null) { if (container.emptyChunkSetVertex().violatesNot(mustNotEmpty, mustNotEmpty)) return false; } if (mustWho != null) { if (!container.matchesWhoVertex(mustWhoMask, mustWho)) return false; } if (mustNotWho != null) { if (container.violatesNotWhoVertex(mustNotWhoMask, mustNotWho)) return false; } if (mustWhat != null) { if (!container.matchesWhatVertex(mustWhatMask, mustWhat)) return false; } if (mustNotWhat != null) { if (container.violatesNotWhatVertex(mustNotWhatMask, mustNotWhat)) return false; } break; case Edge: if (mustEmpty != null) { if (!container.emptyChunkSetEdge().matches(mustEmpty, mustEmpty)) return false; } if (mustNotEmpty != null) { if (container.emptyChunkSetEdge().violatesNot(mustNotEmpty, mustNotEmpty)) return false; } if (mustWho != null) { if (!container.matchesWhoEdge(mustWhoMask, mustWho)) return false; } if (mustNotWho != null) { if (container.violatesNotWhoEdge(mustNotWhoMask, mustNotWho)) return false; } if (mustWhat != null) { if (!container.matchesWhatEdge(mustWhatMask, mustWhat)) return false; } if (mustNotWhat != null) { if (container.violatesNotWhatEdge(mustNotWhatMask, mustNotWhat)) return false; } break; default: break; } return true; } //------------------------------------------------------------------------- /** * We say that a Feature Instance A generalises another Feature Instance B * if and only if any restrictions encoded in the various ChunkSets of * A are also contained in B. Note that A and B are also considered to * be generalising each other if they happen to have exactly the same * ChunkSets. * * Other properties (rotation, reflection, anchor, parent feature, etc.) * are not included in the generalisation test. * * Note that this definition of generalisation is a bit different from * the generalisation tests of full Feature objects. * * @param other * @return True if and only if this Feature Instance generalises the other */ public boolean generalises(final FeatureInstance other) { if (other.mustEmpty == null) { if (mustEmpty != null) return false; } else { if (mustEmpty != null && !other.mustEmpty.matches(mustEmpty, mustEmpty)) return false; } if (other.mustNotEmpty == null) { if (mustNotEmpty != null) return false; } else { if (mustNotEmpty != null && !other.mustNotEmpty.matches(mustNotEmpty, mustNotEmpty)) return false; } if (other.mustWho == null) { if (mustWho != null) return false; } else { if (mustWho != null && !other.mustWho.matches(mustWhoMask, mustWho)) return false; } if (other.mustNotWho == null) { if (mustNotWho != null) return false; } else { if (mustNotWho != null && !other.mustNotWho.matches(mustNotWhoMask, mustNotWho)) return false; } if (other.mustWhat == null) { if (mustWhat != null) return false; } else { if (mustWhat != null && !other.mustWhat.matches(mustWhatMask, mustWhat)) return false; } if (other.mustNotWhat == null) { if (mustNotWhat != null) return false; } else { if (mustNotWhat != null && !other.mustNotWhat.matches(mustNotWhatMask, mustNotWhat)) return false; } return true; } //------------------------------------------------------------------------- /** * Removes any tests from this instance that are also already contained * in the other given Feature Instance. This implies that we'll make sure * to only attempt matching this Feature Instance to game states in which * we have already previously verified that the other Feature Instance * matches. * * @param other */ public void removeTests(final FeatureInstance other) { if (other.mustEmpty != null) { mustEmpty.andNot(other.mustEmpty); if (mustEmpty.cardinality() == 0) { // no longer need this mustEmpty = null; } } if (other.mustNotEmpty != null) { mustNotEmpty.andNot(other.mustNotEmpty); if (mustNotEmpty.cardinality() == 0) { // no longer need this mustNotEmpty = null; } } if (other.mustWho != null) { mustWho.andNot(other.mustWho); mustWhoMask.andNot(other.mustWhoMask); if (mustWho.cardinality() == 0) { // no longer need this mustWho = null; mustWhoMask = null; } } if (other.mustNotWho != null) { mustNotWho.andNot(other.mustNotWho); mustNotWhoMask.andNot(other.mustNotWhoMask); if (mustNotWho.cardinality() == 0) { // no longer need this mustNotWho = null; mustNotWhoMask = null; } } if (other.mustWhat != null) { mustWhat.andNot(other.mustWhat); mustWhatMask.andNot(other.mustWhatMask); if (mustWhat.cardinality() == 0) { // no longer need this mustWhat = null; mustWhatMask = null; } } if (other.mustNotWhat != null) { mustNotWhat.andNot(other.mustNotWhat); mustNotWhatMask.andNot(other.mustNotWhatMask); if (mustNotWhat.cardinality() == 0) { // no longer need this mustNotWhat = null; mustNotWhatMask = null; } } allRestrictionsNull = hasNoTests(); } //------------------------------------------------------------------------- /** * @return True if and only if this Feature Instance has no meaningful * tests (i.e. all ChunkSets are null) */ @Override public final boolean hasNoTests() { return (mustEmpty == null && mustNotEmpty == null && mustWho == null && mustWhoMask == null && mustNotWho == null && mustNotWhoMask == null && mustWhat == null && mustWhatMask == null && mustNotWhat == null && mustNotWhatMask == null); } @Override public final boolean onlyRequiresSingleMustEmpty() { if ( mustEmpty != null && mustNotEmpty == null && mustWho == null && mustWhoMask == null && mustNotWho == null && mustNotWhoMask == null && mustWhat == null && mustWhatMask == null && mustNotWhat == null && mustNotWhatMask == null ) { return mustEmpty.numNonZeroChunks() == 1; } return false; } @Override public final boolean onlyRequiresSingleMustWho() { if ( mustEmpty == null && mustNotEmpty == null && mustWho != null && mustWhoMask != null && mustNotWho == null && mustNotWhoMask == null && mustWhat == null && mustWhatMask == null && mustNotWhat == null && mustNotWhatMask == null ) { return mustWhoMask.numNonZeroChunks() == 1; } return false; } @Override public final boolean onlyRequiresSingleMustWhat() { if ( mustEmpty == null && mustNotEmpty == null && mustWho == null && mustWhoMask == null && mustNotWho == null && mustNotWhoMask == null && mustWhat != null && mustWhatMask != null && mustNotWhat == null && mustNotWhatMask == null ) { return mustWhatMask.numNonZeroChunks() == 1; } return false; } //------------------------------------------------------------------------- /** * @return Feature of which this is an instance */ public final SpatialFeature feature() { return parentFeature; } /** * @return Anchor site for this instance */ public final int anchorSite() { return anchorSite; } /** * @return Reflection applied to parent feature to obtain this instance */ public final int reflection() { return reflection; } /** * @return Rotation applied to parent feature to obtain this instance */ public final float rotation() { return rotation; } @Override public final SiteType graphElementType() { return graphElementType; } /** * @return From-position (-1 if not restricted) */ public final int from() { return fromPosition; } /** * @return To-position (-1 if not restricted) */ public final int to() { return toPosition; } /** * @return Last-from-position (-1 if not restricted) */ public final int lastFrom() { return lastFromPosition; } /** * @return Last-to-position (-1 if not restricted) */ public final int lastTo() { return lastToPosition; } /** * Set action corresponding to this feature (instance) * @param toPos * @param fromPos */ public void setAction(final int toPos, final int fromPos) { this.toPosition = toPos; this.fromPosition = fromPos; } /** * Set last action (which we're reacting to) corresponding to this * feature (instance) * @param lastToPos * @param lastFromPos */ public void setLastAction(final int lastToPos, final int lastFromPos) { this.lastToPosition = lastToPos; this.lastFromPosition = lastFromPos; } /** * @return ChunkSet of sites that must be empty */ public final ChunkSet mustEmpty() { return mustEmpty; } /** * @return ChunkSet of sites that must NOT be empty */ public final ChunkSet mustNotEmpty() { return mustNotEmpty; } /** * @return mustWho ChunkSet */ public final ChunkSet mustWho() { return mustWho; } /** * @return mustNotWho ChunkSet */ public final ChunkSet mustNotWho() { return mustNotWho; } /** * @return mustWhoMask ChunkSet */ public final ChunkSet mustWhoMask() { return mustWhoMask; } /** * @return mustNotWhoMask ChunkSet */ public final ChunkSet mustNotWhoMask() { return mustNotWhoMask; } /** * @return mustWhat ChunkSet */ public final ChunkSet mustWhat() { return mustWhat; } /** * @return mustNotWhat ChunkSet */ public final ChunkSet mustNotWhat() { return mustNotWhat; } /** * @return mustWhatMask ChunkSet */ public final ChunkSet mustWhatMask() { return mustWhatMask; } /** * @return mustNotWhatMask ChunkSet */ public final ChunkSet mustNotWhatMask() { return mustNotWhatMask; } //------------------------------------------------------------------------- /** * @return List of all the atomic propositions this feature instance requires. */ public List<AtomicProposition> generateAtomicPropositions() { final List<AtomicProposition> propositions = new ArrayList<AtomicProposition>(); switch (graphElementType) { case Cell: if (mustEmpty != null) { final TIntArrayList nonzeroChunks = mustEmpty.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { propositions.add(new SingleMustEmptyCell(nonzeroChunks.getQuick(i))); } } if (mustNotEmpty != null) { final TIntArrayList nonzeroChunks = mustNotEmpty.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { propositions.add(new SingleMustNotEmptyCell(nonzeroChunks.getQuick(i))); } } if (mustWho != null) { final TIntArrayList nonzeroChunks = mustWho.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustWhoCell(chunk, mustWho.getChunk(chunk), mustWho.chunkSize())); } } if (mustNotWho != null) { final TIntArrayList nonzeroChunks = mustNotWho.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustNotWhoCell(chunk, mustNotWho.getChunk(chunk), mustNotWho.chunkSize())); } } if (mustWhat != null) { final TIntArrayList nonzeroChunks = mustWhat.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustWhatCell(chunk, mustWhat.getChunk(chunk), mustWhat.chunkSize())); } } if (mustNotWhat != null) { final TIntArrayList nonzeroChunks = mustNotWhat.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustNotWhatCell(chunk, mustNotWhat.getChunk(chunk), mustNotWhat.chunkSize())); } } break; case Vertex: if (mustEmpty != null) { final TIntArrayList nonzeroChunks = mustEmpty.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { propositions.add(new SingleMustEmptyVertex(nonzeroChunks.getQuick(i))); } } if (mustNotEmpty != null) { final TIntArrayList nonzeroChunks = mustNotEmpty.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { propositions.add(new SingleMustNotEmptyVertex(nonzeroChunks.getQuick(i))); } } if (mustWho != null) { final TIntArrayList nonzeroChunks = mustWho.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustWhoVertex(chunk, mustWho.getChunk(chunk), mustWho.chunkSize())); } } if (mustNotWho != null) { final TIntArrayList nonzeroChunks = mustNotWho.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustNotWhoVertex(chunk, mustNotWho.getChunk(chunk), mustNotWho.chunkSize())); } } if (mustWhat != null) { final TIntArrayList nonzeroChunks = mustWhat.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustWhatVertex(chunk, mustWhat.getChunk(chunk), mustWhat.chunkSize())); } } if (mustNotWhat != null) { final TIntArrayList nonzeroChunks = mustNotWhat.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustNotWhatVertex(chunk, mustNotWhat.getChunk(chunk), mustNotWhat.chunkSize())); } } break; case Edge: if (mustEmpty != null) { final TIntArrayList nonzeroChunks = mustEmpty.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { propositions.add(new SingleMustEmptyEdge(nonzeroChunks.getQuick(i))); } } if (mustNotEmpty != null) { final TIntArrayList nonzeroChunks = mustNotEmpty.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { propositions.add(new SingleMustNotEmptyEdge(nonzeroChunks.getQuick(i))); } } if (mustWho != null) { final TIntArrayList nonzeroChunks = mustWho.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustWhoEdge(chunk, mustWho.getChunk(chunk), mustWho.chunkSize())); } } if (mustNotWho != null) { final TIntArrayList nonzeroChunks = mustNotWho.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustNotWhoEdge(chunk, mustNotWho.getChunk(chunk), mustNotWho.chunkSize())); } } if (mustWhat != null) { final TIntArrayList nonzeroChunks = mustWhat.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustWhatEdge(chunk, mustWhat.getChunk(chunk), mustWhat.chunkSize())); } } if (mustNotWhat != null) { final TIntArrayList nonzeroChunks = mustNotWhat.getNonzeroChunks(); for (int i = 0; i < nonzeroChunks.size(); ++i) { final int chunk = nonzeroChunks.getQuick(i); propositions.add(new SingleMustNotWhatEdge(chunk, mustNotWhat.getChunk(chunk), mustNotWhat.chunkSize())); } } break; default: break; } return propositions; } //------------------------------------------------------------------------- /** * @param instances * @return New list of feature instances where duplicates in given list * have been removed */ public static List<FeatureInstance> deduplicate(final List<FeatureInstance> instances) { final Set<FeatureInstance> deduplicated = new HashSet<FeatureInstance>(); deduplicated.addAll(instances); return new ArrayList<FeatureInstance>(deduplicated); } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + anchorSite; result = prime * result + fromPosition; result = prime * result + lastFromPosition; result = prime * result + lastToPosition; result = prime * result + ((mustEmpty == null) ? 0 : mustEmpty.hashCode()); result = prime * result + ((mustNotEmpty == null) ? 0 : mustNotEmpty.hashCode()); result = prime * result + ((mustNotWhat == null) ? 0 : mustNotWhat.hashCode()); result = prime * result + ((mustNotWhatMask == null) ? 0 : mustNotWhatMask.hashCode()); result = prime * result + ((mustNotWho == null) ? 0 : mustNotWho.hashCode()); result = prime * result + ((mustNotWhoMask == null) ? 0 : mustNotWhoMask.hashCode()); result = prime * result + ((mustWhat == null) ? 0 : mustWhat.hashCode()); result = prime * result + ((mustWhatMask == null) ? 0 : mustWhatMask.hashCode()); result = prime * result + ((mustWho == null) ? 0 : mustWho.hashCode()); result = prime * result + ((mustWhoMask == null) ? 0 : mustWhoMask.hashCode()); result = prime * result + reflection; result = prime * result + Float.floatToIntBits(rotation); result = prime * result + toPosition; // Order of elements in initTimeElements should not matter int initTimeElementsHash = 0; for (final FeatureElement element : initTimeElements) { // XORing them all means order does not matter initTimeElementsHash ^= element.hashCode(); } result = prime * result + (prime + initTimeElementsHash); return result; } @Override public boolean equals(final Object other) { if (!(other instanceof FeatureInstance)) return false; final FeatureInstance otherInstance = (FeatureInstance) other; // Order of elements in initTimeElements should not matter if (initTimeElements.size() != otherInstance.initTimeElements.size()) return false; for (final FeatureElement element : initTimeElements) { if (!otherInstance.initTimeElements.contains(element)) return false; } return ( toPosition == otherInstance.toPosition && fromPosition == otherInstance.fromPosition && lastToPosition == otherInstance.lastToPosition && lastFromPosition == otherInstance.lastFromPosition && anchorSite == otherInstance.anchorSite && rotation == otherInstance.rotation && reflection == otherInstance.reflection && Objects.equals(mustEmpty, otherInstance.mustEmpty) && Objects.equals(mustNotEmpty, otherInstance.mustNotEmpty) && Objects.equals(mustWho, otherInstance.mustWho) && Objects.equals(mustWhoMask, otherInstance.mustWhoMask) && Objects.equals(mustNotWho, otherInstance.mustNotWho) && Objects.equals(mustNotWhoMask, otherInstance.mustNotWhoMask) && Objects.equals(mustWhat, otherInstance.mustWhat) && Objects.equals(mustWhatMask, otherInstance.mustWhatMask) && Objects.equals(mustNotWhat, otherInstance.mustNotWhat) && Objects.equals(mustNotWhatMask, otherInstance.mustNotWhatMask) ); } /** * @param other * @return True if and only if the given other feature instance is functionally equal * (has the same tests). */ public boolean functionallyEquals(final FeatureInstance other) { return ( toPosition == other.toPosition && fromPosition == other.fromPosition && lastToPosition == other.lastToPosition && lastFromPosition == other.lastFromPosition && Objects.equals(mustEmpty, other.mustEmpty) && Objects.equals(mustNotEmpty, other.mustNotEmpty) && Objects.equals(mustWho, other.mustWho) && Objects.equals(mustWhoMask, other.mustWhoMask) && Objects.equals(mustNotWho, other.mustNotWho) && Objects.equals(mustNotWhoMask, other.mustNotWhoMask) && Objects.equals(mustWhat, other.mustWhat) && Objects.equals(mustWhatMask, other.mustWhatMask) && Objects.equals(mustNotWhat, other.mustNotWhat) && Objects.equals(mustNotWhatMask, other.mustNotWhatMask) ); } /** * @param other * @return True if and only if we would have been equal to the given other * instance if our anchors were the same. */ public boolean equalsIgnoreAnchor(final FeatureInstance other) { return ( rotation == other.rotation && reflection == other.reflection && feature().equals(other.feature()) ); } /** * @return Hash code that takes into account rotation and reflection and * feature, but not anchor. */ public int hashCodeIgnoreAnchor() { final int prime = 31; int result = 1; result = prime * result + feature().hashCode(); result = prime * result + reflection; result = prime * result + Float.floatToIntBits(rotation); return result; } //------------------------------------------------------------------------- @Override public String toString() { String requirementsStr = ""; if (fromPosition >= 0) { requirementsStr += String.format( "Move from %s to %s: ", Integer.valueOf(fromPosition), Integer.valueOf(toPosition)); } else { requirementsStr += String.format("Move to %s: ", Integer.valueOf(toPosition)); } if (mustEmpty != null) { for (int i = mustEmpty.nextSetBit(0); i >= 0; i = mustEmpty.nextSetBit(i + 1)) { requirementsStr += i + " must be empty, "; } } if (mustNotEmpty != null) { for (int i = mustNotEmpty.nextSetBit(0); i >= 0; i = mustNotEmpty.nextSetBit(i + 1)) { requirementsStr += i + " must NOT be empty, "; } } if (mustWho != null) { for (int i = 0; i < mustWho.numChunks(); ++i) { if (mustWhoMask.getChunk(i) != 0) { requirementsStr += i + " must belong to " + mustWho.getChunk(i) + ", "; } } } if (mustNotWho != null) { for (int i = 0; i < mustNotWho.numChunks(); ++i) { if (mustNotWhoMask.getChunk(i) != 0) { requirementsStr += i + " must NOT belong to " + mustNotWho.getChunk(i) + ", "; } } } if (mustWhat != null) { for (int i = 0; i < mustWhat.numChunks(); ++i) { if (mustWhatMask.getChunk(i) != 0) { requirementsStr += i + " must contain " + mustWhat.getChunk(i) + ", "; } } } if (mustNotWhat != null) { for (int i = 0; i < mustNotWhat.numChunks(); ++i) { if (mustNotWhatMask.getChunk(i) != 0) { requirementsStr += i + " must NOT contain " + mustNotWhat.getChunk(i) + ", "; } } } if (lastToPosition >= 0) { if (lastFromPosition >= 0) { requirementsStr += " (response to last move from " + lastFromPosition + " to " + lastToPosition + ")"; } else { requirementsStr += " (response to last move to " + lastToPosition + ")"; } } String metaStr = String.format( "anchor=%d, ref=%d, rot=%.2f", Integer.valueOf(anchorSite), Integer.valueOf(reflection), Float.valueOf(rotation)); return String.format( "Feature Instance [%s] [%s] [%s]", requirementsStr, metaStr, parentFeature); } //------------------------------------------------------------------------- }
38,743
23.724952
112
java
Ludii
Ludii-master/Features/src/features/spatial/instances/OneOfMustEmpty.java
package features.spatial.instances; import game.types.board.SiteType; import main.collections.ChunkSet; import other.state.State; import other.state.container.ContainerState; /** * Simultaneously tests multiple chunks of the "empty" ChunkSet, returning * true if at least one of them is indeed empty. * * TODO could make special cases of this class for cells, vertices, and edges * * @author Dennis Soemers */ public final class OneOfMustEmpty implements BitwiseTest { //------------------------------------------------------------------------- /** Set of chunks of which at least one must be empty for test to succeed */ protected final ChunkSet mustEmpties; /** The first non-zero word in the mustEmpties ChunkSet */ protected final int firstUsedWord; /** Graph element type we want to test on */ protected final SiteType graphElementType; //------------------------------------------------------------------------- /** * Constructor * @param mustEmpties * @param graphElementType */ public OneOfMustEmpty(final ChunkSet mustEmpties, final SiteType graphElementType) { this.mustEmpties = mustEmpties; this.graphElementType = graphElementType; firstUsedWord = mustEmpties.nextSetBit(0) / Long.SIZE; } //------------------------------------------------------------------------- @Override public final boolean matches(final State state) { final ContainerState container = state.containerStates()[0]; final ChunkSet chunkSet; switch (graphElementType) { case Cell: chunkSet = container.emptyChunkSetCell(); break; case Vertex: chunkSet = container.emptyChunkSetVertex(); break; case Edge: chunkSet = container.emptyChunkSetEdge(); break; //$CASES-OMITTED$ Hint default: chunkSet = null; break; } return chunkSet.violatesNot(mustEmpties, mustEmpties, firstUsedWord); } //------------------------------------------------------------------------- @Override public final boolean hasNoTests() { return false; } @Override public final boolean onlyRequiresSingleMustEmpty() { return true; } @Override public final boolean onlyRequiresSingleMustWho() { return false; } @Override public final boolean onlyRequiresSingleMustWhat() { return false; } @Override public final SiteType graphElementType() { return graphElementType; } //------------------------------------------------------------------------- /** * @return Chunks of which at least one must be empty */ public final ChunkSet mustEmpties() { return mustEmpties; } //------------------------------------------------------------------------- @Override public String toString() { String requirementsStr = ""; for (int i = mustEmpties.nextSetBit(0); i >= 0; i = mustEmpties.nextSetBit(i + 1)) { requirementsStr += i + ", "; } return String.format( "One of these must be empty: [%s]", requirementsStr); } //------------------------------------------------------------------------- }
3,042
21.708955
83
java
Ludii
Ludii-master/Features/src/features/spatial/instances/OneOfMustWhat.java
package features.spatial.instances; import game.types.board.SiteType; import main.collections.ChunkSet; import other.state.State; import other.state.container.ContainerState; /** * Simultaneously tests multiple chunks of the "what" ChunkSet. * * TODO could make special cases of this class for cells, vertices, and edges * * @author Dennis Soemers */ public final class OneOfMustWhat implements BitwiseTest { //------------------------------------------------------------------------- /** * Set of chunks of which at least one must match game state's What * ChunkSet for test to succeed. */ protected final ChunkSet mustWhats; /** Mask for must-what tests */ protected final ChunkSet mustWhatsMask; /** The first non-zero word in the mustWhatsMask ChunkSet */ protected final int firstUsedWord; /** Graph element type we want to test on */ protected final SiteType graphElementType; //------------------------------------------------------------------------- /** * Constructor * @param mustWhats * @param mustWhatsMask * @param graphElementType */ public OneOfMustWhat(final ChunkSet mustWhats, final ChunkSet mustWhatsMask, final SiteType graphElementType) { this.mustWhats = mustWhats; this.mustWhatsMask = mustWhatsMask; this.graphElementType = graphElementType; firstUsedWord = mustWhatsMask.nextSetBit(0) / Long.SIZE; } //------------------------------------------------------------------------- @Override public final boolean matches(final State state) { final ContainerState container = state.containerStates()[0]; switch (graphElementType) { case Cell: return (container.violatesNotWhatCell(mustWhatsMask, mustWhats, firstUsedWord)); case Vertex: return (container.violatesNotWhatVertex(mustWhatsMask, mustWhats, firstUsedWord)); case Edge: return (container.violatesNotWhatEdge(mustWhatsMask, mustWhats, firstUsedWord)); //$CASES-OMITTED$ Hint default: break; } return false; } //------------------------------------------------------------------------- @Override public final boolean hasNoTests() { return false; } @Override public final boolean onlyRequiresSingleMustEmpty() { return false; } @Override public final boolean onlyRequiresSingleMustWho() { return true; } @Override public final boolean onlyRequiresSingleMustWhat() { return false; } @Override public final SiteType graphElementType() { return graphElementType; } //------------------------------------------------------------------------- /** * @return mustWhats ChunkSet */ public final ChunkSet mustWhats() { return mustWhats; } /** * @return mustWhatsMask ChunkSet */ public final ChunkSet mustWhatsMask() { return mustWhatsMask; } //------------------------------------------------------------------------- @Override public String toString() { String requirementsStr = ""; for (int i = 0; i < mustWhats.numChunks(); ++i) { if (mustWhatsMask.getChunk(i) != 0) { requirementsStr += i + " must contain " + mustWhats.getChunk(i) + ", "; } } return String.format( "One of these what-conditions must hold: [%s]", requirementsStr); } //------------------------------------------------------------------------- }
3,324
21.619048
110
java
Ludii
Ludii-master/Features/src/features/spatial/instances/OneOfMustWho.java
package features.spatial.instances; import game.types.board.SiteType; import main.collections.ChunkSet; import other.state.State; import other.state.container.ContainerState; /** * Simultaneously tests multiple chunks of the "who" ChunkSet. * * TODO could make special cases of this class for cells, vertices, and edges * * @author Dennis Soemers */ public final class OneOfMustWho implements BitwiseTest { //------------------------------------------------------------------------- /** * Set of chunks of which at least one must match game state's Who * ChunkSet for test to succeed. */ protected final ChunkSet mustWhos; /** Mask for must-who tests */ protected final ChunkSet mustWhosMask; /** The first non-zero word in the mustWhosMask ChunkSet */ protected final int firstUsedWord; /** Graph element type we want to test on */ protected final SiteType graphElementType; //------------------------------------------------------------------------- /** * Constructor * @param mustWhos * @param mustWhosMask * @param graphElementType */ public OneOfMustWho(final ChunkSet mustWhos, final ChunkSet mustWhosMask, final SiteType graphElementType) { this.mustWhos = mustWhos; this.mustWhosMask = mustWhosMask; this.graphElementType = graphElementType; firstUsedWord = mustWhosMask.nextSetBit(0) / Long.SIZE; } //------------------------------------------------------------------------- @Override public final boolean matches(final State state) { final ContainerState container = state.containerStates()[0]; switch (graphElementType) { case Cell: return (container.violatesNotWhoCell(mustWhosMask, mustWhos, firstUsedWord)); case Vertex: return (container.violatesNotWhoVertex(mustWhosMask, mustWhos, firstUsedWord)); case Edge: return (container.violatesNotWhoEdge(mustWhosMask, mustWhos, firstUsedWord)); //$CASES-OMITTED$ Hint default: break; } return false; } //------------------------------------------------------------------------- @Override public final boolean hasNoTests() { return false; } @Override public final boolean onlyRequiresSingleMustEmpty() { return false; } @Override public final boolean onlyRequiresSingleMustWho() { return true; } @Override public final boolean onlyRequiresSingleMustWhat() { return false; } @Override public final SiteType graphElementType() { return graphElementType; } //------------------------------------------------------------------------- /** * @return mustWhos ChunkSet */ public final ChunkSet mustWhos() { return mustWhos; } /** * @return mustWhosMask ChunkSet */ public final ChunkSet mustWhosMask() { return mustWhosMask; } //------------------------------------------------------------------------- @Override public String toString() { String requirementsStr = ""; for (int i = 0; i < mustWhos.numChunks(); ++i) { if (mustWhosMask.getChunk(i) != 0) { requirementsStr += i + " must belong to " + mustWhos.getChunk(i) + ", "; } } return String.format( "One of these who-conditions must hold: [%s]", requirementsStr); } //------------------------------------------------------------------------- }
3,290
21.387755
107
java
Ludii
Ludii-master/Features/src/features/spatial/instances/SingleMustEmptyCell.java
package features.spatial.instances; import game.Game; import game.types.board.SiteType; import main.collections.ChunkSet; import other.state.State; /** * A test that check for a single specific cell that must be empty * * @author Dennis Soemers */ public class SingleMustEmptyCell extends AtomicProposition { //------------------------------------------------------------------------- /** The site that must be empty */ protected final int mustEmptySite; //------------------------------------------------------------------------- /** * Constructor * @param mustEmptySite */ public SingleMustEmptyCell(final int mustEmptySite) { this.mustEmptySite = mustEmptySite; } //------------------------------------------------------------------------- @Override public boolean matches(final State state) { return state.containerStates()[0].emptyChunkSetCell().get(mustEmptySite); } @Override public boolean onlyRequiresSingleMustEmpty() { return true; } @Override public boolean onlyRequiresSingleMustWho() { return false; } @Override public boolean onlyRequiresSingleMustWhat() { return false; } @Override public SiteType graphElementType() { return SiteType.Cell; } @Override public void addMaskTo(final ChunkSet chunkSet) { chunkSet.set(mustEmptySite); } @Override public StateVectorTypes stateVectorType() { return StateVectorTypes.Empty; } @Override public int testedSite() { return mustEmptySite; } @Override public int value() { return 1; } @Override public boolean negated() { return false; } //------------------------------------------------------------------------- @Override public boolean provesIfTrue(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; // If empty, we prove the same (equal prop, probably shouldn't happen) if (other.stateVectorType() == StateVectorTypes.Empty) return !other.negated(); // If empty, we prove that it's not friend, not enemy, not piece 1, not piece 2, etc. return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && other.negated()); } @Override public boolean disprovesIfTrue(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; // If empty, we disprove not empty if (other.stateVectorType() == StateVectorTypes.Empty) return other.negated(); // If empty, we disprove friend, enemy, piece 1, piece 2, etc. return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && !other.negated()); } @Override public boolean provesIfFalse(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; // If not empty, we prove not empty return (other.stateVectorType() == StateVectorTypes.Empty && other.negated()); } @Override public boolean disprovesIfFalse(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; return false; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mustEmptySite; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof SingleMustEmptyCell)) return false; final SingleMustEmptyCell other = (SingleMustEmptyCell) obj; return (mustEmptySite == other.mustEmptySite); } @Override public String toString() { return "[Cell " + mustEmptySite + " must be empty]"; } //------------------------------------------------------------------------- }
4,064
20.62234
102
java
Ludii
Ludii-master/Features/src/features/spatial/instances/SingleMustEmptyEdge.java
package features.spatial.instances; import game.Game; import game.types.board.SiteType; import main.collections.ChunkSet; import other.state.State; /** * A test that check for a single specific edge that must be empty * * @author Dennis Soemers */ public class SingleMustEmptyEdge extends AtomicProposition { //------------------------------------------------------------------------- /** The site that must be empty */ protected final int mustEmptySite; //------------------------------------------------------------------------- /** * Constructor * @param mustEmptySite */ public SingleMustEmptyEdge(final int mustEmptySite) { this.mustEmptySite = mustEmptySite; } //------------------------------------------------------------------------- @Override public boolean matches(final State state) { return state.containerStates()[0].emptyChunkSetEdge().get(mustEmptySite); } @Override public boolean onlyRequiresSingleMustEmpty() { return true; } @Override public boolean onlyRequiresSingleMustWho() { return false; } @Override public boolean onlyRequiresSingleMustWhat() { return false; } @Override public SiteType graphElementType() { return SiteType.Edge; } @Override public void addMaskTo(final ChunkSet chunkSet) { chunkSet.set(mustEmptySite); } @Override public StateVectorTypes stateVectorType() { return StateVectorTypes.Empty; } @Override public int testedSite() { return mustEmptySite; } @Override public int value() { return 1; } @Override public boolean negated() { return false; } //------------------------------------------------------------------------- @Override public boolean provesIfTrue(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; // If empty, we prove the same (equal prop, probably shouldn't happen) if (other.stateVectorType() == StateVectorTypes.Empty) return !other.negated(); // If empty, we prove that it's not friend, not enemy, not piece 1, not piece 2, etc. return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && other.negated()); } @Override public boolean disprovesIfTrue(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; // If empty, we disprove not empty if (other.stateVectorType() == StateVectorTypes.Empty) return other.negated(); // If empty, we disprove friend, enemy, piece 1, piece 2, etc. return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && !other.negated()); } @Override public boolean provesIfFalse(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; // If not empty, we prove not empty return (other.stateVectorType() == StateVectorTypes.Empty && other.negated()); } @Override public boolean disprovesIfFalse(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; return false; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mustEmptySite; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof SingleMustEmptyEdge)) return false; final SingleMustEmptyEdge other = (SingleMustEmptyEdge) obj; return (mustEmptySite == other.mustEmptySite); } @Override public String toString() { return "[Edge " + mustEmptySite + " must be empty]"; } //------------------------------------------------------------------------- }
4,063
20.617021
102
java
Ludii
Ludii-master/Features/src/features/spatial/instances/SingleMustEmptyVertex.java
package features.spatial.instances; import game.Game; import game.types.board.SiteType; import main.collections.ChunkSet; import other.state.State; /** * A test that check for a single specific vertex that must be empty * * @author Dennis Soemers */ public class SingleMustEmptyVertex extends AtomicProposition { //------------------------------------------------------------------------- /** The site that must be empty */ protected final int mustEmptySite; //------------------------------------------------------------------------- /** * Constructor * @param mustEmptySite */ public SingleMustEmptyVertex(final int mustEmptySite) { this.mustEmptySite = mustEmptySite; } //------------------------------------------------------------------------- @Override public boolean matches(final State state) { return state.containerStates()[0].emptyChunkSetVertex().get(mustEmptySite); } @Override public boolean onlyRequiresSingleMustEmpty() { return true; } @Override public boolean onlyRequiresSingleMustWho() { return false; } @Override public boolean onlyRequiresSingleMustWhat() { return false; } @Override public SiteType graphElementType() { return SiteType.Vertex; } @Override public void addMaskTo(final ChunkSet chunkSet) { chunkSet.set(mustEmptySite); } @Override public StateVectorTypes stateVectorType() { return StateVectorTypes.Empty; } @Override public int testedSite() { return mustEmptySite; } @Override public int value() { return 1; } @Override public boolean negated() { return false; } //------------------------------------------------------------------------- @Override public boolean provesIfTrue(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; // If empty, we prove the same (equal prop, probably shouldn't happen) if (other.stateVectorType() == StateVectorTypes.Empty) return !other.negated(); // If empty, we prove that it's not friend, not enemy, not piece 1, not piece 2, etc. return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && other.negated()); } @Override public boolean disprovesIfTrue(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; // If empty, we disprove not empty if (other.stateVectorType() == StateVectorTypes.Empty) return other.negated(); // If empty, we disprove friend, enemy, piece 1, piece 2, etc. return (other.stateVectorType() != StateVectorTypes.Empty && other.value() > 0 && !other.negated()); } @Override public boolean provesIfFalse(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; // If not empty, we prove not empty return (other.stateVectorType() == StateVectorTypes.Empty && other.negated()); } @Override public boolean disprovesIfFalse(final AtomicProposition other, final Game game) { if (graphElementType() != other.graphElementType()) return false; if (testedSite() != other.testedSite()) return false; return false; } //------------------------------------------------------------------------- @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mustEmptySite; return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (!(obj instanceof SingleMustEmptyVertex)) return false; final SingleMustEmptyVertex other = (SingleMustEmptyVertex) obj; return (mustEmptySite == other.mustEmptySite); } @Override public String toString() { return "[Vertex " + mustEmptySite + " must be empty]"; } //------------------------------------------------------------------------- }
4,081
20.712766
102
java