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/Mining/src/gameDistance/metrics/bagOfWords/Overlap.java
|
package gameDistance.metrics.bagOfWords;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
import main.Constants;
//-----------------------------------------------------------------------------
/**
* Percentage of overlapping entries
*
* @author Matthew.Stephenson
*/
public class Overlap implements DistanceMetric
{
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final Map<String, Double> datasetA = dataset.getBagOfWords(gameA);
final Map<String, Double> datasetB = dataset.getBagOfWords(gameB);
double nominator = 0.0;
final double denominator = vocabulary.keySet().size();
for (final String word : vocabulary.keySet())
{
boolean existsA = false;
boolean existsB = false;
if (datasetA.containsKey(word))
existsA = datasetA.get(word).doubleValue() > 0.5;
if (datasetB.containsKey(word))
existsB = datasetB.get(word).doubleValue() > 0.5;
if (existsA == existsB)
nominator += 1;
}
final double finalVal = 1-(nominator/denominator);
// Handle floating point imprecision
if (finalVal < Constants.EPSILON)
return 0;
return finalVal;
}
}
| 1,275 | 23.538462 | 120 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/sequence/GlobalAlignment.java
|
package gameDistance.metrics.sequence;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
import gameDistance.utils.DistanceUtils;
//-----------------------------------------------------------------------------
/**
* Uses the NeedlemanWunsch algorithm to align the ludemes.
* https://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm
*
* @author Matthew.Stephenson, Markus
*/
public class GlobalAlignment implements DistanceMetric
{
//-----------------------------------------------------------------------------
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final List<String> gameAString = dataset.getSequence(gameA);
final List<String> gameBString = dataset.getSequence(gameB);
final String[] wordsA = gameAString.toArray(new String[0]);
final String[] wordsB = gameBString.toArray(new String[0]);
final double d = needlemanWunshAllignment(wordsA, wordsB);
final double finalScore = 1.0-(d / Math.max(wordsA.length, wordsB.length)/ maxValue());
return finalScore;
}
//-----------------------------------------------------------------------------
private static double needlemanWunshAllignment(final String[] wordsA, final String[] wordsB)
{
int maximumValue = 0;
final int[][] distances = new int[wordsA.length + 1][wordsB.length + 1];
for (int i = 0; i < distances.length; i++)
distances[i][0] = i * DistanceUtils.GAP_PENALTY;
for (int i = 0; i < distances[0].length; i++)
distances[0][i] = i * DistanceUtils.GAP_PENALTY;
for (int i = 1; i < distances.length; i++)
{
for (int j = 1; j < distances[0].length; j++)
{
final int valueFromLeft = DistanceUtils.GAP_PENALTY + distances[i-1][j];
final int valueFromTop = DistanceUtils.GAP_PENALTY + distances[i][j-1];
int valueFromTopLeft;
if (wordsA[i-1].equals(wordsB[j-1]))
valueFromTopLeft = DistanceUtils.HIT_VALUE + distances[i-1][j-1];
else
valueFromTopLeft = DistanceUtils.MISS_VALUE + distances[i-1][j-1];
final int finalVal = Math.max(valueFromTopLeft, Math.max(valueFromTop, valueFromLeft));
distances[i][j] = finalVal;
if (finalVal > maximumValue)
maximumValue = finalVal;
}
}
return distances[distances.length - 1][distances[0].length - 1];
}
//-----------------------------------------------------------------------------
private static int maxValue()
{
final int first = Math.max(Math.abs(DistanceUtils.HIT_VALUE), Math.abs(DistanceUtils.GAP_PENALTY));
final int second = Math.max(first, Math.abs(DistanceUtils.MISS_VALUE));
return second;
}
//-----------------------------------------------------------------------------
}
| 2,823 | 31.837209 | 120 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/sequence/Levenshtein.java
|
package gameDistance.metrics.sequence;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
//-----------------------------------------------------------------------------
/**
* https://en.wikipedia.org/wiki/Levenshtein_distance
*
* @author Matthew.Stephenson, Markus
*/
public class Levenshtein implements DistanceMetric
{
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final List<String> gameAString = dataset.getSequence(gameA);
final List<String> gameBString = dataset.getSequence(gameB);
final int [] costs = new int [gameBString.size() + 1];
for (int j = 0; j < costs.length; j++)
costs[j] = j;
for (int i = 1; i <= gameAString.size(); i++)
{
costs[0] = i;
int nw = i - 1;
for (int j = 1; j <= gameBString.size(); j++)
{
final int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), gameAString.get(i - 1).equals(gameBString.get(j - 1)) ? nw : nw + 1);
nw = costs[j];
costs[j] = cj;
}
}
final int edits = costs[gameBString.size()];
final int maxLength = Math.max(gameAString.size(), gameBString.size());
final double score = (double) edits / maxLength;
return score;
}
}
| 1,482 | 28.078431 | 147 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/sequence/LocalAlignment.java
|
package gameDistance.metrics.sequence;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
import gameDistance.utils.DistanceUtils;
//-----------------------------------------------------------------------------
/**
* Uses Smith Waterman Alignment, which is a local alignment of ludemes
* https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm
*
* @author Matthew.Stephenson, Markus
*/
public class LocalAlignment implements DistanceMetric
{
//-----------------------------------------------------------------------------
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final List<String> gameAString = dataset.getSequence(gameA);
final List<String> gameBString = dataset.getSequence(gameB);
final String[] wordsA = gameAString.toArray(new String[0]);
final String[] wordsB = gameBString.toArray(new String[0]);
final double d = smithWatermanAlignment(wordsA, wordsB);
final double maxCost = Math.max(wordsA.length, wordsB.length) * DistanceUtils.HIT_VALUE;
final double finalScore = 1 - d / maxCost;
return finalScore;
}
//-----------------------------------------------------------------------------
// Smith Waterman Alignment
// https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm
private static int smithWatermanAlignment(final String[] wordsA, final String[] wordsB)
{
int maximumValue = 0;
final int[][] distances = new int[wordsA.length + 1][wordsB.length + 1];
for (int i = 1; i < distances.length; i++)
{
for (int j = 1; j < distances[0].length; j++)
{
final int valueFromLeft = DistanceUtils.GAP_PENALTY + distances[i - 1][j];
final int valueFromTop = DistanceUtils.GAP_PENALTY + distances[i][j - 1];
int valueFromTopLeft;
if (wordsA[i - 1].equals(wordsB[j - 1]))
valueFromTopLeft = DistanceUtils.HIT_VALUE + distances[i - 1][j - 1];
else
valueFromTopLeft = DistanceUtils.MISS_VALUE + distances[i - 1][j - 1];
final int finalVal = Math.max(0, Math.max(valueFromTopLeft, Math.max(valueFromTop, valueFromLeft)));
distances[i][j] = finalVal;
if (finalVal > maximumValue)
maximumValue = finalVal;
}
}
return maximumValue;
}
//-----------------------------------------------------------------------------
}
| 2,445 | 30.766234 | 120 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/sequence/RepeatedLocalAlignment.java
|
package gameDistance.metrics.sequence;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
import gameDistance.utils.DistanceUtils;
//-----------------------------------------------------------------------------
/**
* Uses repeated Smith Waterman Alignment, which is a local alignment of ludemes
* https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm
*
* @author Matthew.Stephenson, Markus
*/
public class RepeatedLocalAlignment implements DistanceMetric
{
//-----------------------------------------------------------------------------
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final List<String> gameAString = dataset.getSequence(gameA);
final List<String> gameBString = dataset.getSequence(gameB);
final String[] wordsA = gameAString.toArray(new String[0]);
final String[] wordsB = gameBString.toArray(new String[0]);
final double d = repeatedSmithWatermanAlignment(wordsA, wordsB, 0);
final double maxCost = Math.max(wordsA.length, wordsB.length) * DistanceUtils.HIT_VALUE;
final double finalScore = 1 - d / maxCost;
return finalScore;
}
//-----------------------------------------------------------------------------
/**
* Find the maximum value and then backtrack along the biggest numbers to 0.
*/
private int repeatedSmithWatermanAlignment(final String[] wordsA, final String[] wordsB, final int score)
{
if (wordsA.length==0 || wordsB.length==0)
return score;
int maximumValue = -1;
int maximumI = 0;
int maximumJ = 0;
int[][] scoreMat = new int[wordsA.length + 1][wordsB.length + 1];
for (int i = 1; i < scoreMat.length; i++)
{
for (int j = 1; j < scoreMat[0].length; j++)
{
final int valueFromLeft = DistanceUtils.GAP_PENALTY + scoreMat[i-1][j];
final int valueFromTop = DistanceUtils.GAP_PENALTY + scoreMat[i][j-1];
int valueFromTopLeft;
if (wordsA[i - 1].equals(wordsB[j - 1]))
valueFromTopLeft = DistanceUtils.HIT_VALUE + scoreMat[i-1][j-1];
else
valueFromTopLeft = DistanceUtils.MISS_VALUE + scoreMat[i-1][j-1];
final int finalVal = Math.max(0, Math.max(valueFromTopLeft, Math.max(valueFromTop, valueFromLeft)));
scoreMat[i][j] = finalVal;
if (finalVal > maximumValue)
{
maximumValue = finalVal;
maximumI = i;
maximumJ = j;
}
}
}
final int[] ij = findStartIJfromAllignmentMatrix(scoreMat,maximumI,maximumJ);
if(maximumValue < DistanceUtils.HIT_VALUE*3)
return score + maximumValue;
if (ij[0] == maximumI || ij[1] == maximumJ)
return score;
scoreMat = null;
final String[] wordsACut = cutAwayAlligned(wordsA,ij[0]-1, maximumI-1);
final String[] wordsBCut = cutAwayAlligned(wordsB,ij[1]-1, maximumJ-1);
return repeatedSmithWatermanAlignment(wordsACut, wordsBCut, score+maximumValue);
}
//-----------------------------------------------------------------------------
/**
* Travel along the maximum values starting from this cell.
*/
private int[] findStartIJfromAllignmentMatrix(final int[][] scoreMat, final int i, final int j)
{
int nextI;
int nextJ;
int maxProgenitor;
final int leftUp = scoreMat[i-1][j-1];
maxProgenitor = leftUp;
nextI = i-1;
nextJ = j-1;
final int up = scoreMat[i][j-1];
if (up > maxProgenitor)
{
maxProgenitor = up;
nextI = i;
nextJ = j-1;
}
final int left = scoreMat[i-1][j];
if (left > maxProgenitor)
{
maxProgenitor = left;
nextI = i-1;
nextJ = j;
}
if (maxProgenitor == 0)
return new int[] {i,j};
else
return findStartIJfromAllignmentMatrix(scoreMat, nextI,nextJ);
}
//-----------------------------------------------------------------------------
private static String[] cutAwayAlligned(final String[] wordsA, final int minI, final int maximumI)
{
final int firstLenght = minI;
final int tailLength= wordsA.length-maximumI-1;
final int newLength = minI+tailLength;
final String[] cutted = new String[newLength];
System.arraycopy(wordsA, 0, cutted, 0, firstLenght);
System.arraycopy(wordsA, maximumI+1,cutted, firstLenght, tailLength);
return cutted;
}
//-----------------------------------------------------------------------------
}
| 4,381 | 28.213333 | 120 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/treeEdit/Apted.java
|
package gameDistance.metrics.treeEdit;
import java.util.List;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
import gameDistance.utils.apted.costmodel.StringUnitCostModel;
import gameDistance.utils.apted.distance.APTED;
import gameDistance.utils.apted.node.Node;
import gameDistance.utils.apted.node.StringNodeData;
import gameDistance.utils.apted.parser.BracketStringInputParser;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Returns Apted tree edit distance.
* https://github.com/DatabaseGroup/apted
* http://tree-edit-distance.dbresearch.uni-salzburg.at
*
* M. Pawlik and N. Augsten. Tree edit distance: Robust and memory- efficient. Information Systems 56. 2016.
* M. Pawlik and N. Augsten. Efficient Computation of the Tree Edit Distance. ACM Transactions on Database Systems (TODS) 40(1). 2015.
*
* @author matthew.stephenson
*/
public class Apted implements DistanceMetric
{
//---------------------------------------------------------------------
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final Tree treeA = dataset.getTree(gameA);
final Tree treeB = dataset.getTree(gameB);
final String treeABracketNotation = treeA.bracketNotation();
final String treeBBracketNotation = treeB.bracketNotation();
final BracketStringInputParser parser = new BracketStringInputParser();
final Node<StringNodeData> t1 = parser.fromString(treeABracketNotation);
final Node<StringNodeData> t2 = parser.fromString(treeBBracketNotation);
final APTED<StringUnitCostModel, StringNodeData> apted = new APTED<>(new StringUnitCostModel());
apted.computeEditDistance(t1, t2);
final List<int[]> mapping = apted.computeEditMapping();
final int maxTreeSize = Math.max(treeA.size(), treeB.size());
return (double) apted.mappingCost(mapping) / maxTreeSize;
}
//---------------------------------------------------------------------
}
| 2,069 | 35.964286 | 134 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/metrics/treeEdit/ZhangShasha.java
|
package gameDistance.metrics.treeEdit;
import java.util.Map;
import game.Game;
import gameDistance.datasets.Dataset;
import gameDistance.metrics.DistanceMetric;
import utils.data_structures.support.zhang_shasha.Tree;
/**
* Returns Zhang-Shasha tree edit distance.
* https://www.researchgate.net/publication/220618233_Simple_Fast_Algorithms_for_the_Editing_Distance_Between_Trees_and_Related_Problems
*
* @author matthew.stephenson
*/
public class ZhangShasha implements DistanceMetric
{
//---------------------------------------------------------------------
@Override
public double distance(final Dataset dataset, final Map<String, Double> vocabulary, final Game gameA, final Game gameB)
{
final Tree treeA = dataset.getTree(gameA);
final Tree treeB = dataset.getTree(gameB);
final int edits = Tree.ZhangShasha(treeA, treeB);
final int maxTreeSize = Math.max(treeA.size(), treeB.size());
return (double) edits / maxTreeSize;
}
//---------------------------------------------------------------------
}
| 1,045 | 27.27027 | 136 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/DistanceUtils.java
|
package gameDistance.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import contextualiser.ContextualSimilarity;
import game.Game;
import gameDistance.datasets.Dataset;
import other.GameLoader;
/**
* Game distance utility functions.
*
* @author matthew.stephenson
*/
public class DistanceUtils
{
// Alignment edit costs
public final static int HIT_VALUE = 5; // Should be positive
public final static int MISS_VALUE = -5; // Should be negative
public final static int GAP_PENALTY = -1; // Should be negative
public final static int nGramLength = 4;
// vocabulary store paths.
private final static String vocabularyStorePath = "res/gameDistance/vocabulary/";
//-----------------------------------------------------------------------------
public static Map<String, Double> fullVocabulary(final Dataset dataset, final String datasetName, final boolean overrideStoredVocabularies)
{
final File vocabularyFile = new File(vocabularyStorePath + datasetName + ".txt");
// Recover vocabulary from previously stored txt file if available.
if (vocabularyFile.exists() && !overrideStoredVocabularies)
{
try (final FileInputStream fileInput = new FileInputStream(vocabularyFile))
{
try (final ObjectInputStream objectInput = new ObjectInputStream(fileInput))
{
@SuppressWarnings("unchecked")
final Map<String, Double> vocabulary = (HashMap<String, Double>)objectInput.readObject();
objectInput.close();
fileInput.close();
return vocabulary;
}
catch (final Exception e)
{
e.printStackTrace();
}
}
catch (final Exception e)
{
e.printStackTrace();
}
}
// Calculate full Ludii game vocabulary.
double numGames = 0.0;
final Map<String, Double> vocabulary = new HashMap<>();
for (final String[] gameRulesetName : GameLoader.allAnalysisGameRulesetNames())
{
final Game game = GameLoader.loadGameFromName(gameRulesetName[0], gameRulesetName[1]);
System.out.println(game.name());
numGames++;
for (final String s : dataset.getBagOfWords(game).keySet())
{
if (vocabulary.containsKey(s))
vocabulary.put(s, Double.valueOf(vocabulary.get(s).doubleValue() + 1.0));
else
vocabulary.put(s, Double.valueOf(1.0));
}
}
for (final Map.Entry<String, Double> entry : vocabulary.entrySet())
entry.setValue(Double.valueOf(Math.log(numGames / entry.getValue().doubleValue())));
// Store vocabulary to txt file.
if (!vocabularyFile.exists())
{
try
{
vocabularyFile.createNewFile();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
try (final FileOutputStream myFileOutStream = new FileOutputStream(vocabularyFile))
{
try (final ObjectOutputStream myObjectOutStream = new ObjectOutputStream(myFileOutStream))
{
myObjectOutStream.writeObject(vocabulary);
myObjectOutStream.close();
myFileOutStream.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
catch (final Exception e)
{
e.printStackTrace();
}
}
return vocabulary;
}
//-----------------------------------------------------------------------------
/**
* @return CSN distance between two rulesetIds
*/
public static double getRulesetCSNDistance(final int rulesetId1, final int rulesetId2)
{
return getAllRulesetCSNDistances(rulesetId1).get(Integer.valueOf(rulesetId2)).doubleValue();
}
/**
* @return Map of rulesetId (key) to CSN distance (value) pairs, based on distance to specified rulesetId.
*/
public static Map<Integer, Double> getAllRulesetCSNDistances(final int rulesetId)
{
// Load ruleset distances from specific directory.
final String distancesFilePath = ContextualSimilarity.rulesetContextualiserFilePath + rulesetId + ".csv";
// Map of rulesetId (key) to CSN distance (value) pairs.
final Map<Integer, Double> rulesetCSNDistances = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(distancesFilePath)))
{
String line = br.readLine(); // column names
while ((line = br.readLine()) != null)
{
final String[] values = line.split(",");
rulesetCSNDistances.put(Integer.valueOf(Integer.parseInt(values[0])), Double.valueOf(Double.parseDouble(values[1])));
}
}
catch (final Exception e)
{
e.printStackTrace();
}
return rulesetCSNDistances;
}
//-----------------------------------------------------------------------------
/**
* @return Geo distance between two rulesetIds
*/
public static double getRulesetGeoDistance(final int rulesetId1, final int rulesetId2)
{
final Map<Integer, Double> geoSimilarities = getAllRulesetGeoDistances(rulesetId1);
final Double geoSimilarity = geoSimilarities.get(Integer.valueOf(rulesetId2));
return geoSimilarity != null ? geoSimilarity.doubleValue() : 0.0;
}
/**
* @return Map of rulesetId (key) to Geo distance (value) pairs, based on distance to specified rulesetId.
*/
public static Map<Integer, Double> getAllRulesetGeoDistances(final int rulesetId)
{
// Load ruleset distances from specific directory.
final String distancesFilePath = "../Mining/res/recons/input/rulesetGeographicalDistances.csv";
final Map<Integer, Double> rulesetGeoDistanceIds = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(distancesFilePath)))
{
br.readLine(); // Skip first line of column headers.
String line;
while ((line = br.readLine()) != null)
{
final String[] values = line.split(",");
if (Integer.valueOf(values[0]).intValue() != rulesetId)
continue;
final double similarity = Math.max((20000 - Double.valueOf(values[2]).doubleValue()) / 20000, 0); // 20000km is the maximum possible distance
rulesetGeoDistanceIds.put(Integer.valueOf(values[1]), Double.valueOf(similarity));
}
}
catch (final Exception e)
{
System.out.println("Could not find similarity file, ruleset probably has no evidence.");
e.printStackTrace();
}
return rulesetGeoDistanceIds;
}
//-----------------------------------------------------------------------------
public static Map<String, Double> getGameDataset(final Dataset dataset, final Game game)
{
final Map<String, Double> datasetGame = dataset.getBagOfWords(game);
// Convert the raw frequency counts for datasetA into probability distributions.
double valueSum = 0.0;
for (final Map.Entry<String, Double> entry : datasetGame.entrySet())
valueSum += entry.getValue().doubleValue();
for (final Map.Entry<String, Double> entry : datasetGame.entrySet())
entry.setValue(Double.valueOf(entry.getValue().doubleValue()/valueSum));
return datasetGame;
}
//-----------------------------------------------------------------------------
public static final Map<String, Double> defaultVocabulary(final Dataset dataset, final Game gameA, final Game gameB)
{
final Map<String, Double> vocabulary = new HashMap<>();
final Map<String, Double> datasetA = getGameDataset(dataset, gameA);
final Map<String, Double> datasetB = getGameDataset(dataset, gameB);
for (final String s : datasetA.keySet())
vocabulary.put(s, Double.valueOf(1.0));
for (final String s : datasetB.keySet())
vocabulary.put(s, Double.valueOf(1.0));
return vocabulary;
}
}
| 7,681 | 31.413502 | 151 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/costmodel/CostModel.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.costmodel;
import gameDistance.utils.apted.node.Node;
/**
* This interface specifies the methods to implement for a custom cost model.
* The methods represent the costs of edit operations (delete, insert, rename).
*
* <p>If the cost function is a metric, the tree edit distance is a metric too.
*
* <p>However, the cost function does not have to be a metric - the costs of
* deletion, insertion and rename can be arbitrary.
*
* <p>IMPORTANT: Mind the <b>float</b> type use for costs.
*
* @param <D> type of node data on which the cost model is defined.
*/
public interface CostModel<D> {
/**
* Calculates the cost of deleting a node.
*
* @param n the node considered to be deleted.
* @return the cost of deleting node n.
*/
public float del(Node<D> n);
/**
* Calculates the cost of inserting a node.
*
* @param n the node considered to be inserted.
* @return the cost of inserting node n.
*/
public float ins(Node<D> n);
/**
* Calculates the cost of renaming (mapping) two nodes.
*
* @param n1 the source node of rename.
* @param n2 the destination node of rename.
* @return the cost of renaming (mapping) node n1 to n2.
*/
public float ren(Node<D> n1, Node<D> n2);
}
| 2,413 | 34.5 | 80 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/costmodel/PerEditOperationStringNodeDataCostModel.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.costmodel;
import gameDistance.utils.apted.node.Node;
import gameDistance.utils.apted.node.StringNodeData;
/**
* This is a cost model defined with a fixed cost
* per edit operation.
*/
public class PerEditOperationStringNodeDataCostModel implements CostModel<StringNodeData> {
/**
* Stores the cost of deleting a node.
*/
private final float delCost;
/**
* Stores the cost of inserting a node.
*/
private final float insCost;
/**
* Stores the cost of mapping two nodes (renaming their labels).
*/
private final float renCost;
/**
* Initialises the cost model with the passed edit operation costs.
*
* @param delCost deletion cost.
* @param insCost insertion cost.
* @param renCost rename cost.
*/
public PerEditOperationStringNodeDataCostModel(final float delCost, final float insCost, final float renCost) {
this.delCost = delCost;
this.insCost = insCost;
this.renCost = renCost;
}
/**
* Calculates the cost of deleting a node.
*
* @param n the node considered to be deleted.
* @return the cost of deleting node n.
*/
@Override
public float del(final Node<StringNodeData> n) {
return delCost;
}
/**
* Calculates the cost of inserting a node.
*
* @param n the node considered to be inserted.
* @return the cost of inserting node n.
*/
@Override
public float ins(final Node<StringNodeData> n) {
return insCost;
}
/**
* Calculates the cost of renaming the string labels of two nodes.
*
* @param n1 the source node of rename.
* @param n2 the destination node of rename.
* @return the cost of renaming node n1 to n2.
*/
@Override
public float ren(final Node<StringNodeData> n1, final Node<StringNodeData> n2) {
return (n1.getNodeData().getLabel().equals(n2.getNodeData().getLabel())) ? 0.0f : renCost;
}
}
| 3,027 | 30.216495 | 113 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/costmodel/StringUnitCostModel.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.costmodel;
import gameDistance.utils.apted.node.Node;
import gameDistance.utils.apted.node.StringNodeData;
/**
* This is a unit-nost model defined on string labels.
*
* @see CostModel
* @see StringNodeData
*/
// TODO: Use a label dictionary to encode string labels with integers for
// faster rename cost computation.
public class StringUnitCostModel implements CostModel<StringNodeData> {
/**
* Calculates the cost of deleting a node.
*
* @param n a node considered to be deleted.
* @return {@code 1} - a fixed cost of deleting a node.
*/
@Override
public float del(final Node<StringNodeData> n) {
return 1.0f;
}
/**
* Calculates the cost of inserting a node.
*
* @param n a node considered to be inserted.
* @return {@code 1} - a fixed cost of inserting a node.
*/
@Override
public float ins(final Node<StringNodeData> n) {
return 1.0f;
}
/**
* Calculates the cost of renaming the label of the source node to the label
* of the destination node.
*
* @param n1 a source node for rename.
* @param n2 a destination node for rename.
* @return {@code 1} if labels of renamed nodes are equal, and {@code 0} otherwise.
*/
@Override
public float ren(final Node<StringNodeData> n1, final Node<StringNodeData> n2) {
return (n1.getNodeData().getLabel().equals(n2.getNodeData().getLabel())) ? 0.0f : 1.0f;
}
}
| 2,567 | 33.702703 | 91 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/distance/APTED.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.distance;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import gameDistance.utils.apted.costmodel.CostModel;
import gameDistance.utils.apted.node.Node;
import gameDistance.utils.apted.node.NodeIndexer;
/**
* Implements APTED algorithm [1,2].
*
* <ul>
* <li>Optimal strategy with all paths.
* <li>Single-node single path function supports currently only unit cost.
* <li>Two-node single path function not included.
* <li>\Delta^L and \Delta^R based on Zhang and Shasha's algorithm for executing
* left and right paths (as in [3]). If only left and right paths are used
* in the strategy, the memory usage is reduced by one quadratic array.
* <li>For any other path \Delta^A from [1] is used.
* </ul>
*
* References:
* <ul>
* <li>[1] M. Pawlik and N. Augsten. Efficient Computation of the Tree Edit
* Distance. ACM Transactions on Database Systems (TODS) 40(1). 2015.
* <li>[2] M. Pawlik and N. Augsten. Tree edit distance: Robust and memory-
* efficient. Information Systems 56. 2016.
* <li>[3] M. Pawlik and N. Augsten. RTED: A Robust Algorithm for the Tree Edit
* Distance. PVLDB 5(4). 2011.
* </ul>
*
* @param <C> type of cost model.
* @param <D> type of node data.
*/
@SuppressWarnings("all")
public class APTED<C extends CostModel, D> {
/**
* Identifier of left path type = {@value LEFT};
*/
private static final byte LEFT = 0;
/**
* Identifier of right path type = {@value RIGHT};
*/
private static final byte RIGHT = 1;
/**
* Identifier of inner path type = {@value INNER};
*/
private static final byte INNER = 2;
/**
* Indexer of the source tree.
*
* @see node.NodeIndexer
*/
private NodeIndexer it1;
/**
* Indexer of the destination tree.
*
* @see node.NodeIndexer
*/
private NodeIndexer it2;
/**
* The size of the source input tree.
*/
private int size1;
/**
* The size of the destination tree.
*/
private int size2;
/**
* The distance matrix [1, Sections 3.4,8.2,8.3]. Used to store intermediate
* distances between pairs of subtrees.
*/
private float delta[][];
/**
* One of distance arrays to store intermediate distances in spfA.
*/
// TODO: Verify if other spf-local arrays are initialised within spf. If yes,
// move q to spf to - then, an offset has to be used to access it.
private float q[];
/**
* Array used in the algorithm before [1]. Using it does not change the
* complexity.
*
* <p>TODO: Do not use it [1, Section 8.4].
*/
private int fn[];
/**
* Array used in the algorithm before [1]. Using it does not change the
* complexity.
*
* <p>TODO: Do not use it [1, Section 8.4].
*/
private int ft[];
/**
* Stores the number of subproblems encountered while computing the distance
* [1, Section 10].
*/
private long counter;
/**
* Cost model to be used for calculating costs of edit operations.
*/
private final C costModel;
/**
* Constructs the APTED algorithm object with the specified cost model.
*
* @param costModel cost model for edit operations.
*/
public APTED(final C costModel) {
this.costModel = costModel;
}
/**
* Compute tree edit distance between source and destination trees using
* APTED algorithm [1,2].
*
* @param t1 source tree.
* @param t2 destination tree.
* @return tree edit distance.
*/
public float computeEditDistance(final Node<D> t1, final Node<D> t2) {
// Index the nodes of both input trees.
init(t1, t2);
// Determine the optimal strategy for the distance computation.
// Use the heuristic from [2, Section 5.3].
if (it1.lchl < it1.rchl) {
delta = computeOptStrategy_postL(it1, it2);
} else {
delta = computeOptStrategy_postR(it1, it2);
}
// Initialise structures for distance computation.
tedInit();
// Compute the distance.
return gted(it1, it2);
}
/**
* This method is only for testing purpose. It computes TED with a fixed
* path type in the strategy to trigger execution of a specific single-path
* function.
*
* @param t1 source tree.
* @param t2 destination tree.
* @param spfType single-path function to trigger (LEFT or RIGHT).
* @return tree edit distance.
*/
public float computeEditDistance_spfTest(final Node<D> t1, final Node<D> t2, final int spfType) {
// Index the nodes of both input trees.
init(t1, t2);
// Initialise delta array.
delta = new float[size1][size2];
// Fix a path type to trigger specific spf.
for (int i = 0; i < delta.length; i++) {
for (int j = 0; j < delta[i].length; j++) {
// Fix path type.
if (spfType == LEFT) {
delta[i][j] = it1.preL_to_lld(i) + 1;
} else if (spfType == RIGHT) {
delta[i][j] = it1.preL_to_rld(i) + 1;
}
}
}
// Initialise structures for distance computation.
tedInit();
// Compute the distance.
return gted(it1, it2);
}
/**
* Initialises node indexers and stores input tree sizes.
*
* @param t1 source input tree.
* @param t2 destination input tree.
*/
public void init(final Node<D> t1, final Node<D> t2) {
it1 = new NodeIndexer(t1, costModel);
it2 = new NodeIndexer(t2, costModel);
size1 = it1.getSize();
size2 = it2.getSize();
}
/**
* After the optimal strategy is computed, initialises distances of deleting
* and inserting subtrees without their root nodes.
*/
private void tedInit() {
// Reset the subproblems counter.
counter = 0L;
// Initialize arrays.
final int maxSize = Math.max(size1, size2) + 1;
// TODO: Move q initialisation to spfA.
q = new float[maxSize];
// TODO: Do not use fn and ft arrays [1, Section 8.4].
fn = new int[maxSize + 1];
ft = new int[maxSize + 1];
// Compute subtree distances without the root nodes when one of subtrees
// is a single node.
int sizeX = -1;
int sizeY = -1;
int parentX = -1;
int parentY = -1;
// Loop over the nodes in reversed left-to-right preorder.
for(int x = 0; x < size1; x++) {
sizeX = it1.sizes[x];
parentX = it1.parents[x];
for(int y = 0; y < size2; y++) {
sizeY = it2.sizes[y];
parentY = it2.parents[y];
// Set values in delta based on the sums of deletion and insertion
// costs. Subtract the costs for root nodes.
// In this method we don't have to verify the order of the input trees
// because it is equal to the original.
if (sizeX == 1 && sizeY == 1) {
delta[x][y] = 0.0f;
} else if (sizeX == 1) {
delta[x][y] = it2.preL_to_sumInsCost[y] - costModel.ins(it2.preL_to_node[y]); // USE COST MODEL.
} else if (sizeY == 1) {
delta[x][y] = it1.preL_to_sumDelCost[x] - costModel.del(it1.preL_to_node[x]); // USE COST MODEL.
}
}
}
}
/**
* Compute the optimal strategy using left-to-right postorder traversal of
* the nodes [2, Algorithm 1].
*
* @param it1 node indexer of the source input tree.
* @param it2 node indexer of the destination input tree.
* @return array with the optimal strategy.
*/
// TODO: Document the internals. Point to lines of the algorithm.
public float[][] computeOptStrategy_postL(final NodeIndexer it1, final NodeIndexer it2) {
final int size1 = it1.getSize();
final int size2 = it2.getSize();
final float strategy[][] = new float[size1][size2];
final float cost1_L[][] = new float[size1][];
final float cost1_R[][] = new float[size1][];
final float cost1_I[][] = new float[size1][];
final float cost2_L[] = new float[size2];
final float cost2_R[] = new float[size2];
final float cost2_I[] = new float[size2];
final int cost2_path[] = new int[size2];
final float leafRow[] = new float[size2];
final int pathIDOffset = size1;
float minCost = 0x7fffffffffffffffL;
int strategyPath = -1;
final int[] pre2size1 = it1.sizes;
final int[] pre2size2 = it2.sizes;
final int[] pre2descSum1 = it1.preL_to_desc_sum;
final int[] pre2descSum2 = it2.preL_to_desc_sum;
final int[] pre2krSum1 = it1.preL_to_kr_sum;
final int[] pre2krSum2 = it2.preL_to_kr_sum;
final int[] pre2revkrSum1 = it1.preL_to_rev_kr_sum;
final int[] pre2revkrSum2 = it2.preL_to_rev_kr_sum;
final int[] preL_to_preR_1 = it1.preL_to_preR;
final int[] preL_to_preR_2 = it2.preL_to_preR;
final int[] preR_to_preL_1 = it1.preR_to_preL;
final int[] preR_to_preL_2 = it2.preR_to_preL;
final int[] pre2parent1 = it1.parents;
final int[] pre2parent2 = it2.parents;
final boolean[] nodeType_L_1 = it1.nodeType_L;
final boolean[] nodeType_L_2 = it2.nodeType_L;
final boolean[] nodeType_R_1 = it1.nodeType_R;
final boolean[] nodeType_R_2 = it2.nodeType_R;
final int[] preL_to_postL_1 = it1.preL_to_postL;
final int[] preL_to_postL_2 = it2.preL_to_postL;
final int[] postL_to_preL_1 = it1.postL_to_preL;
final int[] postL_to_preL_2 = it2.postL_to_preL;
int size_v, parent_v_preL, parent_w_preL, parent_w_postL = -1, size_w, parent_v_postL = -1;
int leftPath_v, rightPath_v;
float[] cost_Lpointer_v, cost_Rpointer_v, cost_Ipointer_v;
float[] strategypointer_v;
float[] cost_Lpointer_parent_v = null, cost_Rpointer_parent_v = null, cost_Ipointer_parent_v = null;
float[] strategypointer_parent_v = null;
int krSum_v, revkrSum_v, descSum_v;
boolean is_v_leaf;
int v_in_preL;
int w_in_preL;
final Stack<float[]> rowsToReuse_L = new Stack<float[]>();
final Stack<float[]> rowsToReuse_R = new Stack<float[]>();
final Stack<float[]> rowsToReuse_I = new Stack<float[]>();
for(int v = 0; v < size1; v++) {
v_in_preL = postL_to_preL_1[v];
is_v_leaf = it1.isLeaf(v_in_preL);
parent_v_preL = pre2parent1[v_in_preL];
if (parent_v_preL != -1) {
parent_v_postL = preL_to_postL_1[parent_v_preL];
}
strategypointer_v = strategy[v_in_preL];
size_v = pre2size1[v_in_preL];
leftPath_v = -(preR_to_preL_1[preL_to_preR_1[v_in_preL] + size_v - 1] + 1);// this is the left path's ID which is the leftmost leaf node: l-r_preorder(r-l_preorder(v) + |Fv| - 1)
rightPath_v = v_in_preL + size_v - 1 + 1; // this is the right path's ID which is the rightmost leaf node: l-r_preorder(v) + |Fv| - 1
krSum_v = pre2krSum1[v_in_preL];
revkrSum_v = pre2revkrSum1[v_in_preL];
descSum_v = pre2descSum1[v_in_preL];
if(is_v_leaf) {
cost1_L[v] = leafRow;
cost1_R[v] = leafRow;
cost1_I[v] = leafRow;
for(int i = 0; i < size2; i++) {
strategypointer_v[postL_to_preL_2[i]] = v_in_preL;
}
}
cost_Lpointer_v = cost1_L[v];
cost_Rpointer_v = cost1_R[v];
cost_Ipointer_v = cost1_I[v];
if(parent_v_preL != -1 && cost1_L[parent_v_postL] == null) {
if (rowsToReuse_L.isEmpty()) {
cost1_L[parent_v_postL] = new float[size2];
cost1_R[parent_v_postL] = new float[size2];
cost1_I[parent_v_postL] = new float[size2];
} else {
cost1_L[parent_v_postL] = rowsToReuse_L.pop();
cost1_R[parent_v_postL] = rowsToReuse_R.pop();
cost1_I[parent_v_postL] = rowsToReuse_I.pop();
}
}
if (parent_v_preL != -1) {
cost_Lpointer_parent_v = cost1_L[parent_v_postL];
cost_Rpointer_parent_v = cost1_R[parent_v_postL];
cost_Ipointer_parent_v = cost1_I[parent_v_postL];
strategypointer_parent_v = strategy[parent_v_preL];
}
Arrays.fill(cost2_L, 0L);
Arrays.fill(cost2_R, 0L);
Arrays.fill(cost2_I, 0L);
Arrays.fill(cost2_path, 0);
for(int w = 0; w < size2; w++) {
w_in_preL = postL_to_preL_2[w];
parent_w_preL = pre2parent2[w_in_preL];
if (parent_w_preL != -1) {
parent_w_postL = preL_to_postL_2[parent_w_preL];
}
size_w = pre2size2[w_in_preL];
if (it2.isLeaf(w_in_preL)) {
cost2_L[w] = 0L;
cost2_R[w] = 0L;
cost2_I[w] = 0L;
cost2_path[w] = w_in_preL;
}
minCost = 0x7fffffffffffffffL;
strategyPath = -1;
float tmpCost = 0x7fffffffffffffffL;
if (size_v <= 1 || size_w <= 1) { // USE NEW SINGLE_PATH FUNCTIONS FOR SMALL SUBTREES
minCost = Math.max(size_v, size_w);
} else {
tmpCost = (float) size_v * (float) pre2krSum2[w_in_preL] + cost_Lpointer_v[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = leftPath_v;
}
tmpCost = (float) size_v * (float) pre2revkrSum2[w_in_preL] + cost_Rpointer_v[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = rightPath_v;
}
tmpCost = (float) size_v * (float) pre2descSum2[w_in_preL] + cost_Ipointer_v[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = (int)strategypointer_v[w_in_preL] + 1;
}
tmpCost = (float) size_w * (float) krSum_v + cost2_L[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = -(preR_to_preL_2[preL_to_preR_2[w_in_preL] + size_w - 1] + pathIDOffset + 1);
}
tmpCost = (float) size_w * (float) revkrSum_v + cost2_R[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = w_in_preL + size_w - 1 + pathIDOffset + 1;
}
tmpCost = (float) size_w * (float) descSum_v + cost2_I[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = cost2_path[w] + pathIDOffset + 1;
}
}
if (parent_v_preL != -1) {
cost_Rpointer_parent_v[w] += minCost;
tmpCost = -minCost + cost1_I[v][w];
if (tmpCost < cost1_I[parent_v_postL][w]) {
cost_Ipointer_parent_v[w] = tmpCost;
strategypointer_parent_v[w_in_preL] = strategypointer_v[w_in_preL];
}
if (nodeType_R_1[v_in_preL]) {
cost_Ipointer_parent_v[w] += cost_Rpointer_parent_v[w];
cost_Rpointer_parent_v[w] += cost_Rpointer_v[w] - minCost;
}
if (nodeType_L_1[v_in_preL]) {
cost_Lpointer_parent_v[w] += cost_Lpointer_v[w];
} else {
cost_Lpointer_parent_v[w] += minCost;
}
}
if (parent_w_preL != -1) {
cost2_R[parent_w_postL] += minCost;
tmpCost = -minCost + cost2_I[w];
if (tmpCost < cost2_I[parent_w_postL]) {
cost2_I[parent_w_postL] = tmpCost;
cost2_path[parent_w_postL] = cost2_path[w];
}
if (nodeType_R_2[w_in_preL]) {
cost2_I[parent_w_postL] += cost2_R[parent_w_postL];
cost2_R[parent_w_postL] += cost2_R[w] - minCost;
}
if (nodeType_L_2[w_in_preL]) {
cost2_L[parent_w_postL] += cost2_L[w];
} else {
cost2_L[parent_w_postL] += minCost;
}
}
strategypointer_v[w_in_preL] = strategyPath;
}
if (!it1.isLeaf(v_in_preL)) {
Arrays.fill(cost1_L[v], 0);
Arrays.fill(cost1_R[v], 0);
Arrays.fill(cost1_I[v], 0);
rowsToReuse_L.push(cost1_L[v]);
rowsToReuse_R.push(cost1_R[v]);
rowsToReuse_I.push(cost1_I[v]);
}
}
return strategy;
}
/**
* Compute the optimal strategy using right-to-left postorder traversal of
* the nodes [2, Algorithm 1].
*
* @param it1 node indexer of the source input tree.
* @param it2 node indexer of the destination input tree.
* @return array with the optimal strategy.
*/
// QUESTION: Is it possible to merge it with the other strategy computation?
// TODO: Document the internals. Point to lines of the algorithm.
public float[][] computeOptStrategy_postR(final NodeIndexer it1, final NodeIndexer it2) {
final int size1 = it1.getSize();
final int size2 = it2.getSize();
final float strategy[][] = new float[size1][size2];
final float cost1_L[][] = new float[size1][];
final float cost1_R[][] = new float[size1][];
final float cost1_I[][] = new float[size1][];
final float cost2_L[] = new float[size2];
final float cost2_R[] = new float[size2];
final float cost2_I[] = new float[size2];
final int cost2_path[] = new int[size2];
final float leafRow[] = new float[size2];
final int pathIDOffset = size1;
float minCost = 0x7fffffffffffffffL;
int strategyPath = -1;
final int[] pre2size1 = it1.sizes;
final int[] pre2size2 = it2.sizes;
final int[] pre2descSum1 = it1.preL_to_desc_sum;
final int[] pre2descSum2 = it2.preL_to_desc_sum;
final int[] pre2krSum1 = it1.preL_to_kr_sum;
final int[] pre2krSum2 = it2.preL_to_kr_sum;
final int[] pre2revkrSum1 = it1.preL_to_rev_kr_sum;
final int[] pre2revkrSum2 = it2.preL_to_rev_kr_sum;
final int[] preL_to_preR_1 = it1.preL_to_preR;
final int[] preL_to_preR_2 = it2.preL_to_preR;
final int[] preR_to_preL_1 = it1.preR_to_preL;
final int[] preR_to_preL_2 = it2.preR_to_preL;
final int[] pre2parent1 = it1.parents;
final int[] pre2parent2 = it2.parents;
final boolean[] nodeType_L_1 = it1.nodeType_L;
final boolean[] nodeType_L_2 = it2.nodeType_L;
final boolean[] nodeType_R_1 = it1.nodeType_R;
final boolean[] nodeType_R_2 = it2.nodeType_R;
int size_v, parent_v, parent_w, size_w;
int leftPath_v, rightPath_v;
float[] cost_Lpointer_v, cost_Rpointer_v, cost_Ipointer_v;
float[] strategypointer_v;
float[] cost_Lpointer_parent_v = null, cost_Rpointer_parent_v = null, cost_Ipointer_parent_v = null;
float[] strategypointer_parent_v = null;
int krSum_v, revkrSum_v, descSum_v;
boolean is_v_leaf;
final Stack<float[]> rowsToReuse_L = new Stack<float[]>();
final Stack<float[]> rowsToReuse_R = new Stack<float[]>();
final Stack<float[]> rowsToReuse_I = new Stack<float[]>();
for(int v = size1 - 1; v >= 0; v--) {
is_v_leaf = it1.isLeaf(v);
parent_v = pre2parent1[v];
strategypointer_v = strategy[v];
size_v = pre2size1[v];
leftPath_v = -(preR_to_preL_1[preL_to_preR_1[v] + pre2size1[v] - 1] + 1);// this is the left path's ID which is the leftmost leaf node: l-r_preorder(r-l_preorder(v) + |Fv| - 1)
rightPath_v = v + pre2size1[v] - 1 + 1; // this is the right path's ID which is the rightmost leaf node: l-r_preorder(v) + |Fv| - 1
krSum_v = pre2krSum1[v];
revkrSum_v = pre2revkrSum1[v];
descSum_v = pre2descSum1[v];
if (is_v_leaf) {
cost1_L[v] = leafRow;
cost1_R[v] = leafRow;
cost1_I[v] = leafRow;
for (int i = 0; i < size2; i++) {
strategypointer_v[i] = v;
}
}
cost_Lpointer_v = cost1_L[v];
cost_Rpointer_v = cost1_R[v];
cost_Ipointer_v = cost1_I[v];
if (parent_v != -1 && cost1_L[parent_v] == null) {
if (rowsToReuse_L.isEmpty()) {
cost1_L[parent_v] = new float[size2];
cost1_R[parent_v] = new float[size2];
cost1_I[parent_v] = new float[size2];
} else {
cost1_L[parent_v] = rowsToReuse_L.pop();
cost1_R[parent_v] = rowsToReuse_R.pop();
cost1_I[parent_v] = rowsToReuse_I.pop();
}
}
if (parent_v != -1) {
cost_Lpointer_parent_v = cost1_L[parent_v];
cost_Rpointer_parent_v = cost1_R[parent_v];
cost_Ipointer_parent_v = cost1_I[parent_v];
strategypointer_parent_v = strategy[parent_v];
}
Arrays.fill(cost2_L, 0L);
Arrays.fill(cost2_R, 0L);
Arrays.fill(cost2_I, 0L);
Arrays.fill(cost2_path, 0);
for (int w = size2 - 1; w >= 0; w--) {
size_w = pre2size2[w];
if (it2.isLeaf(w)) {
cost2_L[w] = 0L;
cost2_R[w] = 0L;
cost2_I[w] = 0L;
cost2_path[w] = w;
}
minCost = 0x7fffffffffffffffL;
strategyPath = -1;
float tmpCost = 0x7fffffffffffffffL;
if (size_v <= 1 || size_w <= 1) { // USE NEW SINGLE_PATH FUNCTIONS FOR SMALL SUBTREES
minCost = Math.max(size_v, size_w);
} else {
tmpCost = (float) size_v * (float) pre2krSum2[w] + cost_Lpointer_v[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = leftPath_v;
}
tmpCost = (float) size_v * (float) pre2revkrSum2[w] + cost_Rpointer_v[w];
if (tmpCost < minCost){
minCost = tmpCost;
strategyPath = rightPath_v;
}
tmpCost = (float) size_v * (float) pre2descSum2[w] + cost_Ipointer_v[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = (int)strategypointer_v[w] + 1;
}
tmpCost = (float) size_w * (float) krSum_v + cost2_L[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = -(preR_to_preL_2[preL_to_preR_2[w] + size_w - 1] + pathIDOffset + 1);
}
tmpCost = (float) size_w * (float) revkrSum_v + cost2_R[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = w + size_w - 1 + pathIDOffset + 1;
}
tmpCost = (float) size_w * (float) descSum_v + cost2_I[w];
if (tmpCost < minCost) {
minCost = tmpCost;
strategyPath = cost2_path[w] + pathIDOffset + 1;
}
}
if (parent_v != -1) {
cost_Lpointer_parent_v[w] += minCost;
tmpCost = -minCost + cost1_I[v][w];
if (tmpCost < cost1_I[parent_v][w]) {
cost_Ipointer_parent_v[w] = tmpCost;
strategypointer_parent_v[w] = strategypointer_v[w];
}
if (nodeType_L_1[v]) {
cost_Ipointer_parent_v[w] += cost_Lpointer_parent_v[w];
cost_Lpointer_parent_v[w] += cost_Lpointer_v[w] - minCost;
}
if (nodeType_R_1[v]) {
cost_Rpointer_parent_v[w] += cost_Rpointer_v[w];
} else {
cost_Rpointer_parent_v[w] += minCost;
}
}
parent_w = pre2parent2[w];
if (parent_w != -1) {
cost2_L[parent_w] += minCost;
tmpCost = -minCost + cost2_I[w];
if (tmpCost < cost2_I[parent_w]) {
cost2_I[parent_w] = tmpCost;
cost2_path[parent_w] = cost2_path[w];
}
if (nodeType_L_2[w]) {
cost2_I[parent_w] += cost2_L[parent_w];
cost2_L[parent_w] += cost2_L[w] - minCost;
}
if (nodeType_R_2[w]) {
cost2_R[parent_w] += cost2_R[w];
} else {
cost2_R[parent_w] += minCost;
}
}
strategypointer_v[w] = strategyPath;
}
if (!it1.isLeaf(v)) {
Arrays.fill(cost1_L[v], 0);
Arrays.fill(cost1_R[v], 0);
Arrays.fill(cost1_I[v], 0);
rowsToReuse_L.push(cost1_L[v]);
rowsToReuse_R.push(cost1_R[v]);
rowsToReuse_I.push(cost1_I[v]);
}
}
return strategy;
}
/**
* Implements spf1 single path function for the case when one of the subtrees
* is a single node [2, Section 6.1, Algorithm 2].
*
* <p>We allow an arbitrary cost model which in principle may allow renames to
* have a lower cost than the respective deletion plus insertion. Thus,
* Formula 4 in [2] has to be modified to account for that case.
*
* <p>In this method we don't have to verify if input subtrees have been
* swapped because they're always passed in the original input order.
*
* @param ni1 node indexer for the source input subtree.
* @param ni2 node indexer for the destination input subtree.
* @param subtreeRootNode1 root node of a subtree in the source input tree.
* @param subtreeRootNode2 root node of a subtree in the destination input tree.
* @return the tree edit distance between two subtrees of the source and destination input subtrees.
*/
// TODO: Merge the initialisation loop in tedInit with this method.
// Currently, spf1 doesn't have to store distances in delta, because
// all of them have been stored in tedInit.
private float spf1 (final NodeIndexer ni1, final int subtreeRootNode1, final NodeIndexer ni2, final int subtreeRootNode2) {
final int subtreeSize1 = ni1.sizes[subtreeRootNode1];
final int subtreeSize2 = ni2.sizes[subtreeRootNode2];
if (subtreeSize1 == 1 && subtreeSize2 == 1) {
final Node<D> n1 = ni1.preL_to_node[subtreeRootNode1];
final Node<D> n2 = ni2.preL_to_node[subtreeRootNode2];
final float maxCost = costModel.del(n1) + costModel.ins(n2);
final float renCost = costModel.ren(n1, n2);
return renCost < maxCost ? renCost : maxCost;
}
if (subtreeSize1 == 1) {
final Node<D> n1 = ni1.preL_to_node[subtreeRootNode1];
Node<D> n2 = null;
float cost = ni2.preL_to_sumInsCost[subtreeRootNode2];
final float maxCost = cost + costModel.del(n1);
float minRenMinusIns = cost;
float nodeRenMinusIns = 0;
for (int i = subtreeRootNode2; i < subtreeRootNode2 + subtreeSize2; i++) {
n2 = ni2.preL_to_node[i];
nodeRenMinusIns = costModel.ren(n1, n2) - costModel.ins(n2);
if (nodeRenMinusIns < minRenMinusIns) {
minRenMinusIns = nodeRenMinusIns;
}
}
cost += minRenMinusIns;
return cost < maxCost ? cost : maxCost;
}
if (subtreeSize2 == 1) {
Node<D> n1 = null;
final Node<D> n2 = ni2.preL_to_node[subtreeRootNode2];
float cost = ni1.preL_to_sumDelCost[subtreeRootNode1];
final float maxCost = cost + costModel.ins(n2);
float minRenMinusDel = cost;
float nodeRenMinusDel = 0;
for (int i = subtreeRootNode1; i < subtreeRootNode1 + subtreeSize1; i++) {
n1 = ni1.preL_to_node[i];
nodeRenMinusDel = costModel.ren(n1, n2) - costModel.del(n1);
if (nodeRenMinusDel < minRenMinusDel) {
minRenMinusDel = nodeRenMinusDel;
}
}
cost += minRenMinusDel;
return cost < maxCost ? cost : maxCost;
}
return -1;
}
/**
* Implements GTED algorithm [1, Section 3.4].
*
* @param it1 node indexer for the source input tree.
* @param it2 node indexer for the destination input tree.
* @return the tree edit distance between the source and destination trees.
*/
// TODO: Document the internals. Point to lines of the algorithm.
private float gted(final NodeIndexer it1, final NodeIndexer it2) {
final int currentSubtree1 = it1.getCurrentNode();
final int currentSubtree2 = it2.getCurrentNode();
final int subtreeSize1 = it1.sizes[currentSubtree1];
final int subtreeSize2 = it2.sizes[currentSubtree2];
// Use spf1.
if ((subtreeSize1 == 1 || subtreeSize2 == 1)) {
return spf1(it1, currentSubtree1, it2, currentSubtree2);
}
final int strategyPathID = (int)delta[currentSubtree1][currentSubtree2];
byte strategyPathType = -1;
int currentPathNode = Math.abs(strategyPathID) - 1;
final int pathIDOffset = it1.getSize();
int parent = -1;
if(currentPathNode < pathIDOffset) {
strategyPathType = getStrategyPathType(strategyPathID, pathIDOffset, it1, currentSubtree1, subtreeSize1);
while((parent = it1.parents[currentPathNode]) >= currentSubtree1) {
int ai[];
final int k = (ai = it1.children[parent]).length;
for(int i = 0; i < k; i++) {
final int child = ai[i];
if(child != currentPathNode) {
it1.setCurrentNode(child);
gted(it1, it2);
}
}
currentPathNode = parent;
}
// TODO: Move this property away from node indexer and pass directly to spfs.
it1.setCurrentNode(currentSubtree1);
// Pass to spfs a boolean that says says if the order of input subtrees
// has been swapped compared to the order of the initial input trees.
// Used for accessing delta array and deciding on the edit operation
// [1, Section 3.4].
if (strategyPathType == 0) {
return spfL(it1, it2, false);
}
if (strategyPathType == 1) {
return spfR(it1, it2, false);
}
return spfA(it1, it2, Math.abs(strategyPathID) - 1, strategyPathType, false);
}
currentPathNode -= pathIDOffset;
strategyPathType = getStrategyPathType(strategyPathID, pathIDOffset, it2, currentSubtree2, subtreeSize2);
while((parent = it2.parents[currentPathNode]) >= currentSubtree2) {
int ai1[];
final int l = (ai1 = it2.children[parent]).length;
for(int j = 0; j < l; j++) {
final int child = ai1[j];
if(child != currentPathNode) {
it2.setCurrentNode(child);
gted(it1, it2);
}
}
currentPathNode = parent;
}
// TODO: Move this property away from node indexer and pass directly to spfs.
it2.setCurrentNode(currentSubtree2);
// Pass to spfs a boolean that says says if the order of input subtrees
// has been swapped compared to the order of the initial input trees. Used
// for accessing delta array and deciding on the edit operation
// [1, Section 3.4].
if (strategyPathType == 0) {
return spfL(it2, it1, true);
}
if (strategyPathType == 1) {
return spfR(it2, it1, true);
}
return spfA(it2, it1, Math.abs(strategyPathID) - pathIDOffset - 1, strategyPathType, true);
}
/**
* Implements the single-path function spfA. Here, we use it strictly for
* inner paths (spfL and spfR have better performance for leaft and right
* paths, respectively) [1, Sections 7 and 8]. However, in this stage it
* also executes correctly for left and right paths.
*
* @param it1 node indexer of the left-hand input subtree.
* @param it2 node indexer of the right-hand input subtree.
* @param pathID the left-to-right preorder id of the strategy path's leaf node.
* @param pathType type of the strategy path (LEFT, RIGHT, INNER).
* @param treesSwapped says if the order of input subtrees has been swapped
* compared to the order of the initial input trees. Used
* for accessing delta array and deciding on the edit
* operation.
* @return tree edit distance between left-hand and right-hand input subtrees.
*/
// TODO: Document the internals. Point to lines of the algorithm.
// The implementation has been micro-tuned: variables initialised once,
// pointers to arrays precomputed and fixed for entire lower-level loops,
// parts of lower-level loops that don't change moved to upper-level loops.
private float spfA(final NodeIndexer it1, final NodeIndexer it2, final int pathID, final byte pathType, final boolean treesSwapped) {
final Node<D>[] it2nodes = it2.preL_to_node;
Node<D> lFNode;
final int[] it1sizes = it1.sizes;
final int[] it2sizes = it2.sizes;
final int[] it1parents = it1.parents;
final int[] it2parents = it2.parents;
final int[] it1preL_to_preR = it1.preL_to_preR;
final int[] it2preL_to_preR = it2.preL_to_preR;
final int[] it1preR_to_preL = it1.preR_to_preL;
final int[] it2preR_to_preL = it2.preR_to_preL;
final int currentSubtreePreL1 = it1.getCurrentNode();
final int currentSubtreePreL2 = it2.getCurrentNode();
// Variables to incrementally sum up the forest sizes.
int currentForestSize1 = 0;
int currentForestSize2 = 0;
int tmpForestSize1 = 0;
// Variables to incrementally sum up the forest cost.
float currentForestCost1 = 0;
float currentForestCost2 = 0;
float tmpForestCost1 = 0;
final int subtreeSize2 = it2.sizes[currentSubtreePreL2];
final int subtreeSize1 = it1.sizes[currentSubtreePreL1];
final float[][] t = new float[subtreeSize2+1][subtreeSize2+1];
final float[][] s = new float[subtreeSize1+1][subtreeSize2+1];
float minCost = -1;
// sp1, sp2 and sp3 correspond to three elements of the minimum in the
// recursive formula [1, Figure 12].
float sp1 = 0;
float sp2 = 0;
float sp3 = 0;
int startPathNode = -1;
int endPathNode = pathID;
int it1PreLoff = endPathNode;
final int it2PreLoff = currentSubtreePreL2;
int it1PreRoff = it1preL_to_preR[endPathNode];
final int it2PreRoff = it2preL_to_preR[it2PreLoff];
// variable declarations which were inside the loops
int rFlast,lFlast,endPathNode_in_preR,startPathNode_in_preR,parent_of_endPathNode,parent_of_endPathNode_in_preR,
lFfirst,rFfirst,rGlast,rGfirst,lGfirst,rG_in_preL,rGminus1_in_preL,parent_of_rG_in_preL,lGlast,lF_in_preR,lFSubtreeSize,
lGminus1_in_preR,parent_of_lG,parent_of_lG_in_preR,rF_in_preL,rFSubtreeSize,
rGfirst_in_preL;
boolean leftPart,rightPart,fForestIsTree,lFIsConsecutiveNodeOfCurrentPathNode,lFIsLeftSiblingOfCurrentPathNode,
rFIsConsecutiveNodeOfCurrentPathNode,rFIsRightSiblingOfCurrentPathNode;
float[] sp1spointer,sp2spointer,sp3spointer,sp3deltapointer,swritepointer,sp1tpointer,sp3tpointer;
// These variables store the id of the source (which array) of looking up
// elements of the minimum in the recursive formula [1, Figures 12,13].
byte sp1source,sp3source;
// Loop A [1, Algorithm 3] - walk up the path.
while (endPathNode >= currentSubtreePreL1) {
it1PreLoff = endPathNode;
it1PreRoff = it1preL_to_preR[endPathNode];
rFlast = -1;
lFlast = -1;
endPathNode_in_preR = it1preL_to_preR[endPathNode];
startPathNode_in_preR = startPathNode == -1 ? 0x7fffffff : it1preL_to_preR[startPathNode];
parent_of_endPathNode = it1parents[endPathNode];
parent_of_endPathNode_in_preR = parent_of_endPathNode == -1 ? 0x7fffffff : it1preL_to_preR[parent_of_endPathNode];
if (startPathNode - endPathNode > 1) {
leftPart = true;
} else {
leftPart = false;
}
if (startPathNode >= 0 && startPathNode_in_preR - endPathNode_in_preR > 1) {
rightPart = true;
} else {
rightPart = false;
}
// Deal with nodes to the left of the path.
if (pathType == 1 || pathType == 2 && leftPart) {
if (startPathNode == -1) {
rFfirst = endPathNode_in_preR;
lFfirst = endPathNode;
} else {
rFfirst = startPathNode_in_preR;
lFfirst = startPathNode - 1;
}
if (!rightPart) {
rFlast = endPathNode_in_preR;
}
rGlast = it2preL_to_preR[currentSubtreePreL2];
rGfirst = (rGlast + subtreeSize2) - 1;
lFlast = rightPart ? endPathNode + 1 : endPathNode;
fn[fn.length - 1] = -1;
for (int i = currentSubtreePreL2; i < currentSubtreePreL2 + subtreeSize2; i++) {
fn[i] = -1;
ft[i] = -1;
}
// Store the current size and cost of forest in F.
tmpForestSize1 = currentForestSize1;
tmpForestCost1 = currentForestCost1;
// Loop B [1, Algorithm 3] - for all nodes in G (right-hand input tree).
for (int rG = rGfirst; rG >= rGlast; rG--) {
lGfirst = it2preR_to_preL[rG];
rG_in_preL = it2preR_to_preL[rG];
rGminus1_in_preL = rG <= it2preL_to_preR[currentSubtreePreL2] ? 0x7fffffff : it2preR_to_preL[rG - 1];
parent_of_rG_in_preL = it2parents[rG_in_preL];
// This if statement decides on the last lG node for Loop D [1, Algorithm 3];
if (pathType == 1){
if (lGfirst == currentSubtreePreL2 || rGminus1_in_preL != parent_of_rG_in_preL) {
lGlast = lGfirst;
} else {
lGlast = it2parents[lGfirst]+1;
}
} else {
lGlast = lGfirst == currentSubtreePreL2 ? lGfirst : currentSubtreePreL2+1;
}
updateFnArray(it2.preL_to_ln[lGfirst], lGfirst, currentSubtreePreL2);
updateFtArray(it2.preL_to_ln[lGfirst], lGfirst);
int rF = rFfirst;
// Reset size and cost of the forest in F.
currentForestSize1 = tmpForestSize1;
currentForestCost1 = tmpForestCost1;
// Loop C [1, Algorithm 3] - for all nodes to the left of the path node.
for (int lF = lFfirst; lF >= lFlast; lF--) {
// This if statement fixes rF node.
if (lF == lFlast && !rightPart) {
rF = rFlast;
}
lFNode = it1.preL_to_node[lF];
// Increment size and cost of F forest by node lF.
currentForestSize1++;
currentForestCost1 += (treesSwapped ? costModel.ins(lFNode) : costModel.del(lFNode)); // USE COST MODEL - sum up deletion cost of a forest.
// Reset size and cost of forest in G to subtree G_lGfirst.
currentForestSize2 = it2sizes[lGfirst];
currentForestCost2 = (treesSwapped ? it2.preL_to_sumDelCost[lGfirst] : it2.preL_to_sumInsCost[lGfirst]); // USE COST MODEL - reset to subtree insertion cost.
lF_in_preR = it1preL_to_preR[lF];
fForestIsTree = lF_in_preR == rF;
lFSubtreeSize = it1sizes[lF];
lFIsConsecutiveNodeOfCurrentPathNode = startPathNode - lF == 1;
lFIsLeftSiblingOfCurrentPathNode = lF + lFSubtreeSize == startPathNode;
sp1spointer = s[(lF + 1) - it1PreLoff];
sp2spointer = s[lF - it1PreLoff];
sp3spointer = s[0];
sp3deltapointer = treesSwapped ? null : delta[lF];
swritepointer = s[lF - it1PreLoff];
sp1source = 1; // Search sp1 value in s array by default.
sp3source = 1; // Search second part of sp3 value in s array by default.
if (fForestIsTree) { // F_{lF,rF} is a tree.
if (lFSubtreeSize == 1) { // F_{lF,rF} is a single node.
sp1source = 3;
} else if (lFIsConsecutiveNodeOfCurrentPathNode) { // F_{lF,rF}-lF is the path node subtree.
sp1source = 2;
}
sp3 = 0;
sp3source = 2;
} else {
if (lFIsConsecutiveNodeOfCurrentPathNode) {
sp1source = 2;
}
sp3 = currentForestCost1 - (treesSwapped ? it1.preL_to_sumInsCost[lF] : it1.preL_to_sumDelCost[lF]); // USE COST MODEL - Delete F_{lF,rF}-F_lF.
if (lFIsLeftSiblingOfCurrentPathNode) {
sp3source = 3;
}
}
if (sp3source == 1) {
sp3spointer = s[(lF + lFSubtreeSize) - it1PreLoff];
}
// Go to first lG.
int lG = lGfirst;
// currentForestSize2++;
// sp1, sp2, sp3 -- Done here for the first node in Loop D. It differs for consecutive nodes.
// sp1 -- START
switch(sp1source) {
case 1: sp1 = sp1spointer[lG - it2PreLoff]; break;
case 2: sp1 = t[lG - it2PreLoff][rG - it2PreRoff]; break;
case 3: sp1 = currentForestCost2; break; // USE COST MODEL - Insert G_{lG,rG}.
}
sp1 += (treesSwapped ? costModel.ins(lFNode) : costModel.del(lFNode));// USE COST MODEL - Delete lF, leftmost root node in F_{lF,rF}.
// sp1 -- END
minCost = sp1; // Start with sp1 as minimal value.
// sp2 -- START
if (currentForestSize2 == 1) { // G_{lG,rG} is a single node.
sp2 = currentForestCost1; // USE COST MODEL - Delete F_{lF,rF}.
} else { // G_{lG,rG} is a tree.
sp2 = q[lF];
}
sp2 += (treesSwapped ? costModel.del(it2nodes[lG]) : costModel.ins(it2nodes[lG]));// USE COST MODEL - Insert lG, leftmost root node in G_{lG,rG}.
if (sp2 < minCost) { // Check if sp2 is minimal value.
minCost = sp2;
}
// sp2 -- END
// sp3 -- START
if (sp3 < minCost) {
sp3 += treesSwapped ? delta[lG][lF] : sp3deltapointer[lG];
if (sp3 < minCost) {
sp3 += (treesSwapped ? costModel.ren(it2nodes[lG], lFNode) : costModel.ren(lFNode, it2nodes[lG])); // USE COST MODEL - Rename the leftmost root nodes in F_{lF,rF} and G_{lG,rG}.
if(sp3 < minCost) {
minCost = sp3;
}
}
}
// sp3 -- END
swritepointer[lG - it2PreLoff] = minCost;
// Go to next lG.
lG = ft[lG];
counter++;
// Loop D [1, Algorithm 3] - for all nodes to the left of rG.
while (lG >= lGlast) {
// Increment size and cost of G forest by node lG.
currentForestSize2++;
currentForestCost2 += (treesSwapped ? costModel.del(it2nodes[lG]) : costModel.ins(it2nodes[lG]));
switch(sp1source) {
case 1: sp1 = sp1spointer[lG - it2PreLoff] + (treesSwapped ? costModel.ins(lFNode) : costModel.del(lFNode)); break; // USE COST MODEL - Delete lF, leftmost root node in F_{lF,rF}.
case 2: sp1 = t[lG - it2PreLoff][rG - it2PreRoff] + (treesSwapped ? costModel.ins(lFNode) : costModel.del(lFNode)); break; // USE COST MODEL - Delete lF, leftmost root node in F_{lF,rF}.
case 3: sp1 = currentForestCost2 + (treesSwapped ? costModel.ins(lFNode) : costModel.del(lFNode)); break; // USE COST MODEL - Insert G_{lG,rG} and elete lF, leftmost root node in F_{lF,rF}.
}
sp2 = sp2spointer[fn[lG] - it2PreLoff] + (treesSwapped ? costModel.del(it2nodes[lG]) : costModel.ins(it2nodes[lG])); // USE COST MODEL - Insert lG, leftmost root node in G_{lG,rG}.
minCost = sp1;
if(sp2 < minCost) {
minCost = sp2;
}
sp3 = treesSwapped ? delta[lG][lF] : sp3deltapointer[lG];
if (sp3 < minCost) {
switch(sp3source) {
case 1: sp3 += sp3spointer[fn[(lG + it2sizes[lG]) - 1] - it2PreLoff]; break;
case 2: sp3 += currentForestCost2 - (treesSwapped ? it2.preL_to_sumDelCost[lG] : it2.preL_to_sumInsCost[lG]); break; // USE COST MODEL - Insert G_{lG,rG}-G_lG.
case 3: sp3 += t[fn[(lG + it2sizes[lG]) - 1] - it2PreLoff][rG - it2PreRoff]; break;
}
if (sp3 < minCost) {
sp3 += (treesSwapped ? costModel.ren(it2nodes[lG], lFNode) : costModel.ren(lFNode, it2nodes[lG])); // USE COST MODEL - Rename the leftmost root nodes in F_{lF,rF} and G_{lG,rG}.
if (sp3 < minCost) {
minCost = sp3;
}
}
}
swritepointer[lG - it2PreLoff] = minCost;
lG = ft[lG];
counter++;
}
}
if (rGminus1_in_preL == parent_of_rG_in_preL) {
if (!rightPart) {
if (leftPart) {
if (treesSwapped) {
delta[parent_of_rG_in_preL][endPathNode] = s[(lFlast + 1) - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff];
} else {
delta[endPathNode][parent_of_rG_in_preL] = s[(lFlast + 1) - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff];
}
}
if (endPathNode > 0 && endPathNode == parent_of_endPathNode + 1 && endPathNode_in_preR == parent_of_endPathNode_in_preR + 1) {
if (treesSwapped) {
delta[parent_of_rG_in_preL][parent_of_endPathNode] = s[lFlast - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff];
} else {
delta[parent_of_endPathNode][parent_of_rG_in_preL] = s[lFlast - it1PreLoff][(rGminus1_in_preL + 1) - it2PreLoff];
}
}
}
for (int lF = lFfirst; lF >= lFlast; lF--) {
q[lF] = s[lF - it1PreLoff][(parent_of_rG_in_preL + 1) - it2PreLoff];
}
}
// TODO: first pointers can be precomputed
for (int lG = lGfirst; lG >= lGlast; lG = ft[lG]) {
t[lG - it2PreLoff][rG - it2PreRoff] = s[lFlast - it1PreLoff][lG - it2PreLoff];
}
}
}
// Deal with nodes to the right of the path.
if (pathType == 0 || pathType == 2 && rightPart || pathType == 2 && !leftPart && !rightPart) {
if (startPathNode == -1) {
lFfirst = endPathNode;
rFfirst = it1preL_to_preR[endPathNode];
} else {
rFfirst = it1preL_to_preR[startPathNode] - 1;
lFfirst = endPathNode + 1;
}
lFlast = endPathNode;
lGlast = currentSubtreePreL2;
lGfirst = (lGlast + subtreeSize2) - 1;
rFlast = it1preL_to_preR[endPathNode];
fn[fn.length - 1] = -1;
for (int i = currentSubtreePreL2; i < currentSubtreePreL2 + subtreeSize2; i++){
fn[i] = -1;
ft[i] = -1;
}
// Store size and cost of the current forest in F.
tmpForestSize1 = currentForestSize1;
tmpForestCost1 = currentForestCost1;
// Loop B' [1, Algorithm 3] - for all nodes in G.
for (int lG = lGfirst; lG >= lGlast; lG--) {
rGfirst = it2preL_to_preR[lG];
updateFnArray(it2.preR_to_ln[rGfirst], rGfirst, it2preL_to_preR[currentSubtreePreL2]);
updateFtArray(it2.preR_to_ln[rGfirst], rGfirst);
int lF = lFfirst;
lGminus1_in_preR = lG <= currentSubtreePreL2 ? 0x7fffffff : it2preL_to_preR[lG - 1];
parent_of_lG = it2parents[lG];
parent_of_lG_in_preR = parent_of_lG == -1 ? -1 : it2preL_to_preR[parent_of_lG];
// Reset size and cost of forest if F.
currentForestSize1 = tmpForestSize1;
currentForestCost1 = tmpForestCost1;
if (pathType == 0) {
if (lG == currentSubtreePreL2) {
rGlast = rGfirst;
} else if (it2.children[parent_of_lG][0] != lG) {
rGlast = rGfirst;
} else {
rGlast = it2preL_to_preR[parent_of_lG]+1;
}
} else {
rGlast = rGfirst == it2preL_to_preR[currentSubtreePreL2] ? rGfirst : it2preL_to_preR[currentSubtreePreL2];
}
// Loop C' [1, Algorithm 3] - for all nodes to the right of the path node.
for (int rF = rFfirst; rF >= rFlast; rF--) {
if (rF == rFlast) {
lF = lFlast;
}
rF_in_preL = it1preR_to_preL[rF];
// Increment size and cost of F forest by node rF.
currentForestSize1++;
currentForestCost1 += (treesSwapped ? costModel.ins(it1.preL_to_node[rF_in_preL]) : costModel.del(it1.preL_to_node[rF_in_preL])); // USE COST MODEL - sum up deletion cost of a forest.
// Reset size and cost of G forest to G_lG.
currentForestSize2 = it2sizes[lG];
currentForestCost2 = (treesSwapped ? it2.preL_to_sumDelCost[lG] : it2.preL_to_sumInsCost[lG]); // USE COST MODEL - reset to subtree insertion cost.
rFSubtreeSize = it1sizes[rF_in_preL];
if (startPathNode > 0) {
rFIsConsecutiveNodeOfCurrentPathNode = startPathNode_in_preR - rF == 1;
rFIsRightSiblingOfCurrentPathNode = rF + rFSubtreeSize == startPathNode_in_preR;
} else {
rFIsConsecutiveNodeOfCurrentPathNode = false;
rFIsRightSiblingOfCurrentPathNode = false;
}
fForestIsTree = rF_in_preL == lF;
final Node<D> rFNode = it1.preL_to_node[rF_in_preL];
sp1spointer = s[(rF + 1) - it1PreRoff];
sp2spointer = s[rF - it1PreRoff];
sp3spointer = s[0];
sp3deltapointer = treesSwapped ? null : delta[rF_in_preL];
swritepointer = s[rF - it1PreRoff];
sp1tpointer = t[lG - it2PreLoff];
sp3tpointer = t[lG - it2PreLoff];
sp1source = 1;
sp3source = 1;
if (fForestIsTree) {
if (rFSubtreeSize == 1) {
sp1source = 3;
} else if (rFIsConsecutiveNodeOfCurrentPathNode) {
sp1source = 2;
}
sp3 = 0;
sp3source = 2;
} else {
if (rFIsConsecutiveNodeOfCurrentPathNode) {
sp1source = 2;
}
sp3 = currentForestCost1 - (treesSwapped ? it1.preL_to_sumInsCost[rF_in_preL] : it1.preL_to_sumDelCost[rF_in_preL]); // USE COST MODEL - Delete F_{lF,rF}-F_rF.
if (rFIsRightSiblingOfCurrentPathNode) {
sp3source = 3;
}
}
if (sp3source == 1) {
sp3spointer = s[(rF + rFSubtreeSize) - it1PreRoff];
}
if (currentForestSize2 == 1) {
sp2 = currentForestCost1;// USE COST MODEL - Delete F_{lF,rF}.
} else {
sp2 = q[rF];
}
int rG = rGfirst;
rGfirst_in_preL = it2preR_to_preL[rGfirst];
currentForestSize2++;
switch (sp1source) {
case 1: sp1 = sp1spointer[rG - it2PreRoff]; break;
case 2: sp1 = sp1tpointer[rG - it2PreRoff]; break;
case 3: sp1 = currentForestCost2; break; // USE COST MODEL - Insert G_{lG,rG}.
}
sp1 += (treesSwapped ? costModel.ins(rFNode) : costModel.del(rFNode)); // USE COST MODEL - Delete rF.
minCost = sp1;
sp2 += (treesSwapped ? costModel.del(it2nodes[rGfirst_in_preL]) : costModel.ins(it2nodes[rGfirst_in_preL])); // USE COST MODEL - Insert rG.
if (sp2 < minCost) {
minCost = sp2;
}
if (sp3 < minCost) {
sp3 += treesSwapped ? delta[rGfirst_in_preL][rF_in_preL] : sp3deltapointer[rGfirst_in_preL];
if (sp3 < minCost) {
sp3 += (treesSwapped ? costModel.ren(it2nodes[rGfirst_in_preL], rFNode) : costModel.ren(rFNode, it2nodes[rGfirst_in_preL]));
if (sp3 < minCost) {
minCost = sp3;
}
}
}
swritepointer[rG - it2PreRoff] = minCost;
rG = ft[rG];
counter++;
// Loop D' [1, Algorithm 3] - for all nodes to the right of lG;
while (rG >= rGlast) {
rG_in_preL = it2preR_to_preL[rG];
// Increment size and cost of G forest by node rG.
currentForestSize2++;
currentForestCost2 += (treesSwapped ? costModel.del(it2nodes[rG_in_preL]) : costModel.ins(it2nodes[rG_in_preL]));
switch (sp1source) {
case 1: sp1 = sp1spointer[rG - it2PreRoff] + (treesSwapped ? costModel.ins(rFNode) : costModel.del(rFNode)); break; // USE COST MODEL - Delete rF.
case 2: sp1 = sp1tpointer[rG - it2PreRoff] + (treesSwapped ? costModel.ins(rFNode) : costModel.del(rFNode)); break; // USE COST MODEL - Delete rF.
case 3: sp1 = currentForestCost2 + (treesSwapped ? costModel.ins(rFNode) : costModel.del(rFNode)); break; // USE COST MODEL - Insert G_{lG,rG} and delete rF.
}
sp2 = sp2spointer[fn[rG] - it2PreRoff] + (treesSwapped ? costModel.del(it2nodes[rG_in_preL]) : costModel.ins(it2nodes[rG_in_preL])); // USE COST MODEL - Insert rG.
minCost = sp1;
if (sp2 < minCost) {
minCost = sp2;
}
sp3 = treesSwapped ? delta[rG_in_preL][rF_in_preL] : sp3deltapointer[rG_in_preL];
if (sp3 < minCost) {
switch (sp3source) {
case 1: sp3 += sp3spointer[fn[(rG + it2sizes[rG_in_preL]) - 1] - it2PreRoff]; break;
case 2: sp3 += currentForestCost2 - (treesSwapped ? it2.preL_to_sumDelCost[rG_in_preL] : it2.preL_to_sumInsCost[rG_in_preL]); break; // USE COST MODEL - Insert G_{lG,rG}-G_rG.
case 3: sp3 += sp3tpointer[fn[(rG + it2sizes[rG_in_preL]) - 1] - it2PreRoff]; break;
}
if (sp3 < minCost) {
sp3 += (treesSwapped ? costModel.ren(it2nodes[rG_in_preL], rFNode) : costModel.ren(rFNode, it2nodes[rG_in_preL])); // USE COST MODEL - Rename rF to rG.
if (sp3 < minCost) {
minCost = sp3;
}
}
}
swritepointer[rG - it2PreRoff] = minCost;
rG = ft[rG];
counter++;
}
}
if (lG > currentSubtreePreL2 && lG - 1 == parent_of_lG) {
if (rightPart) {
if (treesSwapped) {
delta[parent_of_lG][endPathNode] = s[(rFlast + 1) - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff];
} else {
delta[endPathNode][parent_of_lG] = s[(rFlast + 1) - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff];
}
}
if (endPathNode > 0 && endPathNode == parent_of_endPathNode + 1 && endPathNode_in_preR == parent_of_endPathNode_in_preR + 1)
if (treesSwapped) {
delta[parent_of_lG][parent_of_endPathNode] = s[rFlast - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff];
} else {
delta[parent_of_endPathNode][parent_of_lG] = s[rFlast - it1PreRoff][(lGminus1_in_preR + 1) - it2PreRoff];
}
for (int rF = rFfirst; rF >= rFlast; rF--) {
q[rF] = s[rF - it1PreRoff][(parent_of_lG_in_preR + 1) - it2PreRoff];
}
}
// TODO: first pointers can be precomputed
for (int rG = rGfirst; rG >= rGlast; rG = ft[rG]) {
t[lG - it2PreLoff][rG - it2PreRoff] = s[rFlast - it1PreRoff][rG - it2PreRoff];
}
}
}
// Walk up the path by one node.
startPathNode = endPathNode;
endPathNode = it1parents[endPathNode];
}
return minCost;
}
// ===================== BEGIN spfL
/**
* Implements single-path function for left paths [1, Sections 3.3,3.4,3.5].
* The parameters represent input subtrees for the single-path function.
* The order of the parameters is important. We use this single-path function
* due to better performance compared to spfA.
*
* @param it1 node indexer of the left-hand input subtree.
* @param it2 node indexer of the right-hand input subtree.
* @param treesSwapped says if the order of input subtrees has been swapped
* compared to the order of the initial input trees. Used
* for accessing delta array and deciding on the edit
* operation.
* @return tree edit distance between left-hand and right-hand input subtrees.
*/
private float spfL(final NodeIndexer it1, final NodeIndexer it2, final boolean treesSwapped) {
// Initialise the array to store the keyroot nodes in the right-hand input
// subtree.
final int[] keyRoots = new int[it2.sizes[it2.getCurrentNode()]];
Arrays.fill(keyRoots, -1);
// Get the leftmost leaf node of the right-hand input subtree.
final int pathID = it2.preL_to_lld(it2.getCurrentNode());
// Calculate the keyroot nodes in the right-hand input subtree.
// firstKeyRoot is the index in keyRoots of the first keyroot node that
// we have to process. We need this index because keyRoots array is larger
// than the number of keyroot nodes.
final int firstKeyRoot = computeKeyRoots(it2, it2.getCurrentNode(), pathID, keyRoots, 0);
// Initialise an array to store intermediate distances for subforest pairs.
final float[][] forestdist = new float[it1.sizes[it1.getCurrentNode()]+1][it2.sizes[it2.getCurrentNode()]+1];
// Compute the distances between pairs of keyroot nodes. In the left-hand
// input subtree only the root is the keyroot. Thus, we compute the distance
// between the left-hand input subtree and all keyroot nodes in the
// right-hand input subtree.
for (int i = firstKeyRoot-1; i >= 0; i--) {
treeEditDist(it1, it2, it1.getCurrentNode(), keyRoots[i], forestdist, treesSwapped);
}
// Return the distance between the input subtrees.
return forestdist[it1.sizes[it1.getCurrentNode()]][it2.sizes[it2.getCurrentNode()]];
}
/**
* Calculates and stores keyroot nodes for left paths of the given subtree
* recursively.
*
* @param it2 node indexer.
* @param subtreeRootNode keyroot node - recursion point.
* @param pathID left-to-right preorder id of the leftmost leaf node of subtreeRootNode.
* @param keyRoots array that stores all key roots in the order of their left-to-right preorder ids.
* @param index the index of keyRoots array where to store the next keyroot node.
* @return the index of the first keyroot node to process.
*/
// TODO: Merge with computeRevKeyRoots - the only difference is between leftmost and rightmost leaf.
private int computeKeyRoots(final NodeIndexer it2, final int subtreeRootNode, final int pathID, final int[] keyRoots, int index) {
// The subtreeRootNode is a keyroot node. Add it to keyRoots.
keyRoots[index] = subtreeRootNode;
// Increment the index to know where to store the next keyroot node.
index++;
// Walk up the left path starting with the leftmost leaf of subtreeRootNode,
// until the child of subtreeRootNode.
int pathNode = pathID;
while (pathNode > subtreeRootNode) {
final int parent = it2.parents[pathNode];
// For each sibling to the right of pathNode, execute this method recursively.
// Each right sibling of pathNode is a keyroot node.
for (final int child : it2.children[parent]) {
// Execute computeKeyRoots recursively for the new subtree rooted at child and child's leftmost leaf node.
if (child != pathNode) index = computeKeyRoots(it2, child, it2.preL_to_lld(child), keyRoots, index);
}
// Walk up.
pathNode = parent;
}
return index;
}
/**
* Implements the core of spfL. Fills in forestdist array with intermediate
* distances of subforest pairs in dynamic-programming fashion.
*
* @param it1 node indexer of the left-hand input subtree.
* @param it2 node indexer of the right-hand input subtree.
* @param it1subtree left-to-right preorder id of the root node of the
* left-hand input subtree.
* @param it2subtree left-to-right preorder id of the root node of the
* right-hand input subtree.
* @param forestdist the array to be filled in with intermediate distances of subforest pairs.
* @param treesSwapped says if the order of input subtrees has been swapped
* compared to the order of the initial input trees. Used
* for accessing delta array and deciding on the edit
* operation.
*/
private void treeEditDist(final NodeIndexer it1, final NodeIndexer it2, final int it1subtree, final int it2subtree, final float[][] forestdist, final boolean treesSwapped) {
// Translate input subtree root nodes to left-to-right postorder.
final int i = it1.preL_to_postL[it1subtree];
final int j = it2.preL_to_postL[it2subtree];
// We need to offset the node ids for accessing forestdist array which has
// indices from 0 to subtree size. However, the subtree node indices do not
// necessarily start with 0.
// Whenever the original left-to-right postorder id has to be accessed, use
// i+ioff and j+joff.
final int ioff = it1.postL_to_lld[i] - 1;
final int joff = it2.postL_to_lld[j] - 1;
// Variables holding costs of each minimum element.
float da = 0;
float db = 0;
float dc = 0;
// Initialize forestdist array with deletion and insertion costs of each
// relevant subforest.
forestdist[0][0] = 0;
for (int i1 = 1; i1 <= i - ioff; i1++) {
forestdist[i1][0] = forestdist[i1 - 1][0] + (treesSwapped ? costModel.ins(it1.postL_to_node(i1 + ioff)) : costModel.del(it1.postL_to_node(i1 + ioff))); // USE COST MODEL - delete i1.
}
for (int j1 = 1; j1 <= j - joff; j1++) {
forestdist[0][j1] = forestdist[0][j1 - 1] + (treesSwapped ? costModel.del(it2.postL_to_node(j1 + joff)) : costModel.ins(it2.postL_to_node(j1 + joff))); // USE COST MODEL - insert j1.
}
// Fill in the remaining costs.
for (int i1 = 1; i1 <= i - ioff; i1++) {
for (int j1 = 1; j1 <= j - joff; j1++) {
// Increment the number of subproblems.
counter++;
// Calculate partial distance values for this subproblem.
final float u = (treesSwapped ? costModel.ren(it2.postL_to_node(j1 + joff), it1.postL_to_node(i1 + ioff)) : costModel.ren(it1.postL_to_node(i1 + ioff), it2.postL_to_node(j1 + joff))); // USE COST MODEL - rename i1 to j1.
da = forestdist[i1 - 1][j1] + (treesSwapped ? costModel.ins(it1.postL_to_node(i1 + ioff)) : costModel.del(it1.postL_to_node(i1 + ioff))); // USE COST MODEL - delete i1.
db = forestdist[i1][j1 - 1] + (treesSwapped ? costModel.del(it2.postL_to_node(j1 + joff)) : costModel.ins(it2.postL_to_node(j1 + joff))); // USE COST MODEL - insert j1.
// If current subforests are subtrees.
if (it1.postL_to_lld[i1 + ioff] == it1.postL_to_lld[i] && it2.postL_to_lld[j1 + joff] == it2.postL_to_lld[j]) {
dc = forestdist[i1 - 1][j1 - 1] + u;
// Store the relevant distance value in delta array.
if (treesSwapped) {
delta[it2.postL_to_preL[j1 + joff]][it1.postL_to_preL[i1 + ioff]] = forestdist[i1 - 1][j1 - 1];
} else {
delta[it1.postL_to_preL[i1 + ioff]][it2.postL_to_preL[j1 + joff]] = forestdist[i1 - 1][j1 - 1];
}
} else {
dc = forestdist[it1.postL_to_lld[i1 + ioff] - 1 - ioff][it2.postL_to_lld[j1 + joff] - 1 - joff] +
(treesSwapped ? delta[it2.postL_to_preL[j1 + joff]][it1.postL_to_preL[i1 + ioff]] : delta[it1.postL_to_preL[i1 + ioff]][it2.postL_to_preL[j1 + joff]]) + u;
}
// Calculate final minimum.
forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da;
}
}
}
// ===================== END spfL
// ===================== BEGIN spfR
/**
* Implements single-path function for right paths [1, Sections 3.3,3.4,3.5].
* The parameters represent input subtrees for the single-path function.
* The order of the parameters is important. We use this single-path function
* due to better performance compared to spfA.
*
* @param it1 node indexer of the left-hand input subtree.
* @param it2 node indexer of the right-hand input subtree.
* @param treesSwapped says if the order of input subtrees has been swapped
* compared to the order of the initial input trees. Used
* for accessing delta array and deciding on the edit
* operation.
* @return tree edit distance between left-hand and right-hand input subtrees.
*/
private float spfR(final NodeIndexer it1, final NodeIndexer it2, final boolean treesSwapped) {
// Initialise the array to store the keyroot nodes in the right-hand input
// subtree.
final int[] revKeyRoots = new int[it2.sizes[it2.getCurrentNode()]];
Arrays.fill(revKeyRoots, -1);
// Get the rightmost leaf node of the right-hand input subtree.
final int pathID = it2.preL_to_rld(it2.getCurrentNode());
// Calculate the keyroot nodes in the right-hand input subtree.
// firstKeyRoot is the index in keyRoots of the first keyroot node that
// we have to process. We need this index because keyRoots array is larger
// than the number of keyroot nodes.
final int firstKeyRoot = computeRevKeyRoots(it2, it2.getCurrentNode(), pathID, revKeyRoots, 0);
// Initialise an array to store intermediate distances for subforest pairs.
final float[][] forestdist = new float[it1.sizes[it1.getCurrentNode()]+1][it2.sizes[it2.getCurrentNode()]+1];
// Compute the distances between pairs of keyroot nodes. In the left-hand
// input subtree only the root is the keyroot. Thus, we compute the distance
// between the left-hand input subtree and all keyroot nodes in the
// right-hand input subtree.
for (int i = firstKeyRoot-1; i >= 0; i--) {
revTreeEditDist(it1, it2, it1.getCurrentNode(), revKeyRoots[i], forestdist, treesSwapped);
}
// Return the distance between the input subtrees.
return forestdist[it1.sizes[it1.getCurrentNode()]][it2.sizes[it2.getCurrentNode()]];
}
/**
* Calculates and stores keyroot nodes for right paths of the given subtree
* recursively.
*
* @param it2 node indexer.
* @param subtreeRootNode keyroot node - recursion point.
* @param pathID left-to-right preorder id of the rightmost leaf node of subtreeRootNode.
* @param revKeyRoots array that stores all key roots in the order of their left-to-right preorder ids.
* @param index the index of keyRoots array where to store the next keyroot node.
* @return the index of the first keyroot node to process.
*/
private int computeRevKeyRoots(final NodeIndexer it2, final int subtreeRootNode, final int pathID, final int[] revKeyRoots, int index) {
// The subtreeRootNode is a keyroot node. Add it to keyRoots.
revKeyRoots[index] = subtreeRootNode;
// Increment the index to know where to store the next keyroot node.
index++;
// Walk up the right path starting with the rightmost leaf of
// subtreeRootNode, until the child of subtreeRootNode.
int pathNode = pathID;
while (pathNode > subtreeRootNode) {
final int parent = it2.parents[pathNode];
// For each sibling to the left of pathNode, execute this method recursively.
// Each left sibling of pathNode is a keyroot node.
for (final int child : it2.children[parent]) {
// Execute computeRevKeyRoots recursively for the new subtree rooted at child and child's rightmost leaf node.
if (child != pathNode) index = computeRevKeyRoots(it2, child, it2.preL_to_rld(child), revKeyRoots, index);
}
// Walk up.
pathNode = parent;
}
return index;
}
/**
* Implements the core of spfR. Fills in forestdist array with intermediate
* distances of subforest pairs in dynamic-programming fashion.
*
* @param it1 node indexer of the left-hand input subtree.
* @param it2 node indexer of the right-hand input subtree.
* @param it1subtree left-to-right preorder id of the root node of the
* left-hand input subtree.
* @param it2subtree left-to-right preorder id of the root node of the
* right-hand input subtree.
* @param forestdist the array to be filled in with intermediate distances of
* subforest pairs.
* @param treesSwapped says if the order of input subtrees has been swapped
* compared to the order of the initial input trees. Used
* for accessing delta array and deciding on the edit
* operation.
*/
private void revTreeEditDist(final NodeIndexer it1, final NodeIndexer it2, final int it1subtree, final int it2subtree, final float[][] forestdist, final boolean treesSwapped) {
// Translate input subtree root nodes to right-to-left postorder.
final int i = it1.preL_to_postR[it1subtree];
final int j = it2.preL_to_postR[it2subtree];
// We need to offset the node ids for accessing forestdist array which has
// indices from 0 to subtree size. However, the subtree node indices do not
// necessarily start with 0.
// Whenever the original right-to-left postorder id has to be accessed, use
// i+ioff and j+joff.
final int ioff = it1.postR_to_rld[i] - 1;
final int joff = it2.postR_to_rld[j] - 1;
// Variables holding costs of each minimum element.
float da = 0;
float db = 0;
float dc = 0;
// Initialize forestdist array with deletion and insertion costs of each
// relevant subforest.
forestdist[0][0] = 0;
for (int i1 = 1; i1 <= i - ioff; i1++) {
forestdist[i1][0] = forestdist[i1 - 1][0] + (treesSwapped ? costModel.ins(it1.postR_to_node(i1 + ioff)) : costModel.del(it1.postR_to_node(i1 + ioff))); // USE COST MODEL - delete i1.
}
for (int j1 = 1; j1 <= j - joff; j1++) {
forestdist[0][j1] = forestdist[0][j1 - 1] + (treesSwapped ? costModel.del(it2.postR_to_node(j1 + joff)) : costModel.ins(it2.postR_to_node(j1 + joff))); // USE COST MODEL - insert j1.
}
// Fill in the remaining costs.
for (int i1 = 1; i1 <= i - ioff; i1++) {
for (int j1 = 1; j1 <= j - joff; j1++) {
// Increment the number of subproblems.
counter++;
// Calculate partial distance values for this subproblem.
final float u = (treesSwapped ? costModel.ren(it2.postR_to_node(j1 + joff), it1.postR_to_node(i1 + ioff)) : costModel.ren(it1.postR_to_node(i1 + ioff), it2.postR_to_node(j1 + joff))); // USE COST MODEL - rename i1 to j1.
da = forestdist[i1 - 1][j1] + (treesSwapped ? costModel.ins(it1.postR_to_node(i1 + ioff)) : costModel.del(it1.postR_to_node(i1 + ioff))); // USE COST MODEL - delete i1.
db = forestdist[i1][j1 - 1] + (treesSwapped ? costModel.del(it2.postR_to_node(j1 + joff)) : costModel.ins(it2.postR_to_node(j1 + joff))); // USE COST MODEL - insert j1.
// If current subforests are subtrees.
if (it1.postR_to_rld[i1 + ioff] == it1.postR_to_rld[i] && it2.postR_to_rld[j1 + joff] == it2.postR_to_rld[j]) {
dc = forestdist[i1 - 1][j1 - 1] + u;
// Store the relevant distance value in delta array.
if (treesSwapped) {
delta[it2.postR_to_preL[j1+joff]][it1.postR_to_preL[i1+ioff]] = forestdist[i1 - 1][j1 - 1];
} else {
delta[it1.postR_to_preL[i1+ioff]][it2.postR_to_preL[j1+joff]] = forestdist[i1 - 1][j1 - 1];
}
} else {
dc = forestdist[it1.postR_to_rld[i1 + ioff] - 1 - ioff][it2.postR_to_rld[j1 + joff] - 1 - joff] +
(treesSwapped ? delta[it2.postR_to_preL[j1 + joff]][it1.postR_to_preL[i1 + ioff]] : delta[it1.postR_to_preL[i1 + ioff]][it2.postR_to_preL[j1 + joff]]) + u;
}
// Calculate final minimum.
forestdist[i1][j1] = da >= db ? db >= dc ? dc : db : da >= dc ? dc : da;
}
}
}
// ===================== END spfR
/**
* Decodes the path from the optimal strategy to its type.
*
* @param pathIDWithPathIDOffset raw path id from strategy array.
* @param pathIDOffset offset used to distinguish between paths in the source and destination trees.
* @param it node indexer.
* @param currentRootNodePreL the left-to-right preorder id of the current subtree processed in tree decomposition phase.
* @param currentSubtreeSize the size of the subtree currently processed in tree decomposition phase.
* @return type of the strategy path (LEFT, RIGHT, INNER).
*/
private byte getStrategyPathType(final int pathIDWithPathIDOffset, final int pathIDOffset, final NodeIndexer it, final int currentRootNodePreL, final int currentSubtreeSize) {
if (Integer.signum(pathIDWithPathIDOffset) == -1) {
return LEFT;
}
int pathID = Math.abs(pathIDWithPathIDOffset) - 1;
if (pathID >= pathIDOffset) {
pathID = pathID - pathIDOffset;
}
if (pathID == (currentRootNodePreL + currentSubtreeSize) - 1) {
return RIGHT;
}
return INNER;
}
/**
* fn array used in the algorithm before [1]. Using it does not change the
* complexity.
*
* <p>TODO: Do not use it [1, Section 8.4].
*
* @param lnForNode ---
* @param node ---
* @param currentSubtreePreL ---
*/
private void updateFnArray(final int lnForNode, final int node, final int currentSubtreePreL) {
if (lnForNode >= currentSubtreePreL) {
fn[node] = fn[lnForNode];
fn[lnForNode] = node;
} else {
fn[node] = fn[fn.length - 1];
fn[fn.length - 1] = node;
}
}
/**
* ft array used in the algorithm before [1]. Using it does not change the
* complexity.
*
* <p>TODO: Do not use it [1, Section 8.4].
*
* @param lnForNode ---
* @param node ---
*/
private void updateFtArray(final int lnForNode, final int node) {
ft[node] = lnForNode;
if(fn[node] > -1) {
ft[fn[node]] = node;
}
}
/**
* Compute the edit mapping between two trees. The trees are input trees
* to the distance computation and the distance must be computed before
* computing the edit mapping (distances of subtree pairs are required).
*
* @return Returns list of pairs of nodes that are mapped as pairs of their
* postorder IDs (starting with 1). Nodes that are deleted or
* inserted are mapped to 0.
*/
// TODO: Mapping computation requires more thorough documentation
// (methods computeEditMapping, forestDist, mappingCost).
// TODO: Before computing the mapping, verify if TED has been computed.
// Mapping computation should trigger distance computation if
// necessary.
public List<int[]> computeEditMapping() {
// Initialize tree and forest distance arrays.
// Arrays for subtree distances is not needed because the distances
// between subtrees without the root nodes are already stored in delta.
final float[][] forestdist = new float[size1 + 1][size2 + 1];
boolean rootNodePair = true;
// forestdist for input trees has to be computed
forestDist(it1, it2, size1, size2, forestdist);
// empty edit mapping
final LinkedList<int[]> editMapping = new LinkedList<int[]>();
// empty stack of tree Pairs
final LinkedList<int[]> treePairs = new LinkedList<int[]>();
// push the pair of trees (ted1,ted2) to stack
treePairs.push(new int[] { size1, size2 });
while (!treePairs.isEmpty()) {
// get next tree pair to be processed
final int[] treePair = treePairs.pop();
final int lastRow = treePair[0];
final int lastCol = treePair[1];
// compute forest distance matrix
if (!rootNodePair) {
forestDist(it1, it2, lastRow, lastCol, forestdist);
}
rootNodePair = false;
// compute mapping for current forest distance matrix
final int firstRow = it1.postL_to_lld[lastRow-1];
final int firstCol = it2.postL_to_lld[lastCol-1];
int row = lastRow;
int col = lastCol;
while ((row > firstRow) || (col > firstCol)) {
if ((row > firstRow) && (forestdist[row - 1][col] + costModel.del(it1.postL_to_node(row-1)) == forestdist[row][col])) { // USE COST MODEL - Delete node row of source tree.
// node with postorderID row is deleted from ted1
editMapping.push(new int[] { row, 0 });
row--;
} else if ((col > firstCol) && (forestdist[row][col - 1] + costModel.ins(it2.postL_to_node(col-1)) == forestdist[row][col])) { // USE COST MODEL - Insert node col of destination tree.
// node with postorderID col is inserted into ted2
editMapping.push(new int[] { 0, col });
col--;
} else {
// node with postorderID row in ted1 is renamed to node col
// in ted2
if ((it1.postL_to_lld[row-1] == it1.postL_to_lld[lastRow-1]) && (it2.postL_to_lld[col-1] == it2.postL_to_lld[lastCol-1])) {
// if both subforests are trees, map nodes
editMapping.push(new int[] { row, col });
row--;
col--;
} else {
// push subtree pair
treePairs.push(new int[] { row, col });
// continue with forest to the left of the popped
// subtree pair
row = it1.postL_to_lld[row-1];
col = it2.postL_to_lld[col-1];
}
}
}
}
return editMapping;
}
/**
* Recalculates distances between subforests of two subtrees. These values
* are used in mapping computation to track back the origin of minimum values.
* It is basen on Zhang and Shasha algorithm.
*
* <p>The rename cost must be added in the last line. Otherwise the formula is
* incorrect. This is due to delta storing distances between subtrees
* without the root nodes.
*
* <p>i and j are postorder ids of the nodes - starting with 1.
*
* @param ted1 node indexer of the source input tree.
* @param ted2 node indexer of the destination input tree.
* @param i subtree root of source tree that is to be mapped.
* @param j subtree root of destination tree that is to be mapped.
* @param forestdist array to store distances between subforest pairs.
*/
private void forestDist(final NodeIndexer ted1, final NodeIndexer ted2, final int i, final int j, final float[][] forestdist) {
forestdist[ted1.postL_to_lld[i-1]][ted2.postL_to_lld[j-1]] = 0;
for (int di = ted1.postL_to_lld[i-1]+1; di <= i; di++) {
forestdist[di][ted2.postL_to_lld[j-1]] = forestdist[di - 1][ted2.postL_to_lld[j-1]] + costModel.del(ted1.postL_to_node(di-1));
for (int dj = ted2.postL_to_lld[j-1]+1; dj <= j; dj++) {
forestdist[ted1.postL_to_lld[i-1]][dj] = forestdist[ted1.postL_to_lld[i-1]][dj - 1] + costModel.ins(ted2.postL_to_node(dj-1));
final float costRen = costModel.ren(ted1.postL_to_node(di-1), ted2.postL_to_node(dj-1));
// TODO: The first two elements of the minimum can be computed here,
// similarly to spfL and spfR.
if ((ted1.postL_to_lld[di-1] == ted1.postL_to_lld[i-1]) && (ted2.postL_to_lld[dj-1] == ted2.postL_to_lld[j-1])) {
forestdist[di][dj] = Math.min(Math.min(
forestdist[di - 1][dj] + costModel.del(ted1.postL_to_node(di-1)),
forestdist[di][dj - 1] + costModel.ins(ted2.postL_to_node(dj-1))),
forestdist[di - 1][dj - 1] + costRen);
// If substituted with delta, this will overwrite the value
// in delta.
// It looks that we don't have to write this value.
// Conceptually it is correct because we already have all
// the values in delta for subtrees without the root nodes,
// and we need these.
// treedist[di][dj] = forestdist[di][dj];
} else {
// di and dj are postorder ids of the nodes - starting with 1
// Substituted 'treedist[di][dj]' with 'delta[it1.postL_to_preL[di-1]][it2.postL_to_preL[dj-1]]'
forestdist[di][dj] = Math.min(Math.min(
forestdist[di - 1][dj] + costModel.del(ted1.postL_to_node(di-1)),
forestdist[di][dj - 1] + costModel.ins(ted2.postL_to_node(dj-1))),
forestdist[ted1.postL_to_lld[di-1]][ted2.postL_to_lld[dj-1]] + delta[it1.postL_to_preL[di-1]][it2.postL_to_preL[dj-1]] + costRen);
}
}
}
}
/**
* Calculates the cost of an edit mapping. It traverses the mapping and sums
* up the cost of each operation. The costs are taken from the cost model.
*
* @param mapping an edit mapping.
* @return cost of edit mapping.
*/
public float mappingCost(final List<int[]> mapping) {
float cost = 0.0f;
for (int i = 0; i < mapping.size(); i++) {
if (mapping.get(i)[0] == 0) { // Insertion.
cost += costModel.ins(it2.postL_to_node(mapping.get(i)[1]-1));
} else if (mapping.get(i)[1] == 0) { // Deletion.
cost += costModel.del(it1.postL_to_node(mapping.get(i)[0]-1));
} else { // Rename.
cost += costModel.ren(it1.postL_to_node(mapping.get(i)[0]-1), it2.postL_to_node(mapping.get(i)[1]-1));
}
}
return cost;
}
}
| 81,165 | 43.498904 | 228 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/distance/AllPossibleMappingsTED.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.distance;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import gameDistance.utils.apted.costmodel.CostModel;
import gameDistance.utils.apted.node.Node;
import gameDistance.utils.apted.node.NodeIndexer;
/**
* Implements an exponential algorithm for the tree edit distance. It computes
* all possible TED mappings between two trees and calculated their minimal
* cost.
*
* @param <C> type of cost model.
* @param <D> type of node data.
*/
@SuppressWarnings("all")
public class AllPossibleMappingsTED<C extends CostModel, D> {
/**
* Indexer of the source tree.
*
* @see node.NodeIndexer
*/
private NodeIndexer it1;
/**
* Indexer of the destination tree.
*
* @see node.NodeIndexer
*/
private NodeIndexer it2;
/**
* The size of the source input tree.
*/
private int size1;
/**
* The size of the destination tree.
*/
private int size2;
/**
* Cost model to be used for calculating costs of edit operations.
*/
private final C costModel;
/**
* Constructs the AllPossibleMappingsTED algorithm with a specific cost model.
*
* @param costModel a cost model used in the algorithm.
*/
public AllPossibleMappingsTED(final C costModel) {
this.costModel = costModel;
}
/**
* Computes the tree edit distance between two trees by trying all possible
* TED mappings. It uses the specified cost model.
*
* @param t1 source tree.
* @param t2 destination tree.
* @return the tree edit distance between two trees.
*/
public float computeEditDistance(final Node<D> t1, final Node<D> t2) {
// Index the nodes of both input trees.
init(t1, t2);
final ArrayList<ArrayList<int[]>> mappings = generateAllOneToOneMappings();
removeNonTEDMappings(mappings);
return getMinCost(mappings);
}
/**
* Indexes the input trees.
*
* @param t1 source tree.
* @param t2 destination tree.
*/
public void init(final Node<D> t1, final Node<D> t2) {
it1 = new NodeIndexer(t1, costModel);
it2 = new NodeIndexer(t2, costModel);
size1 = it1.getSize();
size2 = it2.getSize();
}
/**
* Generate all possible 1-1 mappings.
*
* <p>These mappings do not conform to TED conditions (sibling-order and
* ancestor-descendant).
*
* <p>A mapping is a list of pairs (arrays) of preorder IDs (identifying
* nodes).
*
* @return set of all 1-1 mappings.
*/
private ArrayList<ArrayList<int[]>> generateAllOneToOneMappings() {
// Start with an empty mapping - all nodes are deleted or inserted.
final ArrayList<ArrayList<int[]>> mappings = new ArrayList<ArrayList<int[]>>(1);
mappings.add(new ArrayList<int[]>(size1 + size2));
// Add all deleted nodes.
for (int n1 = 0; n1 < size1; n1++) {
mappings.get(0).add(new int[]{n1, -1});
}
// Add all inserted nodes.
for (int n2 = 0; n2 < size2; n2++) {
mappings.get(0).add(new int[]{-1, n2});
}
// For each node in the source tree.
for (int n1 = 0; n1 < size1; n1++) {
// Duplicate all mappings and store in mappings_copy.
final ArrayList<ArrayList<int[]>> mappings_copy = deepMappingsCopy(mappings);
// For each node in the destination tree.
for (int n2 = 0; n2 < size2; n2++) {
// For each mapping (produced for all n1 values smaller than
// current n1).
for (final ArrayList<int[]> m : mappings_copy) {
// Produce new mappings with the pair (n1, n2) by adding this
// pair to all mappings where it is valid to add.
boolean element_add = true;
// Verify if (n1, n2) can be added to mapping m.
// All elements in m are checked with (n1, n2) for possible
// violation.
// One-to-one condition.
for (final int[] e : m) {
// n1 is not in any of previous mappings
if (e[0] != -1 && e[1] != -1 && e[1] == n2) {
element_add = false;
// System.out.println("Add " + n2 + " false.");
break;
}
}
// New mappings must be produced by duplicating a previous
// mapping and extending it by (n1, n2).
if (element_add) {
final ArrayList<int[]> m_copy = deepMappingCopy(m);
m_copy.add(new int[]{n1, n2});
// If a pair (n1,n2) is added, (n1,-1) and (-1,n2) must be removed.
removeMappingElement(m_copy, new int[]{n1, -1});
removeMappingElement(m_copy, new int[]{-1, n2});
mappings.add(m_copy);
}
}
}
}
return mappings;
}
/**
* Given all 1-1 mappings, discard these that violate TED conditions
* (ancestor-descendant and sibling order).
*
* @param mappings set of all 1-1 mappings.
*/
private void removeNonTEDMappings(final ArrayList<ArrayList<int[]>> mappings) {
// Validate each mapping separately.
// Iterator safely removes mappings while iterating.
for (final Iterator<ArrayList<int[]>> mit = mappings.iterator(); mit.hasNext();) {
final ArrayList<int[]> m = mit.next();
if (!isTEDMapping(m)) {
mit.remove();
}
}
}
/**
* Test if a 1-1 mapping is a TED mapping.
*
* @param m a 1-1 mapping.
* @return {@code true} if {@code m} is a TED mapping, and {@code false}
* otherwise.
*/
boolean isTEDMapping(final ArrayList<int[]> m) {
// Validate each pair of pairs of mapped nodes in the mapping.
for (final int[] e1 : m) {
// Use only pairs of mapped nodes for validation.
if (e1[0] == -1 || e1[1] == -1) {
continue;
}
for (final int[] e2 : m) {
// Use only pairs of mapped nodes for validation.
if (e2[0] == -1 || e2[1] == -1) {
continue;
}
// If any of the conditions below doesn't hold, discard m.
// Validate ancestor-descendant condition.
boolean a = e1[0] < e2[0] && it1.preL_to_preR[e1[0]] < it1.preL_to_preR[e2[0]];
boolean b = e1[1] < e2[1] && it2.preL_to_preR[e1[1]] < it2.preL_to_preR[e2[1]];
if ((a && !b) || (!a && b)) {
// Discard the mapping.
// If this condition doesn't hold, the next condition
// doesn't have to be verified any more and any other
// pair (e1, e2) doesn't have to be verified any more.
return false;
}
// Validate sibling-order condition.
a = e1[0] < e2[0] && it1.preL_to_preR[e1[0]] > it1.preL_to_preR[e2[0]];
b = e1[1] < e2[1] && it2.preL_to_preR[e1[1]] > it2.preL_to_preR[e2[1]];
if ((a && !b) || (!a && b)) {
// Discard the mapping.
return false;
}
}
}
return true;
}
/**
* Given list of all TED mappings, calculate the cost of the minimal-cost
* mapping.
*
* @param tedMappings set of all TED mappings.
* @return the minimal cost among all TED mappings.
*/
float getMinCost(final ArrayList<ArrayList<int[]>> tedMappings) {
// Initialize min_cost to the upper bound.
float min_cost = size1 + size2;
// System.out.println("min_cost = " + min_cost);
// Verify cost of each mapping.
for (final ArrayList<int[]> m : tedMappings) {
float m_cost = 0;
// Sum up edit costs for all elements in the mapping m.
for (final int[] e : m) {
// Add edit operation cost.
if (e[0] > -1 && e[1] > -1) {
m_cost += costModel.ren(it1.preL_to_node[e[0]], it2.preL_to_node[e[1]]); // USE COST MODEL - rename e[0] to e[1].
} else if (e[0] > -1) {
m_cost += costModel.del(it1.preL_to_node[e[0]]); // USE COST MODEL - insert e[1].
} else {
m_cost += costModel.ins(it2.preL_to_node[e[1]]); // USE COST MODEL - delete e[0].
}
// Break as soon as the current min_cost is exceeded.
// Only for early loop break.
if (m_cost >= min_cost) {
break;
}
}
// Store the minimal cost - compare m_cost and min_cost
if (m_cost < min_cost) {
min_cost = m_cost;
}
// System.out.printf("min_cost = %.8f\n", min_cost);
}
return min_cost;
}
/**
* Makes a deep copy of a mapping.
*
* @param mapping mapping to copy.
* @return a mapping.
*/
private ArrayList<int[]> deepMappingCopy(final ArrayList<int[]> mapping) {
final ArrayList<int[]> mapping_copy = new ArrayList<int[]>(mapping.size());
for (final int[] me : mapping) { // for each mapping element in a mapping
mapping_copy.add(Arrays.copyOf(me, me.length));
}
return mapping_copy;
}
/**
* Makes a deep copy of a set of mappings.
*
* @param mappings set of mappings to copy.
* @return set of mappings.
*/
private ArrayList<ArrayList<int[]>> deepMappingsCopy(final ArrayList<ArrayList<int[]>> mappings) {
final ArrayList<ArrayList<int[]>> mappings_copy = new ArrayList<ArrayList<int[]>>(mappings.size());
for (final ArrayList<int[]> m : mappings) { // for each mapping in mappings
final ArrayList<int[]> m_copy = new ArrayList<int[]>(m.size());
for (final int[] me : m) { // for each mapping element in a mapping
m_copy.add(Arrays.copyOf(me, me.length));
}
mappings_copy.add(m_copy);
}
return mappings_copy;
}
/**
* Constructs a string representation of a set of mappings.
*
* @param mappings set of mappings to convert.
* @return string representation of a set of mappings.
*/
private String mappingsToString(final ArrayList<ArrayList<int[]>> mappings) {
String result = "Mappings:\n";
for (final ArrayList<int[]> m : mappings) {
result += "{";
for (final int[] me : m) {
result += "[" + me[0] + "," + me[1] + "]";
}
result += "}\n";
}
return result;
}
/**
* Removes an element (edit operation) from a mapping by its value. In our
* case the element to remove can be always found in the mapping.
*
* @param m an edit mapping.
* @param e element to remove from {@code m}.
* @return {@code true} if {@code e} has been removed, and {@code false}
* otherwise.
*/
private boolean removeMappingElement(final ArrayList<int[]> m, final int[] e) {
for (final int[] me : m) {
if (me[0] == e[0] && me[1] == e[1]) {
m.remove(me);
return true;
}
}
return false;
}
}
| 11,614 | 32.961988 | 123 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/node/Node.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.node;
import java.util.ArrayList;
import java.util.List;
/**
* This is a recursive representation of an ordered tree. Each node stores a
* list of pointers to its children. The order of children is significant and
* must be observed while implmeneting a custom input parser.
*
* @param <D> the type of node data (node label).
*/
@SuppressWarnings("all")
public class Node<D> {
/**
* Information associated to and stored at each node. This can be anything
* and depends on the application, for example, string label, key-value pair,
* list of values, etc.
*/
private D nodeData;
/**
* Array of pointers to this node's children. The order of children is
* significant due to the definition of ordered trees.
*/
private final List<Node<D>> children;
/**
* Constructs a new node with the passed node data and an empty list of
* children.
*
* @param nodeData instance of node data (node label).
*/
public Node(final D nodeData) {
this.children = new ArrayList<>();
setNodeData(nodeData);
}
/**
* Counts the number of nodes in a tree rooted at this node.
*
* <p>This method runs in linear time in the tree size.
*
* @return number of nodes in the tree rooted at this node.
*/
public int getNodeCount() {
int sum = 1;
for(final Node<D> child : getChildren()) {
sum += child.getNodeCount();
}
return sum;
}
/**
* Adds a new child at the end of children list. The added child will be
* the last child of this node.
*
* @param c child node to add.
*/
public void addChild(final Node c) {
this.children.add(c);
}
/**
* Returns a string representation of the tree in bracket notation.
*
* <p>IMPORTANT: Works only for nodes storing {@link node.StringNodeData}
* due to using {@link node.StringNodeData#getLabel()}.
*
* @return tree in bracket notation.
*/
@Override
public String toString() {
String res = (new StringBuilder("{")).append(((StringNodeData)getNodeData()).getLabel()).toString();
for(final Node<D> child : getChildren()) {
res = (new StringBuilder(String.valueOf(res))).append(child.toString()).toString();
}
res = (new StringBuilder(String.valueOf(res))).append("}").toString();
return res;
}
/**
* Returns node data. Used especially for calculating rename cost.
*
* @return node data (label of a node).
*/
public D getNodeData() {
return nodeData;
}
/**
* Sets the node data of this node.
*
* @param nodeData instance of node data (node label).
*/
public void setNodeData(final D nodeData) {
this.nodeData = nodeData;
}
/**
* Returns the list with all node's children.
*
* @return children of the node.
*/
public List<Node<D>> getChildren() {
return children;
}
}
| 4,012 | 28.947761 | 104 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/node/NodeIndexer.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.node;
import java.util.ArrayList;
import java.util.Iterator;
import gameDistance.utils.apted.costmodel.CostModel;
/**
* Indexes nodes of the input tree to the algorithm that is already parsed to
* tree structure using {@link node.Node} class. Stores various indices on
* nodes required for efficient computation of APTED [1,2]. Additionally, it
* stores
* single-value properties of the tree.
*
* <p>For indexing we use four tree traversals that assign ids to the nodes:
* <ul>
* <li>left-to-right preorder [1],
* <li>right-to-left preorder [1],
* <li>left-to-right postorder [2],
* <li>right-to-left postorder [2].
* </ul>
*
* <p>See the source code for more algorithm-related comments.
*
* <p>References:
* <ul>
* <li>[1] M. Pawlik and N. Augsten. Efficient Computation of the Tree Edit
* Distance. ACM Transactions on Database Systems (TODS) 40(1). 2015.
* <li>[2] M. Pawlik and N. Augsten. Tree edit distance: Robust and memory-
* efficient. Information Systems 56. 2016.
* </ul>
*
* @param <D> type of node data.
* @param <C> type of cost model.
* @see node.Node
* @see parser.InputParser
*/
@SuppressWarnings("all")
public class NodeIndexer<D, C extends CostModel> {
// [TODO] Be consistent in naming index variables: <FROM>_to_<TO>.
// Structure indices.
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to Node object corresponding to n. Used for cost of edit operations.
*
* @see node.Node
*/
public Node<D> preL_to_node[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the size of n's subtree (node n and all its descendants).
*/
public int sizes[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the left-to-right preorder id of n's parent.
*/
public int parents[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the array of n's children. Size of children array at node n equals the number
* of n's children.
*/
public int children[][];
/**
* Index from left-to-right postorder id of node n (starting with {@code 0})
* to the left-to-right postorder id of n's leftmost leaf descendant.
*/
public int postL_to_lld[];
/**
* Index from right-to-left postorder id of node n (starting with {@code 0})
* to the right-to-left postorder id of n's rightmost leaf descendant.
*/
public int postR_to_rld[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the left-to-right preorder id of the first leaf node to the left of n.
* If there is no leaf node to the left of n, it is represented with the
* value {@code -1} [1, Section 8.4].
*/
public int preL_to_ln[];
/**
* Index from right-to-left preorder id of node n (starting with {@code 0})
* to the right-to-left preorder id of the first leaf node to the right of n.
* If there is no leaf node to the right of n, it is represented with the
* value {@code -1} [1, Section 8.4].
*/
public int preR_to_ln[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to a boolean value that states if node n lies on the leftmost path
* starting at n's parent [2, Algorithm 1, Lines 26,36].
*/
public boolean nodeType_L[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to a boolean value that states if node n lies on the rightmost path
* starting at n's parent input tree [2, Section 5.3, Algorithm 1, Lines 26,36].
*/
public boolean nodeType_R[];
// Traversal translation indices.
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the right-to-left preorder id of n.
*/
public int preL_to_preR[];
/**
* Index from right-to-left preorder id of node n (starting with {@code 0})
* to the left-to-right preorder id of n.
*/
public int preR_to_preL[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the left-to-right postorder id of n.
*/
public int preL_to_postL[];
/**
* Index from left-to-right postorder id of node n (starting with {@code 0})
* to the left-to-right preorder id of n.
*/
public int postL_to_preL[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the right-to-left postorder id of n.
*/
public int preL_to_postR[];
/**
* Index from right-to-left postorder id of node n (starting with {@code 0})
* to the left-to-right preorder id of n.
*/
public int postR_to_preL[];
// Cost indices.
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the cost of spf_L (single path function using the leftmost path) for
* the subtree rooted at n [1, Section 5.2].
*/
public int preL_to_kr_sum[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the cost of spf_R (single path function using the rightmost path) for
* the subtree rooted at n [1, Section 5.2].
*/
public int preL_to_rev_kr_sum[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the cost of spf_A (single path function using an inner path) for the
* subtree rooted at n [1, Section 5.2].
*/
public int preL_to_desc_sum[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the cost of deleting all nodes in the subtree rooted at n.
*/
public float preL_to_sumDelCost[];
/**
* Index from left-to-right preorder id of node n (starting with {@code 0})
* to the cost of inserting all nodes in the subtree rooted at n.
*/
public float preL_to_sumInsCost[];
// Variables holding values modified at runtime while the algorithm executes.
/**
* Stores the left-to-right preorder id of the current subtree's root node.
* Used in the tree decomposition phase of APTED [1, Algorithm 1].
*/
private int currentNode;
// Structure single-value variables.
/**
* Stores the size of the input tree.
*/
private final int treeSize;
/**
* Stores the number of leftmost-child leaf nodes in the input tree
* [2, Section 5.3].
*/
public int lchl;
/**
* Stores the number of rightmost-child leaf nodes in the input tree
* [2, Section 5.3].
*/
public int rchl;
// Variables used temporarily while indexing.
/**
* Temporary variable used in indexing for storing subtree size.
*/
private int sizeTmp;
/**
* Temporary variable used in indexing for storing sum of subtree sizes
* rooted at descendant nodes.
*/
private int descSizesTmp;
/**
* Temporary variable used in indexing for storing sum of keyroot node sizes.
*/
private int krSizesSumTmp;
/**
* Temporary variable used in indexing for storing sum of right-to-left
* keyroot node sizes.
*/
private int revkrSizesSumTmp;
/**
* Temporary variable used in indexing for storing preorder index of a node.
*/
private int preorderTmp;
private final C costModel;
/**
* Indexes the nodes of input trees and stores the indices for quick access
* from APTED algorithm.
*
* @param inputTree an input tree to APTED. Its nodes will be indexed.
* @param costModel instance of a cost model to compute preL_to_sumDelCost
* and preL_to_sumInsCost.
*/
public NodeIndexer(final Node<D> inputTree, final C costModel) {
// Initialise variables.
sizeTmp = 0;
descSizesTmp = 0;
krSizesSumTmp = 0;
revkrSizesSumTmp = 0;
preorderTmp = 0;
currentNode = 0;
treeSize = inputTree.getNodeCount();
// Initialise indices with the lengths equal to the tree size.
sizes = new int[treeSize];
preL_to_preR = new int[treeSize];
preR_to_preL = new int[treeSize];
preL_to_postL = new int[treeSize];
postL_to_preL = new int[treeSize];
preL_to_postR = new int[treeSize];
postR_to_preL = new int[treeSize];
postL_to_lld = new int[treeSize];
postR_to_rld = new int[treeSize];
preL_to_node = new Node[treeSize];
preL_to_ln = new int[treeSize];
preR_to_ln = new int[treeSize];
preL_to_kr_sum = new int[treeSize];
preL_to_rev_kr_sum = new int[treeSize];
preL_to_desc_sum = new int[treeSize];
preL_to_sumDelCost = new float[treeSize];
preL_to_sumInsCost = new float[treeSize];
children = new int[treeSize][];
nodeType_L = new boolean[treeSize];
nodeType_R = new boolean[treeSize];
parents = new int[treeSize];
parents[0] = -1; // The root has no parent.
this.costModel = costModel;
// Index the nodes.
indexNodes(inputTree, -1);
postTraversalIndexing();
}
/**
* Indexes the nodes of the input tree. Stores information about each tree
* node in index arrays. It computes the following indices: {@link #parents},
* {@link #children}, {@link #nodeType_L}, {@link #nodeType_R},
* {@link #preL_to_desc_sum}, {@link #preL_to_kr_sum},
* {@link #preL_to_rev_kr_sum}, {@link #preL_to_node}, {@link #sizes},
* {@link #preL_to_preR}, {@link #preR_to_preL}, {@link #postL_to_preL},
* {@link #preL_to_postL}, {@link #preL_to_postR}, {@link #postR_to_preL}.
*
* <p>It is a recursive method that traverses the tree once.
*
* @param node is the current node while traversing the input tree.
* @param postorder is the postorder id of the current node.
* @return postorder id of the current node.
*/
private int indexNodes(final Node<D> node, int postorder) {
// Initialise variables.
int currentSize = 0;
int childrenCount = 0;
int descSizes = 0;
int krSizesSum = 0;
int revkrSizesSum = 0;
final int preorder = preorderTmp;
int preorderR = 0;
int currentPreorder = -1;
// Initialise empty array to store children of this node.
final ArrayList<Integer> childrenPreorders = new ArrayList<>();
// Store the preorder id of the current node to use it after the recursion.
preorderTmp++;
// Loop over children of a node.
final Iterator<Node<D>> childrenIt = node.getChildren().iterator();
while (childrenIt.hasNext()) {
childrenCount++;
currentPreorder = preorderTmp;
parents[currentPreorder] = preorder;
// Execute method recursively for next child.
postorder = indexNodes(childrenIt.next(), postorder);
childrenPreorders.add(Integer.valueOf(currentPreorder));
currentSize += 1 + sizeTmp;
descSizes += descSizesTmp;
if(childrenCount > 1) {
krSizesSum += krSizesSumTmp + sizeTmp + 1;
} else {
krSizesSum += krSizesSumTmp;
nodeType_L[currentPreorder] = true;
}
if(childrenIt.hasNext()) {
revkrSizesSum += revkrSizesSumTmp + sizeTmp + 1;
} else {
revkrSizesSum += revkrSizesSumTmp;
nodeType_R[currentPreorder] = true;
}
}
postorder++;
final int currentDescSizes = descSizes + currentSize + 1;
preL_to_desc_sum[preorder] = ((currentSize + 1) * (currentSize + 1 + 3)) / 2 - currentDescSizes;
preL_to_kr_sum[preorder] = krSizesSum + currentSize + 1;
preL_to_rev_kr_sum[preorder] = revkrSizesSum + currentSize + 1;
// Store pointer to a node object corresponding to preorder.
preL_to_node[preorder] = node;
sizes[preorder] = currentSize + 1;
preorderR = treeSize - 1 - postorder;
preL_to_preR[preorder] = preorderR;
preR_to_preL[preorderR] = preorder;
children[preorder] = toIntArray(childrenPreorders);
descSizesTmp = currentDescSizes;
sizeTmp = currentSize;
krSizesSumTmp = krSizesSum;
revkrSizesSumTmp = revkrSizesSum;
postL_to_preL[postorder] = preorder;
preL_to_postL[preorder] = postorder;
preL_to_postR[preorder] = treeSize-1-preorder;
postR_to_preL[treeSize-1-preorder] = preorder;
return postorder;
}
/**
* Indexes the nodes of the input tree. It computes the following indices,
* which could not be computed immediately while traversing the tree in
* {@link #indexNodes}: {@link #preL_to_ln}, {@link #postL_to_lld},
* {@link #postR_to_rld}, {@link #preR_to_ln}.
*
* <p>Runs in linear time in the input tree size. Currently requires two
* loops over input tree nodes. Can be reduced to one loop (see the code).
*/
private void postTraversalIndexing() {
int currentLeaf = -1;
int nodeForSum = -1;
int parentForSum = -1;
for(int i = 0; i < treeSize; i++) {
preL_to_ln[i] = currentLeaf;
if(isLeaf(i)) {
currentLeaf = i;
}
// This block stores leftmost leaf descendants for each node
// indexed in postorder. Used for mapping computation.
// Added by Victor.
final int postl = i; // Assume that the for loop iterates postorder.
int preorder = postL_to_preL[i];
if (sizes[preorder] == 1) {
postL_to_lld[postl] = postl;
} else {
postL_to_lld[postl] = postL_to_lld[preL_to_postL[children[preorder][0]]];
}
// This block stores rightmost leaf descendants for each node
// indexed in right-to-left postorder.
// [TODO] Use postL_to_lld and postR_to_rld instead of APTED.getLLD
// and APTED.gerRLD methods, remove these method.
// Result: faster lookup of these values.
final int postr = i; // Assume that the for loop iterates reversed postorder.
preorder = postR_to_preL[postr];
if (sizes[preorder] == 1) {
postR_to_rld[postr] = postr;
} else {
postR_to_rld[postr] = postR_to_rld[preL_to_postR[children[preorder][children[preorder].length-1]]];
}
// Count lchl and rchl.
// [TODO] There are no values for parent node.
if (sizes[i] == 1) {
final int parent = parents[i];
if (parent > -1) {
if (parent+1 == i) {
lchl++;
} else if (preL_to_preR[parent]+1 == preL_to_preR[i]) {
rchl++;
}
}
}
// Sum up costs of deleting and inserting entire subtrees.
// Reverse the node index. Here, we need traverse nodes bottom-up.
nodeForSum = treeSize - i - 1;
parentForSum = parents[nodeForSum];
// Update myself.
preL_to_sumDelCost[nodeForSum] += costModel.del(preL_to_node[nodeForSum]);
preL_to_sumInsCost[nodeForSum] += costModel.ins(preL_to_node[nodeForSum]);
if (parentForSum > -1) {
// Update my parent.
preL_to_sumDelCost[parentForSum] += preL_to_sumDelCost[nodeForSum];
preL_to_sumInsCost[parentForSum] += preL_to_sumInsCost[nodeForSum];
}
}
currentLeaf = -1;
// [TODO] Merge with the other loop. Assume different traversal.
for(int i = 0; i < sizes[0]; i++) {
preR_to_ln[i] = currentLeaf;
if(isLeaf(preR_to_preL[i])) {
currentLeaf = i;
}
}
}
/**
* An abbreviation that uses indices to calculate the left-to-right preorder
* id of the leftmost leaf node of the given node.
*
* @param preL left-to-right preorder id of a node.
* @return left-to-right preorder id of the leftmost leaf node of preL.
*/
public int preL_to_lld(final int preL) {
return postL_to_preL[postL_to_lld[preL_to_postL[preL]]];
}
/**
* An abbreviation that uses indices to calculate the left-to-right preorder
* id of the rightmost leaf node of the given node.
*
* @param preL left-to-right preorder id of a node.
* @return left-to-right preorder id of the rightmost leaf node of preL.
*/
public int preL_to_rld(final int preL) {
return postR_to_preL[postR_to_rld[preL_to_postR[preL]]];
}
/**
* An abbreviation that uses indices to retrieve pointer to {@link node.Node}
* of the given node.
*
* @param postL left-to-right postorder id of a node.
* @return {@link node.Node} corresponding to postL.
*/
public Node<D> postL_to_node(final int postL) {
return preL_to_node[postL_to_preL[postL]];
}
/**
* An abbreviation that uses indices to retrieve pointer to {@link node.Node}
* of the given node.
*
* @param postR right-to-left postorder id of a node.
* @return {@link node.Node} corresponding to postR.
*/
public Node<D> postR_to_node(final int postR) {
return preL_to_node[postR_to_preL[postR]];
}
/**
* Returns the number of nodes in the input tree.
*
* @return number of nodes in the tree.
*/
public int getSize() {
return treeSize;
}
/**
* Verifies if node is a leaf.
*
* @param node preorder id of a node to verify.
* @return {@code true} if {@code node} is a leaf, {@code false} otherwise.
*/
public boolean isLeaf(final int node) {
return sizes[node] == 1;
}
/**
* Converts {@link ArrayList} of integer values to an array. Reads all items
* in the list and copies to the output array. The size of output array equals
* the number of elements in the list.
*
* @param integers ArrayList with integer values.
* @return array with values from input ArrayList.
*/
private int[] toIntArray(final ArrayList<Integer> integers) {
final int ints[] = new int[integers.size()];
int i = 0;
for (final Integer n : integers) {
ints[i++] = n.intValue();
}
return ints;
}
/**
* Returns the root node of the currently processed subtree in the tree
* decomposition part of APTED [1, Algorithm 1]. At each point, we have to
* know which subtree do we process.
*
* @return current subtree root node.
*/
public int getCurrentNode() {
return currentNode;
}
/**
* Stores the root nodes's preorder id of the currently processes subtree.
*
* @param preorder preorder id of the root node.
*/
public void setCurrentNode(final int preorder) {
currentNode = preorder;
}
}
| 19,113 | 31.562181 | 107 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/node/StringNodeData.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.node;
/**
* Represents a node label that consists of a single string value. Such label
* belongs to a node.
*
* @see Node
*/
public class StringNodeData {
/**
* The label of a node.
*/
private final String label;
/**
* Constructs node data with a specified label.
*
* @param label string label of a node.
*/
public StringNodeData(final String label) {
this.label = label;
}
/**
* Returns the label of a node.
*
* @return node label.
*/
public String getLabel() {
return label;
}
}
| 1,712 | 29.052632 | 80 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/parser/BracketStringInputParser.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik, Nikolaus Augsten
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.parser;
import java.util.List;
import gameDistance.utils.apted.node.Node;
import gameDistance.utils.apted.node.StringNodeData;
import gameDistance.utils.apted.util.FormatUtilities;
// [TODO] Make this parser independent from FormatUtilities - move here relevant elements.
/**
* Parser for the input trees in the bracket notation with a single string-value
* label of type {@link StringNodeData}.
*
* <p>Bracket notation encodes the trees with nested parentheses, for example,
* in tree {A{B{X}{Y}{F}}{C}} the root node has label A and two children with
* labels B and C. Node with label B has three children with labels X, Y, F.
*
* @see Node
* @see StringNodeData
*/
@SuppressWarnings("all")
public class BracketStringInputParser implements InputParser<StringNodeData> {
/**
* Parses the input tree as a string and converts it to our tree
* representation using the {@link Node} class.
*
* @param s input tree as string in bracket notation.
* @return tree representation of the bracket notation input.
* @see Node
*/
@Override
public Node<StringNodeData> fromString(String s) {
s = s.substring(s.indexOf("{"), s.lastIndexOf("}") + 1);
final Node<StringNodeData> node = new Node<StringNodeData>(new StringNodeData(FormatUtilities.getRoot(s)));
final List<String> c = FormatUtilities.getChildren(s);
for(int i = 0; i < c.size(); i++)
node.addChild(fromString(c.get(i)));
return node;
}
}
| 2,643 | 39.060606 | 111 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/parser/InputParser.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.parser;
import gameDistance.utils.apted.node.Node;
/**
* This interface specifies methods (currently only one) that must be
* implemented for a custom input parser.
*
* @param <D> the type of node data.
*/
public interface InputParser<D> {
/**
* Convert the input tree passed as string (e.g., bracket notation, XML)
* into the tree structure.
*
* @param s input tree as string.
* @return tree structure.
*/
public Node<D> fromString(String s);
}
| 1,644 | 35.555556 | 80 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/test/java/CorrectnessTest.java
|
package gameDistance.utils.apted.test.java;
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import gameDistance.utils.apted.costmodel.StringUnitCostModel;
import gameDistance.utils.apted.distance.APTED;
import gameDistance.utils.apted.node.Node;
import gameDistance.utils.apted.node.StringNodeData;
import gameDistance.utils.apted.parser.BracketStringInputParser;
/**
* Correctness unit tests of distance and mapping computation.
*
* <p>In case of mapping, only mapping cost is verified against the correct
* distance.
*
* <p>Currently tests only for unit-cost model and single string-value labels.
*
* @see StringNodeData
* @see StringUnitCostModel
*/
@SuppressWarnings("all")
@RunWith(Parameterized.class)
public class CorrectnessTest {
/**
* Test case object holding parameters of a single test case.
*
* <p>Could be also deserialized here but without much benefit.
*/
private final TestCase testCase;
/**
* This class represents a single test case from the JSON file. JSON keys
* are mapped to fields of this class.
*/
// [TODO] Verify if this is the best placement for this class.
private static class TestCase {
/**
* Test identifier to quickly find failed test case in JSON file.
*/
private int testID;
/**
* Source tree as string.
*/
private String t1;
/**
* Destination tree as string.
*/
private String t2;
/**
* Correct distance value between source and destination trees.
*/
private int d;
/**
* Used in printing the test case details on failure with '(name = "{0}")'.
*
* @return test case details.
* @see CorrectnessTest#data()
*/
@Override
public String toString() {
return "testID:" + testID + ",t1:" + t1 + ",t2:" + t2 + ",d:" + d;
}
/**
* Returns identifier of this test case.
*
* @return test case identifier.
*/
public int getTestID() {
return testID;
}
/**
* Returns source tree of this test case.
*
* @return source tree.
*/
public String getT1() {
return t1;
}
/**
* Returns destination tree of this test case.
*
* @return destination tree.
*/
public String getT2() {
return t2;
}
/**
* Returns correct distance value between source and destination trees
* of this test case.
*
* @return correct distance.
*/
public int getD() {
return d;
}
}
/**
* Constructs a single test for a single test case. Used for parameterised
* tests.
*
* @param testCase single test case.
*/
public CorrectnessTest(final TestCase testCase) {
this.testCase = testCase;
}
/**
* Parse trees from bracket notation to {node.StringNodeData}, convert back
* to strings and verify equality with the input.
*/
@Test
public void parsingBracketNotationToStringNodeData() {
// Parse the input.
final BracketStringInputParser parser = new BracketStringInputParser();
final Node<StringNodeData> t1 = parser.fromString(testCase.getT1());
final Node<StringNodeData> t2 = parser.fromString(testCase.getT2());
assertEquals(testCase.getT1(), t1.toString());
assertEquals(testCase.getT2(), t2.toString());
}
/**
* Compute TED for a single test case and compare to the correct value. Uses
* node labels with a single string value and unit cost model.
*
* @see node.StringNodeData
* @see costmodel.StringUnitCostModel
*/
@Test
public void distanceUnitCostStringNodeDataCostModel() {
// Parse the input.
final BracketStringInputParser parser = new BracketStringInputParser();
final Node<StringNodeData> t1 = parser.fromString(testCase.getT1());
final Node<StringNodeData> t2 = parser.fromString(testCase.getT2());
// Initialise APTED.
final APTED<StringUnitCostModel, StringNodeData> apted = new APTED<>(new StringUnitCostModel());
// This cast is safe due to unit cost.
int result = (int)apted.computeEditDistance(t1, t2);
assertEquals(testCase.getD(), result);
// Verify the symmetric case.
result = (int)apted.computeEditDistance(t2, t1);
assertEquals(testCase.getD(), result);
}
/**
* Compute TED for a single test case and compare to the correct value. Uses
* node labels with a single string value and unit cost model.
*
* <p>Triggers spf_L to execute. The strategy is fixed to left paths in the
* left-hand tree.
*
* @see node.StringNodeData
* @see costmodel.StringUnitCostModel
*/
@Test
public void distanceUnitCostStringNodeDataCostModelSpfL() {
// Parse the input.
final BracketStringInputParser parser = new BracketStringInputParser();
final Node<StringNodeData> t1 = parser.fromString(testCase.getT1());
final Node<StringNodeData> t2 = parser.fromString(testCase.getT2());
// Initialise APTED.
final APTED<StringUnitCostModel, StringNodeData> apted = new APTED<>(new StringUnitCostModel());
// This cast is safe due to unit cost.
final int result = (int)apted.computeEditDistance_spfTest(t1, t2, 0);
assertEquals(testCase.getD(), result);
}
/**
* Compute TED for a single test case and compare to the correct value. Uses
* node labels with a single string value and unit cost model.
*
*<p>Triggers spf_R to execute. The strategy is fixed to right paths in the
* left-hand tree.
*
* @see node.StringNodeData
* @see costmodel.StringUnitCostModel
*/
@Test
public void distanceUnitCostStringNodeDataCostModelSpfR() {
// Parse the input.
final BracketStringInputParser parser = new BracketStringInputParser();
final Node<StringNodeData> t1 = parser.fromString(testCase.getT1());
final Node<StringNodeData> t2 = parser.fromString(testCase.getT2());
// Initialise APTED.
final APTED<StringUnitCostModel, StringNodeData> apted = new APTED<>(new StringUnitCostModel());
// This cast is safe due to unit cost.
final int result = (int)apted.computeEditDistance_spfTest(t1, t2, 1);
assertEquals(testCase.getD(), result);
}
// IDEA: Write test that triggers spf_A for each subtree pair - disallow
// using spf_L and spf_R.
/**
* Compute minimum-cost edit mapping for a single test case and compare its
* cost to the correct TED value. Uses node labels with a single string value
* and unit cost model.
*
* @see node.StringNodeData
* @see costmodel.StringUnitCostModel
*/
@Test
public void mappingCostUnitCostStringNodeDataCostModel() {
// Parse the input.
final BracketStringInputParser parser = new BracketStringInputParser();
final Node<StringNodeData> t1 = parser.fromString(testCase.getT1());
final Node<StringNodeData> t2 = parser.fromString(testCase.getT2());
// Initialise APTED.
final APTED<StringUnitCostModel, StringNodeData> apted = new APTED<>(new StringUnitCostModel());
// Although we don't need TED value yet, TED must be computed before the
// mapping. This cast is safe due to unit cost.
apted.computeEditDistance(t1, t2);
// Get TED value corresponding to the computed mapping.
final List<int[]> mapping = apted.computeEditMapping();
// This cast is safe due to unit cost.
final int result = (int)apted.mappingCost(mapping);
assertEquals(testCase.getD(), result);
}
}
| 8,632 | 32.076628 | 100 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/test/java/PerEditOperationCorrectnessTest.java
|
package gameDistance.utils.apted.test.java;
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import gameDistance.utils.apted.costmodel.PerEditOperationStringNodeDataCostModel;
import gameDistance.utils.apted.distance.APTED;
import gameDistance.utils.apted.distance.AllPossibleMappingsTED;
import gameDistance.utils.apted.node.Node;
import gameDistance.utils.apted.node.StringNodeData;
import gameDistance.utils.apted.parser.BracketStringInputParser;
/**
* Correctness unit tests of distance computation for node labels with a single
* string value and per-edit-operation cost model.
*
* @see node.StringNodeData
* @see costmodel.PerEditOperationStringNodeDataCostModel
*/
@SuppressWarnings("all")
@RunWith(Parameterized.class)
public class PerEditOperationCorrectnessTest {
/**
* Test case object holding parameters of a single test case.
*
* <p>Could be also deserialized here but without much benefit.
*/
private final TestCase testCase;
/**
* This class represents a single test case from the JSON file. JSON keys
* are mapped to fields of this class.
*/
// [TODO] Verify if this is the best placement for this class.
private static class TestCase {
/**
* Test identifier to quickly find failed test case in JSON file.
*/
private int testID;
/**
* Source tree as string.
*/
private String t1;
/**
* Destination tree as string.
*/
private String t2;
/**
* Correct distance value between source and destination trees.
*/
private int d;
/**
* Used in printing the test case details on failure with '(name = "{0}")'.
*
* @return test case details.
* @see CorrectnessTest#data()
*/
@Override
public String toString() {
return "testID:" + testID + ",t1:" + t1 + ",t2:" + t2 + ",d:" + d;
}
/**
* Returns identifier of this test case.
*
* @return test case identifier.
*/
public int getTestID() {
return testID;
}
/**
* Returns source tree of this test case.
*
* @return source tree.
*/
public String getT1() {
return t1;
}
/**
* Returns destination tree of this test case.
*
* @return destination tree.
*/
public String getT2() {
return t2;
}
/**
* Returns correct distance value between source and destination trees
* of this test case.
*
* @return correct distance.
*/
public int getD() {
return d;
}
}
/**
* Constructs a single test for a single test case. Used for parameterised
* tests.
*
* @param testCase single test case.
*/
public PerEditOperationCorrectnessTest(final TestCase testCase) {
this.testCase = testCase;
}
/**
* Compute TED for a single test case and compare to the correct value. Uses
* node labels with a single string value and per-edit-operation cost model.
*
* <p>The correct value is calculated using AllPossibleMappingsTED algorithm.
* <p>The costs of edit operations are set to some example values different
* than in the unit cost model.
*
* @see node.StringNodeData
* @see costmodel.PerEditOperationStringNodeDataCostModel
* @see distance.AllPossibleMappingsTED
*/
@Test
public void distancePerEditOperationStringNodeDataCostModel() {
// Parse the input.
final BracketStringInputParser parser = new BracketStringInputParser();
final Node<StringNodeData> t1 = parser.fromString(testCase.getT1());
final Node<StringNodeData> t2 = parser.fromString(testCase.getT2());
// Initialise algorithms.
final APTED<PerEditOperationStringNodeDataCostModel, StringNodeData> apted = new APTED<>(new PerEditOperationStringNodeDataCostModel(0.4f, 0.4f, 0.6f));
final AllPossibleMappingsTED<PerEditOperationStringNodeDataCostModel, StringNodeData> apmted = new AllPossibleMappingsTED<>(new PerEditOperationStringNodeDataCostModel(0.4f, 0.4f, 0.6f));
// Calculate distances using both algorithms.
final float result = apted.computeEditDistance(t1, t2);
final float correctResult = apmted.computeEditDistance(t1, t2);
assertEquals(correctResult, result, 0.0001);
}
}
| 5,441 | 30.824561 | 191 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/util/CommandLine.java
|
/* MIT License
*
* Copyright (c) 2017 Mateusz Pawlik
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Date;
import java.util.List;
import gameDistance.utils.apted.costmodel.CostModel;
import gameDistance.utils.apted.costmodel.StringUnitCostModel;
import gameDistance.utils.apted.distance.APTED;
import gameDistance.utils.apted.node.Node;
import gameDistance.utils.apted.node.StringNodeData;
import gameDistance.utils.apted.parser.BracketStringInputParser;
import gameDistance.utils.apted.parser.InputParser;
/**
* This is the command line interface for executing APTED algorithm.
*
* @param <C> type of cost model.
* @param <P> type of input parser.
* @see CostModel
* @see InputParser
*/
@SuppressWarnings("all")
public class CommandLine<C extends CostModel, P extends InputParser> {
private final String helpMessage =
"\n" +
"Compute the edit distance between two trees.\n" +
"\n" +
"SYNTAX\n" +
"\n" +
" java -jar APTED.jar {-t TREE1 TREE2 | -f FILE1 FILE2} [-m] [-v]\n" +
"\n" +
" java -jar APTED.jar -h\n" +
"\n" +
"DESCRIPTION\n" +
"\n" +
" Compute the edit distance between two trees with APTED algorithm [1,2].\n" +
" APTED supersedes our RTED algorithm [3].\n" +
" By default unit cost model is supported where each edit operation\n" +
" has cost 1 (in case of equal labels the cost is 0).\n" +
"\n" +
" For implementing other cost models see the details on github website\n" +
" (https://github.com/DatabaseGroup/apted).\n" +
"\n" +
"LICENCE\n" +
"\n" +
" The source code of this program is published under the MIT licence and\n" +
" can be found on github (https://github.com/DatabaseGroup/apted).\n" +
"\n" +
"OPTIONS\n" +
"\n" +
" -h, --help \n" +
" print this help message.\n" +
"\n" +
" -t TREE1 TREE2,\n" +
" --trees TREE1 TREE2\n" +
" compute the tree edit distance between TREE1 and TREE2. The\n" +
" trees are encoded in the bracket notation, for example, in tree\n" +
" {A{B{X}{Y}{F}}{C}} the root node has label A and two children\n" +
" with labels B and C. B has three children with labels X, Y, F.\n" +
"\n" +
" -f FILE1 FILE2, \n" +
" --files FILE1 FILE2\n" +
" compute the tree edit distance between the two trees stored in\n" +
" the files FILE1 and FILE2. The trees are encoded in bracket\n" +
" notation.\n" +
// "\n" +
// " -c CD CI CR, \n" +
// " --costs CD CI CR\n" +
// " set custom cost for edit operations. Default is -c 1 1 1.\n" +
// " CD - cost of node deletion\n" +
// " CI - cost of node insertion\n" +
// " CR - cost of node renaming\n" +
"\n" +
" -v, --verbose\n" +
" print verbose output, including tree edit distance, runtime,\n" +
" number of relevant subproblems and strategy statistics.\n" +
"\n" +
" -m, --mapping\n" +
" compute the minimal edit mapping between two trees. There might\n" +
" be multiple minimal edit mappings. This option computes only one\n" +
" of them. The first line of the output is the cost of the mapping.\n" +
" The following lines represent the edit operations. n and m are\n" +
" postorder IDs (beginning with 1) of nodes in the left-hand and\n" +
" the right-hand trees respectively.\n" +
" n->m - rename node n to m\n" +
" n->0 - delete node n\n" +
" 0->m - insert node m\n" +
"EXAMPLES\n" +
"\n" +
" java -jar APTED.jar -t {a{b}{c}} {a{b{d}}}\n" +// -c 1 1 0.5\n" +
" java -jar APTED.jar -f 1.tree 2.tree\n" +
" java -jar APTED.jar -t {a{b}{c}} {a{b{d}}} -m -v\n" +
"\n" +
"REFERENCES\n" +
"\n" +
" [1] M. Pawlik and N. Augsten. Efficient Computation of the Tree Edit\n" +
" Distance. ACM Transactions on Database Systems (TODS) 40(1). 2015.\n" +
" [2] M. Pawlik and N. Augsten. Tree edit distance: Robust and memory-\n" +
" efficient. Information Systems 56. 2016.\n" +
" [3] M. Pawlik and N. Augsten. RTED: A Robust Algorithm for the Tree Edit\n" +
" Distance. PVLDB 5(4). 2011.\n" +
"\n" +
"AUTHORS\n" +
"\n" +
" Mateusz Pawlik, Nikolaus Augsten";
// TODO: Review if all fields are necessary.
private final String wrongArgumentsMessage = "Wrong arguments. Try \"java -jar RTED.jar --help\" for help.";
private boolean run, custom, array, strategy, ifSwitch, sota, verbose, demaine, mapping;
private int sotaStrategy;
private String customStrategy, customStrategyArrayFile;
private APTED rted;
private double ted;
private final C costModel;
private final P inputParser;
private Node t1;
private Node t2;
/**
* Constructs the command line. Initialises the cost model and input parser
* of specific types.
*
* @param costModel instance of a specific cost model.
* @param inputParser instance of a specific inputParser.
* @see CostModel
* @see InputParser
*/
public CommandLine(final C costModel, final P inputParser) {
this.costModel = costModel;
this.inputParser = inputParser;
}
/**
* Main method, invoked when executing the jar file.
*
* @param args array of command line arguments passed when executing jar file.
*/
public static void main(final String[] args) {
final CommandLine<StringUnitCostModel, BracketStringInputParser> rtedCL = new CommandLine<>(new StringUnitCostModel(), new BracketStringInputParser());
rtedCL.runCommandLine(args);
}
/**
* Run the command line with given arguments.
*
* @param args array of command line arguments passed when executing jar file.
*/
public void runCommandLine(final String[] args) {
rted = new APTED<C, StringNodeData>(costModel);
try {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("--help") || args[i].equals("-h")) {
System.out.println(helpMessage);
System.exit(0);
} else if (args[i].equals("-t") || args[i].equals("--trees")) {
parseTreesFromCommandLine(args[i+1], args[i+2]);
i = i+2;
run = true;
} else if (args[i].equals("-f") || args[i].equals("--files")) {
parseTreesFromFiles(args[i+1], args[i+2]);
i = i+2;
run = true;
// TODO: -f option temporarily disabled for refactoring.
// } else if (args[i].equals("-c") || args[i].equals("--costs")) {
// setCosts(args[i+1], args[i+2], args[i+3]);
// i = i+3;
} else if (args[i].equals("-v") || args[i].equals("--verbose")) {
verbose = true;
} else if (args[i].equals("-m") || args[i].equals("--mapping")) {
mapping = true;
} else {
System.out.println(wrongArgumentsMessage);
System.exit(0);
}
}
} catch (final ArrayIndexOutOfBoundsException e) {
System.out.println("Too few arguments.");
System.exit(0);
}
if (!run) {
System.out.println(wrongArgumentsMessage);
System.exit(0);
}
final long time1 = (new Date()).getTime();
ted = rted.computeEditDistance(t1, t2);
final long time2 = (new Date()).getTime();
if (verbose) {
System.out.println("distance: " + ted);
System.out.println("runtime: " + ((time2 - time1) / 1000.0));
} else {
System.out.println(ted);
}
if (mapping) { // TED is computed anyways.
final List<int[]> editMapping = rted.computeEditMapping();
for (final int[] nodeAlignment : editMapping) {
System.out.println(nodeAlignment[0] + "->" + nodeAlignment[1]);
}
}
}
/**
* Parse two input trees from the command line and convert them to tree
* representation using {@link Node} class.
*
* @param ts1 source input tree as string.
* @param ts2 destination input tree as string.
* @see Node
*/
private void parseTreesFromCommandLine(final String ts1, final String ts2) {
try {
t1 = inputParser.fromString(ts1);
} catch (final Exception e) {
System.out.println("TREE1 argument has wrong format");
System.exit(0);
}
try {
t2 = inputParser.fromString(ts2);
} catch (final Exception e) {
System.out.println("TREE2 argument has wrong format");
System.exit(0);
}
}
/**
* Parses two input trees from given files and convert them to tree
* representation using {@link Node} class.
*
* @param fs1 path to file with source tree.
* @param fs2 path to file with destination tree.
* @see Node
*/
private void parseTreesFromFiles(final String fs1, final String fs2) {
try {
t1 = inputParser.fromString((new BufferedReader(new FileReader(fs1))).readLine());
} catch (final Exception e) {
System.out.println("TREE1 argument has wrong format");
System.exit(0);
}
try {
t2 = inputParser.fromString((new BufferedReader(new FileReader(fs2))).readLine());
} catch (final Exception e) {
System.out.println("TREE2 argument has wrong format");
System.exit(0);
}
}
// TODO: Bring the functionalities below back to life.
// /**
// * Set custom costs for the edit operations.
// *
// * @deprecated
// * @param cds cost of deletion.
// * @param cis cost of insertion.
// * @param cms cost of rename (mapping).
// */
// private void setCosts(String cds, String cis, String cms) {
// try {
// rted.setCustomCosts(Float.parseFloat(cds), Float.parseFloat(cis), Float.parseFloat(cms));
// } catch (Exception e) {
// System.out.println("One of the costs has wrong format.");
// System.exit(0);
// }
// }
}
| 11,227 | 36.178808 | 155 |
java
|
Ludii
|
Ludii-master/Mining/src/gameDistance/utils/apted/util/FormatUtilities.java
|
/* MIT License
*
* Copyright (c) 2017 Nikolaus Augsten
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package gameDistance.utils.apted.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
/**
* Various formatting utilities.
*
* @author Nikolaus Augsten
*
*/
@SuppressWarnings("all")
public class FormatUtilities
{
public FormatUtilities()
{
}
public static String getField(final int fieldNr, final String line, final char seperator)
{
if(line != null)
{
int pos = 0;
for(int i = 0; i < fieldNr; i++)
{
pos = line.indexOf(seperator, pos);
if(pos == -1)
return null;
pos++;
}
final int pos2 = line.indexOf(seperator, pos);
String res;
if(pos2 == -1)
res = line.substring(pos);
else
res = line.substring(pos, pos2);
return res.trim();
} else
{
return null;
}
}
public static String[] getFields(final String line, final char separator)
{
if(line != null && !line.equals(""))
{
StringBuffer field = new StringBuffer();
final LinkedList fieldArr = new LinkedList();
for(int i = 0; i < line.length(); i++)
{
final char ch = line.charAt(i);
if(ch == separator)
{
fieldArr.add(field.toString().trim());
field = new StringBuffer();
} else
{
field.append(ch);
}
}
fieldArr.add(field.toString().trim());
return (String[])fieldArr.toArray(new String[fieldArr.size()]);
} else
{
return new String[0];
}
}
public static String[] getFields(final String line, final char separator, final char quote)
{
final String parse[] = getFields(line, separator);
for(int i = 0; i < parse.length; i++)
parse[i] = stripQuotes(parse[i], quote);
return parse;
}
public static String stripQuotes(final String s, final char quote)
{
if(s.length() >= 2 && s.charAt(0) == quote && s.charAt(s.length() - 1) == quote)
return s.substring(1, s.length() - 1);
else
return s;
}
public static String resizeEnd(final String s, final int size)
{
return resizeEnd(s, size, ' ');
}
public static String getRandomString(final int length)
{
final Date d = new Date();
final Random r = new Random(d.getTime());
String str = "";
for(int i = 0; i < length; i++)
str = (new StringBuilder(String.valueOf(str))).append((char)(65 + r.nextInt(26))).toString();
return str;
}
public static String resizeEnd(final String s, final int size, final char fillChar)
{
String res;
try
{
res = s.substring(0, size);
}
catch(final IndexOutOfBoundsException e)
{
res = s;
for(int i = s.length(); i < size; i++)
res = (new StringBuilder(String.valueOf(res))).append(fillChar).toString();
}
return res;
}
public static String resizeFront(final String s, final int size)
{
return resizeFront(s, size, ' ');
}
public static String resizeFront(final String s, final int size, final char fillChar)
{
String res;
try
{
res = s.substring(0, size);
}
catch(final IndexOutOfBoundsException e)
{
res = s;
for(int i = s.length(); i < size; i++)
res = (new StringBuilder(String.valueOf(fillChar))).append(res).toString();
}
return res;
}
public static int matchingBracket(final String s, int pos)
{
if(s == null || pos > s.length() - 1)
return -1;
final char open = s.charAt(pos);
char close;
switch(open)
{
case 123: // '{'
close = '}';
break;
case 40: // '('
close = ')';
break;
case 91: // '['
close = ']';
break;
case 60: // '<'
close = '>';
break;
default:
return -1;
}
pos++;
int count;
for(count = 1; count != 0 && pos < s.length(); pos++)
if(s.charAt(pos) == open)
count++;
else
if(s.charAt(pos) == close)
count--;
if(count != 0)
return -1;
else
return pos - 1;
}
public static int getTreeID(final String s)
{
if(s != null && s.length() > 0)
{
final int end = s.indexOf(':', 1);
if(end == -1)
return -1;
else
return Integer.parseInt(s.substring(0, end));
} else
{
return -1;
}
}
public static String getRoot(final String s)
{
if(s != null && s.length() > 0 && s.startsWith("{") && s.endsWith("}"))
{
int end = s.indexOf('{', 1);
if(end == -1)
end = s.indexOf('}', 1);
return s.substring(1, end);
} else
{
return null;
}
}
public static List<String> getChildren(final String s)
{
if(s != null && s.length() > 0 && s.startsWith("{") && s.endsWith("}"))
{
final List<String> children = new ArrayList<>();
final int end = s.indexOf('{', 1);
if(end == -1)
return children;
String rest = s.substring(end, s.length() - 1);
for(int match = 0; rest.length() > 0 && (match = matchingBracket(rest, 0)) != -1;)
{
children.add(rest.substring(0, match + 1));
if(match + 1 < rest.length())
rest = rest.substring(match + 1);
else
rest = "";
}
return children;
} else
{
return null;
}
}
public static String parseTree(final String s, final List<String> children)
{
children.clear();
if(s != null && s.length() > 0 && s.startsWith("{") && s.endsWith("}"))
{
int end = s.indexOf('{', 1);
if(end == -1)
{
end = s.indexOf('}', 1);
return s.substring(1, end);
}
final String root = s.substring(1, end);
String rest = s.substring(end, s.length() - 1);
for(int match = 0; rest.length() > 0 && (match = matchingBracket(rest, 0)) != -1;)
{
children.add(rest.substring(0, match + 1));
if(match + 1 < rest.length())
rest = rest.substring(match + 1);
else
rest = "";
}
return root;
} else
{
return null;
}
}
public static String commaSeparatedList(final String list[])
{
final StringBuffer s = new StringBuffer();
for(int i = 0; i < list.length; i++)
{
s.append(list[i]);
if(i != list.length - 1)
s.append(",");
}
return s.toString();
}
public static String commaSeparatedList(final String list[], final char quote)
{
final StringBuffer s = new StringBuffer();
for(int i = 0; i < list.length; i++)
{
s.append((new StringBuilder(String.valueOf(quote))).append(list[i]).append(quote).toString());
if(i != list.length - 1)
s.append(",");
}
return s.toString();
}
public static String spellOutNumber(final String num)
{
final StringBuffer sb = new StringBuffer();
for(int i = 0; i < num.length(); i++)
{
final char ch = num.charAt(i);
switch(ch)
{
case 48: // '0'
sb.append("zero");
break;
case 49: // '1'
sb.append("one");
break;
case 50: // '2'
sb.append("two");
break;
case 51: // '3'
sb.append("three");
break;
case 52: // '4'
sb.append("four");
break;
case 53: // '5'
sb.append("five");
break;
case 54: // '6'
sb.append("six");
break;
case 55: // '7'
sb.append("seven");
break;
case 56: // '8'
sb.append("eight");
break;
case 57: // '9'
sb.append("nine");
break;
default:
sb.append(ch);
break;
}
}
return sb.toString();
}
public static String substituteBlanks(final String s, final String subst)
{
final StringBuffer sb = new StringBuffer();
for(int i = 0; i < s.length(); i++)
if(s.charAt(i) != ' ')
sb.append(s.charAt(i));
else
sb.append(subst);
return sb.toString();
}
public static String escapeLatex(final String s)
{
final StringBuffer sb = new StringBuffer();
for(int i = 0; i < s.length(); i++)
{
String c = (new StringBuilder(String.valueOf(s.charAt(i)))).toString();
if(c.equals("#"))
c = "\\#";
if(c.equals("&"))
c = "\\&";
if(c.equals("$"))
c = "\\$";
if(c.equals("_"))
c = "\\_";
sb.append(c);
}
return sb.toString();
}
}
| 11,278 | 26.442822 | 106 |
java
|
Ludii
|
Ludii-master/Mining/src/ludemeplexDetection/DatabaseFunctions.java
|
package ludemeplexDetection;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import game.Game;
import main.grammar.Call;
import main.grammar.LudemeInfo;
import main.grammar.Report;
import other.GameLoader;
import utils.DBGameInfo;
/**
* Provides functions for reading/saving DB information from/to external CSV files.
*
* @author matthew.stephenson
*/
public class DatabaseFunctions
{
//-------------------------------------------------------------------------
// Output
private static String ludemesOutputFilePath = "./res/ludemeplexDetection/output/ludemes.csv";
private static String ludemeplexesOutputFilePath = "./res/ludemeplexDetection/output/ludemeplexes.csv";
private static String defineLudemeplexesOutputFilePath = "./res/ludemeplexDetection/output/defineLudemeplexes.csv";
private static String rulesetLudemeplexesOutputFilePath = "./res/ludemeplexDetection/output/rulesetLudemeplexes.csv";
private static String defineRulesetludemeplexesOutputFilePath = "./res/ludemeplexDetection/output/rulesetDefineLudemeplexes.csv";
private static String ludemeplexesLudemesOutputFilePath = "./res/ludemeplexDetection/output/ludemeplexLudemes.csv";
private static String rulesetLudemesOutputFilePath = "./res/ludemeplexDetection/output/rulesetLudemes.csv";
private static String notFoundLudemesFilePath = "./res/ludemeplexDetection/output/NOTFOUNDLUDEMES.csv";
//-------------------------------------------------------------------------
/**
* Saves all relevant information about the set of identified ludemeplexes, in an output csv.
* @param allludemeplexescount
*/
public static void storeLudemeplexInfo(final Map<Call, Set<String>> allLudemeplexes, final Map<Call, Integer> allludemeplexescount)
{
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(ludemeplexesOutputFilePath, false)))
{
int ludemeplexId = 1;
for (final Map.Entry<Call, Set<String>> entry : allLudemeplexes.entrySet())
{
String outputLine = ludemeplexId + ",";
final List<String> ludemeplexStringList = entry.getKey().ludemeFormat(0);
final String ludemeplexString = String.join("", ludemeplexStringList);
// Try to compile ludemeplex
try
{
final Object compiledObject =
compiler.Compiler.compileObject
(
ludemeplexString, entry.getKey().cls().getName(), new Report()
);
if (compiledObject == null)
throw new Exception();
}
catch (final Exception E)
{
System.out.println("Game " + entry.getValue());
System.err.println("ERROR Failed to compile " + ludemeplexString);
System.err.println("ERROR symbolName = " + entry.getKey().cls().getName());
System.err.println("ERROR className = " + entry.getKey().cls().getName());
}
String defineLudemeplexString = ludemeplexString.trim();
defineLudemeplexString = "(define \"DLP.Ludemeplexes." + ludemeplexId + "\" " + defineLudemeplexString + ")";
// Replace all quotes with double quotes for database importing
defineLudemeplexString = defineLudemeplexString.replaceAll("\"", "\"\"");
outputLine += "\"" + defineLudemeplexString + "\""; // define version in .lud format
//outputLine += "\"" + entry.getKey().toString() + "\""; // call tree string
outputLine += "," + allludemeplexescount.get(entry.getKey()); // total count
outputLine += "," + allLudemeplexes.get(entry.getKey()).size(); // # rulesets
outputLine += "\n";
ludemeplexId++;
writer.write(outputLine);
}
writer.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Records all Define Ludemeplexes (ludemeplexes with a # in them).
* NOTE This loops over everything twice, so could be optimised more.
* @param allLudemeplexescount
*/
public static Map<String, Set<String>> storeDefineLudemeplexInfo(final Map<Call, Set<String>> allLudemeplexes, final Map<Call, Integer> allLudemeplexescount, final int maxNumDifferences)
{
// Map of all ludemeplexes (lud format) and the games they are in.
final Map<String, Set<String>> allDefineLudemeplexes = new HashMap<>();
// Map of all ludemeplexes (lud format) and the original Ludemeplexes that they relate to.
final Map<String, Set<Call>> allDefineLudemeplexesOriginalLudemeplexes = new HashMap<>();
// Record all Define ludemeplexes
int counter1 = 1;
for (final Map.Entry<Call, Set<String>> ludemeplexEntry : allLudemeplexes.entrySet())
{
System.out.println("" + counter1 + " / " + allLudemeplexes.entrySet().size());
counter1++;
final List<String> ludemeplexStringList = ludemeplexEntry.getKey().ludemeFormat(0);
int counter2 = 1;
for (final Map.Entry<Call, Set<String>> entry : allLudemeplexes.entrySet())
{
// Skip any pairs of ludemeplexes that have already been compared.
counter2++;
if (counter1 > counter2)
continue;
final List<String> storedLudemeplexStringList = entry.getKey().ludemeFormat(0);
if (storedLudemeplexStringList.size() != ludemeplexStringList.size())
continue;
final List<String> newDefineLudemeplexStringList = new ArrayList<>();
int numDifferences = 0;
for (int i = 0; i < ludemeplexStringList.size(); i++)
{
if (ludemeplexStringList.get(i).replaceAll("[(){}]", "").trim().length() == 0
&& storedLudemeplexStringList.get(i).replaceAll("[(){}]", "").trim().length() == 0
&& !ludemeplexStringList.get(i).equals(storedLudemeplexStringList.get(i)))
{
numDifferences = maxNumDifferences + 1;
break;
}
if (!ludemeplexStringList.get(i).equals(storedLudemeplexStringList.get(i)))
{
if (i == 1)
{
numDifferences = maxNumDifferences + 1;
break;
}
numDifferences++;
newDefineLudemeplexStringList.add("#" + numDifferences + " ");
}
else
{
newDefineLudemeplexStringList.add(ludemeplexStringList.get(i));
}
if (numDifferences > maxNumDifferences)
break;
}
if (numDifferences <= maxNumDifferences && numDifferences > 0)
{
final String newDefineString = String.join("", newDefineLudemeplexStringList);
// Store the games that use this define ludemeplex.
final Set<String> newSetOfGames = new HashSet<>();
if (allDefineLudemeplexes.containsKey(newDefineString))
newSetOfGames.addAll(allDefineLudemeplexes.get(newDefineString));
newSetOfGames.addAll(entry.getValue());
newSetOfGames.addAll(ludemeplexEntry.getValue());
allDefineLudemeplexes.put(newDefineString, newSetOfGames);
// Store all ludemeplexes that are associated with each define ludemeplex.
final Set<Call> ludemeplexesThisDefineUses = new HashSet<>();
if (allDefineLudemeplexesOriginalLudemeplexes.containsKey(newDefineString))
ludemeplexesThisDefineUses.addAll(allDefineLudemeplexesOriginalLudemeplexes.get(newDefineString));
ludemeplexesThisDefineUses.add(entry.getKey());
ludemeplexesThisDefineUses.add(ludemeplexEntry.getKey());
allDefineLudemeplexesOriginalLudemeplexes.put(newDefineString, ludemeplexesThisDefineUses);
}
}
}
// Write them to output file
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(defineLudemeplexesOutputFilePath, false)))
{
int ludemeplexId = 1;
for (final Map.Entry<String, Set<String>> entry : allDefineLudemeplexes.entrySet())
{
String outputLine = ludemeplexId + ",";
String defineLudemeplexString = entry.getKey().trim();
defineLudemeplexString = "(define \"DLP.Ludemeplexes." + ludemeplexId + "\" " + defineLudemeplexString + ")";
// Replace all quotes with double quotes for database importing
defineLudemeplexString = defineLudemeplexString.replaceAll("\"", "\"\"");
int totalCount = 0;
for (final Call c : allDefineLudemeplexesOriginalLudemeplexes.get(entry.getKey()))
totalCount += allLudemeplexescount.get(c).intValue();
outputLine += "\"" + defineLudemeplexString + "\"";
outputLine += "," + totalCount; // total count
outputLine += "," + allDefineLudemeplexes.get(entry.getKey()).size(); // # rulesets
outputLine += "\n";
ludemeplexId++;
writer.write(outputLine);
}
}
catch (final Exception e)
{
e.printStackTrace();
}
return allDefineLudemeplexes;
}
//-------------------------------------------------------------------------
/**
* Saves all relevant information about the set of identified ludemes in an output csv.
*/
public static void storeLudemeInfo()
{
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(ludemesOutputFilePath, false)))
{
for (final LudemeInfo ludeme : GetLudemeInfo.getLudemeInfo())
{
writer.write(ludeme.id() + "," + ludeme.getDBString() + "\n");
}
writer.close();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Saves all LudemeplexID-RulesetID pairs, in an output csv.
*/
public static void storeLudemeplexRulesetPairs(final Map<Call, Set<String>> allLudemeplexes)
{
int IdCounter = 1;
int ludemeplexId = 1;
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(rulesetLudemeplexesOutputFilePath, false)))
{
for (final Map.Entry<Call, Set<String>> entry : allLudemeplexes.entrySet())
{
// Store the ID of all rulesets that use this ludemeplex
for (final String name : entry.getValue())
{
if (DBGameInfo.getRulesetIds().containsKey(name))
{
writer.write(IdCounter + "," + DBGameInfo.getRulesetIds().get(name) + "," + ludemeplexId + "\n");
IdCounter++;
}
else
{
System.out.println("could not find game name_1: " + name);
}
}
ludemeplexId++;
}
writer.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Saves all Define LudemeplexID-RulesetID pairs, in an output csv.
*/
public static void storeDefineLudemeplexRulesetPairs(final Map<String, Set<String>> allDefineLudemeplexes)
{
int IdCounter = 1;
int defineLudemeplexId = 1;
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(defineRulesetludemeplexesOutputFilePath, false)))
{
for (final Map.Entry<String, Set<String>> entry : allDefineLudemeplexes.entrySet())
{
// Store the ID of all rulesets that use this ludemeplex
for (final String name : entry.getValue())
{
if (DBGameInfo.getRulesetIds().containsKey(name))
{
writer.write(IdCounter + "," + DBGameInfo.getRulesetIds().get(name) + "," + defineLudemeplexId + "\n");
IdCounter++;
}
else
{
System.out.println("could not find game name_2: " + name);
}
}
defineLudemeplexId++;
}
writer.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Saves all LudemeplexID-LudemeID pairs, in an output csv.
*/
public static void storeLudemesInLudemeplex(final Map<Call, Set<String>> allLudemeplexes)
{
// All ludeme strings found within at least one call tree (testing purposes)
final Set<LudemeInfo> allFoundLudemes = new HashSet<>();
int IdCounter = 1;
int ludemeplexId = 1;
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(ludemeplexesLudemesOutputFilePath, false)))
{
for (final Map.Entry<Call, Set<String>> entry : allLudemeplexes.entrySet())
{
// Get all ludemes in this ludemeplex
final Map<LudemeInfo, Integer> ludemesInLudemeplex = entry.getKey().analysisFormat(0, GetLudemeInfo.getLudemeInfo());
ludemesInLudemeplex.remove(null);
for (final LudemeInfo ludeme : ludemesInLudemeplex.keySet())
{
if (GetLudemeInfo.getLudemeInfo().contains(ludeme))
{
allFoundLudemes.add(ludeme);
writer.write(IdCounter + "," + ludemeplexId + "," + ludeme.id() + "\n");
IdCounter++;
}
else
{
System.out.println("could not find ludeme: " + ludeme);
}
}
ludemeplexId++;
}
writer.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
public static void storeLudemesInGames(final List<LudemeInfo> allValidLudemes, final List<String[]> gameRulesetNames)
{
int IdCounter = 1;
final Set<LudemeInfo> allLudemesfound = new HashSet<LudemeInfo>();
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(rulesetLudemesOutputFilePath, false)))
{
for (final String[] gameRulesetName : gameRulesetNames)
{
final Game game = GameLoader.loadGameFromName(gameRulesetName[0], gameRulesetName[1]);
final String name = DBGameInfo.getUniqueName(game);
final Map<LudemeInfo, Integer> ludemesInGame = game.description().callTree().analysisFormat(0, allValidLudemes);
for (final LudemeInfo ludeme : ludemesInGame.keySet())
{
allLudemesfound.add(ludeme);
if (DBGameInfo.getRulesetIds().containsKey(name))
{
writer.write(IdCounter + "," + DBGameInfo.getRulesetIds().get(name) + "," + ludeme.id() + "," + ludemesInGame.get(ludeme) +"\n");
IdCounter++;
}
else
{
System.out.println("could not find game name_3: " + name);
}
}
}
writer.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
// Record all ludemes that weren't found in any game.
String notFoundLudemesString = "";
for (final LudemeInfo ludeme : allValidLudemes)
if (!allLudemesfound.contains(ludeme))
notFoundLudemesString += ludeme.getDBString() + "\n";
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(notFoundLudemesFilePath, false)))
{
writer.write(notFoundLudemesString);
writer.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
}
| 14,447 | 33.156028 | 188 |
java
|
Ludii
|
Ludii-master/Mining/src/ludemeplexDetection/GetLudemeInfo.java
|
package ludemeplexDetection;
import java.util.Collection;
import java.util.List;
import grammar.Grammar;
import main.EditorHelpData;
import main.grammar.LudemeInfo;
import main.grammar.Symbol.LudemeType;
//-----------------------------------------------------------------------------
/**
* Get ludeme info from JavaDoc help and database.
*
* @author cambolbro and Matthew.Stephenson
*/
public class GetLudemeInfo
{
// Cached version of ludeme information.
private static List<LudemeInfo> ludemeInfo = null;
//-------------------------------------------------------------------------
/**
* Get ludeme info.
*/
public static List<LudemeInfo> getLudemeInfo()
{
if (ludemeInfo == null)
{
final List<LudemeInfo> ludemes = Grammar.grammar().ludemesUsed();
System.out.println(ludemes.size() + " ludemes loaded.");
// Get ids from database for known ludemes
int idCounter = 1;
// Get JavaDoc help for known ludemes
final EditorHelpData help = EditorHelpData.get();
for (final LudemeInfo ludeme : ludemes)
{
String classPath = ludeme.symbol().cls().getName();
String description = "";
if (ludeme.symbol().ludemeType() == null)
{
System.out.println("** Null ludemeType for: " + ludeme.symbol());
continue;
}
ludeme.setId(idCounter);
idCounter++;
// Check for ludemes that could be Structural type but aren't
if
(
ludeme.symbol().usedInGrammar()
&&
!ludeme.symbol().usedInDescription()
&&
!ludeme.symbol().usedInMetadata()
&&
ludeme.symbol().ludemeType() != LudemeType.Structural
&&
ludeme.symbol().ludemeType() != LudemeType.Constant
)
System.out.println("Could be made a Structural ludeme: " + ludeme.symbol());
if (ludeme.symbol().ludemeType().equals(LudemeType.Primitive))
{
if (classPath.equals("int"))
description = "An integer value.";
else if (classPath.equals("float"))
description = "A floating point value.";
else if (classPath.equals("boolean"))
description = "A boolean value.";
}
else if (ludeme.symbol().ludemeType().equals(LudemeType.Constant))
{
// Handle enum constant
classPath += "$" + ludeme.symbol().name();
String key = classPath.replace('$', '.');
Collection<String> enums = help.enumConstantLines(key);
// Get list of descriptions for this enum type
if (enums==null || enums.size()==0)
{
final String[] parts = classPath.split("\\$");
key = parts[0];
enums = help.enumConstantLines(key);
}
// Find matching description
if (enums != null)
{
for (final String str : enums)
{
final String[] parts = str.split(": ");
if (parts[0].equals(ludeme.symbol().name()))
{
description = parts[1];
break;
}
}
}
}
else
{
// Is ludeme class
description = help.typeDocString(classPath);
}
ludeme.setDescription(description);
}
ludemeInfo = ludemes;
}
return ludemeInfo;
}
//-------------------------------------------------------------------------
public static void main(final String[] args)
{
getLudemeInfo();
}
//-------------------------------------------------------------------------
}
| 3,354 | 23.851852 | 82 |
java
|
Ludii
|
Ludii-master/Mining/src/ludemeplexDetection/LudemeplexDetection.java
|
package ludemeplexDetection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import game.Game;
import main.StringRoutines;
import main.grammar.Call;
import other.GameLoader;
import utils.DBGameInfo;
/**
* Detects all ludemes and ludemeplexes within all games in Ludii.
*
* The database csv tables will be created in "Mining/res/ludemeplexDetection/output"
* Import all of these (except for "NOTFOUNDLUDEMES.csv") to the Ludii database.
*
* Make sure the file located at "Ludii/Mining/res/concepts/input/GameRulesets.csv" is up to date.
* You can run the SQL command inside the "SQL_command.txt" file on the Ludii database to export the required file.
*
* @author matthew.stephenson
*/
public class LudemeplexDetection
{
final static boolean DETECTLUDEMEPLEXES = false; // Set to true to also detect ludemeplexes (slow)
final static int MINLUDMEPLEXSIZE = 4; // Minimum number of ludemes inside a ludemeplex
final static int MAXLUDEMEPLEXSIZE = 6; // Maximum number of ludemes inside a ludemeplex
final static int MAXDEFINELUDEMEPLEXDIFFERENCE = 2; // Maximum number of # symbols inside define ludemeplexes
//-------------------------------------------------------------------------
// Stored results
// Map of all ludemeplexes and the games they are in.
final static Map<Call, Set<String>> allLudemeplexes = new HashMap<>();
// Map of all ludemeplexes and the number of times they occur across all games.
final static Map<Call, Integer> allLudemeplexesCount = new HashMap<>();
//-------------------------------------------------------------------------
/**
* Records all ludemeplexes for a given Game.
*/
private static void recordLudemeplexesInGame(final Game game)
{
final Call callTree = game.description().callTree();
final String gameName = DBGameInfo.getUniqueName(game);
System.out.println(gameName);
// Convert callTree for the game into a list tokens, with unique Ids for each token.
storeludemeplexes(callTree, gameName);
}
//-------------------------------------------------------------------------
/**
* Stores all ludemeplexes found within a Call object, for an associated game name.
*/
private static void storeludemeplexes(final Call c, final String gameName)
{
// Count the number of ludemes used in the ludemeplex.
//final int numTokens = c.countClassesAndTerminals();
final String ludemeList = StringRoutines.join("", c.ludemeFormat(0));
final int ludemeCount = ludemeList.split(" ").length;
// Don't store arrays.
if (c.toString().charAt(0) != '{' && ludemeCount >= MINLUDMEPLEXSIZE && ludemeCount <= MAXLUDEMEPLEXSIZE)
{
Set<String> gameNameArray = new HashSet<>();
if (allLudemeplexes.containsKey(c))
gameNameArray = allLudemeplexes.get(c);
gameNameArray.add(gameName);
allLudemeplexes.put(c, gameNameArray);
Integer count = Integer.valueOf(0);
if (allLudemeplexesCount.containsKey(c))
count = allLudemeplexesCount.get(c);
count = Integer.valueOf((count.intValue() + 1));
allLudemeplexesCount.put(c, count);
}
for (final Call arg : c.args())
if (arg.args().size() > 0)
storeludemeplexes(arg, gameName);
}
//-------------------------------------------------------------------------
/**
* Returns the count for every ludemeplex in a call object.
*/
@SuppressWarnings("unused") // DO NOT KILL: May be used in future.
private static Map<Call, Integer> countLudemeplexes(final Call c, final Map<Call, Integer> currentCount)
{
if (currentCount.containsKey(c))
currentCount.put(c, Integer.valueOf(currentCount.get(c).intValue()+1));
else
currentCount.put(c, Integer.valueOf(1));
for (final Call arg : c.args())
if (arg.args().size() > 0)
countLudemeplexes(arg, currentCount);
return currentCount;
}
//-------------------------------------------------------------------------
/**
* Predicts the win-rate for a variety of games, AI agents and prediction algorithms.
*/
public static void main(final String[] args)
{
// All rulesets to be analysed.
final List<String[]> chosenGames = GameLoader.allAnalysisGameRulesetNames();
System.out.println("//-------------------------------------------------------------------------");
// Record ludemes across all rulesets.
DatabaseFunctions.storeLudemeInfo();
DatabaseFunctions.storeLudemesInGames(GetLudemeInfo.getLudemeInfo(), chosenGames);
System.out.println("Ludemes Recorded");
System.out.println("//-------------------------------------------------------------------------");
if (DETECTLUDEMEPLEXES)
{
// Record ludemeplexes across all rulesets.
for (final String[] gameRulesetName : chosenGames)
recordLudemeplexesInGame(GameLoader.loadGameFromName(gameRulesetName[0], gameRulesetName[1]));
DatabaseFunctions.storeLudemeplexInfo(allLudemeplexes, allLudemeplexesCount);
DatabaseFunctions.storeLudemesInLudemeplex(allLudemeplexes);
DatabaseFunctions.storeLudemeplexRulesetPairs(allLudemeplexes);
System.out.println("Ludemeplexes Recorded");
System.out.println("//-------------------------------------------------------------------------");
// Record possible define ludemeplexes.
final Map<String, Set<String>> allDefineLudemeplexes = DatabaseFunctions.storeDefineLudemeplexInfo(allLudemeplexes, allLudemeplexesCount, MAXDEFINELUDEMEPLEXDIFFERENCE);
DatabaseFunctions.storeDefineLudemeplexRulesetPairs(allDefineLudemeplexes);
System.out.println("Define Ruleset Ludemeplexes Recorded");
System.out.println("//-------------------------------------------------------------------------");
}
}
//-------------------------------------------------------------------------
}
| 5,790 | 36.36129 | 172 |
java
|
Ludii
|
Ludii-master/Mining/src/reconstruction/ReconstructionGenerator.java
|
package reconstruction;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import compiler.Compiler;
import completer.Completion;
import game.Game;
import game.rules.play.moves.Moves;
import main.FileHandling;
import main.Status.EndType;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.grammar.Description;
import other.AI;
import other.GameLoader;
import other.concept.Concept;
import other.context.Context;
import other.move.Move;
import other.trial.Trial;
import reconstruction.completer.CompleterWithPrepro;
import reconstruction.utils.FormatReconstructionOutputs;
import utils.RandomAI;
/**
* Reconstruction Generator.
*
* @author Eric.Piette
*/
public class ReconstructionGenerator
{
final static String defaultOutputPath = "./res/recons/output/";
final static int defaultNumReconsExpected = 10;
final static int defaultNumAttempts = 20000;
final static String defaultReconsPath = "/lud/reconstruction/pending/board/war/replacement/checkmate/chaturanga/Shatranj (Egypt)";
final static String defaultOptionName = "Variant/Incomplete";
final static double defaultConceptualWeight = 0.0;
final static double defaultHistoricalWeight = 0.5;
final static double defaultGeographicalWeight = 0.5;
final static double defaultThreshold = 0.99;
final static boolean geographicalOrder = true;
final static boolean checkTimeoutRandomPlayout = false;
final static int defaultPlayoutsAttempts = 100;
/**
* Main method to call the reconstruction with command lines.
* @param args
*/
public static void main(final String[] args)
{
String outputPath = args.length == 0 ? defaultOutputPath : args[0];
int numReconsNoWarningExpectedConcepts = args.length < 1 ? defaultNumReconsExpected : Integer.parseInt(args[1]);
int maxNumberAttempts = args.length < 2 ? defaultNumAttempts : Integer.parseInt(args[2]);
double conceptualWeight = args.length < 3 ? defaultConceptualWeight : Double.parseDouble(args[3]);
double historicalWeight = args.length < 4 ? defaultHistoricalWeight : Double.parseDouble(args[4]);
double geoWeight = args.length < 5 ? defaultGeographicalWeight : Double.parseDouble(args[5]);
String reconsPath = args.length < 6 ? defaultReconsPath : args[6];
String optionName = args.length < 7 ? defaultOptionName : args[7];
reconstruction(outputPath, numReconsNoWarningExpectedConcepts, maxNumberAttempts, conceptualWeight, historicalWeight, geoWeight, reconsPath, optionName);
}
/**
* @param outputPath The path of the folder to place the reconstructions.
* @param numReconsExpected The number of reconstruction expected to generate.
* @param maxNumberAttempts The number of attempts.
* @param conceptualWeight The weight of the expected concepts.
* @param historicalWeight The weight of the historical similarity.
* @param reconsPath The path of the file to recons.
*/
public static void reconstruction
(
String outputPath,
int numReconsExpected,
int maxNumberAttempts,
double conceptualWeight,
double historicalWeight,
double geographicalWeight,
String reconsPath,
String optionName
)
{
System.out.println("\n=========================================\nStart reconstruction:\n");
System.out.println("Output Path = " + outputPath);
System.out.println("Historical Weight = " + historicalWeight + " Conceptual Weight = " + conceptualWeight + " Geographical Weight = " + geographicalWeight);
final long startAt = System.nanoTime();
// Load from memory
final String[] choices = FileHandling.listGames();
CompleterWithPrepro completer = new CompleterWithPrepro(conceptualWeight, historicalWeight, geographicalWeight, defaultThreshold, (geographicalOrder ? 0.99 : -1));
for (final String fileName : choices)
{
if (!fileName.replaceAll(Pattern.quote("\\"), "/").contains(reconsPath))
continue;
final String gameName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length() - 4);
// Get game description from resource
System.out.println("Game: " + gameName);
String path = fileName.replaceAll(Pattern.quote("\\"), "/");
path = path.substring(path.indexOf("/lud/"));
String desc = "";
String line;
try
(
final InputStream in = GameLoader.class.getResourceAsStream(path);
final BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
)
{
while ((line = rdr.readLine()) != null)
desc += line + "\n";
}
catch (final IOException e1)
{
e1.printStackTrace();
}
// To check the expected concepts detected.
// final List<Concept> expectedConcepts = ComputeCommonExpectedConcepts.computeCommonExpectedConcepts(desc);
// for(Concept c: expectedConcepts)
// System.out.println(c.name());
// Extract the metadata.
final String metadata = desc.contains("(metadata") ? desc.substring(desc.indexOf("(metadata")) : "";
String reconsMetadata = "";
if(metadata.contains("(recon"))
{
reconsMetadata = metadata.substring(metadata.indexOf("(recon"));
int countParenthesis = 0;
int charIndex = 0;
for(; charIndex < reconsMetadata.length(); charIndex++)
{
if(reconsMetadata.charAt(charIndex) == '(')
countParenthesis++;
else
if(reconsMetadata.charAt(charIndex) == ')')
countParenthesis--;
if(countParenthesis == -1)
{
charIndex--;
break;
}
}
reconsMetadata = reconsMetadata.substring(0, charIndex);
reconsMetadata = "(metadata " + reconsMetadata + ")";
}
// Extract the id of the reconstruction.
String idStr = metadata.contains("(id") ? metadata.substring(metadata.indexOf("(id") + 5) : "";
idStr = idStr.substring(0, idStr.indexOf(')') - 1);
final int idRulesetToRecons = Integer.valueOf(idStr).intValue();
//System.out.println(desc);
final Description description = new Description(desc);
CompleterWithPrepro.expandRecons(description, optionName);
desc = StringRoutines.formatOneLineDesc(description.expanded());
// System.out.println(desc);
// System.out.println(FormatReconstructionOutputs.indentNicely(StringRoutines.unformatOneLineDesc(desc)));
int numAttempts = 0;
List<Completion> correctCompletions = new ArrayList<Completion>();
// Run the recons process until enough attempts are executed or all reconstructions are generated.
while(numAttempts < maxNumberAttempts && correctCompletions.size() < numReconsExpected)
{
Completion completion = null;
// Run the completer.
try
{
completion = completer.completeSampled(desc, idRulesetToRecons);
}
catch (final Exception e)
{
e.printStackTrace();
}
// Check the completions.
if (completion != null)
{
final String completionRaw = FormatReconstructionOutputs.indentNicely(StringRoutines.unformatOneLineDesc(completion.raw()));
// Test if the completion compiles.
Game game = null;
//System.out.println(completionRaw);
try{game = (Game) Compiler.compileReconsTest(new Description(completionRaw), false);}
catch(final Exception e)
{
// System.out.println("Impossible to compile");
// System.out.println("DESC IS");
// System.out.println(completionRaw);
// e.printStackTrace();
}
// It compiles.
if(game != null)
{
final String rawDescMetadata = completionRaw + "\n" + reconsMetadata;
completion.setRaw(rawDescMetadata);
System.out.print("One Completion found");
// Check if no warning and if no potential crash.
if(!game.hasMissingRequirement() && !game.willCrash())
{
System.out.print( " with no warning");
// Check if the concepts expected are present.
//System.out.println(rawDescMetadata);
if(Concept.isExpectedConcepts(rawDescMetadata))
{
System.out.print( " and with the expected concepts");
final Context context = new Context(game, new Trial(game));
game.start(context);
final Moves legalMoves = context.game().moves(context);
// Check if a non pass move is part of the first legal moves (BE CAREFUL WITH DICE GAMES)
boolean aNonPassMove = false;
for(Move move: legalMoves.moves())
if(!move.isPass())
{
aNonPassMove = true;
break;
}
if(aNonPassMove)
{
System.out.print( " and with legal moves");
boolean allGood = true;
if(checkTimeoutRandomPlayout)
{
// Run 10 random playouts and check if at least one of them is not timeout.
allGood = false;
int playoutAttempts = 0;
while (!allGood && playoutAttempts <= defaultPlayoutsAttempts)
{
final Context contextRandomPlayout = new Context(game, new Trial(game));
final List<AI> ais = new ArrayList<AI>();
ais.add(null);
// Init the ais.
for (int p = 1; p <= game.players().count(); ++p)
{
ais.add(new RandomAI());
ais.get(p).initAI(game, p);
}
game.start(contextRandomPlayout);
game.playout(contextRandomPlayout, ais, 1.0, null, 0, -1, null);
final Trial trial = contextRandomPlayout.trial();
// System.out.println("run playout");
// System.out.println("num Turns = " + trial.numTurns());
// System.out.println("num real moves = " + trial.numberRealMoves());
// System.out.println("game max Turn limits = " + game.getMaxTurnLimit());
boolean trialTimedOut = trial.status().endType() == EndType.MoveLimit || trial.status().endType() == EndType.TurnLimit;
if(!trialTimedOut)
allGood = true;
}
}
else
{
System.out.println( " and with at least a complete playout");
}
// All good, add to the list of correct completions.
if(allGood)
{
boolean descAlreadyObtained = false;
for(Completion correctCompletion: correctCompletions)
{
if(correctCompletion.raw().hashCode() == completion.raw().hashCode()) // We check if we already obtained this description.
{
correctCompletion.addOtherIds(completion.idsUsed());
System.out.println("FOUND ONE MORE COMBINATION OF A COMPLETION ALREADY REACHED");
System.out.println("Still " + correctCompletions.size() + " COMPLETIONS GENERATED.");
descAlreadyObtained = true;
break;
}
}
if(!descAlreadyObtained)
{
correctCompletions.add(completion);
System.out.println("Score = " + completion.score() + " Cultural Score = " + completion.culturalScore() + " Conceptual Score = " + completion.conceptualScore() + " Geographical Score = " + completion.geographicalScore()) ;
System.out.println("ids used = " + completion.idsUsed());
System.out.println(completion.raw());
System.out.println(correctCompletions.size() + " COMPLETIONS GENERATED.");
}
}
}
}
}
System.out.println();
}
}
numAttempts++;
System.out.println("Current Num Attempts = " + numAttempts);
System.out.println(correctCompletions.size() + " recons generated for now");
}
// We rank the completions.
Collections.sort(correctCompletions, (c1, c2) -> c1.score() < c2.score() ? 1 : c1.score() == c2.score() ? 0 : -1);
for (int n = 1; n < correctCompletions.size() + 1; n++)
{
System.out.println("Completion " + n + " has a score of " + correctCompletions.get(n -1).score() + " Cultural Score = " + correctCompletions.get(n -1).culturalScore() + " conceptual score = " + correctCompletions.get(n - 1).conceptualScore() + " geographical score = " + correctCompletions.get(n - 1).geographicalScore() + " IDS used = " + correctCompletions.get(n -1).idsUsed() + (correctCompletions.get(n -1).otherIdsUsed().isEmpty() ? "" : " other possible IDS = " + correctCompletions.get(n -1).otherIdsUsed()));
CompleterWithPrepro.saveCompletion(outputPath + gameName + "/", gameName + " (Ludii " + n + ")", correctCompletions.get(n -1).raw());
}
System.out.println("Num Attempts = " + numAttempts);
System.out.println(correctCompletions.size() + " recons generated");
final String outputReconsData = outputPath + gameName + ".csv";
try (final PrintWriter writer = new UnixPrintWriter(new File(outputReconsData), "UTF-8"))
{
for (int n = 1; n < correctCompletions.size() + 1; n++)
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(gameName + " (Ludii " + n + ")");
lineToWrite.add(idRulesetToRecons+"");
lineToWrite.add(correctCompletions.get(n-1).score() +"");
lineToWrite.add(correctCompletions.get(n-1).culturalScore() +"");
lineToWrite.add(correctCompletions.get(n-1).conceptualScore() +"");
lineToWrite.add(correctCompletions.get(n-1).geographicalScore() +"");
lineToWrite.add(correctCompletions.get(n-1).idsUsed() +"");
lineToWrite.add(correctCompletions.get(n-1).otherIdsUsed() +"");
writer.println(StringRoutines.join(",", lineToWrite));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
final long stopAt = System.nanoTime();
final double secs = (stopAt - startAt) / 1000000000.0;
System.out.println("\nDone in " + secs + "s.");
}
}
| 14,203 | 39.23796 | 521 |
java
|
Ludii
|
Ludii-master/Mining/src/reconstruction/completer/CompleterWithPrepro.java
|
package reconstruction.completer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import completer.Completion;
import contextualiser.ContextualSimilarity;
import gameDistance.utils.DistanceUtils;
import gnu.trove.list.array.TIntArrayList;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.FVector;
import main.grammar.Description;
import main.grammar.Report;
import main.options.UserSelections;
import parser.Expander;
/**
* Completes partial game descriptions ready for expansion.
* @author cambolbro and Eric.Piette
*/
public class CompleterWithPrepro
{
public static final char CHOICE_DIVIDER_CHAR = '|';
private static final int MAX_PARENTS = 10;
private static final int MAX_RANGE = 1000;
/** The path of the csv with the id of the rulesets for each game and its description on one line. */
private static final String RULESETS_PATH = "/recons/input/RulesetFormatted.csv";
/** The ruleset id and their corresponding description formatted on one line */
private final Map<Integer, String> ludMap;
/** The ruleset ids greater than the threshold. */
private Map<Integer, String> ludMapUsed;
/** The weight of the expected concepts. */
private final double conceptualWeight;
/** The weight of the historical similarity. */
private final double historicalWeight;
/** The weight of the geographical distance. */
private final double geographicalWeight;
/** The list of completions already tried. */
private final List<Completion> history = new ArrayList<Completion>();
/** threshold used to look first the top similarities scores. */
private double threshold = 0.99;
/** Geographical threshold to return the rulesets with the shortest geographical order. */
private double geoThreshold = 0.99;
/** The geographical similarities between all the rulesets */
private static Map<Integer, Double> allRulesetGeoSimilarities = null;
//-------------------------------------------------------------------------
/**
* Constructor getting the rulesets expanded description on one line and rulesets ids.
*/
public CompleterWithPrepro
(
final double conceptualWeight,
final double historicalWeight,
final double geographicalWeight,
final double threshold,
final double geoThreshold
)
{
this.conceptualWeight = conceptualWeight;
this.historicalWeight = historicalWeight;
this.geographicalWeight = geographicalWeight;
this.threshold = threshold;
this.geoThreshold = geoThreshold;
ludMap = new HashMap<Integer, String>();
// Get the ids and descriptions of the rulesets.
try (final InputStream in = CompleterWithPrepro.class.getResourceAsStream(RULESETS_PATH);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));)
{
String line = reader.readLine();
while (line != null)
{
String lineNoQuote = line;
int separatorIndex = lineNoQuote.indexOf(',');
final String gameName = lineNoQuote.substring(0, separatorIndex);
lineNoQuote = lineNoQuote.substring(gameName.length() + 1);
separatorIndex = lineNoQuote.indexOf(',');
final String rulesetName = lineNoQuote.substring(0, separatorIndex);
lineNoQuote = lineNoQuote.substring(rulesetName.length() + 1);
separatorIndex = lineNoQuote.indexOf(',');
final String rulesetIdStr = lineNoQuote.substring(0, separatorIndex);
final int rulesetId = Integer.parseInt(rulesetIdStr);
lineNoQuote = lineNoQuote.substring(rulesetIdStr.length() + 1);
final String desc = lineNoQuote;
// To check if a specific part of the ludemes appear in some games.
// if(desc.contains("\"Marker1\""))
// {
// System.out.println(gameName + " HAS IT");
// System.out.println(desc);
// }
// System.out.println("game = " + gameName);
// System.out.println("ruleset = " + rulesetName);
// System.out.println("rulesetId = " + rulesetId);
// System.out.println("desc = " + desc);
ludMap.put(Integer.valueOf(rulesetId), desc);
line = reader.readLine();
}
reader.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Create a completion.
* @param raw Incomplete raw game description.
* @param rulesetReconId Id of the ruleset to recons.
* @return A (raw) game description.
*/
public Completion completeSampled
(
final String raw,
final int rulesetReconId
)
{
// System.out.println("\nCompleter.complete(): Completing at most " + maxCompletions + " descriptions...");
// Expand the defines of rulesets needed reconstruction.
final Description description = new Description(raw);
expandRecons(description, "");
// Format the description.
final String rulesetDescriptionOneLine = StringRoutines.formatOneLineDesc(description.expanded()); // Same format of all other rulesets.
//System.out.println(rulesetDescriptionOneLine);
allRulesetGeoSimilarities = DistanceUtils.getAllRulesetGeoDistances(rulesetReconId);
Completion comp = new Completion(rulesetDescriptionOneLine);
if(geoThreshold == -1)
System.out.println("new threshold = " + threshold);
else
System.out.println("new threshold = " + threshold + " new geoThreshold = " + geoThreshold);
applyThresholdToLudMap(rulesetReconId);
while (needsCompleting(comp.raw()))
{
//System.out.println("before \n" + comp.raw());
comp = nextCompletionSampled(comp, rulesetReconId);
//System.out.println("after \n" + comp.raw());
if(comp == null)
{
if(threshold <= 0.0)
{
System.out.println("All combinations tried, no result.");
return null;
}
if(geoThreshold == -1)
{
threshold = threshold - 0.01;
System.out.println("new threshold = " + threshold);
}
else
{
if(geoThreshold >= 0)
geoThreshold = geoThreshold - 0.03;
else
{
threshold = threshold - 0.01;
geoThreshold = 0.99;
}
System.out.println("new threshold = " + threshold + " new geoThreshold = " + geoThreshold);
}
comp = new Completion(rulesetDescriptionOneLine);
applyThresholdToLudMap(rulesetReconId);
}
}
// System.out.println("\nList of completions:");
// for (final Completion comp : completions)
// System.out.println(comp.raw());
// System.out.println();
history.add(comp);
return comp;
}
//-------------------------------------------------------------------------
/**
* Process next completion and add results to queue.
* Solves the next completion independently by sampling from candidates.
* @param rulesetReconId Id of the ruleset to recons.
*/
public Completion nextCompletionSampled
(
final Completion completion,
final int rulesetReconId
)
{
// System.out.println("\nCompleting next completion for raw string:\n" + completion.raw());
final List<Completion> completions = new ArrayList<Completion>();
// Find opening and closing bracket locations
final String raw = completion.raw();
final int from = raw.indexOf("[");
final int to = StringRoutines.matchingBracketAt(raw, from);
// Get reconstruction clause (substring within square brackets)
final String left = raw.substring(0, from);
final String clause = raw.substring(from + 1, to);
final String right = raw.substring(to + 1);
//System.out.println("left is: " + left);
//System.out.println("clause is: " + clause);
//System.out.println("right is: " + right);
// Determine left and right halves of parents
final List<String[]> parents = determineParents(left, right);
// System.out.println("Parents:\n");
// for (final String[] parent : parents)
// System.out.println(parent[0] + "?" + parent[1] + "\n");
final List<String> choices = extractChoices(clause);
final List<String> inclusions = new ArrayList<String>();
final List<String> exclusions = new ArrayList<String>();
//final List<String> enumerations = new ArrayList<String>();
int enumeration = 0;
//System.out.println(choices);
for (int c = choices.size() - 1; c >= 0; c--)
{
final String choice = choices.get(c);
//System.out.println("choice is: " + choice);
if
(
choice.length() > 3 && choice.charAt(0) == '['
&&
choice.charAt(1) == '+' && choice.charAt(choice.length() - 1) == ']'
)
{
// Is an inclusion
inclusions.add(choice.substring(2, choice.length() - 1).trim());
choices.remove(c);
}
else if
(
choice.length() > 3 && choice.charAt(0) == '['
&&
choice.charAt(1) == '-' && choice.charAt(choice.length() - 1) == ']'
)
{
// Is an exclusion
exclusions.add(choice.substring(2, choice.length() - 1).trim());
choices.remove(c);
}
else if
(
choice.length() >= 1 && choice.charAt(0) == '#'
||
choice.length() >= 3 && choice.charAt(0) == '['
&&
choice.charAt(1) == '#' && choice.charAt(choice.length() - 1) == ']'
)
{
// Is an enumeration
//enumerations.add(choice.substring(1, choice.length() - 1).trim());
enumeration = numHashes(choice);
//System.out.println("Enumeration has " + enumeration + " hashes...");
choices.remove(c);
}
}
if (enumeration > 0)
{
// Enumerate on parents
final String[] parent = parents.get(enumeration - 1);
// To print the parents
// System.out.println(parent[0]);
// System.out.println(parent[1]);
// System.out.println("\nEnumerating on parent " + enumeration + ": \"" + parent[0] + "\" + ? + \"" + parent[1] + "\"");
enumerateMatches(completion, left, right, parent, completions, completion.score(), rulesetReconId);
}
else
{
// Handle choices as usual
for (int n = 0; n < choices.size(); n++)
{
final String choice = choices.get(n);
if (!exclusions.isEmpty())
{
// Check whether this choice contains excluded text
boolean found = false;
for (final String exclusion : exclusions)
if (choice.contains(exclusion))
{
found = true;
break;
}
if (found)
continue; // excluded text is present
}
if (!inclusions.isEmpty())
{
// Check that this choice contains included text
boolean found = false;
for (final String inclusion : inclusions)
if (choice.contains(inclusion))
{
found = true;
break;
}
if (!found)
continue; // included text is not present
}
final String str = raw.substring(0, from) + choice + raw.substring(to + 1);
final Completion newCompletion = new Completion(str);
newCompletion.setScore(completion.score());
// System.out.println("\n**********************************************************");
// System.out.println("completion " + n + "/" + choices.size() + " is:\n" + completion);
//queue.add(newCompletion);
newCompletion.setIdsUsed(completion.idsUsed());
newCompletion.setScore(completion.score());
newCompletion.setCulturalScore(completion.culturalScore());
newCompletion.setConceptualScore(completion.conceptualScore());
newCompletion.setGeographicalScore(completion.geographicalScore());
completions.add(newCompletion);
}
}
if (completions.isEmpty())
return null;
// Get a random completion according to the score of each completion.
final FVector vectorCompletions = new FVector(completions.size());
for(int i = 0; i < completions.size(); i++)
vectorCompletions.add((float) completions.get(i).score());
final Completion returnCompletion = completions.get(vectorCompletions.sampleProportionally());
return returnCompletion;
}
//-------------------------------------------------------------------------
/**
* Enumerate all parent matches in the specified map.
* @param parent
* @param queue
* @param rulesetReconId Id of the ruleset to recons.
*/
private void enumerateMatches
(
final Completion completion,
final String left,
final String right,
final String[] parent,
final List<Completion> queue,
final double confidence,
final int rulesetReconId
)
{
for (final Map.Entry<Integer, String> entry : ludMapUsed.entrySet())
{
final String otherDescription = entry.getValue();
final int rulesetId = entry.getKey().intValue();
final String candidate = new String(otherDescription);
double culturalSimilarity = 0.0;
double conceptualSimilarity = 0.0;
double geoSimilarity = 0.0;
if(rulesetReconId == -1) // We do not use the CSN.
culturalSimilarity = 1.0;
else
{
final String similaryFilePath = ContextualSimilarity.rulesetContextualiserFilePath;
final File fileSimilarity1 = new File(similaryFilePath + rulesetReconId + ".csv");
final File fileSimilarity2 = new File(similaryFilePath + entry.getKey().intValue() + ".csv");
if(!fileSimilarity1.exists() || !fileSimilarity2.exists() || (rulesetReconId == rulesetId)) // If CSN not computing or comparing the same rulesets, similarity is 0.
culturalSimilarity = 0.0;
else
culturalSimilarity = DistanceUtils.getRulesetCSNDistance(rulesetId, rulesetReconId);
if(!fileSimilarity1.exists() || !fileSimilarity2.exists() || (rulesetReconId == rulesetId)) // If Geo not computing or comparing the same rulesets, similarity is 0.
geoSimilarity = 0.0;
else
geoSimilarity = getRulesetGeoDistance(rulesetId);
conceptualSimilarity = getAVGCommonExpectedConcept(rulesetReconId, rulesetId);
}
// We ignore all the ludemes coming from a negative similarity value or 0.
if(culturalSimilarity <= 0)
continue;
// We ignore all the ludemes coming from a negative similarity value or 0.
if(geographicalWeight != 0 && geoSimilarity <= 0)
continue;
final double score = historicalWeight * culturalSimilarity + conceptualWeight * conceptualSimilarity + geographicalWeight * geoSimilarity;
final int l = candidate.indexOf(parent[0]);
if (l < 0)
continue; // not a match
final String secondPart = candidate.substring(l + parent[0].length()); //.trim();
// System.out.println("\notherDescription is: " + otherDescription);
// System.out.println("parent[0] is: " + parent[0]);
// System.out.println("parent[1] is: " + parent[1]);
// System.out.println("secondPart is: " + secondPart);
// System.out.println("left is: " + left);
// System.out.println("right is: " + right);
// final int r = secondPart.indexOf(parent[1]);
// We get the right parent index.
int countParenthesis = 0;
int r = 0;
for(; r < secondPart.length(); r++)
{
if(secondPart.charAt(r) == '(' || secondPart.charAt(r) == '{')
countParenthesis++;
else
if(secondPart.charAt(r) == ')' || secondPart.charAt(r) == '}')
countParenthesis--;
if(countParenthesis == -1)
{
r--;
break;
}
}
// final int r = (StringRoutines.isBracket(secondPart.charAt(0)))
// ? StringRoutines.matchingBracketAt(secondPart, 0)
// : secondPart.indexOf(parent[1]) - 1;
if (r >= 0)
{
// Is a match
//final String match = mapString.substring(l, l + parent[0].length() + r + parent[1].length());
final String match = secondPart.substring(0, r + 1); //l, l + parent[0].length() + r + parent[1].length());
//System.out.println("match is: " + match);
// final String str =
// left.substring(0, left.length() - parent[0].length())
// +
// match
// +
// right.substring(parent[1].length());
//final String str = left + " " + match + " " + right;
final String str = left + match + right;
//System.out.println(right);
final Completion newCompletion = new Completion(str);
//System.out.println("completion is:\n" + completion.raw());
//System.out.println("Adding completion:\n" + completion.raw());
final double newScore = (completion.idsUsed().size() == 0) ? score : ((completion.score() * completion.idsUsed().size() + score) / (1 + completion.idsUsed().size()));
final double newSimilarityScore = (completion.idsUsed().size() == 0) ? culturalSimilarity : ((completion.score() * completion.idsUsed().size() + culturalSimilarity) / (1 + completion.idsUsed().size()));
final double newGeographicalScore = (completion.idsUsed().size() == 0) ? geoSimilarity : ((completion.score() * completion.idsUsed().size() + geoSimilarity) / (1 + completion.idsUsed().size()));
final double newCommonTrueConceptsAvgScore = (completion.idsUsed().size() == 0) ? conceptualSimilarity : ((completion.score() * completion.idsUsed().size() + conceptualSimilarity) / (1 + completion.idsUsed().size()));
newCompletion.setIdsUsed(completion.idsUsed());
newCompletion.addId(rulesetId);
newCompletion.setScore(newScore);
newCompletion.setCulturalScore(newSimilarityScore);
newCompletion.setGeographicalScore(newGeographicalScore);
newCompletion.setConceptualScore(newCommonTrueConceptsAvgScore);
//System.out.println("SCORE IS " + completion.score());
if (!queue.contains(newCompletion) && !historyContainIds(newCompletion))
queue.add(newCompletion);
}
}
}
//-------------------------------------------------------------------------
/**
* @return Number of hash characters '#' in string.
*/
private static int numHashes(final String str)
{
int numHashes = 0;
for (int c = 0; c < str.length(); c++)
if (str.charAt(c) == '#')
numHashes++;
return numHashes;
}
//-------------------------------------------------------------------------
/**
* @return List of successively nested parents based on left and right substrings.
*/
private static final List<String[]> determineParents
(
final String left, final String right
)
{
final List<String[]> parents = new ArrayList<String[]>();
// Step backwards to previous bracket on left side
int l = left.length() - 1;
int r = 0;
boolean lZero = false;
boolean rEnd = false;
for (int p = 0; p < MAX_PARENTS; p++)
{
// Step backwards to previous "("
while (l > 0 && left.charAt(l) != '(' && left.charAt(l) != '{')
{
// Step past embedded clauses
if (left.charAt(l) == ')' || left.charAt(l) == '}')
{
int depth = 1;
if (left.charAt(l) == ')' || left.charAt(l) == '}')
depth++;
while (l >= 0 && depth > 0)
{
l--;
if (l < 0)
break;
if (left.charAt(l) == ')' || left.charAt(l) == '}')
depth++;
else if (left.charAt(l) == '(' || left.charAt(l) == '{')
depth--;
}
}
else
{
l--;
}
}
if (l > 0)
l--;
if (l == 0)
{
if (lZero)
break;
lZero = true;
}
if (l < 0)
break;
// System.out.println(left.charAt(l + 1));
// Step forwards to next bracket on right side
final boolean curly = left.charAt(l + 1) == '{';
while (r < right.length() && (!curly && right.charAt(r) != ')' || curly && right.charAt(r) != '}'))
{
// Step past embedded clauses
if (right.charAt(r) == '(' || right.charAt(r) == '{')
{
int depth = 1;
while (r < right.length() && depth > 0)
{
r++;
if (r >= right.length())
break;
if (right.charAt(r) == '(' || right.charAt(r) == '{')
depth++;
else if (right.charAt(r) == ')' || right.charAt(r) == '}')
depth--;
}
}
else
{
r++;
}
}
// if (r < right.length() - 1 && right.charAt(r) != ')' && right.charAt(r) != '}')
// r++;
if (r < right.length() - 1)
r++;
if (r == right.length() - 1)
{
if (rEnd)
break;
rEnd = true;
}
if (r >= right.length())
break;
// Store the two halves of the parent
final String[] parent = new String[2];
parent[0] = left.substring(l); //.trim();
parent[1] = right.substring(0, r); //.trim();
// Strip leading spaces from parent[0]
while (parent[0].length() > 0 && parent[0].charAt(0) == ' ')
parent[0] = parent[0].substring(1);
//System.out.println("Parent " + p + " is " + parent[0] + "?" + parent[1]);
parents.add(parent);
}
return parents;
}
//-------------------------------------------------------------------------
/**
* Extract completion choices from reconstruction clause.
* @param clause
* @return
*/
static List<String> extractChoices(final String clause)
{
final List<String> choices = new ArrayList<String>();
if (clause.length() >= 1 && clause.charAt(0) == '#')
{
// Is an enumeration, just return as is
choices.add(clause);
return choices;
}
final StringBuilder sb = new StringBuilder();
int depth = 0;
for (int c = 0; c < clause.length(); c++)
{
final char ch = clause.charAt(c);
if (depth == 0 && (c >= clause.length() - 1 || ch == CHOICE_DIVIDER_CHAR))
{
if(ch != CHOICE_DIVIDER_CHAR)
sb.append(ch);
// Store this choice and reset sb
final String choice = sb.toString().trim();
//System.out.println("extractChoices choice is: " + choice);
if (choice.contains("..") && !choice.contains("("))
{
// Handle range
final List<String> rangeChoices = expandRanges(new String(choice), null);
if (!rangeChoices.isEmpty() && !rangeChoices.get(0).contains(".."))
{
// Is a number range
//System.out.println(rangeChoices.size() + " range choices:" + rangeChoices);
choices.addAll(rangeChoices);
}
else
{
// Check for site ranges
final List<String> siteChoices = expandSiteRanges(new String(choice), null);
if (!siteChoices.isEmpty())
choices.addAll(siteChoices);
}
}
else
{
choices.add(choice);
}
// Reset to accumulate next choice
sb.setLength(0);
}
else
{
if (ch == '[')
depth++;
else if (ch == ']')
depth--;
sb.append(ch);
}
}
return choices;
}
//-------------------------------------------------------------------------
/**
* @param strIn
* @return Game description with all number range occurrences expanded.
*/
private static List<String> expandRanges
(
final String strIn,
final Report report
)
{
final List<String> choices = new ArrayList<String>();
if (!strIn.contains(".."))
return choices; // nothing to do
String str = new String(strIn);
int ref = 1;
while (ref < str.length() - 2)
{
if
(
str.charAt(ref) == '.' && str.charAt(ref+1) == '.'
&&
Character.isDigit(str.charAt(ref-1))
&&
Character.isDigit(str.charAt(ref+2))
)
{
// Is a range: expand it
int c = ref - 1;
while (c >= 0 && Character.isDigit(str.charAt(c)))
c--;
c++;
final String strM = str.substring(c, ref);
final int m = Integer.parseInt(strM);
c = ref + 2;
while (c < str.length() && Character.isDigit(str.charAt(c)))
c++;
final String strN = str.substring(ref+2, c);
final int n = Integer.parseInt(strN);
if (Math.abs(n - m) > MAX_RANGE)
{
if (report == null)
{
System.out.println("** Range exceeded maximum of " + MAX_RANGE + ".");
}
else
{
report.addError("Range exceeded maximum of " + MAX_RANGE + ".");
return null;
}
}
// Generate the expanded range substring
String sub = " ";
final int inc = (m <= n) ? 1 : -1;
for (int step = m; step != n; step += inc)
{
if (step == m || step == n)
continue; // don't include end points
sub += step + " ";
}
str = str.substring(0, ref) + sub + str.substring(ref+2);
ref += sub.length();
}
ref++;
}
final String[] subs = str.split(" ");
for (final String sub : subs)
choices.add(sub);
return choices;
}
/**
* @param strIn
* @return Game description with all site range occurrences expanded.
*/
private static List<String> expandSiteRanges
(
final String strIn,
final Report report
)
{
final List<String> choices = new ArrayList<String>();
//System.out.println("** Warning: Completer: Site ranges not expanded yet.");
//return choices;
if (!strIn.contains(".."))
return choices; // nothing to do
String str = new String(strIn);
int ref = 1;
while (ref < str.length() - 2)
{
if
(
str.charAt(ref) == '.' && str.charAt(ref+1) == '.'
&&
str.charAt(ref-1) == '"' && str.charAt(ref+2) == '"'
)
{
// Must be a site range
int c = ref - 2;
while (c >= 0 && str.charAt(c) != '"')
c--;
final String strC = str.substring(c+1, ref-1);
// System.out.println("strC: " + strC);
int d = ref + 3;
while (d < str.length() && str.charAt(d) != '"')
d++;
d++;
final String strD = str.substring(ref+3, d-1);
// System.out.println("strD: " + strD);
// System.out.println("Range: " + str.substring(c, d));
if (strC.length() < 2 || !Character.isLetter(strC.charAt(0)))
{
if (report != null)
report.addError("Bad 'from' coordinate in site range: " + str.substring(c, d));
return null;
}
final int fromChar = Character.toUpperCase(strC.charAt(0)) - 'A';
if (strD.length() < 2 || !Character.isLetter(strD.charAt(0)))
{
if (report != null)
report.addError("Bad 'to' coordinate in site range: " + str.substring(c, d));
return null;
}
final int toChar = Character.toUpperCase(strD.charAt(0)) - 'A';
// System.out.println("fromChar=" + fromChar + ", toChar=" + toChar + ".");
final int fromNum = Integer.parseInt(strC.substring(1));
final int toNum = Integer.parseInt(strD.substring(1));
// System.out.println("fromNum=" + fromNum + ", toNum=" + toNum + ".");
// Generate the expanded range substring
String sub = "";
for (int m = fromChar; m < toChar + 1; m++)
for (int n = fromNum; n < toNum + 1; n++)
sub += "\"" + (char)('A' + m) + (n) + "\" ";
str = str.substring(0, c) + sub.trim() + str.substring(d);
ref += sub.length();
}
ref++;
}
//System.out.println("str is: " + str);
final String[] subs = str.split(" ");
for (final String sub : subs)
choices.add(sub);
return choices;
}
//-------------------------------------------------------------------------
/**
* Save reconstruction to file.
* @param path Path to save output file (will use default /Common/res/out/recons/ if null).
* @param name Output file name for reconstruction.
*/
public static void saveCompletion
(
final String path,
final String name,
final String completionRaw
)
{
final String savePath = (path != null) ? path : "../Common/res/out/recons/";
final String outFileName = savePath + name + ".lud";
// Create the file if it is not existing.
final File folder = new File(path);
if(!folder.exists())
folder.mkdirs();
try (final PrintWriter writer = new UnixPrintWriter(new File(outFileName), "UTF-8"))
{
writer.print(completionRaw);
}
catch (FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
public static boolean needsCompleting(final String desc)
{
// Remove comments first, so that recon syntax can be commented out
// to not trigger a reconstruction without totally removing it.
final String str = Expander.removeComments(desc);
return str.contains("[") && str.contains("]");
}
//-------------------------------------------------------------------------
/**
* Expands defines in user string to give full description of a description needed reconstruction.
*
* @param description The description.
*/
public static void expandRecons(final Description description, final String selectedOptions)
{
final Report report = new Report();
String str = new String(description.raw());
// Remove comments before any expansions
str = Expander.removeComments(str); // remove comment.
final int c = str.indexOf("(metadata");
if (c >= 0)
{
// Remove metadata
str = str.substring(0, c).trim();
}
final List<String> selectedOptionStrings = new ArrayList<String>();
if(!selectedOptions.isEmpty())
selectedOptionStrings.add(selectedOptions);
str = Expander.realiseOptions(str, description, new UserSelections(selectedOptionStrings), report);
if (report.isError())
return;
if(str.contains("(rulesets"))
{
str = Expander.realiseRulesets(str, description, report);
str = str.substring(0, str.length()-1);
if (report.isError())
return;
}
// Continue expanding defines for full description
str = Expander.expandDefines(str, report, description.defineInstances());
// Do again after expanding defines, as external defines could have comments
str = Expander.removeComments(str); // remove comment.
// Do after expanding defines, as external defines could have ranges
str = Expander.expandRanges(str, report);
str = Expander.expandSiteRanges(str, report);
str = Expander.cleanUp(str, report);
description.setExpanded(str);
}
/**
* @return Map of rulesetId (key) to CSN distance (value) pairs, based on distance to specified rulesetId.
*/
public static double getAVGCommonExpectedConcept(final int reconsRulesetId, final int rulesetID)
{
// Load ruleset avg common true concepts from specific directory.
final String commonExpectedConceptsFilePath = "./res/recons/input/commonExpectedConcepts/CommonExpectedConcept_" + reconsRulesetId + ".csv";
final File fileTrueConcept = new File(commonExpectedConceptsFilePath);
if(!fileTrueConcept.exists() || (reconsRulesetId == rulesetID)) // If TrueConcept not computing or comparing the same rulesets, trueConceptsAvg is 0.
return 0.0;
// Map of rulesetId (key) to common true concepts avg pairs.
final Map<Integer, Double> rulesetCommonTrueConcept = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(commonExpectedConceptsFilePath)))
{
String line = br.readLine(); // column names
while ((line = br.readLine()) != null)
{
final String[] values = line.split(",");
rulesetCommonTrueConcept.put(Integer.valueOf(Integer.parseInt(values[0])), Double.valueOf(Double.parseDouble(values[1])));
}
}
catch (final Exception e)
{
e.printStackTrace();
}
final Double mapValue = rulesetCommonTrueConcept.get(Integer.valueOf(rulesetID));
final double avgCommonTrueConcepts = (mapValue == null) ? 0.0 : mapValue.doubleValue();
return avgCommonTrueConcepts;
}
//-------------------------------------------------------------------------
/**
* @param newCompletion The new completion computed
* @return True if this new completion is in the history list.
*/
public boolean historyContainIds(final Completion newCompletion)
{
final TIntArrayList idsUsedNewRecons = newCompletion.idsUsed();
for(final Completion completion: history)
{
final TIntArrayList idsUsed = completion.idsUsed();
if(idsUsed.size() == idsUsedNewRecons.size())
{
boolean equalIds = true;
for(int i = 0; i < idsUsed.size(); i++)
{
if(idsUsed.get(i) != idsUsedNewRecons.get(i))
{
equalIds = false;
break;
}
}
if(equalIds)
return true;
}
}
return false;
}
/** To update the list of luds to use for recons after each update of the threshold.*/
public void applyThresholdToLudMap(final int rulesetReconId)
{
// The map used according to the thresholds.
ludMapUsed = new HashMap<Integer, String>();
// A temporary map used only in this method to do not waste time to look at the geo threshold if the score threshold can not get any rulesets to recons.
final Map<Integer, String> ludMapUsedWithoutGeo = new HashMap<Integer, String>();
do
{
for (final Map.Entry<Integer, String> entry : ludMap.entrySet())
{
final int rulesetId = entry.getKey().intValue();
double culturalSimilarity = 0.0;
double conceptualSimilarity = 0.0;
double geoSimilarity = 0.0;
if(rulesetReconId == -1) // We do not use the CSN.
culturalSimilarity = 1.0;
else
{
final String similaryFilePath = ContextualSimilarity.rulesetContextualiserFilePath;
final File fileSimilarity1 = new File(similaryFilePath + rulesetReconId + ".csv");
final File fileSimilarity2 = new File(similaryFilePath + entry.getKey().intValue() + ".csv");
if(!fileSimilarity1.exists() || !fileSimilarity2.exists() || (rulesetReconId == rulesetId)) // If CSN not computing or comparing the same rulesets, similarity is 0.
culturalSimilarity = 0.0;
else
culturalSimilarity = DistanceUtils.getRulesetCSNDistance(rulesetId, rulesetReconId);
//System.out.println("Id = " + rulesetId + " Other Id = " + rulesetReconId + " CSN Value = " + DistanceUtils.getRulesetCSNDistance(rulesetId, rulesetReconId));
if(!fileSimilarity1.exists() || !fileSimilarity2.exists() || (rulesetReconId == rulesetId)) // If Geo not computing or comparing the same rulesets, similarity is 0.
geoSimilarity = 0.0;
else
geoSimilarity = getRulesetGeoDistance(rulesetId);
conceptualSimilarity = getAVGCommonExpectedConcept(rulesetReconId, rulesetId);
}
// We ignore all the ludemes coming from a negative similarity value or 0.
if(culturalSimilarity <= 0)
continue;
// We ignore all the ludemes coming from a negative similarity value or 0.
if(geographicalWeight != 0 && geoSimilarity <= 0)
continue;
final double score = historicalWeight * culturalSimilarity + conceptualWeight * conceptualSimilarity + geographicalWeight * geoSimilarity;
if(geoThreshold == -1)
{
if(score >= threshold)
{
ludMapUsed.put(entry.getKey(), entry.getValue());
ludMapUsedWithoutGeo.put(entry.getKey(), entry.getValue());
}
}
else
{
if(score >= threshold && geoSimilarity >= geoThreshold)
{
//System.out.println("score = " + score + " geoScore = " + geoSimilarity);
ludMapUsed.put(entry.getKey(), entry.getValue());
}
if(score >= threshold)
ludMapUsedWithoutGeo.put(entry.getKey(), entry.getValue());
}
}
if(ludMapUsedWithoutGeo.isEmpty())
{
threshold = threshold - 0.01;
geoThreshold = 0.99;
System.out.println("new threshold = " + threshold + " new geoThreshold = " + geoThreshold);
}
} while(ludMapUsedWithoutGeo.isEmpty());
System.out.println("num Rulesets used to recons = " + ludMapUsed.size());
}
/**
* @return Geo distance between two rulesetIds
*/
public static double getRulesetGeoDistance(final int rulesetId2)
{
final Double geoSimilarity = allRulesetGeoSimilarities.get(Integer.valueOf(rulesetId2));
return geoSimilarity != null ? geoSimilarity.doubleValue() : 0.0;
}
}
| 35,799 | 30.02253 | 223 |
java
|
Ludii
|
Ludii-master/Mining/src/reconstruction/output/UpdateGameRulesetsTable.java
|
package reconstruction.output;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import compiler.Compiler;
import game.Game;
import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.grammar.Description;
/**
* To generate the new lines to add to GameRulesets Table with the outcome rulesets from the reconstruction process.
* @author Eric.Piette
*/
public class UpdateGameRulesetsTable
{
// Load ruleset avg common true concepts from specific directory.
final static String gameRulesetsFilePath = "./res/recons/input/GameRulesets.csv";
// The rulesets reconstructed.
final static String pathReconstructed = "./res/recons/output/";
// The game name.
final static String gameName = "Shatranj (Egypt)";
// The precision of the double to use.
final static int DOUBLE_PRECISION = 5;
//-------------------------------------------------------------------------
/**
* Main method.
* @param args
*/
public static void main(final String[] args)
{
final int nextId = 1 + getMaxId();
updateGameRulesets(nextId);
}
/**
* Generate the new lines to add to GameRulesets.csv with the new rulesets.
* @param nextId The next id to use.
*/
private static void updateGameRulesets(int nextId)
{
final String pathReportReconstrution = pathReconstructed + gameName + ".csv";
final String pathFolderReconstrutions = pathReconstructed + gameName + "/";
final List<String> rulesetNameList = new ArrayList<String>();
final TIntArrayList idReconsList = new TIntArrayList();
final TDoubleArrayList scoreList = new TDoubleArrayList();
final TDoubleArrayList similaryScoreList = new TDoubleArrayList();
final TDoubleArrayList conceptualScoreList = new TDoubleArrayList();
final TDoubleArrayList geographicalScoreList = new TDoubleArrayList();
final List<String> idsUsedList = new ArrayList<String>();
final List<String> otherIdsList = new ArrayList<String>();
final List<String> toEnglishList = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(pathReportReconstrution)))
{
String line = br.readLine();
while (line != null)
{
String lineNoQuote = line.replaceAll(Pattern.quote("\""), "");
int separatorIndex = lineNoQuote.indexOf(',');
final String rulesetName = lineNoQuote.substring(0, separatorIndex);
lineNoQuote = lineNoQuote.substring(rulesetName.length() + 1);
rulesetNameList.add(rulesetName);
separatorIndex = lineNoQuote.indexOf(',');
final String idReconsStr = lineNoQuote.substring(0, separatorIndex);
idReconsList.add(Integer.parseInt(idReconsStr));
lineNoQuote = lineNoQuote.substring(idReconsStr.length() + 1);
separatorIndex = lineNoQuote.indexOf(',');
String scoreStr = lineNoQuote.substring(0, separatorIndex);
scoreList.add(Double.parseDouble(scoreStr.length() > DOUBLE_PRECISION ? scoreStr.substring(0, DOUBLE_PRECISION) : scoreStr));
lineNoQuote = lineNoQuote.substring(scoreStr.length() + 1);
separatorIndex = lineNoQuote.indexOf(',');
String similarityScoreStr = lineNoQuote.substring(0, separatorIndex);
similaryScoreList.add(Double.parseDouble(similarityScoreStr.length() > DOUBLE_PRECISION ? similarityScoreStr.substring(0, DOUBLE_PRECISION) : similarityScoreStr));
lineNoQuote = lineNoQuote.substring(similarityScoreStr.length() + 1);
separatorIndex = lineNoQuote.indexOf(',');
String culturalScoreStr = lineNoQuote.substring(0, separatorIndex);
conceptualScoreList.add(Double.parseDouble(culturalScoreStr.length() > DOUBLE_PRECISION ? culturalScoreStr.substring(0, DOUBLE_PRECISION) : culturalScoreStr));
lineNoQuote = lineNoQuote.substring(culturalScoreStr.length() + 1);
separatorIndex = lineNoQuote.indexOf(',');
String geographicalScoreStr = lineNoQuote.substring(0, separatorIndex);
geographicalScoreList.add(Double.parseDouble(geographicalScoreStr.length() > DOUBLE_PRECISION ? geographicalScoreStr.substring(0, DOUBLE_PRECISION) : geographicalScoreStr));
lineNoQuote = lineNoQuote.substring(geographicalScoreStr.length() + 1);
separatorIndex = lineNoQuote.indexOf('}') + 1 ;
String ids = lineNoQuote.substring(1, separatorIndex - 1);
idsUsedList.add(ids);
lineNoQuote = lineNoQuote.substring(ids.length() + 3);
final String otherIds = lineNoQuote.substring(0, lineNoQuote.length());
otherIdsList.add(otherIds);
final String pathReconstruction = pathFolderReconstrutions + rulesetName + ".lud";
String desc = FileHandling.loadTextContentsFromFile(pathReconstruction);
final Game game = (Game) Compiler.compileTest(new Description(desc), false);
toEnglishList.add(game.toEnglish(game));
line = br.readLine();
}
br.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
final String output = "GameRulesets.csv";
// Write the new CSV.
try (final PrintWriter writer = new UnixPrintWriter(new File(output), "UTF-8"))
{
for(int i = 0; i < rulesetNameList.size(); i++)
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add("\"" + (nextId + i) + "\"");
lineToWrite.add("\"" + getGameReconsId(idReconsList.get(i)) + "\"");
lineToWrite.add("\"" + rulesetNameList.get(i) + "\"");
lineToWrite.add("NULL");
lineToWrite.add("\"Reconstructed with Ludii\"");
lineToWrite.add("\"2\"");
lineToWrite.add("NULL");
lineToWrite.add("\"" + toEnglishList.get(i) + "\"");
lineToWrite.add("NULL");
lineToWrite.add("NULL");
lineToWrite.add("NULL");
lineToWrite.add("NULL");
lineToWrite.add("NULL");
lineToWrite.add("NULL");
lineToWrite.add("NULL");
lineToWrite.add("\"0\"");
lineToWrite.add("NULL");
lineToWrite.add("\"0\"");
lineToWrite.add("\"0\"");
lineToWrite.add("\"" + scoreList.get(i) + "\"");
lineToWrite.add("\"" + similaryScoreList.get(i) + "\"");
lineToWrite.add("\"" + conceptualScoreList.get(i) + "\"");
lineToWrite.add("\"" + geographicalScoreList.get(i) + "\"");
lineToWrite.add("\"" + idsUsedList.get(i) + "\"");
lineToWrite.add("\"" + otherIdsList.get(i) + "\"");
writer.println(StringRoutines.join(",", lineToWrite));
}
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (UnsupportedEncodingException e1)
{
e1.printStackTrace();
}
System.out.println("GameRulesets CSV Updated");
}
/**
* @return the max id of the rulesets
*/
private static int getMaxId()
{
// ids of the rulesets
final TIntArrayList ids = new TIntArrayList();
try (BufferedReader br = new BufferedReader(new FileReader(gameRulesetsFilePath)))
{
String line; // column names
while ((line = br.readLine()) != null)
{
if(line.length() > 2 && line.charAt(0) == '"' && Character.isDigit(line.charAt(1)))
{
final String subLine = line.substring(1);
int i = 0;
char c = subLine.charAt(i);
while(c != '"')
{
i++;
c = subLine.charAt(i);
}
ids.add(Integer.parseInt(subLine.substring(0,i)));
}
}
}
catch (final Exception e)
{
e.printStackTrace();
}
return ids.max();
}
/**
* @return the id of the game to recons.
*/
private static int getGameReconsId(final int reconsRulesetId)
{
try (BufferedReader br = new BufferedReader(new FileReader(gameRulesetsFilePath)))
{
String line; // column names
while ((line = br.readLine()) != null)
{
if(line.length() > 2 && line.charAt(0) == '"' && Character.isDigit(line.charAt(1)))
{
String subLine = line.substring(1);
int i = 0;
char c = subLine.charAt(i);
while(c != '"')
{
i++;
c = subLine.charAt(i);
}
final int rulesetId = Integer.parseInt(subLine.substring(0, i));
if(rulesetId == reconsRulesetId)
{
subLine = subLine.substring(i+3);
i = 0;
c = subLine.charAt(i);
while(c != '"')
{
i++;
c = subLine.charAt(i);
}
return Integer.parseInt(subLine.substring(0, i));
}
}
}
}
catch (final Exception e)
{
e.printStackTrace();
}
return Constants.UNDEFINED;
}
}
| 8,745 | 32.899225 | 177 |
java
|
Ludii
|
Ludii-master/Mining/src/reconstruction/output/UpdateReconsGame.java
|
package reconstruction.output;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import main.FileHandling;
import main.UnixPrintWriter;
import other.GameLoader;
/**
* Update the GameRulesets Table with the outcome rulesets from the reconstruction process.
* @author Eric.Piette
*/
public class UpdateReconsGame
{
// Load ruleset avg common true concepts from specific directory.
final static String gameRulesetsFilePath = "./res/recons/input/GameRulesets.csv";
// rulesets reconstructed.
final static String pathReconstructed = "./res/recons/output/";
// game name.
final static String gameName = "Shatranj (Egypt)";
public static void main(final String[] args)
{
updateReconsGame();
}
/**
* Generate the new GameRulesets.csv with the new rulesets.
* @param nextId The next id to use.
*/
private static void updateReconsGame()
{
final String pathFolderReconstrutions = pathReconstructed + gameName + "/";
// Get the current description of the game to reconstruct.
final String[] choices = FileHandling.listGames();
String desc = "";
for (final String fileName : choices)
{
if (!fileName.replaceAll(Pattern.quote("\\"), "/").contains(gameName))
continue;
String path = fileName.replaceAll(Pattern.quote("\\"), "/");
path = path.substring(path.indexOf("/lud/"));
String line;
try
(
final InputStream in = GameLoader.class.getResourceAsStream(path);
final BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
)
{
while ((line = rdr.readLine()) != null)
desc += line + "\n";
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
//System.out.println(desc);
String temp = desc;
final String separation = "//------------------------------------------------------------------------------";
final String beforeOptions = temp.substring(0, temp.indexOf("(option"));
temp = temp.substring(temp.indexOf("(option"));
int countParenthesis = 0;
int indexChar = 0;
for(; indexChar < temp.length(); indexChar++)
{
if(temp.charAt(indexChar) == '(')
countParenthesis++;
else
if(temp.charAt(indexChar) == ')')
countParenthesis--;
if(countParenthesis == 0)
break;
}
String options = temp.substring(0, indexChar+1);
//System.out.println(options);
temp = temp.substring(temp.indexOf("(rulesets"));
countParenthesis = 0;
indexChar = 0;
for(; indexChar < temp.length(); indexChar++)
{
if(temp.charAt(indexChar) == '(')
countParenthesis++;
else
if(temp.charAt(indexChar) == ')')
countParenthesis--;
if(countParenthesis == 0)
break;
}
final String rulesets = temp.substring(0, indexChar+1);
final String metadata = temp.substring(temp.indexOf("(metadata"));
//System.out.println(rulesets);
File folder = new File(pathFolderReconstrutions);
File[] listOfFiles = folder.listFiles();
// We sort the files by number.
List<File> recons = new ArrayList<File>();
for (int i = 0; i < listOfFiles.length; i++)
recons.add(listOfFiles[i]);
Collections.sort(recons, (r1, r2) -> extractInt(r1.getName()) < extractInt(r2.getName()) ? -1 : extractInt(r1.getName()) > extractInt(r2.getName()) ? 1 : 0);
// We update the rulesets and options
final StringBuffer newRulesets = new StringBuffer("(rulesets {\n");
final StringBuffer newOptions = new StringBuffer("(option \"Variant\" <Variant> args:{ <variant> }\n{\n");
for (int i = 0; i < recons.size(); i++) {
final String reconsName = recons.get(i).getName().substring(0,recons.get(i).getName().length()-4); // 4 is the ".lud"
// Update the rulesets list.
final String rulesetToAdd = "\n(ruleset \"Ruleset/" + reconsName + " (Reconstructed)\" {\n \"Variant/"+reconsName+"\"\n})";
newRulesets.append(rulesetToAdd);
// Get the description of the recons.
final StringBuffer descReconsBuffer = new StringBuffer("");
try (BufferedReader br = new BufferedReader(new FileReader(pathFolderReconstrutions + reconsName + ".lud")))
{
String line = br.readLine();
while (line != null)
{
descReconsBuffer.append(line+"\n");
line = br.readLine();
}
br.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
String descRecons = descReconsBuffer.toString();
// Remove the metadata if it is there
if(descRecons.contains("(metadata"))
descRecons = descRecons.substring(0, descRecons.indexOf("(metadata"));
// Remove the last closing parenthesis
descRecons = descRecons.substring(0, descRecons.lastIndexOf(')'));
// Remove the first line with the (game "...)
descRecons = descRecons.substring(8 + gameName.length());
// Compute the option to add to the list of option
final String optionToAdd = "(item \""+reconsName+"\" <\n" + descRecons + "\n > \"The " + reconsName + " ruleset.\")\n\n";
newOptions.append(optionToAdd);
}
newRulesets.append(rulesets.substring(rulesets.indexOf("(rulesets {") + 11) + "\n\n");
int countCurlyBracket = 0;
indexChar = 0;
for(; indexChar < options.length(); indexChar++)
{
if(options.charAt(indexChar) == '{')
countCurlyBracket++;
if(countCurlyBracket == 2)
break;
}
options = options.substring(indexChar+1);
options = options.substring(0,options.length() - 2);
newOptions.append(options);
newOptions.append("\n })");
final String newFileContent = beforeOptions + newOptions.toString() + "\n\n" + separation + "\n\n" + newRulesets.toString() + separation + "\n\n " + metadata;
//System.out.println(newFileContent);
// Write the file.
final String output = gameName + ".lud";
try (final PrintWriter writer = new UnixPrintWriter(new File(output), "UTF-8"))
{
writer.println(newFileContent);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (UnsupportedEncodingException e1)
{
e1.printStackTrace();
}
System.out.println("New " + gameName + ".lud generated." );
}
//-------------------------------------------------------------------------
/**
* @param s The input string.
* @return The digits in a string.
*/
private static int extractInt(String s) {
String num = s.replaceAll("\\D", "");
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
}
| 6,681 | 29.372727 | 160 |
java
|
Ludii
|
Ludii-master/Mining/src/reconstruction/preprocessing/ComputeCommonExpectedConcepts.java
|
package reconstruction.preprocessing;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import compiler.Compiler;
import game.Game;
import grammar.Grammar;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.grammar.Description;
import main.grammar.Report;
import main.grammar.Symbol;
import main.options.Ruleset;
import other.GameLoader;
import other.concept.Concept;
import reconstruction.completer.CompleterWithPrepro;
/**
* Compute the average of common expected concepts between each reconstruction and each complete rulesets.
* @author Eric.Piette
*/
public class ComputeCommonExpectedConcepts
{
/**
* Generate the CSVs with the common expected concepts between each reconstruction and the complete rulesets.
*/
public static void generateCSVs()
{
System.out.println("Compute average common expected concepts between reconstruction and rulesets.");
// Compute % Common Expected Concepts in each complete ruleset.
final String[] gameNames = FileHandling.listGames();
final Map<Integer, BitSet> conceptsNonBoolean = new HashMap<Integer, BitSet>();
// Get the concepts of all complete description for each ruleset.
for (int index = 0; index < gameNames.length; index++)
{
final String nameGame = gameNames[index];
if (nameGame.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (nameGame.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (nameGame.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (nameGame.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (nameGame.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (nameGame.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction"))
continue;
final Game game = GameLoader.loadGameFromName(nameGame);
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Code for games with many rulesets
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty()) // We check if the ruleset is implemented.
{
final Game rulesetGame = GameLoader.loadGameFromName(nameGame, ruleset.optionSettings());
final List<String> ids = rulesetGame.metadata().info().getId();
if(ids == null || ids.isEmpty())
continue;
final int id = Integer.parseInt(ids.get(0));
final BitSet concepts = rulesetGame.booleanConcepts();
conceptsNonBoolean.put(Integer.valueOf(id), concepts);
System.out.println("id = " + id + " Done.");
}
}
}
else // Code for games with a single ruleset.
{
final List<String> ids = game.metadata().info().getId();
if(ids == null || ids.isEmpty())
continue;
final int id = Integer.parseInt(ids.get(0));
final BitSet concepts = game.booleanConcepts();
conceptsNonBoolean.put(Integer.valueOf(id), concepts);
System.out.println("id = " + id + " Done.");
}
}
System.out.println("Start compute Common Expected concepts for recons description.");
// Check each recons description.
final String[] choices = FileHandling.listGames();
for (final String fileName : choices)
{
if (!fileName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/"))
continue;
final String gameName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length() - 4);
//System.out.println("TEST: " + gameName);
String path = fileName.replaceAll(Pattern.quote("\\"), "/");
path = path.substring(path.indexOf("/lud/"));
String desc = "";
String line;
try
(
final InputStream in = GameLoader.class.getResourceAsStream(path);
final BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
)
{
while ((line = rdr.readLine()) != null)
desc += line + "\n";
}
catch (final IOException e1)
{
e1.printStackTrace();
}
final String metadata = desc.contains("(metadata") ? desc.substring(desc.indexOf("(metadata")) : "";
String idStr = metadata.contains("(id") ? metadata.substring(metadata.indexOf("(id")+ 5) : "";
idStr = idStr.substring(0, idStr.indexOf(')')-1);
final int idRulesetToRecons = Integer.valueOf(idStr).intValue();
// Get game description from resource
System.out.println("Game: " + gameName + " id = " + idRulesetToRecons);
final List<Concept> commonExpectedConcepts = computeCommonExpectedConcepts(desc);
final String beginOutput = "CommonExpectedConcept_";
final String endOutput = ".csv";
try (final PrintWriter writer = new UnixPrintWriter(new File(beginOutput + idRulesetToRecons + endOutput), "UTF-8"))
{
for (final Map.Entry<Integer, BitSet> entry : conceptsNonBoolean.entrySet())
{
final int rulesetId = entry.getKey().intValue();
final BitSet conceptsRuleset = entry.getValue();
int countCommonConcepts = 0;
for(Concept concept: commonExpectedConcepts)
if(conceptsRuleset.get(concept.id()))
countCommonConcepts++;
final double avgCommonConcepts = commonExpectedConcepts.size() == 0 ? 0.0 : ((double) countCommonConcepts / (double) commonExpectedConcepts.size());
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(rulesetId+"");
lineToWrite.add(avgCommonConcepts+"");
writer.println(StringRoutines.join(",", lineToWrite));
// System.out.println("id = " + rulesetId);
// System.out.println("% Common Expected Concepts = " + avgCommonConcepts);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
System.out.println("CommonExpectedConcepts CSVs Generated");
}
//-----------------------------------------------------------------------------
/**
* @param desc The reconstruction description of the game.
* @return The list of concepts which are sure to be true for a reconstruction description.
*/
public static List<Concept> computeCommonExpectedConcepts(final String desc)
{
final List<Concept> commonExpectedConcepts = new ArrayList<Concept>();
// Keep only the game description.
String descNoMetadata = desc.substring(0,desc.lastIndexOf("(metadata"));
descNoMetadata = descNoMetadata.substring(0, descNoMetadata.lastIndexOf(')') + 1);
Description description = new Description(descNoMetadata);
CompleterWithPrepro.expandRecons(description, "");
descNoMetadata = description.expanded();
// Get all the ludemeplexes between parenthesis.
final List<String> ludemeplexes = new ArrayList<String>();
for(int i = 0; i < descNoMetadata.length(); i++)
{
final char c = descNoMetadata.charAt(i);
if(c == '(')
{
int countParenthesis = 1;
int indexCorrespondingParenthesis = i + 1;
for(; indexCorrespondingParenthesis < descNoMetadata.length(); indexCorrespondingParenthesis++)
{
if(descNoMetadata.charAt(indexCorrespondingParenthesis) == '(')
countParenthesis++;
else
if(descNoMetadata.charAt(indexCorrespondingParenthesis) == ')')
countParenthesis--;
if(countParenthesis == 0)
{
indexCorrespondingParenthesis++;
break;
}
}
final String ludemeplex = descNoMetadata.substring(i, indexCorrespondingParenthesis);
// We keep the ludemeplexes with no completion point.
if(!ludemeplex.contains("#") && !ludemeplex.contains("[") && !ludemeplex.contains("]"))
ludemeplexes.add(ludemeplex);
}
}
// Get the common concepts.
for(String ludemeplex : ludemeplexes)
{
for(Concept concept: getCommonExpectedConcepts(ludemeplex))
{
if(!commonExpectedConcepts.contains(concept))
commonExpectedConcepts.add(concept);
}
}
return commonExpectedConcepts;
}
//----------------------CODE TO GET THE CONCEPTS OF A STRING (TO MOVE TO ANOTHER CLASS LATER)------------------------------------
/**
* @param str The description of the ludemeplex.
* @return The common expected concepts of the ludemeplex.
*/
static List<Concept> getCommonExpectedConcepts(final String str)
{
final List<Concept> commonConcepts = new ArrayList<Concept>();
if (str == null || str.equals(""))
return commonConcepts;
try
{
final Object compiledObject = compileString(str);
if (compiledObject != null)
commonConcepts.addAll(evalConceptCompiledObject(compiledObject));
}
catch (final Exception ex)
{
ex.getStackTrace();
// Nothing to do.
}
return commonConcepts;
}
/**
* Attempts to get the concepts from a ludemeplex.
*/
static List<Concept> evalConceptCompiledObject(final Object obj)
{
// Default Game description to make the compiler happy, but not used except for this.
final Game tempGame = (Game)Compiler.compileTest(new Description("(game \"Test\" (players 2) (equipment { (board (square 3)) "
+ " (piece \"Disc\" Each) }) (rules (play (move Add (to "
+ " (sites Empty)))) (end (if (is Line 3) (result Mover Win)))))"), false);
final List<Concept> commonConcepts = new ArrayList<Concept>();
// Need to preprocess the ludemes before to call the eval method.
Method preprocess = null;
try
{
preprocess = obj.getClass().getDeclaredMethod("preprocess", tempGame.getClass());
if (preprocess != null)
preprocess.invoke(obj, tempGame);
}
catch (final Exception e)
{
// Nothing to do.
//e.printStackTrace();
}
// get the concepts by reflection.
Method conceptMethod = null;
BitSet concepts = new BitSet();
try
{
conceptMethod = obj.getClass().getDeclaredMethod("concepts", tempGame.getClass());
if (conceptMethod != null)
concepts = ((BitSet) conceptMethod.invoke(obj, tempGame));
}
catch (final Exception e)
{
// Nothing to do.
//e.printStackTrace();
}
for (int i = 0; i < Concept.values().length; i++)
{
final Concept concept = Concept.values()[i];
if (concepts.get(concept.id()))
commonConcepts.add(concept);
}
return commonConcepts;
}
/**
* Attempts to compile a given string for every possible symbol class.
* @return Compiled object if possible, else null.
*/
static Object compileString(final String str)
{
Object obj = null;
final String token = StringRoutines.getFirstToken(str);
final List<Symbol> symbols = Grammar.grammar().symbolsWithPartialKeyword(token);
// Try each possible symbol for this token
for (final Symbol symbol : symbols)
{
final String className = symbol.cls().getName();
final Report report = new Report();
try
{
obj = Compiler.compileObject(str, className, report);
}
catch (final Exception ex)
{
//System.out.println("Couldn't compile.");
}
if (obj != null)
break;
}
return obj;
}
}
| 11,556 | 31.01385 | 153 |
java
|
Ludii
|
Ludii-master/Mining/src/reconstruction/preprocessing/FormatRulesetAndIdOnOneLine.java
|
package reconstruction.preprocessing;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
/**
* Format all the complete ruleset descriptions on a single line and place them in a CSV.
* @author Eric.Piette
*
*/
public class FormatRulesetAndIdOnOneLine
{
/**
* Generate the CSVs
*/
public static void generateCSV()
{
final String[] gameNames = FileHandling.listGames();
final String output = "RulesetFormatted.csv";
try (final PrintWriter writer = new UnixPrintWriter(new File(output), "UTF-8"))
{
// Look at each ruleset.
for (int index = 0; index < gameNames.length; index++)
{
final String gameName = gameNames[index];
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction"))
continue;
final Game game = GameLoader.loadGameFromName(gameName);
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Get all the rulesets of the game if it has some.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty()) // We check if the ruleset is implemented.
{
final Game rulesetGame = GameLoader.loadGameFromName(gameName, ruleset.optionSettings());
final List<String> ids = rulesetGame.metadata().info().getId();
if(!ids.isEmpty())
{
final String rulesetId = ids.get(0);
System.out.println("Game: " + game.name() + " RulesetName = " + rulesetGame.getRuleset().heading() + " RulesetID = " + rulesetId);
final String formattedDesc = StringRoutines.formatOneLineDesc(rulesetGame.description().expanded());
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(game.name());
lineToWrite.add(rulesetGame.getRuleset().heading());
lineToWrite.add(rulesetId);
lineToWrite.add(formattedDesc);
writer.println(StringRoutines.join(",", lineToWrite));
}
}
}
}
else
{
final List<String> ids = game.metadata().info().getId();
if(!ids.isEmpty())
{
final String rulesetId = ids.get(0);
System.out.println("Game: " + game.name() + " RulesetID = " + rulesetId);
final String formattedDesc = StringRoutines.formatOneLineDesc(game.description().expanded());
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(game.name());
lineToWrite.add("ONLY ONE RULESET");
lineToWrite.add(rulesetId);
lineToWrite.add(formattedDesc);
writer.println(StringRoutines.join(",", lineToWrite));
}
}
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("RulesetFormatted CSV generated");
}
}
| 3,676 | 31.254386 | 138 |
java
|
Ludii
|
Ludii-master/Mining/src/reconstruction/preprocessing/PreProcessReconstruction.java
|
package reconstruction.preprocessing;
/**
* Run the preprocessing steps of the recons process (not the CSN generation).
*
* @author Eric.Piette
*/
public final class PreProcessReconstruction
{
public static void main(final String[] args)
{
System.out.println("********** Generate all the complete ruleset description on a single line **********");
FormatRulesetAndIdOnOneLine.generateCSV();
System.out.println("********** Generate avg true concepts between recons and complete rulesets **********");
ComputeCommonExpectedConcepts.generateCSVs();
}
}
| 569 | 30.666667 | 110 |
java
|
Ludii
|
Ludii-master/Mining/src/reconstruction/utils/FormatReconstructionOutputs.java
|
package reconstruction.utils;
import java.util.ArrayList;
import java.util.List;
import main.StringRoutines;
/**
* Format the generation reconstructions.
* @author Eric.Piette
*/
public class FormatReconstructionOutputs
{
/**
* Nicely indents the description in entry.
*/
public static String indentNicely(final String desc)
{
final String linesArray[] = desc.split("\\r?\\n");
final List<String> lines = new ArrayList<String>();
for (int n = 0; n < linesArray.length; n++)
lines.add(linesArray[n]);
// Left justify all lines
for (int n = 0; n < lines.size(); n++)
{
String str = lines.get(n);
final int c = 0;
while (c < str.length() && (str.charAt(c) == ' ' || str.charAt(c) == '\t'))
str = str.substring(1);
lines.remove(n);
lines.add(n, str);
}
removeDoubleEmptyLines(lines);
indentLines(lines);
final StringBuffer outputDesc = new StringBuffer();
for (final String result : lines)
outputDesc.append(result + "\n");
return outputDesc.toString();
}
/**
* Removes double empty lines.
*/
final static void removeDoubleEmptyLines(final List<String> lines)
{
int n = 1;
while (n < lines.size())
{
if (lines.get(n).equals("") && lines.get(n-1).equals(""))
lines.remove(n);
else
n++;
}
}
/**
* Nicely indents the lines of a desc.
*/
final static void indentLines(final List<String> lines)
{
final String indentString = " ";
int indent = 0;
for (int n = 0; n < lines.size(); n++)
{
String str = lines.get(n);
final int numOpen = StringRoutines.numChar(str, '('); // don't count curly braces!
final int numClose = StringRoutines.numChar(str, ')');
final int difference = numOpen - numClose;
if (difference < 0)
{
// Unindent from this line
indent += difference;
if (indent < 0)
indent = 0;
}
for (int step = 0; step < indent; step++)
str = indentString + str;
lines.remove(n);
lines.add(n, str);
if (difference > 0)
indent += difference; // indent from next line
}
}
}
| 2,438 | 24.14433 | 93 |
java
|
Ludii
|
Ludii-master/Mining/src/skillTraceAnalysis/SkillTraceAnalysis.java
|
package skillTraceAnalysis;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import game.Game;
import main.FileHandling;
import metrics.designer.SkillTrace;
import other.GameLoader;
import other.context.Context;
import other.trial.Trial;
/**
* Calculates the Skill Trace statistics for all games in Ludii.
*
* @author Matthew.Stephenson
*/
public class SkillTraceAnalysis
{
/**
* Main entry point.
*/
public static void main(final String[] args)
{
final SkillTrace skillTraceMetric = new SkillTrace();
skillTraceMetric.setAddToDatabaseFile(true);
// Order all games by their branching factor estimate.
final Map<String,Integer> choicesBranchingFactors = new HashMap<>();
for (final String s : FileHandling.listGames())
{
if (FileHandling.shouldIgnoreLudRelease(s))
continue;
// Load the game and estimate branching factor as the number of legal moves at the start of the game.
final Game game = GameLoader.loadGameFromName(s);
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(game.name() + " BF: " + bf);
choicesBranchingFactors.put(s, Integer.valueOf(bf));
}
final LinkedHashMap<String, Integer> choicesSortedBranchingFactors = new LinkedHashMap<>();
choicesBranchingFactors.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEachOrdered(x -> choicesSortedBranchingFactors.put(x.getKey(), x.getValue()));
final Set<String> choicesSorted = choicesSortedBranchingFactors.keySet();
// Record games that have already been done, and should not be redone.
final List<String> gameNamesAlreadyDone = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(skillTraceMetric.combinedResultsOutputPath()), "UTF-8")))
{
while (true)
{
final String line = reader.readLine();
if (line == null)
{
break;
}
final String gameName = line.split(",")[0];
gameNamesAlreadyDone.add(gameName);
}
}
catch (final Exception e)
{
e.printStackTrace();
}
// Calculate skill trace metrics for all games (in order of branching factor) that haven't already been done.
for (final String s : choicesSorted)
{
final Game game = GameLoader.loadGameFromName(s);
if (gameNamesAlreadyDone.contains(game.name()))
{
System.out.println("\n------------");
System.out.println(game.name() + " skipped");
continue;
}
System.out.println("\n------------");
System.out.println(game.name());
skillTraceMetric.apply(game, null, null, null);
}
}
}
| 2,874 | 29.263158 | 164 |
java
|
Ludii
|
Ludii-master/Mining/src/translate/TranslateToSwedish.java
|
package translate;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import main.UnixPrintWriter;
/**
* Code to add a Swedish description to all the games in the Games table.
* @author Eric.Piette
*/
public class TranslateToSwedish
{
final static String defaultInputPath = "./res/Games.csv";
public static void main(String[] args) throws IOException {
// Read the CSV line by line.
final List<String> CSVlines = new ArrayList<String>();
StringBuffer tempLine = new StringBuffer();
try (BufferedReader br = new BufferedReader(new FileReader(defaultInputPath)))
{
String line = br.readLine();
while (line != null)
{
// System.out.println(line);
// System.out.println("OTHER LINE");
if(line.length() > 2 && line.charAt(0) == '"' && Character.isDigit(line.charAt(1)))
{
if(!tempLine.toString().isEmpty())
CSVlines.add(tempLine.toString());
tempLine= new StringBuffer("");
}
tempLine.append(line);
line = br.readLine();
}
CSVlines.add(tempLine.toString());
}
// Translate all the description from English to Swedish.
final List<String> swedishDescriptions = new ArrayList<String>();
for(int i = 1; i < CSVlines.size(); i++)
{
String csvLine = CSVlines.get(i);
boolean inQuote = false;
int numColumn = 0;
StringBuffer descriptionBuffer = new StringBuffer("");
for(int c = 0; c < csvLine.length(); c++)
{
char ch = csvLine.charAt(c);
if(ch == '"')
inQuote = !inQuote;
if(ch == ',' && !inQuote)
numColumn++;
else
if(numColumn == 3)
descriptionBuffer.append(ch);
if(numColumn == 4)
break;
}
final String description = descriptionBuffer.toString().substring(1, descriptionBuffer.toString().length()-1);
String descriptionSwedish = translate("en", "sv", description);
descriptionSwedish = descriptionSwedish.replaceAll("""", "\"\"");
descriptionSwedish = descriptionSwedish.replaceAll(""", "\"\"");
swedishDescriptions.add(descriptionSwedish);
System.out.println("Line " + i + " done.");
}
final String output = "Games.csv";
// Write the new CSV.
try (final PrintWriter writer = new UnixPrintWriter(new File(output), "UTF-8"))
{
writer.println(CSVlines.get(0));
for(int i = 1; i < CSVlines.size(); i++)
{
writer.print(CSVlines.get(i).substring(0, CSVlines.get(i).length() - 4));
writer.println("\"" + swedishDescriptions.get(i-1) + "\"");
}
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (UnsupportedEncodingException e1)
{
e1.printStackTrace();
}
}
/**
* Translate any String to another language.
* @param langFrom The language from.
* @param langTo the language to.
* @param text The string to translate.
* @return The translated string.
* @throws IOException
*/
private static String translate(String langFrom, String langTo, String text) throws IOException {
// INSERT YOU URL HERE
String urlStr = "https://script.google.com/macros/s/AKfycbxohIwAG-uJMG864Rc_yoDkZvJhJe3vpxcWSGNomLC62LNK1xaY89-UU2b7RddEYq8HXA/exec" +
"?q=" + URLEncoder.encode(text, "UTF-8") +
"&target=" + langTo +
"&source=" + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
@SuppressWarnings("resource")
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
| 4,141 | 30.861538 | 142 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/DBGameInfo.java
|
package utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import game.Game;
import main.options.Ruleset;
/**
* Gets the unique name representation for a given game object (including ruleset name).
*
* @author Matthew.Stephenson
*/
public class DBGameInfo
{
// SQL command to update this file located in the same directory
private static String rulesetIdsInputFilePath = "./res/concepts/input/GameRulesets.csv";
// Cached version of ruleset-Id information.
private static Map<String, Integer> rulesetIds = null;
//-------------------------------------------------------------------------
/**
* @param game
* @return the unique name representation for a given game object (including ruleset name).
*/
public static String getUniqueName(final Game game)
{
final String gameName = game.name();
String rulesetName = "";
if (game.getRuleset() != null && game.description().rulesets().size() > 1)
{
final Ruleset ruleset = game.getRuleset();
final String startString = "Ruleset/";
rulesetName = ruleset.heading().substring(startString.length(), ruleset.heading().lastIndexOf('(') - 1);
}
String gameRulesetName = gameName + "-" + rulesetName;
gameRulesetName = gameRulesetName.replace(" ", "_").replaceAll("[\"',()]", "");
return gameRulesetName;
}
//-------------------------------------------------------------------------
public static Map<String, Integer> getRulesetIds()
{
return getRulesetIds(rulesetIdsInputFilePath);
}
/**
* @return a Map giving the DB Id for each ruleset in the database (names in same format as getUniqueName)
*/
public static Map<String, Integer> getRulesetIds(final String filePath)
{
if (rulesetIds == null)
{
final Map<String, Integer> rulesetNameIdPairs = new HashMap<>();
final List<String[]> allLines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
String line;
while ((line = br.readLine()) != null)
{
final String[] values = line.split(",");
allLines.add(values);
}
}
catch (final Exception e1)
{
e1.printStackTrace();
}
for (final String[] line : allLines)
{
final String gameName = line[0];
final String rulesetName = line[1];
final Integer Id = Integer.valueOf(line[2].replace("\"", ""));
// If game name occurs more than ones, then add ruleset name.
int gameCounter = 0;
for (final String[] checkLine : allLines)
if (checkLine[0].equals(gameName))
gameCounter++;
String gameRulesetName = gameName + "-";
if (gameCounter > 1)
gameRulesetName = gameName + "-" + rulesetName;
gameRulesetName = gameRulesetName.replace(" ", "_").replaceAll("[\"',()]", "");
rulesetNameIdPairs.put(gameRulesetName, Id);
}
rulesetIds = rulesetNameIdPairs;
}
return rulesetIds;
}
//-------------------------------------------------------------------------
/**
* @return The DB Id for a the ruleset in the database corresponding to a given Game object.
*/
public static Integer getRulesetId(final Game game)
{
return getRulesetIds().get(getUniqueName(game));
}
//-------------------------------------------------------------------------
}
| 3,501 | 27.942149 | 107 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/ExportGameType.java
|
package utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.regex.Pattern;
import game.Game;
import game.types.state.GameType;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import other.GameLoader;
/**
* Method to create a csv file listing all the GameTypes used by each game.
*
* @author Eric Piette
*/
public class ExportGameType
{
/**
* Main method
*
* @param args
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(final String[] args) throws IllegalArgumentException, IllegalAccessException
{
try (final PrintWriter writer = new UnixPrintWriter(new File("./res/concepts/output/LudiiGameFlags.csv"),
"UTF-8"))
{
final Field[] fields = GameType.class.getFields();
final String[] flags = new String[fields.length];
final long[] flagsValues = new long[fields.length];
for (int i = 0; i < fields.length; i++)
{
flags[i] = fields[i].toString();
flags[i] = flags[i].substring(flags[i].lastIndexOf('.') + 1);
flagsValues[i] = fields[i].getLong(GameType.class);
}
final String[] headers = new String[flags.length + 1];
headers[0] = "Game Name";
for (int i = 0; i < flags.length; i++)
headers[i + 1] = flags[i];
// Write header line
writer.println(StringRoutines.join(",", headers));
final String[] gameNames = FileHandling.listGames();
for (final String gameName : gameNames)
{
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
System.out.println("Loading game: " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
final String flagsOn[] = new String[flags.length + 1];
flagsOn[0] = game.name();
for (int i = 0; i < flagsValues.length; i++)
{
if ((game.gameFlags() & flagsValues[i]) != 0L)
flagsOn[i + 1] = "Yes";
else
flagsOn[i + 1] = "";
}
// Write row for this game
writer.println(StringRoutines.join(",", flagsOn));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
| 2,557 | 26.212766 | 107 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/IdRuleset.java
|
package utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import main.options.Ruleset;
import utils.concepts.db.ExportDbCsvConcepts;
/**
* To get the id from the db for a game object compiled with a ruleset.
*
* @author Eric.Piette
*/
public class IdRuleset
{
/** The path of the csv with the id of the rulesets for each game. */
private static final String GAME_RULESET_PATH = "/concepts/input/GameRulesets.csv";
/**
* @param game The game object.
* @return The id from the csv exported from the db.
*/
public static int get(final Game game)
{
final List<String> gameNames = new ArrayList<String>();
final List<String> rulesetsNames = new ArrayList<String>();
final TIntArrayList ids = new TIntArrayList();
String rulesetName = null;
try
(
final InputStream in = ExportDbCsvConcepts.class.getResourceAsStream(GAME_RULESET_PATH);
final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
)
{
String line = reader.readLine();
while (line != null)
{
String lineNoQuote = line.replaceAll(Pattern.quote("\""), "");
int separatorIndex = lineNoQuote.indexOf(',');
final String gameName = lineNoQuote.substring(0, separatorIndex);
gameNames.add(gameName);
lineNoQuote = lineNoQuote.substring(gameName.length() + 1);
separatorIndex = lineNoQuote.indexOf(',');
rulesetName = lineNoQuote.substring(0, separatorIndex);
rulesetsNames.add(rulesetName);
lineNoQuote = lineNoQuote.substring(rulesetName.length() + 1);
final int id = Integer.parseInt(lineNoQuote);
ids.add(id);
// System.out.println(gameName + " --- " + rulesetName + " --- " + id);
line = reader.readLine();
}
reader.close();
final Ruleset ruleset = game.getRuleset();
rulesetName = (ruleset == null) ? null : ruleset.heading();
if (rulesetName == null)
{
for (int i = 0; i < gameNames.size(); i++)
if (gameNames.get(i).equals(game.name()))
return ids.get(i);
}
else
{
final String name_ruleset = ruleset.heading();
final String startString = "Ruleset/";
final String name_ruleset_csv = name_ruleset.substring(startString.length(),
ruleset.heading().lastIndexOf('(') - 1);
for (int i = 0; i < gameNames.size(); i++)
if (gameNames.get(i).equals(game.name()) && rulesetsNames.get(i).equals(name_ruleset_csv))
return ids.get(i);
}
}
catch (final IOException e)
{
e.printStackTrace();
}
catch (final NullPointerException e)
{
System.err.println("Try cleaning your Eclipse projects!");
e.printStackTrace();
}
System.err.println("NOT FOUND");
System.err.println("gameName = " + game.name());
System.err.println("rulesetName = " + rulesetName);
return Constants.UNDEFINED;
}
}
| 3,023 | 27.8 | 95 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/RulesetNames.java
|
package utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.options.Ruleset;
/**
* Helper class to extract standardised (game+ruleset) names from Game objects,
* following this format:
*
* - Amazons_Default
* - Asalto_Asalto
* - Alquerque_Murray
*
* @author Dennis Soemers
*/
public class RulesetNames
{
//-------------------------------------------------------------------------
/**
* Filepath for our CSV file. Since this only works with access to private repo
* anyway, the filepath has been hardcoded for use from Eclipse.
*
* This would usually be private and final, but making it public and non-final
* is very useful for editing the filepath when running on cluster (where LudiiPrivate
* is not available).
*/
public static String FILEPATH = "../../Ludii/Mining/res/concepts/input/GameRulesets.csv";
/** List of game names loaded from CSV */
private static List<String> gameNames = null;
/** List of ruleset names loaded from CSV */
private static List<String> rulesetNames = null;
//-------------------------------------------------------------------------
/**
* No constructor
*/
private RulesetNames()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* @param game
* @return Game+ruleset name in format GameName_RulesetName
*/
public static String gameRulesetName(final Game game)
{
if (gameNames == null)
loadData();
final Ruleset ruleset = game.getRuleset();
final String rulesetName = (ruleset == null) ? null : ruleset.heading();
if (rulesetName == null)
{
for (int i = 0; i < gameNames.size(); i++)
if (gameNames.get(i).equals(game.name()))
return
(gameNames.get(i) + "_" + rulesetNames.get(i))
.replaceAll(Pattern.quote(" "), "_")
.replaceAll(Pattern.quote("("), "")
.replaceAll(Pattern.quote(")"), "")
.replaceAll(Pattern.quote("'"), "");
}
else
{
final String nameRuleset = ruleset.heading();
final String startString = "Ruleset/";
final String nameRulesetCSV =
nameRuleset.substring(startString.length(), ruleset.heading().lastIndexOf('(') - 1);
return
(game.name() + "_" + nameRulesetCSV)
.replaceAll(Pattern.quote(" "), "_")
.replaceAll(Pattern.quote("("), "")
.replaceAll(Pattern.quote(")"), "")
.replaceAll(Pattern.quote("'"), "");
}
return null;
}
//-------------------------------------------------------------------------
/**
* Load our data from the CSV file
*/
private static void loadData()
{
try (final BufferedReader reader = new BufferedReader(new FileReader(new File(FILEPATH))))
{
gameNames = new ArrayList<String>();
rulesetNames = new ArrayList<String>();
for (String line; (line = reader.readLine()) != null; /**/)
{
final String[] lineSplit = line.split(Pattern.quote(","));
final String gameName = lineSplit[0].replaceAll(Pattern.quote("\""), "");
final String rulesetName = lineSplit[1].replaceAll(Pattern.quote("\""), "");
gameNames.add(gameName);
rulesetNames.add(rulesetName);
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
}
| 3,459 | 25.821705 | 92 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/agents/GenerateBaseAgentScoresDatabaseCSVs.java
|
package utils.agents;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.map.TObjectDoubleMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.options.Ruleset;
import other.GameLoader;
import utils.IdRuleset;
/**
* Generates CSV files for database, describing scores of all base agents
* (untrained AIs) for all games.
*
* @author Dennis Soemers
*/
public class GenerateBaseAgentScoresDatabaseCSVs
{
/** Hard-coded set of agent Ids based on Agents table in the database. */
private static final Map<String, Integer> agentCSVIds;
static {
agentCSVIds = new HashMap<>();
agentCSVIds.put("AlphaBeta", Integer.valueOf(6));
agentCSVIds.put("UCT", Integer.valueOf(3));
agentCSVIds.put("Random", Integer.valueOf(1));
agentCSVIds.put("MAST", Integer.valueOf(8));
agentCSVIds.put("MC-GRAVE", Integer.valueOf(5));
agentCSVIds.put("ProgressiveHistory", Integer.valueOf(7));
agentCSVIds.put("BRS+", Integer.valueOf(11));
}
/** If the above hard coded map should be used to determine agentIds. */
private static final boolean useAgentCSVIds = true;
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private GenerateBaseAgentScoresDatabaseCSVs()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our CSV
* @param argParse
* @throws IOException
* @throws FileNotFoundException
*/
private static void generateCSVs(final CommandLineArgParse argParse) throws FileNotFoundException, IOException
{
String resultsDir = argParse.getValueString("--results-dir");
resultsDir = resultsDir.replaceAll(Pattern.quote("\\"), "/");
if (!resultsDir.endsWith("/"))
resultsDir += "/";
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
final List<AgentData> agentsList = new ArrayList<AgentData>();
final List<ScoreData> scoreDataList = new ArrayList<ScoreData>();
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.hasSubgames())
continue;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
final File rulesetResultsDir = new File(resultsDir + filepathsGameName + filepathsRulesetName);
if (rulesetResultsDir.exists())
{
final int rulesetID = IdRuleset.get(game);
// Map from agent names to sum of scores for this ruleset
final TObjectDoubleMap<String> agentScoreSums = new TObjectDoubleHashMap<String>();
// Map from agent names to how often we observed this heuristic in this ruleset
final TObjectIntMap<String> agentCounts = new TObjectIntHashMap<String>();
final File[] matchupDirs = rulesetResultsDir.listFiles();
for (final File matchupDir : matchupDirs)
{
if (matchupDir.isDirectory())
{
final String[] resultLines =
FileHandling.loadTextContentsFromFile(
matchupDir.getAbsolutePath() + "/alpha_rank_data.csv"
).split(Pattern.quote("\n"));
// Skip index 0, that's just the headings
for (int i = 1; i < resultLines.length; ++i)
{
final String line = resultLines[i];
final int idxQuote1 = 0;
final int idxQuote2 = line.indexOf("\"", idxQuote1 + 1);
final int idxQuote3 = line.indexOf("\"", idxQuote2 + 1);
final int idxQuote4 = line.indexOf("\"", idxQuote3 + 1);
final String agentsTuple =
line
.substring(idxQuote1 + 2, idxQuote2 - 1)
.replaceAll(Pattern.quote(" "), "")
.replaceAll(Pattern.quote("'"), "");
final String scoresTuple =
line
.substring(idxQuote3 + 2, idxQuote4 - 1)
.replaceAll(Pattern.quote(" "), "");
final String[] agentNames = agentsTuple.split(Pattern.quote(","));
final String[] scores = scoresTuple.split(Pattern.quote(","));
for (int j = 0; j < agentNames.length; ++j)
{
if (Double.parseDouble(scores[j]) < -1.0 || Double.parseDouble(scores[j]) > 1.0)
{
System.out.println(scores[j]);
System.out.println("Line " + i + " of " + matchupDir.getAbsolutePath() + "/alpha_rank_data.csv");
}
// Convert score to "win percentage"
final double score = ((Double.parseDouble(scores[j]) + 1.0) / 2.0) * 100.0;
agentScoreSums.adjustOrPutValue(agentNames[j], score, score);
agentCounts.adjustOrPutValue(agentNames[j], 1, 1);
}
}
}
}
final List<ScoreData> rulesetScoreData = new ArrayList<ScoreData>();
for (final String agent : agentScoreSums.keySet())
{
AgentData agentData = null;
for (final AgentData data : agentsList)
{
if (data.name.equals(agent))
{
agentData = data;
break;
}
}
if (agentData == null)
{
if (useAgentCSVIds)
{
agentData = new AgentData(agentCSVIds.get(agent).intValue(), agent);
agentsList.add(agentData);
}
else
{
agentData = new AgentData(agent);
agentsList.add(agentData);
}
}
final int agentID = agentData.id;
final double score = agentScoreSums.get(agent) / agentCounts.get(agent);
rulesetScoreData.add(new ScoreData(rulesetID, agentID, score));
}
scoreDataList.addAll(rulesetScoreData);
}
}
}
try (final PrintWriter writer = new PrintWriter(new File("../Mining/res/agents/Agents.csv"), "UTF-8"))
{
for (final AgentData data : agentsList)
{
writer.println(data);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
try (final PrintWriter writer = new PrintWriter(new File("../Mining/res/agents/RulesetAgents.csv"), "UTF-8"))
{
for (final ScoreData data : scoreDataList)
{
writer.println(data);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Data for Agents table
*
* @author Dennis Soemers
*/
private static class AgentData
{
private static int nextID = 1;
protected final int id;
protected final String name;
public AgentData(final String name)
{
id = nextID++;
this.name = name;
}
public AgentData(final int id, final String name)
{
this.id = id;
this.name = name;
}
@Override
public String toString()
{
return id + "," + name;
}
}
/**
* Data for the table of ruleset+agent scores
*
* @author Dennis Soemers
*/
private static class ScoreData
{
private static int nextID = 1;
protected final int id;
protected final int rulesetID;
protected final int agentID;
protected double score;
public ScoreData(final int rulesetID, final int agentID, final double score)
{
id = nextID++;
this.rulesetID = rulesetID;
this.agentID = agentID;
this.score = score;
}
@Override
public String toString()
{
return id + "," + rulesetID + "," + agentID + "," + score;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates CSV files for database, describing scores of all base agents for all games."
);
argParse.addOption(new ArgOption()
.withNames("--results-dir")
.help("Filepath for directory with per-game subdirectories of matchup directories.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateCSVs(argParse);
}
//-------------------------------------------------------------------------
}
| 10,811 | 28.867403 | 131 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/agents/GeneratePortfolioAgentScoresDatabaseCSV.java
|
package utils.agents;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.map.TObjectDoubleMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.options.Ruleset;
import other.GameLoader;
import utils.IdRuleset;
/**
* Generates CSV files for database, describing scores of all building blocks
* of agents for portfolio.
*
* @author Dennis Soemers
*/
public class GeneratePortfolioAgentScoresDatabaseCSV
{
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private GeneratePortfolioAgentScoresDatabaseCSV()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our CSV
* @param argParse
* @throws IOException
* @throws FileNotFoundException
*/
private static void generateCSVs(final CommandLineArgParse argParse) throws FileNotFoundException, IOException
{
String resultsDir = argParse.getValueString("--results-dir");
resultsDir = resultsDir.replaceAll(Pattern.quote("\\"), "/");
if (!resultsDir.endsWith("/"))
resultsDir += "/";
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
final List<ScoreData> scoreDataList = new ArrayList<ScoreData>();
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
// if (game.isDeductionPuzzle())
// continue;
//
// if (game.isSimulationMoveGame())
// continue;
//
// if (!game.isAlternatingMoveGame())
// continue;
//
// if (game.hasSubgames())
// continue;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
final File rulesetResultsDir = new File(resultsDir + filepathsGameName + filepathsRulesetName);
if (rulesetResultsDir.exists())
{
final int rulesetID = IdRuleset.get(game);
// Map from agent names to sum of scores for this ruleset
final TObjectDoubleMap<String> agentScoreSums = new TObjectDoubleHashMap<String>();
// Map from agent names to how often we observed this heuristic in this ruleset
final TObjectIntMap<String> agentCounts = new TObjectIntHashMap<String>();
final File[] jobDirs = rulesetResultsDir.listFiles();
for (final File jobDir : jobDirs)
{
if (jobDir.isDirectory())
{
final String[] resultLines =
FileHandling.loadTextContentsFromFile(
jobDir.getAbsolutePath() + "/alpha_rank_data.csv"
).split(Pattern.quote("\n"));
// Skip index 0, that's just the headings
for (int i = 1; i < resultLines.length; ++i)
{
final String line = resultLines[i];
final int idxQuote1 = 0;
final int idxQuote2 = line.indexOf("\"", idxQuote1 + 1);
final int idxQuote3 = line.indexOf("\"", idxQuote2 + 1);
final int idxQuote4 = line.indexOf("\"", idxQuote3 + 1);
final String agentsTuple =
line
.substring(idxQuote1 + 2, idxQuote2 - 1)
.replaceAll(Pattern.quote(" "), "")
.replaceAll(Pattern.quote("'"), "");
final String scoresTuple =
line
.substring(idxQuote3 + 2, idxQuote4 - 1)
.replaceAll(Pattern.quote(" "), "");
final String[] agentNames = agentsTuple.split(Pattern.quote(","));
final String[] scores = scoresTuple.split(Pattern.quote(","));
for (int j = 0; j < agentNames.length; ++j)
{
final String agentName = agentNames[j].replaceAll(Pattern.quote("'"), "");
if (Double.parseDouble(scores[j]) < -1.0 || Double.parseDouble(scores[j]) > 1.0)
{
System.out.println(scores[j]);
System.out.println("Line " + i + " of " + jobDir.getAbsolutePath() + "/alpha_rank_data.csv");
}
// Convert score to "win percentage"
final double score = ((Double.parseDouble(scores[j]) + 1.0) / 2.0) * 100.0;
agentScoreSums.adjustOrPutValue(agentName, score, score);
agentCounts.adjustOrPutValue(agentName, 1, 1);
}
}
}
}
final List<ScoreData> rulesetScoreData = new ArrayList<ScoreData>();
for (final String agent : agentScoreSums.keySet())
{
final double score = agentScoreSums.get(agent) / agentCounts.get(agent);
rulesetScoreData.add(new ScoreData(rulesetID, agent, score, agentCounts.get(agent)));
}
scoreDataList.addAll(rulesetScoreData);
}
}
}
try (final PrintWriter writer = new PrintWriter(new File("../Mining/res/agents/RulesetPortfolioAgents.csv"), "UTF-8"))
{
for (final ScoreData data : scoreDataList)
{
writer.println(data);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Data for the table of ruleset+agent scores
*
* @author Dennis Soemers
*/
private static class ScoreData
{
private static int nextID = 1;
protected final int id;
protected final int rulesetID;
protected final String agent;
protected double score;
protected int numMatchups;
public ScoreData(final int rulesetID, final String agent, final double score, final int numMatchups)
{
id = nextID++;
this.rulesetID = rulesetID;
this.agent = agent;
this.score = score;
this.numMatchups = numMatchups;
}
@Override
public String toString()
{
final String[] agentParts = Arrays.copyOf(agent.split(Pattern.quote("-")), 5);
for (int i = 0; i < agentParts.length; ++i)
{
if (agentParts[i] == null)
agentParts[i] = "NULL";
}
return id + "," + rulesetID + "," + StringRoutines.join(",", agentParts) + "," + score + "," + numMatchups;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates CSV files for database, describing scores of all building blocks for agents for portfolio."
);
argParse.addOption(new ArgOption()
.withNames("--results-dir")
.help("Filepath for directory with per-game subdirectories.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateCSVs(argParse);
}
//-------------------------------------------------------------------------
}
| 9,176 | 31.2 | 131 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/bgg/BggData.java
|
package utils.bgg;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
//-----------------------------------------------------------------------------
/**
* Parse BGG user ratings data in CSV format (tab separated).
*
* @author cambolbro
*/
public class BggData
{
private final List<BggGame> games = new ArrayList<BggGame>();
private final Map<String, List<BggGame>> gamesByName = new HashMap<String, List<BggGame>>();
private final Map<Integer, BggGame> gamesByBggId = new HashMap<Integer, BggGame>();
private final Map<String, User> usersByName = new HashMap<String, User>();
//-------------------------------------------------------------------------
public List<BggGame> games()
{
return games;
}
public Map<String, List<BggGame>> gamesByName()
{
return gamesByName;
}
public Map<Integer, BggGame> gamesByBggId()
{
return gamesByBggId;
}
public Map<String, User> usersByName()
{
return usersByName;
}
//-------------------------------------------------------------------------
void loadGames(final String filePath)
{
final long startAt = System.currentTimeMillis();
games.clear();
gamesByName.clear();
gamesByBggId.clear();
try
(
BufferedReader reader = new BufferedReader
(
new InputStreamReader(new FileInputStream(filePath), "UTF-8")
)
)
{
String line;
while (true)
{
line = reader.readLine();
if (line == null)
break;
final String[] subs = line.split("\t");
final int bggId = Integer.parseInt(subs[0].trim());
final String name = subs[1].trim();
final String date = subs[2].trim();
final BggGame game = new BggGame(games.size(), bggId, name, date, subs);
// Add game to reference list
games.add(game);
// Add game to map of names
List<BggGame> nameList = gamesByName.get(name.toLowerCase());
if (nameList == null)
{
nameList = new ArrayList<BggGame>();
gamesByName.put(name.toLowerCase(), nameList);
}
nameList.add(game);
// Add game to map of ids -- should be unique
gamesByBggId.put(Integer.valueOf(bggId), game);
if (name.equals("scrabble"))
System.out.println(game.name() + " has BGG id " + game.bggId() + ".");
}
}
catch (final IOException e)
{
e.printStackTrace();
}
final long stopAt = System.currentTimeMillis();
final double secs = (stopAt - startAt) / 1000.0;
System.out.println(games.size() + " games loaded in " + secs + "s.");
System.out.println(gamesByName.size() + " entries by name and " + gamesByBggId.size() + " by BGG id.");
}
//-------------------------------------------------------------------------
void loadUserData(final String filePath)
{
final long startAt = System.currentTimeMillis();
usersByName.clear();
int items = 0;
int kept = 0;
try
(
BufferedReader reader = new BufferedReader
(
new InputStreamReader(new FileInputStream(filePath), "UTF-8")
)
)
{
String line;
int lineIndex = 0;
while (true)
{
line = reader.readLine();
if (line == null)
break;
final BggGame game = games.get(lineIndex);
final String[] subs = line.split("\t");
items += subs.length;
for (final String sub : subs)
kept += processUserData(sub, game) ? 1 : 0;
lineIndex++;
}
}
catch (final IOException e)
{
e.printStackTrace();
}
final long stopAt = System.currentTimeMillis();
final double secs = (stopAt - startAt) / 1000.0;
System.out.println(kept + "/" + items + " items processed for " + usersByName.size() + " users in " + secs + "s.");
}
//-------------------------------------------------------------------------
/**
* @return Whether data item was kept.
*/
boolean processUserData(final String entry, final BggGame game)
{
boolean kept = false;
int c = 0;
while (c < entry.length() && entry.charAt(c) != '\'')
c++;
int cc = c + 1;
while (cc < entry.length() && entry.charAt(cc) != '\'')
cc++;
if (c >= entry.length() || cc >= entry.length())
return false;
final String name = entry.substring(c+1, cc);
// Ensure that user is in database
User user = null;
if (usersByName.containsKey(name))
{
user = usersByName.get(name);
}
else
{
user = new User(name);
usersByName.put(name, user);
}
// Create the actual rating object and cross-reference it
final Rating rating = new Rating(game, user, entry);
if (rating.score() != 0)
{
// A lot of ratings seem to be placeholder 0s
kept = true;
game.add(rating);
user.add(rating);
}
return kept;
}
//-------------------------------------------------------------------------
/**
* Sanity test based on my ratings.
*/
void testCamb()
{
final User camb = usersByName.get("camb");
if (camb == null)
{
System.out.println("camb not found.");
}
else
{
System.out.println("camb ratings:");
for (final Rating rating : usersByName.get("camb").ratings())
System.out.println(" " + rating.game().name() + "=" + rating.score());
}
}
//-------------------------------------------------------------------------
/**
* List games rated only by the specified user.
*/
public void findUniqueRatings(final String userName)
{
final User user = usersByName.get(userName);
if (user == null)
{
System.out.println("Couldn't find user '" + userName + "'.");
return;
}
System.out.println(user.name() + " has " + user.ratings().size() + " ratings, and is the only person to have rated:");
for (final Rating rating : user.ratings())
{
final BggGame game = rating.game();
if (game.ratings().size() == 1)
System.out.println(game.name() + " (" + game.date() + ")");
}
}
//-------------------------------------------------------------------------
public void runDialog()
{
while (true)
{
final Object[] options =
{
"Similar Games",
"Similar Games (rating)",
"Similar Games (binary)",
"Similar Users",
"Suggestions for User",
"Similar Games (by user)",
};
final int searchType = JOptionPane.showOptionDialog
(
null,
"Query BGG Data",
"Query Type",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
Integer.valueOf(-1)
);
String message = "";
if (searchType == 0)
{
final String selection = JOptionPane.showInputDialog("Game Name or Id (Optionally Comma, Year)");
final String[] subs = selection.split(",");
final String name = (subs.length < 1) ? "" : subs[0].trim().toLowerCase();
final String year = (subs.length < 2) ? "" : subs[1].trim().toLowerCase();
message = Recommender.recommendCBB(this, name, year);
}
else if (searchType == 1)
{
final String selection = JOptionPane.showInputDialog("Game Name or Id (Optionally Comma, Year)");
final String[] subs = selection.split(",");
final String name = (subs.length < 1) ? "" : subs[0].trim().toLowerCase();
final String year = (subs.length < 2) ? "" : subs[1].trim().toLowerCase();
message = Recommender.ratingSimilarityRecommendFor(this, name, year);
}
else if (searchType == 2)
{
final String selection = JOptionPane.showInputDialog("Game Name or Id (Optionally Comma, Year)");
final String[] subs = selection.split(",");
final String name = (subs.length < 1) ? "" : subs[0].trim().toLowerCase();
final String year = (subs.length < 2) ? "" : subs[1].trim().toLowerCase();
message = Recommender.binaryRecommendFor(this, name, year);
}
else if (searchType == 3)
{
final String selection = JOptionPane.showInputDialog("BGG User Name");
message = Recommender.findMatchingUsers(this, selection);
}
else if (searchType == 4)
{
final String selection = JOptionPane.showInputDialog("BGG User Name");
message = Recommender.recommendFor(this, selection, false);
}
else if (searchType == 5)
{
final String selection = JOptionPane.showInputDialog("Game Name or Id (Optionally Comma, Year)");
final String[] subs = selection.split(",");
final String name = (subs.length < 1) ? "" : subs[0].trim().toLowerCase();
final String year = (subs.length < 2) ? "" : subs[1].trim().toLowerCase();
message = Recommender.recommendGameByUser(this, name, year);
}
System.out.println(message);
JOptionPane.showMessageDialog(null,message);
}
}
//-------------------------------------------------------------------------
public void run()
{
loadGames("../Mining/res/bgg/input/BGG_dataset.csv");
loadUserData("../Mining/res/bgg/input/user_rating.csv");
final String dbGamesFilePath = "../Mining/res/bgg/input/Games.csv";
final String outputFilePath = "../Mining/res/bgg/output/Results.csv";
/** Uncomment this line to only include results for Ludii games. */
//Database.saveValidGameIds(dbGamesFilePath);
//runDialog();
/** Used for generating useful database information. */
Database.findDBGameMatches(this, false, dbGamesFilePath, outputFilePath);
}
//-------------------------------------------------------------------------
public static void main(final String[] args)
{
final BggData bgg = new BggData();
bgg.run();
}
//-------------------------------------------------------------------------
}
| 9,653 | 25.742382 | 120 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/bgg/BggGame.java
|
package utils.bgg;
import java.util.ArrayList;
import java.util.List;
/**
* Record of a BGG game entry.
* @author cambolbro
*/
public class BggGame
{
private final int index;
private final int bggId;
private final String name;
private final String date;
private final String[] details;
private final List<Rating> ratings = new ArrayList<Rating>();
public BggGame
(
final int index, final int bggId, final String name,
final String date, final String[] details
)
{
this.index = index;
this.bggId = bggId;
this.name = name;
this.date = date;
this.details = details;
}
public int index()
{
return index;
}
public int bggId()
{
return bggId;
}
public String name()
{
return name;
}
public String date()
{
return date;
}
public String[] details()
{
return details;
}
public List<Rating> ratings()
{
return ratings;
}
public double averageRating()
{
// If no ratings yet, use score of -1
if (ratings.size() == 0)
return -1;
double averageScore = 0.0;
for (final Rating rating : ratings)
averageScore += rating.score();
return averageScore / ratings.size();
}
public void add(final Rating rating)
{
ratings.add(rating);
}
}
| 1,247 | 14.6 | 62 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/bgg/Database.java
|
package utils.bgg;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import main.AliasesData;
public class Database
{
/** valid game Ids for the recommendation process. */
private final static List<Integer> validGameIds = new ArrayList<Integer>();
//-------------------------------------------------------------------------
/**
* Populates the validGameIds list will all BGGIds which have been associated with Ludii games (validBGGId.txt)
*/
public static void saveValidGameIds(final String dbGamesFilePath)
{
try (BufferedReader reader = new BufferedReader(new FileReader(dbGamesFilePath)))
{
String line = reader.readLine();
while (line != null)
{
try
{
final int gameId = Integer.parseInt(line.split(",")[1].trim().toLowerCase().replace("\"", ""));
validGameIds.add(Integer.valueOf(gameId));
}
catch (final Exception E)
{
// probably null
}
line = reader.readLine();
}
reader.close();
} catch (final IOException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Finds BGGId or recommended games for all game names in Games.csv
* @param data
* @param getRecommendations
*/
public static void findDBGameMatches(final BggData data, final boolean getRecommendations, final String dbGamesFilePath, final String outputFilePath)
{
String outputString = "";
try (BufferedReader reader = new BufferedReader(new FileReader(dbGamesFilePath)))
{
String line = reader.readLine();
while (line != null)
{
// Read in the DB data from csv.
final String gameName = line.split(",")[0].trim().replace("\"", "");
final String bggIdString = line.trim().split(",")[1].replace("\"", "");
BggGame game = null;
// Try to find the matching entry for each game in BGG, based on either its ID or Name
if (!bggIdString.equals("NULL"))
{
game = data.gamesByBggId().get(Integer.valueOf(bggIdString));
}
else
{
// load in the aliases for this game
final List<String> aliases = new ArrayList<String>();
aliases.add(gameName.toLowerCase());
final AliasesData aliasesData = AliasesData.loadData();
final List<String> loadedAliases = aliasesData.aliasesForGameName(gameName);
if (loadedAliases != null)
for (final String alias : loadedAliases)
aliases.add(alias);
for (final String name : aliases)
{
final BggGame tempGame = Recommender.findGame(data, name, "", true, true);
if (tempGame != null)
{
game = tempGame;
break;
}
}
}
if (game != null)
{
if (getRecommendations)
{
// Give a set of recommended games
System.out.print(gameName + ": ");
Recommender.ratingSimilarityRecommendFor(data, String.valueOf(game.bggId()), "");
}
else
{
// Give BGGID
final String outputLine = gameName.replace(" ", "_") + ", " + game.bggId() + ", " + game.averageRating();
System.out.println(outputLine);
outputString += outputLine + "\n";
}
}
line = reader.readLine();
}
reader.close();
} catch (final IOException e)
{
e.printStackTrace();
}
// Save results in output file
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath, false)))
{
writer.write("Name,BGGId,AverageRating\n" + outputString);
writer.close();
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
//-------------------------------------------------------------------------
public static List<Integer> validGameIds()
{
return validGameIds;
}
//-------------------------------------------------------------------------
}
| 3,918 | 26.405594 | 150 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/bgg/Matches.java
|
package utils.bgg;
import java.util.ArrayList;
import java.util.List;
/**
* Record of matches for user scores.
* @author cambolbro
*/
public class Matches
{
private final BggGame game;
private final List<Double> scores = new ArrayList<Double>();
private double score = 0;
private int numberMatches = 0;
//-------------------------------------------------------------------------
public Matches(final BggGame game)
{
this.game = game;
}
//-------------------------------------------------------------------------
public BggGame game()
{
return game;
}
public List<Double> scores()
{
return scores;
}
public double score()
{
return score;
}
public void add(final double value)
{
scores.add(Double.valueOf(value));
score += value;
}
public void setScore(final double value)
{
score = value;
}
public void normalise()
{
if (scores.size() == 0)
score = 0;
else
score /= scores.size();
}
public int getNumberMatches()
{
return numberMatches;
}
public void setNumberMatches(final int numberMatches)
{
this.numberMatches = numberMatches;
}
}
| 1,117 | 14.746479 | 76 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/bgg/Rating.java
|
package utils.bgg;
/**
* Rating of a game by a BGG user.
* @author cambolbro
*/
public class Rating
{
private final BggGame game;
private final User user;
private final byte score;
//private final String stat;
//private final String time;
public Rating(final BggGame game, final User user, final String details)
{
this.game = game;
this.user = user;
this.score = extractScore(details);
//this.stat = extractStat(details);
//this.time = extractTime(details);
}
//-------------------------------------------------------------------------
public BggGame game()
{
return game;
}
public User user()
{
return user;
}
public int score()
{
return score;
}
// public String stat()
// {
// return stat;
// }
//
// public String time()
// {
// return time;
// }
//-------------------------------------------------------------------------
@SuppressWarnings("static-method")
byte extractScore(final String details)
{
final int c = details.indexOf("'score':");
if (c < 0)
{
System.out.println("** Failed to find score in: " + details);
return -1; //"";
}
int cc = c + 1;
while (cc < details.length() && details.charAt(cc) != ',')
cc++;
if (cc >= details.length())
{
System.out.println("** Failed to find closing ',' for score in: " + details);
return -1; //"";
}
final String str = details.substring(c + 9, cc).trim();
double value = -1;
try { value = Double.parseDouble(str); }
catch (NumberFormatException e)
{
try { value = Integer.parseInt(str); }
catch (NumberFormatException f) { /** */ }
}
//System.out.println(details);
//System.out.println(value);
return (byte)(value + 0.5); //str;
}
// String extractStat(final String details)
// {
// // ...
// return details; //null;
// }
//
//
// String extractTime(final String details)
// {
// // ...
// return details; //null;
// }
//-------------------------------------------------------------------------
}
| 2,025 | 18.295238 | 80 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/bgg/Recommender.java
|
package utils.bgg;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
public class Recommender
{
private final static DecimalFormat df3 = new DecimalFormat("#.###");
//-------------------------------------------------------------------------
/**
* Find game by name, using date if necessary to disambiguate.
*/
public static BggGame findGame(final BggData data, final String gameName, final String date, final boolean pickMostRated, final boolean skipNullGames)
{
BggGame game = null;
List<BggGame> candidates = data.gamesByName().get(gameName);
// If no name found, try searching for Id instead.
if (candidates == null)
{
try
{
final BggGame gameById = data.gamesByBggId().get(Integer.valueOf(Integer.parseInt(gameName)));
if(gameById != null)
{
candidates = new ArrayList<BggGame>();
candidates.add(gameById);
}
}
catch (final NumberFormatException E)
{
// name was not a number....
}
}
if (candidates == null)
{
if(!skipNullGames)
{
JOptionPane.showMessageDialog
(
null,
"Couldn't find game with name '" + gameName + "'.",
"Failed to Find Game",
JOptionPane.PLAIN_MESSAGE,
null
);
}
return null;
}
if (candidates.size() == 1)
{
// Immediate match on name
game = candidates.get(0);
}
else
{
// Match game by date
for (final BggGame gm : candidates)
if (gm.date().equalsIgnoreCase(date))
{
game = gm;
break;
}
}
if (game == null)
{
if (pickMostRated)
{
BggGame mostRatedCandidate = null;
int mostRatings = -1;
for (final BggGame gm : candidates)
{
if (gm.ratings().size() > mostRatings)
{
mostRatings = gm.ratings().size();
mostRatedCandidate = gm;
}
}
game = mostRatedCandidate;
}
else
{
// Failed to find game
final StringBuilder sb = new StringBuilder();
sb.append("Couldn't choose game among candidates:\n");
for (final BggGame gm : candidates)
sb.append(gm.name() + " (" + gm.date() + ")\n");
System.out.println(sb.toString());
JOptionPane.showMessageDialog
(
null,
sb.toString(),
"Failed to Find Game",
JOptionPane.PLAIN_MESSAGE,
null
);
return null;
}
}
return game;
}
//-------------------------------------------------------------------------
/**
* List top 50 recommendations based on game and year.
*/
public static String recommendCBB(final BggData data, final String gameName, final String date)
{
final StringBuilder sb = new StringBuilder();
final BggGame game = findGame(data, gameName, date, false, false);
if (game == null)
return "";
sb.append("\n" + game.name() + " (" + date + ") has " + game.ratings().size() + " ratings.\n");
final int ratingsThreshold = 30;
final int matchesThreshold = 5;
final Map<Integer, Matches> ratingMap = new HashMap<Integer, Matches>();
for (final Rating gameRating : game.ratings())
{
// Check the user who made each rating
final User user = gameRating.user();
final double baseScore = gameRating.score() / 10.0;
// Determine a penalty based on number of ratings: the fewer ratings the better
final double userPenalty = 1;
//final double userPenalty = 1 / (double)user.ratings().size();
//final double userPenalty = 1 / Math.sqrt(user.ratings().size() );
//final double userPenalty = 1 / Math.log10(user.ratings().size() + 1);
for (final Rating userRating : user.ratings())
{
final BggGame otherGame = userRating.game();
final double otherScore = userRating.score() / 10.0;
Matches matches = ratingMap.get(Integer.valueOf(otherGame.index()));
if (matches == null)
{
matches = new Matches(otherGame);
ratingMap.put(Integer.valueOf(otherGame.index()), matches);
}
matches.add(baseScore * otherScore * userPenalty);
}
}
// Divide each matches tally by the total number of ratings for that game
final List<Matches> result = new ArrayList<Matches>();
for (final Matches matches : ratingMap.values())
{
//matches.normalise();
if
(
matches.game().ratings().size() < ratingsThreshold
||
matches.scores().size() < matchesThreshold
)
{
// Eliminate this game from the possible winners
matches.setScore(0);
}
else
{
// Normalise to account for number of ratings
matches.setScore(matches.score() / Math.sqrt(matches.game().ratings().size()));
//matches.setScore(matches.score() / (double)matches.game().ratings().size());
}
if (Database.validGameIds().size() == 0 || Database.validGameIds().contains(Integer.valueOf(matches.game().bggId())))
result.add(matches);
}
Collections.sort(result, new Comparator<Matches>()
{
@Override
public int compare(final Matches a, final Matches b)
{
if (a.score() == b.score())
return 0;
return (a.score() > b.score()) ? -1 : 1;
}
});
for (int n = 0; n < Math.min(50, result.size()); n++)
{
final Matches matches = result.get(n);
// message += String.format("%2d. %s (%s) %.3f / %d\n",
// Integer.valueOf(n + 1),
// matches.game().name(), matches.game().date(),
// Double.valueOf(matches.score()),
// Integer.valueOf(matches.scores().size()));
sb.append
(
"" + (n + 1) + ". " +
matches.game().name() + " (" +
matches.game().date() + ") " +
df3.format(matches.score()) + " / " +
matches.scores().size() + ".\n"
);
}
return sb.toString();
}
//-------------------------------------------------------------------------
/**
* List top 50 recommendations based on game and year.
*/
public static String recommendGameByUser(final BggData data, final String gameName, final String date)
{
// String message = "";
//
// final BggGame game = findGame(data, gameName, date, false, false);
// if (game == null)
// return "";
//
// message = ("\n" + game.name() + " (" + date + ") has " + game.ratings().size() + " ratings.\n");
//
// final int ratingsThreshold = 30;
// final int matchesThreshold = 5;
//
// final Map<Integer, Matches> ratingMap = new HashMap<Integer, Matches>();
//
// for (final Rating gameRating : game.ratings())
// {
// // Check the user who made each rating
// final User user = gameRating.user();
// final double baseScore = gameRating.score() / 10.0;
//
// // Determine a penalty based on number of ratings: the fewer ratings the better
// final double userPenalty = 1;
// //final double userPenalty = 1 / (double)user.ratings().size();
// //final double userPenalty = 1 / Math.sqrt(user.ratings().size() );
// //final double userPenalty = 1 / Math.log10(user.ratings().size() + 1);
//
// for (final Rating userRating : user.ratings())
// {
// final BggGame otherGame = userRating.game();
// final double otherScore = userRating.score() / 10.0;
//
// Matches matches = ratingMap.get(Integer.valueOf(otherGame.index()));
// if (matches == null)
// {
// matches = new Matches(otherGame);
// ratingMap.put(Integer.valueOf(otherGame.index()), matches);
// }
// matches.add(baseScore * otherScore * userPenalty);
// }
// }
//
// // Divide each matches tally by the total number of ratings for that game
// final List<Matches> result = new ArrayList<Matches>();
// for (final Matches matches : ratingMap.values())
// {
// //matches.normalise();
// if
// (
// matches.game().ratings().size() < ratingsThreshold
// ||
// matches.scores().size() < matchesThreshold
// )
// {
// // Eliminate this game from the possible winners
// matches.setScore(0);
// }
// else
// {
// // Normalise to account for number of ratings
// matches.setScore(matches.score() / Math.sqrt(matches.game().ratings().size()));
// //matches.setScore(matches.score() / (double)matches.game().ratings().size());
// }
//
// if (Database.validGameIds().size() == 0 || Database.validGameIds().contains(Integer.valueOf(matches.game().bggId())))
// result.add(matches);
// }
//
// Collections.sort(result, new Comparator<Matches>()
// {
// @Override
// public int compare(final Matches a, final Matches b)
// {
// if (a.score() == b.score())
// return 0;
//
// return (a.score() > b.score()) ? -1 : 1;
// }
// });
//
// for (int n = 0; n < Math.min(50, result.size()); n++)
// {
// final Matches matches = result.get(n);
// message += String.format("%2d. %s (%s) %.3f / %d\n",
// (n+1), matches.game().name(), matches.game().date(),
// matches.score(), matches.scores().size());
// }
//
// return message;
return "Not implement yet.";
}
//-------------------------------------------------------------------------
/**
* List top 50 recommendations for a given user.
* @param includeOwn Whether to include games rated by the user.
*/
public static String recommendFor(final BggData data, final String userName, final boolean includeOwn)
{
String messageString = "";
final User userA = data.usersByName().get(userName);
if (userA == null)
{
return "Couldn't find user '" + userName + "'.";
}
messageString += userA.name() + " has " + userA.ratings().size() + " ratings.\n";
final Map<Integer, Matches> ratingMap = new HashMap<Integer, Matches>();
for (final Rating ratingA : userA.ratings())
{
final BggGame gameA = ratingA.game();
for (final Rating ratingB : gameA.ratings())
{
// Check other games rated by user
final User userB = ratingB.user();
final double scoreB = ratingB.score() / 10.0;
for (final Rating ratingC : userB.ratings())
{
final BggGame gameC = ratingC.game();
final double scoreC = ratingC.score() / 10.0;
//if (!includeOwn)
// (user rates this game)
// continue;
Matches matches = ratingMap.get(Integer.valueOf(gameC.index()));
if (matches == null)
{
matches = new Matches(gameC);
ratingMap.put(Integer.valueOf(gameC.index()), matches);
}
matches.add(scoreB * scoreC);
}
}
}
final List<Matches> result = new ArrayList<Matches>();
for (final Matches matches : ratingMap.values())
if (Database.validGameIds().size() == 0 || Database.validGameIds().contains(Integer.valueOf(matches.game().bggId())))
result.add(matches);
Collections.sort(result, new Comparator<Matches>()
{
@Override
public int compare(final Matches a, final Matches b)
{
if (a.score() == b.score())
return 0;
return (a.score() > b.score()) ? -1 : 1;
}
});
for (int n = 0; n < Math.min(20, result.size()); n++)
{
final Matches matches = result.get(n);
messageString += ("Match: " + matches.score() + " (" + matches.scores().size() + ") " + matches.game().name() + "\n");
}
return messageString;
}
//-------------------------------------------------------------------------
/**
* @return Estimated match between the two users.
*/
public static double userMatch(final BggData data, final User userA, final User userB)
{
// Accumulate the number of games rated by both players and the difference in ratings
double tally = 0;
int count = 0;
final User minUser = (userA.ratings().size() < userB.ratings().size()) ? userA : userB;
final User maxUser = (userA.ratings().size() < userB.ratings().size()) ? userB : userA;
for (final Rating ratingMin : minUser.ratings())
{
final int gameIndexMin = ratingMin.game().index();
double score = 0; // unless proven otherwise
for (final Rating ratingMax : maxUser.ratings())
if (ratingMax.game().index() == gameIndexMin)
{
// Update the game match with the actual value
score = 1 - Math.abs(ratingMin.score() - ratingMax.score()) / 10.0;
count++;
break;
}
tally += score;
}
if (count == 0)
{
System.out.println("** No shared rating between users.");
return 0;
}
return tally / minUser.ratings().size();
}
//-------------------------------------------------------------------------
/**
* List top 100 users who gave similar scores to similar games.
*/
public static String findMatchingUsers(final BggData data, final String userName)
{
String messageString = "";
final User user = data.usersByName().get(userName);
if (user == null)
{
return "Couldn't find user '" + userName + "'.";
}
messageString += (user.name() + " has " + user.ratings().size() + " ratings.\n");
// Find other users who've scored at least one game this user has scored
final List<User> others = new ArrayList<User>();
final Map<String, User> othersMap = new HashMap<String, User>();
for (final Rating rating : user.ratings())
{
final BggGame game = rating.game();
for (final Rating otherRating : game.ratings())
othersMap.put(otherRating.user().name(), otherRating.user());
}
for (final User other : othersMap.values())
others.add(other);
messageString += (others.size() + " users have scored at least one game that " + userName + " has scored.\n");
// Determine scores for overlapping users
for (final User other : others)
{
// Find match for each game scored by user
double tally = 0;
for (final Rating userRating : user.ratings())
{
double score = 0;
for (final Rating otherRating : other.ratings())
{
if (userRating.game().index() == otherRating.game().index())
{
// Match!
score = 1 - Math.abs(userRating.score() - otherRating.score()) / 10.0;
break;
}
}
tally += score;
}
tally /= user.ratings().size();
other.setMatch(tally);
// other.setMatch(userMatch(data, user, other));
}
Collections.sort(others, new Comparator<User>()
{
@Override
public int compare(final User a, final User b)
{
if (a.match() == b.match())
return 0;
return (a.match() > b.match()) ? -1 : 1;
}
});
for (int n = 0; n < Math.min(100, others.size()); n++)
{
final User other = others.get(n);
messageString += ((n + 1) + ". " + other.name() + ", " + other.ratings().size() + " ratings, match=" + other.match() + ".\n");
}
return messageString;
}
//-------------------------------------------------------------------------
/**
* List top 50 recommendations based on game and year (binary version).
*/
public static String binaryRecommendFor(final BggData data, final String gameName, final String date)
{
String messageString = "";
final BggGame game = findGame(data, gameName, date, false, false);
if (game == null)
return "";
messageString = ("\n" + game.name() + " (" + date + ") has " + game.ratings().size() + " ratings.\n");
int threshold = 10;
if (game.ratings().size() > 100)
threshold = 20;
if (game.ratings().size() > 1000)
threshold = 30;
final Map<Integer, Integer> numberOfRecommendsMap = new HashMap<Integer, Integer>();
final Map<Integer, Integer> numberOfMatchesMap = new HashMap<Integer, Integer>();
for (final Rating gameRating : game.ratings())
{
// Check other games rated by this user
final User user = gameRating.user();
final boolean wouldrecommend = gameRating.score() >= 7.0;
// only look at the rating of users who would recommend this game.
if (wouldrecommend)
{
for (final Rating userRating : user.ratings())
{
final BggGame otherGame = userRating.game();
final boolean wouldrecommendOther = userRating.score() >= 7.0;
final int gameIndex = otherGame.index();
int newScore = 1;
if (numberOfMatchesMap.containsKey(Integer.valueOf(gameIndex)))
newScore = numberOfMatchesMap.get(Integer.valueOf(gameIndex)).intValue()+1;
numberOfMatchesMap.put(Integer.valueOf(gameIndex), Integer.valueOf(newScore));
if (wouldrecommendOther)
{
newScore = 1;
if (numberOfRecommendsMap.containsKey(Integer.valueOf(gameIndex)))
newScore = numberOfRecommendsMap.get(Integer.valueOf(gameIndex)).intValue()+1;
numberOfRecommendsMap.put(Integer.valueOf(gameIndex), Integer.valueOf(newScore));
}
}
}
}
// Divide each matches tally by the total number of ratings for that game
final List<Matches> result = new ArrayList<Matches>();
for (final Integer gameId : numberOfRecommendsMap.keySet())
{
if (numberOfRecommendsMap.get(gameId).intValue() > threshold)
{
final Matches match = new Matches(data.games().get(gameId.intValue()));
match.setNumberMatches(numberOfRecommendsMap.get(gameId).intValue());
match.setScore(Double.valueOf(numberOfRecommendsMap.get(gameId).intValue()).doubleValue() / Double.valueOf(numberOfMatchesMap.get(gameId).intValue()).doubleValue());
if (Database.validGameIds().size() == 0 || Database.validGameIds().contains(Integer.valueOf(match.game().bggId())))
result.add(match);
}
}
Collections.sort(result, new Comparator<Matches>()
{
@Override
public int compare(final Matches a, final Matches b)
{
if (a.score() == b.score())
return 0;
return (a.score() > b.score()) ? -1 : 1;
}
});
for (int n = 0; n < Math.min(50, result.size()); n++)
{
final Matches matches = result.get(n);
messageString += ((n + 1) + ". Match: " + matches.score() + " (" + matches.getNumberMatches() + ") " + matches.game().name() + "\n");
}
return messageString;
}
//-------------------------------------------------------------------------
/**
* List top 50 recommendations based on game and year (rating similarity version).
*/
public static String ratingSimilarityRecommendFor(final BggData data, final String gameName, final String date)
{
String messageString = "";
final BggGame game = findGame(data, gameName, date, false, false);
if (game == null)
return "";
messageString = ("\n" + game.name() + " (" + date + ") has " + game.ratings().size() + " ratings.\n");
int threshold = 0;
if (game.ratings().size() > 50)
threshold = 10;
if (game.ratings().size() > 100)
threshold = 20;
if (game.ratings().size() > 1000)
threshold = 30;
final Map<Integer, Integer> scoreSimilarityMap = new HashMap<Integer, Integer>();
final Map<Integer, Integer> numberOfMatchesMap = new HashMap<Integer, Integer>();
for (final Rating gameRating : game.ratings())
{
// Check other games rated by this user
final User user = gameRating.user();
final int gameScore = gameRating.score();
for (final Rating userRating : user.ratings())
{
final BggGame otherGame = userRating.game();
final int otherGameScore = userRating.score();
final int gameIndex = otherGame.index();
final int scoreSimilarity = 10 - Math.abs(gameScore - otherGameScore);
int newTotal = 1;
if (numberOfMatchesMap.containsKey(Integer.valueOf(gameIndex)))
newTotal = numberOfMatchesMap.get(Integer.valueOf(gameIndex)).intValue()+1;
numberOfMatchesMap.put(Integer.valueOf(gameIndex), Integer.valueOf(newTotal));
int newScore = scoreSimilarity;
if (scoreSimilarityMap.containsKey(Integer.valueOf(gameIndex)))
newScore = scoreSimilarityMap.get(Integer.valueOf(gameIndex)).intValue()+newScore;
scoreSimilarityMap.put(Integer.valueOf(gameIndex), Integer.valueOf(newScore));
}
}
// Divide each matches tally by the total number of ratings for that game
final List<Matches> result = new ArrayList<Matches>();
for (final Integer gameId : numberOfMatchesMap.keySet())
{
if (numberOfMatchesMap.get(gameId).intValue() > threshold)
{
final Matches match = new Matches(data.games().get(gameId.intValue()));
match.setNumberMatches(numberOfMatchesMap.get(gameId).intValue());
match.setScore(Double.valueOf(scoreSimilarityMap.get(gameId).intValue()).doubleValue() / Double.valueOf(numberOfMatchesMap.get(gameId).intValue()).doubleValue());
if (Database.validGameIds().size() == 0 || Database.validGameIds().contains(Integer.valueOf(match.game().bggId())))
result.add(match);
}
}
Collections.sort(result, new Comparator<Matches>()
{
@Override
public int compare(final Matches a, final Matches b)
{
if (a.score() == b.score())
return 0;
return (a.score() > b.score()) ? -1 : 1;
}
});
for (int n = 0; n < Math.min(50, result.size()); n++)
{
final Matches matches = result.get(n);
messageString += ((n + 1) + ". Match: " + matches.score() + " (" + matches.getNumberMatches() + ") " + matches.game().name() + "\n");
System.out.print(matches.game().bggId() + ", ");
}
System.out.println("");
return messageString;
}
}
| 21,136 | 29.500722 | 169 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/bgg/User.java
|
package utils.bgg;
import java.util.ArrayList;
import java.util.List;
public class User
{
private final String name;
private final List<Rating> ratings = new ArrayList<Rating>();
private double match = 0;
//private BitSet gamesRated = new BitSet();
//-------------------------------------------------------------------------
public User(final String name)
{
this.name = name;
}
//-------------------------------------------------------------------------
public String name()
{
return name;
}
public List<Rating> ratings()
{
return ratings;
}
public void add(final Rating rating)
{
//gamesRated.set(rating.game().id());
ratings.add(rating);
}
public double match()
{
return match;
}
public void setMatch(final double value)
{
match = value;
}
}
| 800 | 15.346939 | 76 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/concepts/CommonConcepts.java
|
package utils.concepts;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import compiler.Compiler;
import main.FileHandling;
import main.grammar.Description;
import other.concept.Concept;
import other.concept.ConceptDataType;
import other.concept.ConceptType;
/**
* Method to get the common concepts (and avg for the numerical ones) between a
* set of games and avg of same value/diff value for each boolean concept.
*
* @author Eric.Piette
*/
public class CommonConcepts
{
/** The games to compare. */
private final static String[] gamesToCompare = new String[]
{ "Go", "Oware" };
/** The list of compiled games. */
final static List<Game> games = new ArrayList<Game>();
/** Put a value here to get only one single concept type. */
final static ConceptType type = null;
//---------------------------------------------------------------------
/**
* Main method.
*
* @param args
*/
public static void main(final String[] args) throws IllegalArgumentException, IllegalAccessException
{
final TIntArrayList booleanConceptsID = new TIntArrayList();
final List<String> booleanConceptsName = new ArrayList<String>();
final TIntArrayList nonBooleanConceptsID = new TIntArrayList();
final List<String> nonBooleanConceptsName = new ArrayList<String>();
// We get the concepts.
for (final Concept concept : Concept.values())
if (concept.dataType().equals(ConceptDataType.BooleanData))
{
if (type == null || concept.type().equals(type))
{
booleanConceptsID.add(concept.id());
booleanConceptsName.add(concept.name());
}
}
else if (!concept.dataType().equals(ConceptDataType.StringData))
{
nonBooleanConceptsID.add(concept.id());
nonBooleanConceptsName.add(concept.name());
}
getGames();
final int totalBooleanConcept = booleanConceptsID.size();
// Check the number of times all the games have the same value for the concepts and the number of times they have a different value (only for boolean).
int sameValue = 0;
int differentValue = 0;
for(int i = booleanConceptsID.size()-1; i>=0; i--)
{
final int idConcept = booleanConceptsID.get(i);
final boolean hasConcept = games.get(0).booleanConcepts().get(idConcept);
boolean allSameValue = true;
for (int j = 1 ; j < games.size(); j++)
{
final Game game = games.get(j);
if ((game.booleanConcepts().get(idConcept) && !hasConcept) || !game.booleanConcepts().get(idConcept) && hasConcept)
{
differentValue++;
allSameValue = false;
break;
}
if(allSameValue)
sameValue++;
}
}
// Keep Only the common boolean concepts.
for(int i = booleanConceptsID.size()-1; i>=0; i--)
{
final int idConcept = booleanConceptsID.get(i);
for (final Game game : games)
{
if (!game.booleanConcepts().get(idConcept))
{
booleanConceptsID.removeAt(i);
booleanConceptsName.remove(i);
break;
}
}
}
System.out.println("Common Boolean Concepts: \n");
for (int i = 0; i < booleanConceptsName.size(); i++)
System.out.println(booleanConceptsName.get(i));
System.out.println("\nAVG Boolean Concepts with same value and AVG Boolean with different values: \n");
System.out.println("Same Value = " + new DecimalFormat("##.##")
.format((((double) sameValue / (double) totalBooleanConcept)) * 100) + " %");
System.out.println("different Value = " + new DecimalFormat("##.##")
.format((((double) differentValue / (double) totalBooleanConcept)) * 100) + " %");
System.out.println("\nAvg Numerical Concepts:\n");
// We export the non boolean concepts.
for (int i = 0; i < nonBooleanConceptsID.size(); i++)
{
final Integer idConcept = Integer.valueOf(nonBooleanConceptsID.get(i));
final String Conceptname = nonBooleanConceptsName.get(i);
double sum = 0.0;
for(final Game game: games)
sum += Double.parseDouble(game.nonBooleanConcepts().get(idConcept));
System.out.println(Conceptname + ": " + (sum / games.size()));
}
}
//---------------------------------------------------------------------
/** Get the compiled games. */
public static void getGames()
{
final File startFolder = new File("../Common/res/lud");
final List<File> gameDirs = new ArrayList<File>();
gameDirs.add(startFolder);
final List<File> entries = new ArrayList<File>();
final String moreSpecificFolder = "";
for (int i = 0; i < gameDirs.size(); ++i)
{
final File gameDir = gameDirs.get(i);
for (final File fileEntry : gameDir.listFiles())
{
if (fileEntry.isDirectory())
{
final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/");
if (fileEntryPath.equals("../Common/res/lud/plex"))
continue;
if (fileEntryPath.equals("../Common/res/lud/wip"))
continue;
if (fileEntryPath.equals("../Common/res/lud/wishlist"))
continue;
if (fileEntryPath.equals("../Common/res/lud/WishlistDLP"))
continue;
if (fileEntryPath.equals("../Common/res/lud/test"))
continue;
if (fileEntryPath.equals("../Common/res/lud/puzzle/deduction"))
continue; // skip deduction puzzles
if (fileEntryPath.equals("../Common/res/lud/bad"))
continue;
if (fileEntryPath.equals("../Common/res/lud/bad_playout"))
continue;
// We exclude that game from the tests because the legal
// moves are too slow to test.
if (fileEntryPath.contains("Residuel"))
continue;
gameDirs.add(fileEntry);
}
else
{
final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/");
if (moreSpecificFolder.equals("") || fileEntryPath.contains(moreSpecificFolder))
entries.add(fileEntry);
}
}
}
for (final File fileEntry : entries)
{
final String gameName = fileEntry.getName();
boolean found = false;
for (final String name : gamesToCompare)
{
if (gameName.equals(name + ".lud"))
{
found = true;
break;
}
}
if (!found)
continue;
final String ludPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/");
String desc = "";
try
{
desc = FileHandling.loadTextContentsFromFile(ludPath);
}
catch (final FileNotFoundException ex)
{
fail("Unable to open file '" + ludPath + "'");
}
catch (final IOException ex)
{
fail("Error reading file '" + ludPath + "'");
}
// Parse and compile the game
final Game game = (Game)Compiler.compileTest(new Description(desc), false);
if (game == null)
fail("COMPILATION FAILED for the file : " + ludPath);
else
games.add(game);
}
}
}
| 6,888 | 27.466942 | 153 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/concepts/ComputePlayoutConcepts.java
|
package utils.concepts;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.commons.rng.RandomProviderState;
import game.Game;
import game.equipment.container.Container;
import game.rules.end.End;
import game.rules.end.EndRule;
import game.rules.phase.Phase;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import metrics.Evaluation;
import metrics.Metric;
import metrics.Utils;
import other.AI;
import other.concept.Concept;
import other.concept.ConceptDataType;
import other.concept.ConceptType;
import other.context.Context;
import other.model.Model;
import other.move.Move;
import other.state.container.ContainerState;
import other.trial.Trial;
import search.minimax.AlphaBetaSearch;
import search.minimax.AlphaBetaSearch.AllowedSearchDepths;
import utils.AIFactory;
/**
* To update a game object with the estimated values of the playout concepts.
*
* @author Eric.Piette
*/
public class ComputePlayoutConcepts
{
/**
* To create RulesetConcepts.csv (Id, RulesetId, ConceptId, Value)
*
* @param game The game to update.
* @param numPlayouts The maximum number of playout.
* @param timeLimit The maximum time to compute the playouts concepts.
* @param thinkingTime The maximum time to take a decision per move.
* @param agentName The name of the agent to use for the playout concepts.
* @param portfolioConcept To compute only the concepts for the portfolio.
*/
public static void updateGame
(
final Game game,
final Evaluation evaluation,
final int numPlayouts,
final double timeLimit,
final double thinkingTime,
final String agentName,
final boolean portfolioConcept
)
{
final List<Concept> nonBooleanConcepts = new ArrayList<Concept>();
for (final Concept concept : (portfolioConcept) ? Concept.portfolioConcepts() : Concept.values())
{
if (!concept.dataType().equals(ConceptDataType.BooleanData))
nonBooleanConcepts.add(concept);
}
final Map<String, Double> frequencyPlayouts = (numPlayouts == 0) ? new HashMap<String, Double>()
: playoutsMetrics(game, evaluation, numPlayouts, timeLimit, thinkingTime, agentName, portfolioConcept);
for (final Concept concept : nonBooleanConcepts)
{
final double value = frequencyPlayouts.get(concept.name()) == null ? Constants.UNDEFINED
: frequencyPlayouts.get(concept.name()).doubleValue();
game.nonBooleanConcepts().put(Integer.valueOf(concept.id()), value+"");
}
}
//------------------------------PLAYOUT CONCEPTS-----------------------------------------------------
/**
* @param game The game
* @param playoutLimit The number of playouts to run.
* @param timeLimit The maximum time to use.
* @param thinkingTime The maximum time to take a decision at each state.
* @param portfolioConcept To compute only the concepts for the portfolio.
* @return The frequency of all the boolean concepts in the number of playouts
* set in entry
*/
private static Map<String, Double> playoutsMetrics
(
final Game game,
final Evaluation evaluation,
final int playoutLimit,
final double timeLimit,
final double thinkingTime,
final String agentName,
final boolean portfolioConcept
)
{
final long startTime = System.currentTimeMillis();
// Used to return the frequency (of each playout concept).
final Map<String, Double> mapFrequency = new HashMap<String, Double>();
// Used to return the value of each metric.
final List<Trial> trials = new ArrayList<Trial>();
final List<RandomProviderState> allStoredRNG = new ArrayList<RandomProviderState>();
// For now I exclude the matches, but can be included too after. The deduc puzzle
// will stay excluded.
if (game.hasSubgames() || game.isDeductionPuzzle() || game.isSimulationMoveGame()
|| game.name().contains("Trax") || game.name().contains("Kriegsspiel"))
{
// We add all the default metrics values corresponding to a concept to the returned map.
final List<Metric> metrics = new Evaluation().conceptMetrics();
for(final Metric metric: metrics)
if(metric.concept() != null)
mapFrequency.put(metric.concept().name(), null);
return mapFrequency;
}
// We run the playouts needed for the computation.
for (int indexPlayout = 0; indexPlayout < playoutLimit; indexPlayout++)
{
final List<AI> ais = chooseAI(game, agentName, indexPlayout);
for(final AI ai : ais)
if(ai != null)
ai.setMaxSecondsPerMove(thinkingTime);
final Context context = new Context(game, new Trial(game));
allStoredRNG.add(context.rng().saveState());
final Trial trial = context.trial();
game.start(context);
// Init the ais (here random).
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, thinkingTime);
trials.add(trial);
final double currentTimeUsed = (System.currentTimeMillis() - startTime) / 1000.0;
if (currentTimeUsed > timeLimit) // We stop if the limit of time is reached.
break;
}
// We get the values of the starting concepts.
mapFrequency.putAll(startsConcepts(game, allStoredRNG));
final long startTimeFrequency = System.currentTimeMillis();
// We get the values of the frequencies.
mapFrequency.putAll(frequencyConcepts(game,trials, allStoredRNG));
final double ms = (System.currentTimeMillis() - startTimeFrequency);
System.out.println("Playouts computation done in " + ms + " ms.");
// We get the values of the metrics.
if(!portfolioConcept)
mapFrequency.putAll(metricsConcepts(game, evaluation, trials, allStoredRNG));
// Computation of the p/s and m/s
if(!portfolioConcept)
mapFrequency.putAll(playoutsEstimationConcepts(game));
return mapFrequency;
}
/**
* @param game The game.
* @param agentName The name of the agent.
* @param indexPlayout The index of the playout.
* @return The list of AIs to play that playout.
*/
private static List<AI> chooseAI(final Game game, final String agentName, final int indexPlayout)
{
final List<AI> ais = new ArrayList<AI>();
ais.add(null);
for (int p = 1; p <= game.players().count(); ++p)
{
if(agentName.equals("UCT"))
{
final AI ai = AIFactory.createAI("UCT");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else if(agentName.equals("Alpha-Beta"))
{
AI ai = AIFactory.createAI("Alpha-Beta");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else if(agentName.equals("Alpha-Beta-UCT")) // AB/UCT/AB/UCT/...
{
if(indexPlayout % 2 == 0)
{
if(p % 2 == 1)
{
AI ai = AIFactory.createAI("Alpha-Beta");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AI ai = AIFactory.createAI("UCT");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if(p % 2 == 1)
{
final AI ai = AIFactory.createAI("UCT");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = AIFactory.createAI("Alpha-Beta");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else if(agentName.equals("AB-Odd-Even")) // Alternating between AB Odd and AB Even
{
if(indexPlayout % 2 == 0)
{
if(p % 2 == 1)
{
AI ai = new AlphaBetaSearch();
((AlphaBetaSearch)ai).setAllowedSearchDepths(AllowedSearchDepths.Odd);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AlphaBetaSearch ai = new AlphaBetaSearch();
ai.setAllowedSearchDepths(AllowedSearchDepths.Even);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if(p % 2 == 1)
{
final AlphaBetaSearch ai = new AlphaBetaSearch();
ai.setAllowedSearchDepths(AllowedSearchDepths.Even);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = new AlphaBetaSearch();
((AlphaBetaSearch)ai).setAllowedSearchDepths(AllowedSearchDepths.Odd);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else
{
ais.add(new utils.RandomAI());
}
}
return ais;
}
/**
*
* @param game The game.
* @param trials The trials.
* @param allStoredRNG The RNG for each trial.
* @return The map of playout concepts to the their values for the starting ones.
*/
private static Map<String, Double> startsConcepts(final Game game, final List<RandomProviderState> allStoredRNG)
{
final Map<String, Double> mapStarting = new HashMap<String, Double>();
final BitSet booleanConcepts = game.booleanConcepts();
double numStartComponents = 0.0;
double numStartComponentsHands = 0.0;
double numStartComponentsBoard = 0.0;
for (int index = 0; index < allStoredRNG.size(); index++)
{
final RandomProviderState rngState = allStoredRNG.get(index);
// Setup a new instance of the game
final Context context = Utils.setupNewContext(game, rngState);
for (int cid = 0; cid < context.containers().length; cid++)
{
final Container cont = context.containers()[cid];
final ContainerState cs = context.containerState(cid);
if (cid == 0)
{
if (booleanConcepts.get(Concept.Cell.id()))
for (int cell = 0; cell < cont.topology().cells().size(); cell++)
{
final int count = game.isStacking() ? cs.sizeStack(cell, SiteType.Cell) : cs.count(cell, SiteType.Cell);
numStartComponents += count;
numStartComponentsBoard += count;
}
if (booleanConcepts.get(Concept.Vertex.id()))
for (int vertex = 0; vertex < cont.topology().vertices().size(); vertex++)
{
final int count = game.isStacking() ? cs.sizeStack(vertex, SiteType.Vertex) : cs.count(vertex, SiteType.Vertex);
numStartComponents += count;
numStartComponentsBoard += count;
}
if (booleanConcepts.get(Concept.Edge.id()))
for (int edge = 0; edge < cont.topology().edges().size(); edge++)
{
final int count = game.isStacking() ? cs.sizeStack(edge, SiteType.Edge) : cs.count(edge, SiteType.Edge);
numStartComponents += count;
numStartComponentsBoard += count;
}
}
else
{
if (booleanConcepts.get(Concept.Cell.id()))
for (int cell = context.sitesFrom()[cid]; cell < context.sitesFrom()[cid]
+ cont.topology().cells().size(); cell++)
{
final int count = game.isStacking() ? cs.sizeStack(cell, SiteType.Cell) : cs.count(cell, SiteType.Cell);
numStartComponents += count;
numStartComponentsHands += count;
}
}
}
}
mapStarting.put(Concept.NumStartComponents.name(), Double.valueOf(numStartComponents / allStoredRNG.size()));
mapStarting.put(Concept.NumStartComponentsHand.name(), Double.valueOf(numStartComponentsHands / allStoredRNG.size()));
mapStarting.put(Concept.NumStartComponentsBoard.name(), Double.valueOf(numStartComponentsBoard / allStoredRNG.size()));
mapStarting.put(Concept.NumStartComponentsPerPlayer.name(), Double.valueOf((numStartComponents / allStoredRNG.size()) / (game.players().count() == 0 ? 1 : game.players().count())));
mapStarting.put(Concept.NumStartComponentsHandPerPlayer.name(), Double.valueOf((numStartComponentsHands / allStoredRNG.size()) / (game.players().count() == 0 ? 1 : game.players().count())));
mapStarting.put(Concept.NumStartComponentsBoardPerPlayer.name(), Double.valueOf((numStartComponentsBoard / allStoredRNG.size()) / (game.players().count() == 0 ? 1 : game.players().count())));
return mapStarting;
}
//------------------------------Frequency CONCEPTS-----------------------------------------------------
/**
* @param game The game.
* @param trials The trials.
* @param allStoredRNG The RNG for each trial.
* @return The map of playout concepts to the their values for the frequency ones.
*/
private static Map<String, Double> frequencyConcepts(final Game game, final List<Trial> trials, final List<RandomProviderState> allStoredRNG)
{
final Map<String, Double> mapFrequency = new HashMap<String, Double>();
// Frequencies of the moves.
final TDoubleArrayList frequencyMoveConcepts = new TDoubleArrayList();
// Frequencies returned by all the playouts.
final TDoubleArrayList frequencyPlayouts = new TDoubleArrayList();
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
frequencyPlayouts.add(0.0);
for (int trialIndex = 0; trialIndex < trials.size(); trialIndex++)
{
final Trial trial = trials.get(trialIndex);
final RandomProviderState rngState = allStoredRNG.get(trialIndex);
// Setup a new instance of the game
final Context context = Utils.setupNewContext(game, rngState);
// Frequencies returned by that playout.
final TDoubleArrayList frenquencyPlayout = new TDoubleArrayList();
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
frenquencyPlayout.add(0);
// Run the playout.
int turnWithMoves = 0;
Context prevContext = null;
for (int i = trial.numInitialPlacementMoves(); i < trial.numMoves(); i++)
{
final Moves legalMoves = context.game().moves(context);
final TIntArrayList frenquencyTurn = new TIntArrayList();
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
frenquencyTurn.add(0);
final double numLegalMoves = legalMoves.moves().size();
if (numLegalMoves > 0)
turnWithMoves++;
for (final Move legalMove : legalMoves.moves())
{
final BitSet moveConcepts = legalMove.moveConcepts(context);
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
if (moveConcepts.get(concept.id()))
frenquencyTurn.set(indexConcept, frenquencyTurn.get(indexConcept) + 1);
}
}
for (int j = 0; j < frenquencyTurn.size(); j++)
frenquencyPlayout.set(j, frenquencyPlayout.get(j) + (numLegalMoves == 0 ? 0 : frenquencyTurn.get(j) / numLegalMoves));
// We keep the context before the ending state for the frequencies of the end conditions.
if(i == trial.numMoves()-1)
prevContext = new Context(context);
// We go to the next move.
context.game().apply(context, trial.getMove(i));
}
// Compute avg for all the playouts.
for (int j = 0; j < frenquencyPlayout.size(); j++)
frequencyPlayouts.set(j, frequencyPlayouts.get(j) + frenquencyPlayout.get(j) / turnWithMoves);
context.trial().lastMove().apply(prevContext, true);
boolean noEndFound = true;
if (game.rules().phases() != null)
{
final int mover = context.state().mover();
final Phase endPhase = game.rules().phases()[context.state().currentPhase(mover)];
final End EndPhaseRule = endPhase.end();
// Only check if action not part of setup
if (context.active() && EndPhaseRule != null)
{
final EndRule[] endRules = EndPhaseRule.endRules();
for (final EndRule endingRule : endRules)
{
final EndRule endRuleResult = endingRule.eval(prevContext);
if (endRuleResult == null)
continue;
final BitSet endConcepts = endingRule.stateConcepts(prevContext);
noEndFound = false;
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
if (concept.type().equals(ConceptType.End) && endConcepts.get(concept.id()))
{
// System.out.println("end with " + concept.name());
frequencyPlayouts.set(indexConcept, frequencyPlayouts.get(indexConcept) + 1);
}
}
// System.out.println();
break;
}
}
}
final End endRule = game.endRules();
if (noEndFound && endRule != null)
{
final EndRule[] endRules = endRule.endRules();
for (final EndRule endingRule : endRules)
{
final EndRule endRuleResult = endingRule.eval(prevContext);
if (endRuleResult == null)
continue;
final BitSet endConcepts = endingRule.stateConcepts(prevContext);
noEndFound = false;
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
if (concept.type().equals(ConceptType.End) && endConcepts.get(concept.id()))
{
// System.out.println("end with " + concept.name());
frequencyPlayouts.set(indexConcept, frequencyPlayouts.get(indexConcept) + 1);
}
}
// System.out.println();
break;
}
}
if (noEndFound)
{
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
if (concept.equals(Concept.Draw))
{
frequencyPlayouts.set(indexConcept, frequencyPlayouts.get(indexConcept) + 1);
break;
}
}
}
}
// Compute avg frequency for the game.
for (int i = 0; i < frequencyPlayouts.size(); i++)
frequencyMoveConcepts.add(frequencyPlayouts.get(i) / trials.size());
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
mapFrequency.put(concept.name(), Double.valueOf(frequencyMoveConcepts.get(indexConcept)));
}
return mapFrequency;
}
//------------------------------Metrics CONCEPTS-----------------------------------------------------
/**
* @param game The game.
* @param trials The trials.
* @param allStoredRNG The RNG for each trial.
* @return The map of playout concepts to the their values for the metric ones.
*/
private static Map<String, Double> metricsConcepts(final Game game, final Evaluation evaluation, final List<Trial> trials, final List<RandomProviderState> allStoredRNG)
{
final Map<String, Double> playoutConceptValues = new HashMap<String, Double>();
// We get the values of the metrics.
final Trial[] trialsMetrics = new Trial[trials.size()];
final RandomProviderState[] rngTrials = new RandomProviderState[trials.size()];
for(int i = 0 ; i < trials.size();i++)
{
trialsMetrics[i] = new Trial(trials.get(i));
rngTrials[i] = allStoredRNG.get(i);
}
// We add all the metrics corresponding to a concept to the returned map.
final List<Metric> metrics = new Evaluation().conceptMetrics();
for(final Metric metric: metrics)
if(metric.concept() != null)
{
double metricValue = metric.apply(game, evaluation, trialsMetrics, rngTrials).doubleValue();
metricValue = (Math.abs(metricValue) < Constants.EPSILON) ? 0 : metricValue;
playoutConceptValues.put(metric.concept().name(), Double.valueOf(metricValue));
}
return playoutConceptValues;
}
//------------------------------Playout Estimation CONCEPTS-----------------------------------------------------
/**
* @param game The game.
* @return The map of playout concepts to the their values for the p/s and m/s ones.
*/
private static Map<String, Double> playoutsEstimationConcepts(final Game game)
{
final Map<String, Double> playoutConceptValues = new HashMap<String, Double>();
// Computation of the p/s and m/s
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
// Warming up
long stopAt = 0L;
long start = System.nanoTime();
final double warmingUpSecs = 1;
final double measureSecs = 3;
double abortAt = start + warmingUpSecs * 1000000000.0;
while (stopAt < abortAt)
{
game.start(context);
game.playout(context, null, 1.0, null, -1, Constants.UNDEFINED, ThreadLocalRandom.current());
stopAt = System.nanoTime();
}
System.gc();
// Set up RNG for this game, Always with a rng of 2077.
final Random rng = new Random((long)game.name().hashCode() * 2077);
// The Test
stopAt = 0L;
start = System.nanoTime();
abortAt = start + measureSecs * 1000000000.0;
int playouts = 0;
int moveDone = 0;
while (stopAt < abortAt)
{
game.start(context);
game.playout(context, null, 1.0, null, -1, Constants.UNDEFINED, rng);
moveDone += context.trial().numMoves();
stopAt = System.nanoTime();
++playouts;
}
final double secs = (stopAt - start) / 1000000000.0;
final double rate = (playouts / secs);
final double rateMove = (moveDone / secs);
playoutConceptValues.put(Concept.PlayoutsPerSecond.name(), Double.valueOf(rate));
playoutConceptValues.put(Concept.MovesPerSecond.name(), Double.valueOf(rateMove));
return playoutConceptValues;
}
}
| 22,332 | 30.904286 | 193 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/concepts/ExportGameConcepts.java
|
package utils.concepts;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
import other.concept.Concept;
import other.concept.ConceptDataType;
import utils.DBGameInfo;
/**
* Method to create the csv files listing all the game concepts used by each
* game.
*
* @author Eric Piette
*/
public class ExportGameConcepts
{
private static final String DOCUMENTED_DLP_LIST_PATH = "res/concepts/input/documentedRulesets.csv";
private static final String DLP_LIST_PATH = "res/concepts/input/dlpRulesets.csv";
// CSV to export
private final static List<String> noHumanCSV = new ArrayList<String>();
private final static List<String> humanCSV = new ArrayList<String>();
private final static List<String> noHumanDocumentedDLPCSV = new ArrayList<String>();
private final static List<String> noHumanDLPCSV = new ArrayList<String>();
private final static List<String> noHumanNotDLPCSV = new ArrayList<String>();
// DLP data
private final static List<String> documentedDLPGames = new ArrayList<String>();
private final static List<List<String>> documentedDLPRulesets = new ArrayList<List<String>>();
private final static List<String> DLPGames = new ArrayList<String>();
private final static List<List<String>> DLPRulesets = new ArrayList<List<String>>();
//-------------------------------------------------------------------------
/**
* Main method.
*
* @param args
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(final String[] args) throws IllegalArgumentException, IllegalAccessException
{
// Get the DLP data.
getDocumentedDLPRulesets();
getDLPRulesets();
// Compilation of all the games.
final String[] allGameNames = FileHandling.listGames();
for (int index = 0; index < allGameNames.length; index++)
{
final String gameName = allGameNames[index];
if (FileHandling.shouldIgnoreLudAnalysis(gameName))
continue;
System.out.println("Compilation of : " + gameName);
final Game game = GameLoader.loadGameFromName(gameName);
exportFor(false, false, false, false, game, gameName); // Non Human, non DLP.
exportFor(true, false, false, false, game, gameName); // Human, non DLP.
exportFor(false, true, false, false, game, gameName); // Non Human, only documented DLP rulesets.
exportFor(false, false, true, false, game, gameName); // Non Human, only DLP games.
exportFor(false, false, false, true, game, gameName); // Non Human, only non DLP games.
}
// for Human CSV: We write the row to count the concepts on.
final TIntArrayList flagsCount = new TIntArrayList();
for (int i = 0; i < humanCSV.get(0).split(",").length - 2; i++)
flagsCount.add(0);
for (int i = 1; i < humanCSV.size(); i++)
{
final String humanString = humanCSV.get(i);
final String[] splitString = humanString.split(",");
for (int j = 2; j < splitString.length; j++)
if (!splitString[j].isEmpty())
flagsCount.set(j - 2, flagsCount.get(j - 2) + 1);
}
final StringBuffer stringToWrite = new StringBuffer();
stringToWrite.append("Num Concepts,");
stringToWrite.append(",");
for (int j = 0; j < flagsCount.size(); j++)
stringToWrite.append(flagsCount.get(j) + ",");
stringToWrite.deleteCharAt(stringToWrite.length() - 1);
humanCSV.add(1, stringToWrite.toString());
// for Human CSV: remove the column with concepts never used.
final TIntArrayList columnToRemove = new TIntArrayList();
final String[] countConcepts = humanCSV.get(1).split(",");
for (int i = 0; i < countConcepts.length; i++)
if (countConcepts[i].equals("0"))
columnToRemove.add(i);
for (int i = 0; i < humanCSV.size(); i++)
{
final String[] stringSplit = humanCSV.get(i).split(",");
final String[] newStringSplit = new String[stringSplit.length - columnToRemove.size()];
int index = 0;
for (int j = 0; j < stringSplit.length; j++)
if (!columnToRemove.contains(j))
{
newStringSplit[index] = stringSplit[j];
index++;
}
humanCSV.set(i, StringRoutines.join(",", newStringSplit));
}
final String fileNameNoHuman = "LudiiGameConcepts";
final String outputFilePathNoHuman = "./res/concepts/output/" + fileNameNoHuman + ".csv";
try (final PrintWriter writer = new UnixPrintWriter(new File(outputFilePathNoHuman), "UTF-8"))
{
for (final String toWrite : noHumanCSV)
writer.println(StringRoutines.join(",", toWrite));
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
final String fileNameHuman = "LudiiGameConceptsHUMAN";
final String outputFilePathHuman = "./res/concepts/output/" + fileNameHuman + ".csv";
try (final PrintWriter writer = new UnixPrintWriter(new File(outputFilePathHuman), "UTF-8"))
{
for (final String toWrite : humanCSV)
writer.println(StringRoutines.join(",", toWrite));
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
final String fileNameNoHumanDocumentedDLP = "LudiiGameConceptsDocumentedDLP";
final String outputFilePathNoHumanDocumentedDLP = "./res/concepts/output/" + fileNameNoHumanDocumentedDLP
+ ".csv";
try (final PrintWriter writer = new UnixPrintWriter(new File(outputFilePathNoHumanDocumentedDLP), "UTF-8"))
{
for (final String toWrite : noHumanDocumentedDLPCSV)
writer.println(StringRoutines.join(",", toWrite));
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
final String fileNameNoHumanDLP = "LudiiGameConceptsDLP";
final String outputFilePathNoHumanDLP = "./res/concepts/output/" + fileNameNoHumanDLP + ".csv";
try (final PrintWriter writer = new UnixPrintWriter(new File(outputFilePathNoHumanDLP), "UTF-8"))
{
for (final String toWrite : noHumanDLPCSV)
writer.println(StringRoutines.join(",", toWrite));
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
final String fileNameNoHumanNotDLP = "LudiiGameConceptsNonDLP";
final String outputFilePathNoHumanNotDLP = "./res/concepts/output/" + fileNameNoHumanNotDLP + ".csv";
try (final PrintWriter writer = new UnixPrintWriter(new File(outputFilePathNoHumanNotDLP), "UTF-8"))
{
for (final String toWrite : noHumanNotDLPCSV)
writer.println(StringRoutines.join(",", toWrite));
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* To run the code according to human or DLP.
*
* @param HUMAN_VERSION To get the human version.
* @param DOCUMENTED_DLP To look only the documented DLP games.
* @param DLP To look only the DLP games.
* @param NonDLP To look only the non DLP games.
*/
public static void exportFor(final boolean HUMAN_VERSION, final boolean DOCUMENTED_DLP, final boolean DLP,
final boolean NonDLP, final Game game,
final String gameName)
{
final TIntArrayList booleanConceptsID = new TIntArrayList();
final TIntArrayList nonBooleanConceptsID = new TIntArrayList();
// We create the header row.
final List<String> headers = new ArrayList<String>();
headers.add("Game Name");
if (HUMAN_VERSION)
headers.add("Num Flags On");
// We get the boolean concepts.
for (final Concept concept : Concept.values())
if (concept.dataType().equals(ConceptDataType.BooleanData))
{
booleanConceptsID.add(concept.id());
headers.add(concept.name());
}
for (final Concept concept : Concept.values())
if (!concept.dataType().equals(ConceptDataType.BooleanData))
{
headers.add(concept.name());
nonBooleanConceptsID.add(concept.id());
}
// In human version we count the game with a flag on.
final TIntArrayList countGamesFlagOn = new TIntArrayList();
for (int i = 0; i < booleanConceptsID.size(); i++)
countGamesFlagOn.add(0);
final List<List<String>> booleanConceptsOn = new ArrayList<List<String>>();
// Some filters in case of DLP games.
if (DOCUMENTED_DLP && !documentedDLPGames.contains(game.name()))
return;
if (DLP && !DLPGames.contains(game.name()))
return;
if (NonDLP && DLPGames.contains(game.name()))
return;
// We got the games (with rulesets) to look at.
final List<Game> rulesetsToLook = new ArrayList<Game>();
final List<String> rulesetNamesToLook = new ArrayList<String>();
final List<Ruleset> rulesets = game.description().rulesets();
if (rulesets != null && !rulesets.isEmpty())
{
for (int rs = 0; rs < rulesets.size(); rs++)
{
final Ruleset ruleset = rulesets.get(rs);
if (!ruleset.optionSettings().isEmpty())
{
final String startString = "Ruleset/";
final String name_ruleset_csv = ruleset.heading().substring(startString.length(),
ruleset.heading().lastIndexOf('(') - 1);
final Game rulesetGame = GameLoader.loadGameFromName(gameName, ruleset.optionSettings());
final String name_ruleset = ruleset.heading();
System.out.println("Compilation of " + rulesetGame.name() + " RULESET = " + name_ruleset);
if (DOCUMENTED_DLP || DLP)
{
boolean found = false;
for (final List<String> list : (DOCUMENTED_DLP ? documentedDLPRulesets : DLPRulesets))
{
if (list.get(0).equals(game.name()))
{
for (int i = 1; i < list.size(); i++)
if (name_ruleset_csv.equals(list.get(i)))
{
rulesetsToLook.add(rulesetGame);
rulesetNamesToLook.add(DBGameInfo.getUniqueName(rulesetGame));
// rulesetNamesToLook.add(game.name() + "_" + list.get(i));
found = true;
break;
}
}
if (found)
break;
}
}
else
{
rulesetsToLook.add(rulesetGame);
rulesetNamesToLook.add(DBGameInfo.getUniqueName(rulesetGame));
}
}
}
}
else
{
if (DOCUMENTED_DLP || DLP)
{
for (final List<String> list : (DOCUMENTED_DLP ? documentedDLPRulesets : DLPRulesets))
{
if (list.get(0).equals(game.name())) // 0 because only one ruleset
{
rulesetsToLook.add(game);
rulesetNamesToLook.add(DBGameInfo.getUniqueName(game));
break;
}
}
}
else
{
rulesetsToLook.add(game);
rulesetNamesToLook.add(DBGameInfo.getUniqueName(game));
}
}
// We get the concepts of each game.
for (int indexGamesToLook = 0; indexGamesToLook < rulesetsToLook.size(); indexGamesToLook++)
{
final Game game_ruleset = rulesetsToLook.get(indexGamesToLook);
final String game_ruleset_name = rulesetNamesToLook.get(indexGamesToLook);
final List<String> flagsOn = new ArrayList<String>();
flagsOn.add(game_ruleset_name.replaceAll("'", "").replaceAll(",", ""));
int count = 0;
for (int i = 0; i < booleanConceptsID.size(); i++)
{
if (game_ruleset.booleanConcepts().get(booleanConceptsID.get(i)))
{
flagsOn.add((HUMAN_VERSION) ? "Yes" : "1");
count++;
countGamesFlagOn.set(i, countGamesFlagOn.get(i) + 1);
}
else
flagsOn.add((HUMAN_VERSION) ? "" : "0");
}
// if human version we add a column for the count of the
// flags on in the second one.
if (HUMAN_VERSION)
{
flagsOn.add("");
for (int j = flagsOn.size() - 1; j > 1; j--)
flagsOn.set(j, flagsOn.get(j - 1));
flagsOn.set(1, count + "");
}
// We export the non boolean concepts.
for (int i = 0; i < nonBooleanConceptsID.size(); i++)
{
final Integer idConcept = Integer.valueOf(nonBooleanConceptsID.get(i));
flagsOn.add(game_ruleset.nonBooleanConcepts().get(idConcept));
}
/** Apply Format Game Name. */
// if (!HUMAN_VERSION)
// {
// flagsOn.set(0, flagsOn.get(0).replaceAll(Pattern.quote(" "), "_"));
// flagsOn.set(0, flagsOn.get(0).replaceAll(Pattern.quote("("), ""));
// flagsOn.set(0, flagsOn.get(0).replaceAll(Pattern.quote(")"), ""));
// flagsOn.set(0, flagsOn.get(0).replaceAll(Pattern.quote(","), ""));
// flagsOn.set(0, flagsOn.get(0).replaceAll(Pattern.quote("\""), ""));
// flagsOn.set(0, flagsOn.get(0).replaceAll(Pattern.quote("'"), ""));
// flagsOn.set(0, flagsOn.get(0).replaceAll(Pattern.quote("["), ""));
// flagsOn.set(0, flagsOn.get(0).replaceAll(Pattern.quote("]"), ""));
// }
booleanConceptsOn.add(flagsOn);
}
if (!HUMAN_VERSION && !DOCUMENTED_DLP && !NonDLP && !DLP && noHumanCSV.isEmpty())
noHumanCSV.add(StringRoutines.join(",", headers));
else if (HUMAN_VERSION && !DOCUMENTED_DLP && !NonDLP && !DLP && humanCSV.isEmpty())
humanCSV.add(StringRoutines.join(",", headers));
else if (!HUMAN_VERSION && DOCUMENTED_DLP && !NonDLP && !DLP && noHumanDocumentedDLPCSV.isEmpty())
noHumanDocumentedDLPCSV.add(StringRoutines.join(",", headers));
else if (!HUMAN_VERSION && DLP && !DOCUMENTED_DLP && !NonDLP && noHumanDLPCSV.isEmpty())
noHumanDLPCSV.add(StringRoutines.join(",", headers));
else if (!HUMAN_VERSION && !DLP && !DOCUMENTED_DLP && NonDLP && noHumanNotDLPCSV.isEmpty())
noHumanNotDLPCSV.add(StringRoutines.join(",", headers));
// Write row for each the game.
for (final List<String> flagsOn : booleanConceptsOn)
if (!HUMAN_VERSION && !DOCUMENTED_DLP && !DLP && !NonDLP)
noHumanCSV.add(StringRoutines.join(",", flagsOn));
else if (HUMAN_VERSION && !DOCUMENTED_DLP && !DLP && !NonDLP)
humanCSV.add(StringRoutines.join(",", flagsOn));
else if (!HUMAN_VERSION && DOCUMENTED_DLP && !DLP && !NonDLP)
noHumanDocumentedDLPCSV.add(StringRoutines.join(",", flagsOn));
else if (!HUMAN_VERSION && DLP && !DOCUMENTED_DLP && !NonDLP)
noHumanDLPCSV.add(StringRoutines.join(",", flagsOn));
else if (!HUMAN_VERSION && !DLP && !DOCUMENTED_DLP && NonDLP)
noHumanNotDLPCSV.add(StringRoutines.join(",", flagsOn));
}
//---------------------------------------------------------------------
/**
* To get the documented DLP rulesets.
*/
public static void getDocumentedDLPRulesets()
{
try (final BufferedReader reader = new BufferedReader(new FileReader("./" + DOCUMENTED_DLP_LIST_PATH)))
{
String line = reader.readLine();
while (line != null)
{
final String name = line.substring(1, line.length() - 1);
final int separatorIndex = name.indexOf(',');
final String game_ruleset = name.substring(0, separatorIndex - 1) + "_"
+ name.substring(separatorIndex + 2, name.length());
final String game_name = game_ruleset.substring(0, game_ruleset.indexOf('_'));
final String ruleset_name = game_ruleset.substring(game_ruleset.indexOf('_') + 1,
game_ruleset.length());
documentedDLPGames.add(game_name);
boolean found = false;
for (final List<String> list : documentedDLPRulesets)
{
if (list.get(0).equals(game_name))
{
found = true;
list.add(ruleset_name);
break;
}
}
if (!found)
{
documentedDLPRulesets.add(new ArrayList<String>());
documentedDLPRulesets.get(documentedDLPRulesets.size() - 1).add(game_name);
documentedDLPRulesets.get(documentedDLPRulesets.size() - 1).add(ruleset_name);
}
line = reader.readLine();
}
reader.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
/**
* To get the documented DLP rulesets.
*/
public static void getDLPRulesets()
{
try (final BufferedReader reader = new BufferedReader(new FileReader("./" + DLP_LIST_PATH)))
{
String line = reader.readLine();
while (line != null)
{
final String name = line.substring(1, line.length() - 1);
final int separatorIndex = name.indexOf(',');
final String game_ruleset = name.substring(0, separatorIndex - 1) + "_"
+ name.substring(separatorIndex + 2, name.length());
final String game_name = game_ruleset.substring(0, game_ruleset.indexOf('_'));
final String ruleset_name = game_ruleset.substring(game_ruleset.indexOf('_') + 1,
game_ruleset.length());
DLPGames.add(game_name);
boolean found = false;
for (final List<String> list : DLPRulesets)
{
if (list.get(0).equals(game_name))
{
found = true;
list.add(ruleset_name);
break;
}
}
if (!found)
{
DLPRulesets.add(new ArrayList<String>());
DLPRulesets.get(DLPRulesets.size() - 1).add(game_name);
DLPRulesets.get(DLPRulesets.size() - 1).add(ruleset_name);
}
line = reader.readLine();
}
reader.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
| 16,871 | 33.787629 | 109 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/concepts/db/ExportDbCsvConcepts.java
|
package utils.concepts.db;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import org.apache.commons.rng.RandomProviderState;
import game.Game;
import game.equipment.container.Container;
import game.match.Match;
import game.rules.end.End;
import game.rules.end.EndRule;
import game.rules.phase.Phase;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ListUtils;
import main.options.Ruleset;
import manager.utils.game_logs.MatchRecord;
import metrics.Evaluation;
import metrics.Metric;
import metrics.Utils;
import other.AI;
import other.GameLoader;
import other.concept.Concept;
import other.concept.ConceptComputationType;
import other.concept.ConceptDataType;
import other.concept.ConceptPurpose;
import other.concept.ConceptType;
import other.context.Context;
import other.model.Model;
import other.move.Move;
import other.state.container.ContainerState;
import other.trial.Trial;
import search.minimax.AlphaBetaSearch;
import search.minimax.AlphaBetaSearch.AllowedSearchDepths;
import utils.AIFactory;
import utils.IdRuleset;
/**
* To export the necessary CSV to build the tables in the database for the
* concepts.
*
* @author Eric.Piette
*
* Structure for the db:
*
* Concepts.csv (Id, Name, Description, TypeId, DataTypeId,
* ComputationTypeId)
*
* ConceptTypes.csv (Id, Name)
*
* ConceptDataTypes.csv (Id, Name)
*
* ConceptComputationTypes.csv (Id, Name)
*
* ConceptKeywords.csv (Id, Name, Description)
*
* ConceptPurposes.csv (Id, Name)
*
* ConceptConceptKeywords.csv (Id, ConceptId, KeywordId)
*
* ConceptConceptPurposes.csv (Id, ConceptId, PurposeId)
*
* RulesetConcepts.csv (Id, RulesetId, ConceptId, Value)
*/
public class ExportDbCsvConcepts
{
/** The path of the csv with the id of the rulesets for each game. */
private static final String GAME_RULESET_PATH = "/concepts/input/GameRulesets.csv";
/** The move limit to use in the trials used. */
private static int moveLimit;
/** The folder with the trials to use. */
private static String folderTrials;
/** The trials. */
private static List<Trial> trials = new ArrayList<Trial>();
// The RNGs of each trial.
private static List<RandomProviderState> allStoredRNG = new ArrayList<RandomProviderState>();
/**
* List of games for which the list of trials to use does not have to be more
* than a specific number to be able to compute in less than 4 days, due to the
* metric computation.
*/
private static List<String> lessTrialsGames = new ArrayList<String>();
/** The limit of trials to use for some games too slow to compute. */
private static final int smallLimitTrials = 30;
/**
* List of games for which the list of trials to use does not have to be more
* than an even lower specific number to be able to compute in less than 4 days, due to the
* metrics.
*/
private static List<String> evenLessTrialsGames = new ArrayList<String>();
/** The limit of trials to use for some games even slower to compute. */
private static final int smallestLimitTrials = 1;
// -------------------------------------------------------------------------
public static void main(final String[] args)
{
// Store the games which needs less trials.
lessTrialsGames.add("Russian Fortress Chess");
lessTrialsGames.add("Puhulmutu");
lessTrialsGames.add("Ludus Latrunculorum");
lessTrialsGames.add("Poprad Game");
lessTrialsGames.add("Unashogi");
lessTrialsGames.add("Taikyoku Shogi");
lessTrialsGames.add("Tai Shogi");
lessTrialsGames.add("Pagade Kayi Ata (Sixteen-handed)");
lessTrialsGames.add("Chex");
lessTrialsGames.add("Poprad Game");
lessTrialsGames.add("Backgammon"); // Mostly for smart agent (AB), the playouts are too long
lessTrialsGames.add("Buffa de Baldrac"); // Mostly for smart agent (AB), the playouts are too long
lessTrialsGames.add("Portes"); // Mostly for smart agent (AB), the playouts are too long
lessTrialsGames.add("Shatranj al-Kabir"); // Mostly for smart agent (AB), the playouts are too long
// Really slow games (included deduc puzzles because the trials always reach the move limit....)
evenLessTrialsGames.add("Kriegsspiel");
evenLessTrialsGames.add("Anti-Knight Sudoku");
evenLessTrialsGames.add("Fill A Pix");
evenLessTrialsGames.add("Futoshiki");
evenLessTrialsGames.add("Hoshi");
evenLessTrialsGames.add("Kakuro");
evenLessTrialsGames.add("Killer Sudoku");
evenLessTrialsGames.add("Latin Square");
evenLessTrialsGames.add("Magic Hexagon");
evenLessTrialsGames.add("Magic Square");
evenLessTrialsGames.add("N Queens");
evenLessTrialsGames.add("Samurai Sudoku");
evenLessTrialsGames.add("Slitherlink");
evenLessTrialsGames.add("Squaro");
evenLessTrialsGames.add("Sudoku");
evenLessTrialsGames.add("Sudoku Mine");
evenLessTrialsGames.add("Sudoku X");
evenLessTrialsGames.add("Sujiken");
evenLessTrialsGames.add("Takuzu");
evenLessTrialsGames.add("Tridoku");
final Evaluation evaluation = new Evaluation();
int numPlayouts = args.length == 0 ? 0 : Integer.parseInt(args[0]);
final double timeLimit = args.length < 2 ? 0 : Double.parseDouble(args[1]);
final double thinkingTime = args.length < 3 ? 1 : Double.parseDouble(args[2]);
moveLimit = args.length < 4 ? Constants.DEFAULT_MOVES_LIMIT : Integer.parseInt(args[3]);
final String agentName = args.length < 5 ? "Random" : args[4];
folderTrials = args.length < 6 ? "" : args[5];
final String gameName = args.length < 7 ? "" : args[6];
final String rulesetName = args.length < 8 ? "" : args[7];
final String agentName2 = args.length < 9 ? "" : args[8];
if (gameName.isEmpty())
{
exportConceptCSV();
exportConceptTypeCSV();
exportConceptDataTypeCSV();
exportConceptComputationTypeCSV();
exportConceptPurposeCSV();
exportConceptConceptPurposesCSV();
}
if (evenLessTrialsGames.contains(gameName) && numPlayouts > smallestLimitTrials)
numPlayouts = smallestLimitTrials;
else if (lessTrialsGames.contains(gameName) && numPlayouts > smallLimitTrials)
numPlayouts = smallLimitTrials;
exportRulesetConceptsCSV(evaluation, numPlayouts, timeLimit, thinkingTime, agentName, gameName, rulesetName, agentName2);
}
// -------------------------------------------------------------------------
/**
* To create Concepts.csv (Id, Name, Description, TypeId, DataTypeId)
*/
public static void exportConceptCSV()
{
List<String> toNotShowOnWebsite = new ArrayList<String>();
toNotShowOnWebsite.add("Properties");
toNotShowOnWebsite.add("Format");
toNotShowOnWebsite.add("Time");
toNotShowOnWebsite.add("Turns");
toNotShowOnWebsite.add("Players");
toNotShowOnWebsite.add("Equipment");
toNotShowOnWebsite.add("Board");
toNotShowOnWebsite.add("Container");
toNotShowOnWebsite.add("Component");
toNotShowOnWebsite.add("Rules");
toNotShowOnWebsite.add("Play");
toNotShowOnWebsite.add("Efficiency");
toNotShowOnWebsite.add("Implementation");
toNotShowOnWebsite.add("Visual");
toNotShowOnWebsite.add("Style");
toNotShowOnWebsite.add("Math");
toNotShowOnWebsite.add("Behaviour");
final String outputConcept = "Concepts.csv";
System.out.println("Writing Concepts.csv");
try (final PrintWriter writer = new UnixPrintWriter(new File(outputConcept), "UTF-8"))
{
for (final Concept concept : Concept.values())
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(concept.id() + "");
lineToWrite.add("\"" + concept.name() + "\"");
lineToWrite.add("\"" + concept.description() + "\"");
lineToWrite.add(concept.type().id() + "");
lineToWrite.add(concept.dataType().id() + "");
lineToWrite.add(concept.computationType().id() + "");
lineToWrite.add("\"" + concept.taxonomy() + "\"");
lineToWrite.add(concept.isleaf() ? "1" : "0");
lineToWrite.add(toNotShowOnWebsite.contains(concept.name()) ? "0" : "1");
writer.println(StringRoutines.join(",", lineToWrite));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("Done.");
}
// -------------------------------------------------------------------------
/**
* To create ConceptTypes.csv (Id, Name)
*/
public static void exportConceptTypeCSV()
{
final String outputConceptType = "ConceptTypes.csv";
System.out.println("Writing ConceptTypes.csv");
try (final PrintWriter writer = new UnixPrintWriter(new File(outputConceptType), "UTF-8"))
{
for (final ConceptType conceptType : ConceptType.values())
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(conceptType.id() + "");
lineToWrite.add("\"" + conceptType.name() + "\"");
writer.println(StringRoutines.join(",", lineToWrite));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("Done.");
}
// -------------------------------------------------------------------------
/**
* To create ConceptDataTypes.csv (Id, Name)
*/
public static void exportConceptDataTypeCSV()
{
final String outputDataType = "ConceptDataTypes.csv";
System.out.println("Writing ConceptDataTypes.csv");
try (final PrintWriter writer = new UnixPrintWriter(new File(outputDataType), "UTF-8"))
{
for (final ConceptDataType dataType : ConceptDataType.values())
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(dataType.id() + "");
lineToWrite.add("\"" + dataType.name() + "\"");
writer.println(StringRoutines.join(",", lineToWrite));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("Done.");
}
// -------------------------------------------------------------------------
/**
* To create ConceptComputationTypes.csv (Id, Name)
*/
public static void exportConceptComputationTypeCSV()
{
final String outputComputationType = "ConceptComputationTypes.csv";
System.out.println("Writing ConceptComputationTypes.csv");
try (final PrintWriter writer = new UnixPrintWriter(new File(outputComputationType), "UTF-8"))
{
for (final ConceptComputationType dataType : ConceptComputationType.values())
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(dataType.id() + "");
lineToWrite.add("\"" + dataType.name() + "\"");
writer.println(StringRoutines.join(",", lineToWrite));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("Done.");
}
// -------------------------------------------------------------------------
/**
* To create ConceptPurposes.csv (Id, Name)
*/
public static void exportConceptPurposeCSV()
{
final String outputConceptPurposes = "ConceptPurposes.csv";
System.out.println("Writing ConceptPurposes.csv");
try (final PrintWriter writer = new UnixPrintWriter(new File(outputConceptPurposes), "UTF-8"))
{
for (final ConceptPurpose purpose : ConceptPurpose.values())
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(purpose.id() + "");
lineToWrite.add("\"" + purpose.name() + "\"");
writer.println(StringRoutines.join(",", lineToWrite));
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("Done.");
}
// -------------------------------------------------------------------------
/**
* To create ConceptConceptPurposes.csv (Id, ConceptId, PurposeId)
*/
public static void exportConceptConceptPurposesCSV()
{
final String outputConceptConceptPurposes = "ConceptConceptPurposes.csv";
System.out.println("Writing ConceptConceptPurposes.csv");
try (final PrintWriter writer = new UnixPrintWriter(new File(outputConceptConceptPurposes), "UTF-8"))
{
int id = 1;
for (final Concept concept : Concept.values())
{
for (final ConceptPurpose purpose : concept.purposes())
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(id + "");
lineToWrite.add(concept.id() + "");
lineToWrite.add(purpose.id() + "");
writer.println(StringRoutines.join(",", lineToWrite));
id++;
}
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("Done.");
}
// -------------------------------------------------------------------------
/**
* To create RulesetConcepts.csv (Id, RulesetId, ConceptId, Value)
*
* @param numPlayouts The maximum number of playout.
* @param timeLimit The maximum time to compute the playouts concepts.
* @param thinkingTime The maximum time to take a decision per move.
* @param agentName The name of the agent to use for the playout concepts
* @param name The name of the game.
* @param rulesetExpected The name of the ruleset of the game.
* @param agentName2 The name for a different second agent (if not empty string)
*/
public static void exportRulesetConceptsCSV
(
final Evaluation evaluation,
final int numPlayouts,
final double timeLimit,
final double thinkingTime,
final String agentName,
final String name,
final String rulesetExpected,
final String agentName2
)
{
final List<Concept> ignoredConcepts = new ArrayList<Concept>();
ignoredConcepts.add(Concept.Behaviour);
ignoredConcepts.add(Concept.StateRepetition);
ignoredConcepts.add(Concept.Duration);
ignoredConcepts.add(Concept.Complexity);
ignoredConcepts.add(Concept.BoardCoverage);
ignoredConcepts.add(Concept.GameOutcome);
ignoredConcepts.add(Concept.StateEvaluation);
ignoredConcepts.add(Concept.Clarity);
ignoredConcepts.add(Concept.Decisiveness);
ignoredConcepts.add(Concept.Drama);
ignoredConcepts.add(Concept.MoveEvaluation);
ignoredConcepts.add(Concept.StateEvaluationDifference);
ignoredConcepts.add(Concept.BoardSitesOccupied);
ignoredConcepts.add(Concept.BranchingFactor);
ignoredConcepts.add(Concept.DecisionFactor);
ignoredConcepts.add(Concept.MoveDistance);
ignoredConcepts.add(Concept.PieceNumber);
ignoredConcepts.add(Concept.ScoreDifference);
final List<String> games = new ArrayList<String>();
final List<String> rulesets = new ArrayList<String>();
final TIntArrayList ids = new TIntArrayList();
// Get the ids of the rulesets.
try (final InputStream in = ExportDbCsvConcepts.class.getResourceAsStream(GAME_RULESET_PATH);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));)
{
String line = reader.readLine();
while (line != null)
{
String lineNoQuote = line.replaceAll(Pattern.quote("\""), "");
int separatorIndex = lineNoQuote.indexOf(',');
final String gameName = lineNoQuote.substring(0, separatorIndex);
games.add(gameName);
lineNoQuote = lineNoQuote.substring(gameName.length() + 1);
separatorIndex = lineNoQuote.indexOf(',');
final String rulesetName = lineNoQuote.substring(0, separatorIndex);
rulesets.add(rulesetName);
lineNoQuote = lineNoQuote.substring(rulesetName.length() + 1);
final int id = Integer.parseInt(lineNoQuote);
ids.add(id);
// System.out.println(gameName + " --- " + rulesetName + " --- " + id);
line = reader.readLine();
}
reader.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
final String fileName = name.isEmpty() ? ""
: name.substring(name.lastIndexOf('/') + 1, name.length() - 4).replace(" ", "");
final String outputRulesetConcepts = rulesetExpected.isEmpty() ? "RulesetConcepts" + fileName + ".csv"
: "RulesetConcepts" + fileName + "-" + rulesetExpected.substring(8) + ".csv";
System.out.println("Writing " + outputRulesetConcepts);
// Do nothing if the files already exist.
final File file = new File(outputRulesetConcepts);
if(file.exists())
return;
// Computation of the concepts
try (final PrintWriter writer = new UnixPrintWriter(new File(outputRulesetConcepts), "UTF-8"))
{
final List<Concept> booleanConcepts = new ArrayList<Concept>();
final List<Concept> nonBooleanConcepts = new ArrayList<Concept>();
for (final Concept concept : Concept.values())
{
if (concept.dataType().equals(ConceptDataType.BooleanData))
booleanConcepts.add(concept);
else
nonBooleanConcepts.add(concept);
}
int id = 1;
final String[] gameNames = FileHandling.listGames();
// Check only the games wanted
for (int index = 0; index < gameNames.length; index++)
{
final String gameName = gameNames[index];
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/pending/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/validation/"))
continue;
if (!name.isEmpty() && !gameName.substring(1).equals(name.replaceAll(Pattern.quote("\\"), "/")))
continue;
final Game game = GameLoader.loadGameFromName(gameName);
game.setMaxMoveLimit(moveLimit);
game.start(new Context(game, new Trial(game)));
System.out.println("Loading game: " + game.name());
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Code for games with many rulesets
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
// We check if we want a specific ruleset.
if (!rulesetExpected.isEmpty() && !rulesetExpected.equals(ruleset.heading()))
continue;
if (!ruleset.optionSettings().isEmpty() && !ruleset.heading().contains("Incomplete")) // We check if the ruleset is implemented.
{
final Game rulesetGame = GameLoader.loadGameFromName(gameName, ruleset.optionSettings());
rulesetGame.setMaxMoveLimit(moveLimit);
System.out.println("Loading ruleset: " + rulesetGame.getRuleset().heading());
final Map<String, Double> playoutConcepts = (numPlayouts == 0)
? new HashMap<String, Double>()
: playoutsMetrics(rulesetGame, evaluation, numPlayouts, timeLimit, thinkingTime, agentName, agentName2);
final int idRuleset = IdRuleset.get(rulesetGame);
final BitSet concepts = rulesetGame.booleanConcepts();
final Map<Integer,String> nonBooleanConceptsValues = rulesetGame.nonBooleanConcepts();
// Boolean concepts
for (final Concept concept : booleanConcepts)
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(id + ""); // id
lineToWrite.add(idRuleset + ""); // id ruleset
lineToWrite.add(concept.id() + ""); // id concept
if(ignoredConcepts.contains(concept))
lineToWrite.add("NULL");
else if (concepts.get(concept.id()))
lineToWrite.add("\"1\"");
else
lineToWrite.add("\"0\"");
writer.println(StringRoutines.join(",", lineToWrite));
id++;
}
System.out.println("NON BOOLEAN CONCEPTS");
// Non Boolean Concepts
for (final Concept concept : nonBooleanConcepts)
{
if (concept.computationType().equals(ConceptComputationType.Compilation))
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(id + "");
lineToWrite.add(idRuleset + "");
lineToWrite.add(concept.id() + "");
lineToWrite.add(
"\"" + nonBooleanConceptsValues.get(Integer.valueOf(concept.id())) + "\"");
writer.println(StringRoutines.join(",", lineToWrite));
id++;
}
else
{
final String conceptName = concept.name();
if (conceptName.indexOf("Frequency") == Constants.UNDEFINED) // Non Frequency concepts added to the csv.
{
final double value = playoutConcepts.get(concept.name()) == null ? Constants.UNDEFINED
: playoutConcepts.get(concept.name()).doubleValue();
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(id + "");
lineToWrite.add(idRuleset + "");
lineToWrite.add(concept.id() + "");
lineToWrite.add(value == Constants.UNDEFINED ? "NULL"
: "\"" + new DecimalFormat("##.##").format(value) + "\""); // the value of the metric
writer.println(StringRoutines.join(",", lineToWrite));
id++;
}
else // Frequency concepts added to the csv.
{
final String correspondingBooleanConceptName = conceptName.substring(0, conceptName.indexOf("Frequency"));
for (final Concept correspondingConcept : booleanConcepts)
{
if (correspondingConcept.name().equals(correspondingBooleanConceptName))
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(id + "");
lineToWrite.add(idRuleset + "");
lineToWrite.add(concept.id() + "");
final double frequency = playoutConcepts
.get(correspondingConcept.name()) == null ? Constants.UNDEFINED
: playoutConcepts.get(correspondingConcept.name()).doubleValue();
if (frequency > 0)
System.out.println(concept + " = " + (frequency * 100) + "%");
lineToWrite.add((frequency > 0 ? "\"" + new DecimalFormat("##.##").format(frequency) + "\"" : "0") + ""); // the frequency
writer.println(StringRoutines.join(",", lineToWrite));
id++;
}
}
}
}
}
}
}
}
else // Code for games with only a single ruleset.
{
final Map<String, Double> playoutConcepts = (numPlayouts == 0) ? new HashMap<String, Double>()
: playoutsMetrics(game, evaluation, numPlayouts, timeLimit, thinkingTime, agentName, agentName2);
final int idRuleset = IdRuleset.get(game);
final BitSet concepts = game.booleanConcepts();
for (final Concept concept : booleanConcepts)
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(id + "");
lineToWrite.add(idRuleset + "");
lineToWrite.add(concept.id() + "");
if(ignoredConcepts.contains(concept))
lineToWrite.add("NULL");
else if (concepts.get(concept.id()))
lineToWrite.add("\"1\"");
else
lineToWrite.add("\"0\"");
writer.println(StringRoutines.join(",", lineToWrite));
id++;
}
for (final Concept concept : nonBooleanConcepts)
{
if (concept.computationType().equals(ConceptComputationType.Compilation))
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(id + "");
lineToWrite.add(idRuleset + "");
lineToWrite.add(concept.id() + "");
lineToWrite.add(
"\"" + game.nonBooleanConcepts().get(Integer.valueOf(concept.id())) + "\"");
writer.println(StringRoutines.join(",", lineToWrite));
id++;
}
else
{
final String conceptName = concept.name();
if (conceptName.indexOf("Frequency") == Constants.UNDEFINED) // Non Frequency concepts added to the csv.
{
final double value = playoutConcepts.get(conceptName) == null ? Constants.UNDEFINED
: playoutConcepts.get(conceptName).doubleValue();
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(id + "");
lineToWrite.add(idRuleset + "");
lineToWrite.add(concept.id() + "");
lineToWrite.add(value == Constants.UNDEFINED ? "NULL"
: "\"" + new DecimalFormat("##.##").format(value) + "\""); // the value of the metric
writer.println(StringRoutines.join(",", lineToWrite));
id++;
// if(value != 0)
// System.out.println("metric: " + concept + " value is " + value);
}
else // Frequency concepts added to the csv.
{
final String correspondingBooleanConceptName = conceptName.substring(0, conceptName.indexOf("Frequency"));
for (final Concept correspondingConcept : booleanConcepts)
{
if (correspondingConcept.name().equals(correspondingBooleanConceptName))
{
final List<String> lineToWrite = new ArrayList<String>();
lineToWrite.add(id + "");
lineToWrite.add(idRuleset + "");
lineToWrite.add(concept.id() + "");
final double frequency = playoutConcepts
.get(correspondingConcept.name()) == null ? Constants.UNDEFINED
: playoutConcepts.get(correspondingConcept.name()).doubleValue();
if(frequency > 0)
System.out.println(concept + " = " + (frequency * 100) +"%");
lineToWrite.add((frequency > 0 ? "\"" + new DecimalFormat("##.##").format(frequency) + "\"" : "0") + ""); // the frequency
writer.println(StringRoutines.join(",", lineToWrite));
id++;
}
}
}
}
}
}
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("Done.");
}
// ------------------------------PLAYOUT CONCEPTS-----------------------------------------------------
/**
* @param game The game
* @param playoutLimit The number of playouts to run.
* @param timeLimit The maximum time to use.
* @param thinkingTime The maximum time to take a decision at each state.
* @return The frequency of all the boolean concepts in the number of playouts
* set in entry
*/
private static Map<String, Double> playoutsMetrics(final Game game, final Evaluation evaluation,
final int playoutLimit, final double timeLimit, final double thinkingTime, final String agentName,
final String agentName2)
{
final long startTime = System.currentTimeMillis();
// Used to return the frequency (of each playout concept).
final Map<String, Double> mapFrequency = new HashMap<String, Double>();
// For now I exclude the matches, but can be included too after. The deduc puzzle
// will stay excluded.
if (//game.hasSubgames() || game.isDeductionPuzzle() || game.isSimulationMoveGame())
game.name().contains("Kriegsspiel"))
{
// We add all the default metrics values corresponding to a concept to the
// returned map.
final List<Metric> metrics = new Evaluation().conceptMetrics();
for (final Metric metric : metrics)
if (metric.concept() != null)
mapFrequency.put(metric.concept().name(), null);
// Computation of the p/s and m/s
mapFrequency.putAll(playoutsEstimationConcepts(game));
return mapFrequency;
}
// We run the playouts needed for the computation.
if (folderTrials.isEmpty())
{
// Create list of AI objects to be used in all trials
final List<AI> aisAllTrials = chooseAI(game, agentName, agentName2, 0);
for (final AI ai : aisAllTrials)
if (ai != null)
ai.setMaxSecondsPerMove(thinkingTime);
final int numPlayers = game.players().count();
List<TIntArrayList> aiListPermutations = new ArrayList<TIntArrayList>();
if (numPlayers <= 5)
{
// Compute all possible permutations of indices for the list of AIs
aiListPermutations = ListUtils.generatePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()));
Collections.shuffle(aiListPermutations);
}
else
{
// Randomly generate some permutations of indices for the list of AIs
aiListPermutations = ListUtils.samplePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()), 120);
}
int playoutsDone = 0;
for (int indexPlayout = 0; indexPlayout < playoutLimit; indexPlayout++)
{
// final List<AI> ais = chooseAI(game, agentName, agentName2, indexPlayout);
//
// for (final AI ai : ais)
// if (ai != null)
// ai.setMaxSecondsPerMove(thinkingTime);
// Create re-ordered list of AIs for this particular playout
final List<AI> ais = new ArrayList<AI>();
ais.add(null);
final int currentAIsPermutation = indexPlayout % aiListPermutations.size();
final TIntArrayList currentPlayersPermutation = aiListPermutations.get(currentAIsPermutation);
for (int i = 0; i < currentPlayersPermutation.size(); ++i)
{
ais.add
(
aisAllTrials.get(currentPlayersPermutation.getQuick(i) % aisAllTrials.size())
);
}
final Context context = new Context(game, new Trial(game));
allStoredRNG.add(context.rng().saveState());
final Trial trial = context.trial();
game.start(context);
// Init the ais.
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, thinkingTime);
trials.add(trial);
playoutsDone++;
for (int p = 1; p <= game.players().count(); ++p)
ais.get(p).closeAI();
final double currentTimeUsed = (System.currentTimeMillis() - startTime) / 1000.0;
if (currentTimeUsed > timeLimit) // We stop if the limit of time is reached.
break;
}
final double allSeconds = (System.currentTimeMillis() - startTime) / 1000.0;
final int seconds = (int) (allSeconds % 60.0);
final int minutes = (int) ((allSeconds - seconds) / 60.0);
System.out.println(
"Playouts done in " + minutes + " minutes " + seconds + " seconds. " + playoutsDone + " playouts.");
}
else
{
getTrials(game);
}
// We get the values of the frequencies.
mapFrequency.putAll(frequencyConcepts(game));
final List<Concept> reconstructionConcepts = new ArrayList<Concept>();
reconstructionConcepts.add(Concept.DurationTurns);
reconstructionConcepts.add(Concept.DurationTurnsStdDev);
reconstructionConcepts.add(Concept.DurationTurnsNotTimeouts);
reconstructionConcepts.add(Concept.DecisionMoves);
reconstructionConcepts.add(Concept.BoardCoverageDefault);
reconstructionConcepts.add(Concept.AdvantageP1);
reconstructionConcepts.add(Concept.Balance);
reconstructionConcepts.add(Concept.Completion);
reconstructionConcepts.add(Concept.Timeouts);
reconstructionConcepts.add(Concept.Drawishness);
reconstructionConcepts.add(Concept.PieceNumberAverage);
reconstructionConcepts.add(Concept.BoardSitesOccupiedAverage);
reconstructionConcepts.add(Concept.BranchingFactorAverage);
reconstructionConcepts.add(Concept.DecisionFactorAverage);
// We get the values of the metrics.
mapFrequency.putAll(metricsConcepts(game, evaluation, reconstructionConcepts));
// We get the values of the starting concepts.
mapFrequency.putAll(startsConcepts(game));
// Computation of the p/s and m/s
mapFrequency.putAll(playoutsEstimationConcepts(game));
return mapFrequency;
}
/**
* @param game The game.
*/
private static void getTrials(final Game game)
{
final File currentFolder = new File(".");
final File folder = new File(currentFolder.getAbsolutePath() + folderTrials);
final String gameName = game.name();
final String rulesetName = game.getRuleset() == null ? "" : game.getRuleset().heading();
// System.out.println("GAME NAME = " + gameName);
// System.out.println("RULESET NAME = " + rulesetName);
String trialFolderPath = folder + "/" + gameName;
if (!rulesetName.isEmpty())
trialFolderPath += File.separator + rulesetName.replace("/", "_");
final File trialFolder = new File(trialFolderPath);
if (trialFolder.exists())
System.out.println("TRIALS FOLDER EXIST");
else
System.out.println("DO NOT FOUND IT - Path is " + trialFolder);
int limit = Constants.UNDEFINED;
if (evenLessTrialsGames.contains(gameName))
limit = smallestLimitTrials;
else if (lessTrialsGames.contains(gameName))
limit = smallLimitTrials;
int num = 0;
for (final File trialFile : trialFolder.listFiles())
{
System.out.println(trialFile.getName());
if(trialFile.getName().contains(".txt"))
{
MatchRecord loadedRecord;
try
{
loadedRecord = MatchRecord.loadMatchRecordFromTextFile(trialFile, game);
final Trial loadedTrial = loadedRecord.trial();
trials.add(loadedTrial);
allStoredRNG.add(loadedRecord.rngState());
num++;
if (num == limit)
break;
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
/**
* @param game The game.
* @param agentName The name of the agent.
* @param agentName2 The name of the second agent (can be empty string if not used).
* @param indexPlayout The index of the playout.
* @return The list of AIs to play that playout.
*/
private static List<AI> chooseAI(final Game game, final String agentName, final String agentName2, final int indexPlayout)
{
final List<AI> ais = new ArrayList<AI>();
//ais.add(null);
if (agentName2.length() > 0)
{
// Special case where we have provided two different names
if (game.players().count() == 2)
{
ais.add(AIFactory.createAI(agentName));
ais.add(AIFactory.createAI(agentName2));
return ais;
}
else
{
System.err.println("Provided 2 agent names, but not a 2-player game!");
}
}
// Continue with Eric's original implementation
for (int p = 1; p <= game.players().count(); ++p)
{
if (agentName.equals("UCT"))
{
final AI ai = AIFactory.createAI("UCT");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else if (agentName.equals("Alpha-Beta"))
{
AI ai = AIFactory.createAI("Alpha-Beta");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else if (agentName.equals("Alpha-Beta-UCT")) // AB/UCT/AB/UCT/...
{
if (indexPlayout % 2 == 0)
{
if (p % 2 == 1)
{
AI ai = AIFactory.createAI("Alpha-Beta");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AI ai = AIFactory.createAI("UCT");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if (p % 2 == 1)
{
final AI ai = AIFactory.createAI("UCT");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = AIFactory.createAI("Alpha-Beta");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else if (agentName.equals("ABONEPLY")) // AB/ONEPLY/AB/ONEPLY/...
{
if (indexPlayout % 2 == 0)
{
if (p % 2 == 1)
{
AI ai = AIFactory.createAI("Alpha-Beta");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("One-Ply (No Heuristic)").supportsGame(game))
{
ai = AIFactory.createAI("One-Ply (No Heuristic)");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AI ai = AIFactory.createAI("One-Ply (No Heuristic)");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if (p % 2 == 1)
{
final AI ai = AIFactory.createAI("One-Ply (No Heuristic)");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = AIFactory.createAI("Alpha-Beta");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("One-Ply (No Heuristic)").supportsGame(game))
{
ai = AIFactory.createAI("One-Ply (No Heuristic)");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else if (agentName.equals("UCTONEPLY")) // UCT/ONEPLY/UCT/ONEPLY/...
{
if (indexPlayout % 2 == 0)
{
if (p % 2 == 1)
{
AI ai = AIFactory.createAI("UCT");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("One-Ply (No Heuristic)").supportsGame(game))
{
ai = AIFactory.createAI("One-Ply (No Heuristic)");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AI ai = AIFactory.createAI("One-Ply (No Heuristic)");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if (p % 2 == 1)
{
final AI ai = AIFactory.createAI("One-Ply (No Heuristic)");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = AIFactory.createAI("UCT");
if (ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("One-Ply (No Heuristic)").supportsGame(game))
{
ai = AIFactory.createAI("One-Ply (No Heuristic)");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else if (agentName.equals("AB-Odd-Even")) // Alternating between AB Odd and AB Even
{
if (indexPlayout % 2 == 0)
{
if (p % 2 == 1)
{
AI ai = new AlphaBetaSearch();
((AlphaBetaSearch) ai).setAllowedSearchDepths(AllowedSearchDepths.Odd);
if (ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AlphaBetaSearch ai = new AlphaBetaSearch();
ai.setAllowedSearchDepths(AllowedSearchDepths.Even);
if (ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if (p % 2 == 1)
{
final AlphaBetaSearch ai = new AlphaBetaSearch();
ai.setAllowedSearchDepths(AllowedSearchDepths.Even);
if (ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = new AlphaBetaSearch();
((AlphaBetaSearch) ai).setAllowedSearchDepths(AllowedSearchDepths.Odd);
if (ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else
{
ais.add(new utils.RandomAI());
}
}
return ais;
}
/**
*
* @param game The game.
* @return The map of playout concepts to the their values for the starting
* ones.
*/
private static Map<String, Double> startsConcepts(final Game game)
{
final Map<String, Double> mapStarting = new HashMap<String, Double>();
final long startTime = System.currentTimeMillis();
final BitSet booleanConcepts = game.booleanConcepts();
double numStartComponents = 0.0;
double numStartComponentsHands = 0.0;
double numStartComponentsBoard = 0.0;
// Check for each initial state of the game.
for (int index = 0; index < allStoredRNG.size(); index++)
{
final RandomProviderState rngState = allStoredRNG.get(index);
// Setup a new instance of the game
final Context context = Utils.setupNewContext(game, rngState);
for (int cid = 0; cid < context.containers().length; cid++)
{
final Container cont = context.containers()[cid];
final ContainerState cs = context.containerState(cid);
if (cid == 0)
{
if (booleanConcepts.get(Concept.Cell.id()))
for (int cell = 0; cell < cont.topology().cells().size(); cell++)
{
final int count = (game.hasSubgames() ? ((Match) game).instances()[0].getGame().isStacking() : game.isStacking())
? cs.sizeStack(cell, SiteType.Cell)
: cs.count(cell, SiteType.Cell);
numStartComponents += count;
numStartComponentsBoard += count;
}
if (booleanConcepts.get(Concept.Vertex.id()))
for (int vertex = 0; vertex < cont.topology().vertices().size(); vertex++)
{
final int count = (game.hasSubgames() ? ((Match) game).instances()[0].getGame().isStacking() : game.isStacking())
? cs.sizeStack(vertex, SiteType.Vertex)
: cs.count(vertex, SiteType.Vertex);
numStartComponents += count;
numStartComponentsBoard += count;
}
if (booleanConcepts.get(Concept.Edge.id()))
for (int edge = 0; edge < cont.topology().edges().size(); edge++)
{
final int count = (game.hasSubgames() ? ((Match) game).instances()[0].getGame().isStacking() : game.isStacking())
? cs.sizeStack(edge, SiteType.Edge)
: cs.count(edge, SiteType.Edge);
numStartComponents += count;
numStartComponentsBoard += count;
}
}
else
{
if (booleanConcepts.get(Concept.Cell.id()))
for (int cell = context.sitesFrom()[cid]; cell < context.sitesFrom()[cid]
+ cont.topology().cells().size(); cell++)
{
final int count = (game.hasSubgames() ? ((Match) game).instances()[0].getGame().isStacking() : game.isStacking())
? cs.sizeStack(cell, SiteType.Cell)
: cs.count(cell, SiteType.Cell);
numStartComponents += count;
numStartComponentsHands += count;
}
}
}
}
mapStarting.put(Concept.NumStartComponents.name(), Double.valueOf(numStartComponents / allStoredRNG.size()));
mapStarting.put(Concept.NumStartComponentsHand.name(), Double.valueOf(numStartComponentsHands / allStoredRNG.size()));
mapStarting.put(Concept.NumStartComponentsBoard.name(), Double.valueOf(numStartComponentsBoard / allStoredRNG.size()));
mapStarting.put(Concept.NumStartComponentsPerPlayer.name(), Double.valueOf((numStartComponents / allStoredRNG.size()) / (game.players().count() == 0 ? 1 : game.players().count())));
mapStarting.put(Concept.NumStartComponentsHandPerPlayer.name(), Double.valueOf((numStartComponentsHands / allStoredRNG.size()) / (game.players().count() == 0 ? 1 : game.players().count())));
mapStarting.put(Concept.NumStartComponentsBoardPerPlayer.name(), Double.valueOf((numStartComponentsBoard / allStoredRNG.size()) / (game.players().count() == 0 ? 1 : game.players().count())));
// System.out.println(Concept.NumStartComponents.name() + " = " + mapStarting.get(Concept.NumStartComponents.name()));
// System.out.println(Concept.NumStartComponentsHand.name() + " = " + mapStarting.get(Concept.NumStartComponentsHand.name()));
// System.out.println(Concept.NumStartComponentsBoard.name() + " = " + mapStarting.get(Concept.NumStartComponentsBoard.name()));
final double allMilliSecond = System.currentTimeMillis() - startTime;
final double allSeconds = allMilliSecond / 1000.0;
final int seconds = (int) (allSeconds % 60.0);
final int minutes = (int) ((allSeconds - seconds) / 60.0);
final int milliSeconds = (int) (allMilliSecond - (seconds * 1000));
System.out.println("Starting concepts done in " + minutes + " minutes " + seconds + " seconds " + milliSeconds + " ms.");
return mapStarting;
}
// ------------------------------Frequency CONCEPTS-----------------------------------------------------
/**
* @param game The game.
* @param trials The trials.
* @param allStoredRNG The RNG for each trial.
* @return The map of playout concepts to the their values for the frequency
* ones.
*/
private static Map<String, Double> frequencyConcepts(final Game game)
{
final Map<String, Double> mapFrequency = new HashMap<String, Double>();
final long startTime = System.currentTimeMillis();
// Frequencies of the moves.
final TDoubleArrayList frequencyMoveConcepts = new TDoubleArrayList();
// Frequencies returned by all the playouts.
final TDoubleArrayList frequencyPlayouts = new TDoubleArrayList();
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
frequencyPlayouts.add(0.0);
// FOR THE MUSEUM GAME
// final TIntArrayList edgesUsage = new TIntArrayList();
// for(int i = 0; i < game.board().topology().edges().size(); i++)
// edgesUsage.add(0);
for (int trialIndex = 0; trialIndex < trials.size(); trialIndex++)
{
final Trial trial = trials.get(trialIndex);
final RandomProviderState rngState = allStoredRNG.get(trialIndex);
// Setup a new instance of the game
final Context context = Utils.setupNewContext(game, rngState);
// Frequencies returned by that playout.
final TDoubleArrayList frequencyPlayout = new TDoubleArrayList();
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
frequencyPlayout.add(0);
// Run the playout.
int turnWithMoves = 0;
Context prevContext = null;
for (int i = trial.numInitialPlacementMoves(); i < trial.numMoves(); i++)
{
final Moves legalMoves = context.game().moves(context);
final TIntArrayList frequencyTurn = new TIntArrayList();
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
frequencyTurn.add(0);
final double numLegalMoves = legalMoves.moves().size();
if (numLegalMoves > 0)
turnWithMoves++;
for (final Move legalMove : legalMoves.moves())
{
final BitSet moveConcepts = legalMove.moveConcepts(context);
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
if (moveConcepts.get(concept.id()))
frequencyTurn.set(indexConcept, frequencyTurn.get(indexConcept) + 1);
}
}
for (int j = 0; j < frequencyTurn.size(); j++)
frequencyPlayout.set(j, frequencyPlayout.get(j)
+ (numLegalMoves == 0 ? 0 : frequencyTurn.get(j) / numLegalMoves));
// We keep the context before the ending state for the frequencies of the end
// conditions.
if (i == trial.numMoves() - 1)
prevContext = new Context(context);
// We go to the next move.
context.game().apply(context, trial.getMove(i));
// FOR THE MUSEUM GAME
// To count the frequency/usage of each edge on the board.
// final Move lastMove = context.trial().lastMove();
// final int vertexFrom = lastMove.fromNonDecision();
// // To not take in account moves coming from the hand.
// if(vertexFrom < 0 || vertexFrom >= game.board().topology().vertices().size())
// continue;
// final int vertexTo = lastMove.toNonDecision();
//
// for(int j = 0; j < game.board().topology().edges().size(); j++)
// {
// final Edge edge = game.board().topology().edges().get(j);
// if((edge.vertices().get(0).index() == vertexFrom && edge.vertices().get(1).index() == vertexTo) ||
// (edge.vertices().get(0).index() == vertexTo && edge.vertices().get(1).index() == vertexFrom))
// edgesUsage.set(j, edgesUsage.get(j) + 1);
// }
// TO PRINT THE NUMBER OF PIECES PER TRIAL (this was for LL xp)
//// int countPieces = 0;
//// int countPiecesP1 = 0;
//// int countPiecesP2 = 0;
//// final ContainerState cs = context.containerState(0);
//// final int numCells = context.topology().cells().size();
//// for(int j = 0; j < numCells; j++)
//// {
//// if(cs.what(j, SiteType.Cell) != 0)
//// countPieces++;
////
//// if(cs.what(j, SiteType.Cell) == 1)
//// countPiecesP1++;
////
//// if(cs.what(j, SiteType.Cell) == 2)
//// countPiecesP2++;
//// }
////
//// System.out.println(countPieces+","+countPiecesP1+","+countPiecesP2);
}
// Compute avg for all the playouts.
for (int j = 0; j < frequencyPlayout.size(); j++)
frequencyPlayouts.set(j, frequencyPlayouts.get(j) + frequencyPlayout.get(j) / turnWithMoves);
context.trial().lastMove().apply(prevContext, true);
boolean noEndFound = true;
if (context.rules().phases() != null)
{
final int mover = context.state().mover();
final Phase endPhase = context.rules().phases()[context.state().currentPhase(mover)];
final End EndPhaseRule = endPhase.end();
// Only check if action not part of setup
if (context.active() && EndPhaseRule != null)
{
final EndRule[] endRules = EndPhaseRule.endRules();
for (final EndRule endingRule : endRules)
{
final EndRule endRuleResult = endingRule.eval(prevContext);
if (endRuleResult == null)
continue;
final BitSet endConcepts = endingRule.stateConcepts(prevContext);
noEndFound = false;
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
if (concept.type().equals(ConceptType.End) && endConcepts.get(concept.id()))
{
// System.out.println("end with " + concept.name());
frequencyPlayouts.set(indexConcept, frequencyPlayouts.get(indexConcept) + 1);
}
}
// System.out.println();
break;
}
}
}
final End endRule = context.rules().end();
if (noEndFound && endRule != null)
{
final EndRule[] endRules = endRule.endRules();
for (final EndRule endingRule : endRules)
{
final EndRule endRuleResult = endingRule.eval(prevContext);
if (endRuleResult == null)
continue;
final BitSet endConcepts = endingRule.stateConcepts(prevContext);
noEndFound = false;
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
if (concept.type().equals(ConceptType.End) && endConcepts.get(concept.id()))
{
// System.out.println("end with " + concept.name());
frequencyPlayouts.set(indexConcept, frequencyPlayouts.get(indexConcept) + 1);
}
}
// System.out.println();
break;
}
}
if (noEndFound)
{
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
if (concept.equals(Concept.Draw))
{
frequencyPlayouts.set(indexConcept, frequencyPlayouts.get(indexConcept) + 1);
break;
}
}
}
}
// FOR THE MUSEUM GAME
// int totalEdgesUsage = 0;
// for(int i = 0; i < edgesUsage.size(); i++)
// totalEdgesUsage += edgesUsage.get(i);
//
// System.out.println("Total Moves on Edges = " + totalEdgesUsage);
// for(int i = 0; i < edgesUsage.size(); i++)
// {
// final Edge edge = game.board().topology().edges().get(i);
// final int vFrom = edge.vertices().get(0).index();
// final int vTo = edge.vertices().get(1).index();
// if(totalEdgesUsage == 0)
// System.out.println("Edge " + i + "(" + vFrom + "-" + vTo + ")"+ " is used " + new DecimalFormat("##.##").format(0.0) + "% ("+edgesUsage.get(i) + " times)");
// else
// System.out.println("Edge " + i + "(" + vFrom + "-" + vTo + ")"+ " is used " + new DecimalFormat("##.##").format(Double.valueOf(((double)edgesUsage.get(i) / (double)totalEdgesUsage)*100.0)) + "% ("+edgesUsage.get(i) + " times)");
// }
//
// final String outputEdgesResults = "EdgesResult" + game.name() + "-" + game.getRuleset().heading().substring(8) + ".csv";
// try (final PrintWriter writer = new UnixPrintWriter(new File(outputEdgesResults), "UTF-8"))
// {
// for(int i = 0; i < edgesUsage.size(); i++)
// {
// if(totalEdgesUsage == 0)
// writer.println(i + ","+ edgesUsage.get(i) + ","+ new DecimalFormat("##.##").format(0.0*100.0));
// else
// writer.println(i + ","+ edgesUsage.get(i) + ","+ new DecimalFormat("##.##").format(Double.valueOf(((double)edgesUsage.get(i) / (double)totalEdgesUsage)*100.0)));
// }
// }
// catch (FileNotFoundException e)
// {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// catch (UnsupportedEncodingException e)
// {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// Compute avg frequency for the game.
for (int i = 0; i < frequencyPlayouts.size(); i++)
frequencyMoveConcepts.add(frequencyPlayouts.get(i) / trials.size());
for (int indexConcept = 0; indexConcept < Concept.values().length; indexConcept++)
{
final Concept concept = Concept.values()[indexConcept];
mapFrequency.put(concept.name(), Double.valueOf(frequencyMoveConcepts.get(indexConcept)));
if (mapFrequency.get(concept.name()).doubleValue() != 0)
{
final double perc= mapFrequency.get(concept.name()).doubleValue() * 100.0;
System.out.println("concept = " + concept.name() + " frequency is "
+ new DecimalFormat("##.##").format(perc) + "%.");
}
}
final double allMilliSecond = System.currentTimeMillis() - startTime;
final double allSeconds = allMilliSecond / 1000.0;
final int seconds = (int) (allSeconds % 60.0);
final int minutes = (int) ((allSeconds - seconds) / 60.0);
final int milliSeconds = (int) (allMilliSecond - (seconds * 1000));
System.out.println("Frequency done in " + minutes + " minutes " + seconds + " seconds " + milliSeconds + " ms.");
return mapFrequency;
}
// ------------------------------Metrics CONCEPTS-----------------------------------------------------
/**
* @param game The game.
* @param trials The trials.
* @param allStoredRNG The RNG for each trial.
* @return The map of playout concepts to the their values for the metric ones.
*/
private static Map<String, Double> metricsConcepts(final Game game, final Evaluation evaluation, final List<Concept> reconstructionConcepts)
{
final Map<String, Double> playoutConceptValues = new HashMap<String, Double>();
// We get the values of the metrics.
final long startTime = System.currentTimeMillis();
final Trial[] trialsMetrics = new Trial[trials.size()];
final RandomProviderState[] rngTrials = new RandomProviderState[trials.size()];
for (int i = 0; i < trials.size(); i++)
{
trialsMetrics[i] = new Trial(trials.get(i));
rngTrials[i] = allStoredRNG.get(i);
}
// We add all the metrics corresponding to a concept to the returned map.
final List<Metric> metrics = new Evaluation().conceptMetrics();
for (final Metric metric : metrics)
{
if (metric.concept() != null)
{
Double value;
if(reconstructionConcepts.contains(metric.concept()))
{
value = metric.apply(game, evaluation, trialsMetrics, rngTrials);
}
else
value = null; // If that's not a reconstruction metrics we put NULL for it.
if(value == null)
playoutConceptValues.put(metric.concept().name(), null);
else
{
double metricValue = metric.apply(game, evaluation, trialsMetrics, rngTrials).doubleValue();
metricValue = (Math.abs(metricValue) < Constants.EPSILON) ? 0 : metricValue;
playoutConceptValues.put(metric.concept().name(), Double.valueOf(metricValue));
if (metricValue != 0)
System.out.println(metric.concept().name() + ": " + metricValue);
}
}
}
final double allMilliSecond = System.currentTimeMillis() - startTime;
final double allSeconds = allMilliSecond / 1000.0;
final int seconds = (int) (allSeconds % 60.0);
final int minutes = (int) ((allSeconds - seconds) / 60.0);
final int milliSeconds = (int) (allMilliSecond - (seconds * 1000));
System.out.println("Metrics done in " + minutes + " minutes " + seconds + " seconds " + milliSeconds + " ms.");
return playoutConceptValues;
}
// ------------------------------Playout Estimation CONCEPTS-----------------------------------------------------
/**
* @param game The game.
* @return The map of playout concepts to the their values for the p/s and m/s
* ones.
*/
private static Map<String, Double> playoutsEstimationConcepts(final Game game)
{
final Map<String, Double> playoutConceptValues = new HashMap<String, Double>();
// Computation of the p/s and m/s
final long startTime = System.currentTimeMillis();
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
// Warming up
long stopAt = 0L;
long start = System.nanoTime();
final double warmingUpSecs = 10;
final double measureSecs = 30;
double abortAt = start + warmingUpSecs * 1000000000.0;
while (stopAt < abortAt)
{
game.start(context);
game.playout(context, null, 1.0, null, -1, Constants.UNDEFINED, ThreadLocalRandom.current());
stopAt = System.nanoTime();
}
System.gc();
// Set up RNG for this game, Always with a rng of 2077.
final Random rng = new Random((long) game.name().hashCode() * 2077);
// The Test
stopAt = 0L;
start = System.nanoTime();
abortAt = start + measureSecs * 1000000000.0;
int playouts = 0;
int moveDone = 0;
while (stopAt < abortAt)
{
game.start(context);
game.playout(context, null, 1.0, null, -1, Constants.UNDEFINED, rng);
moveDone += context.trial().numMoves();
stopAt = System.nanoTime();
++playouts;
}
final double secs = (stopAt - start) / 1000000000.0;
final double rate = (playouts / secs);
final double rateMove = (moveDone / secs);
playoutConceptValues.put(Concept.PlayoutsPerSecond.name(), Double.valueOf(rate));
playoutConceptValues.put(Concept.MovesPerSecond.name(), Double.valueOf(rateMove));
final double allSeconds = (System.currentTimeMillis() - startTime) / 1000.0;
final int seconds = (int) (allSeconds % 60.0);
final int minutes = (int) ((allSeconds - seconds) / 60.0);
System.out.println("p/s = " + rate);
System.out.println("m/s = " + rateMove);
System.out.println(
"Playouts/Moves per second estimation done in " + minutes + " minutes " + seconds + " seconds.");
return playoutConceptValues;
}
}
| 59,992 | 33.24258 | 234 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/concepts/script/CreateAachenClusterConceptScript.java
|
package utils.concepts.script;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
/**
* Script to run the state concepts computation on the cluster.
*
* @author Eric.Piette
*/
public class CreateAachenClusterConceptScript
{
public static void main(final String[] args)
{
final int maxTimeMinutesCluster = 6000; // 6000
final int numPlayout = 100;
final int maxTime = 175000;
final int maxMove = 5000; //250; //5000; // Constants.DEFAULT_MOVES_LIMIT;
final int allocatedMemoryJava = 4096;
final int thinkingTime = 1;
final String agentName = "Alpha-Beta"; // Can be "UCT", "Alpha-Beta", "Alpha-Beta-UCT", "AB-Odd-Even", "ABONEPLY", "UCTONEPLY", or "Random"
final String clusterLogin = "ls670643";
final String folder = "/../Trials/TrialsAlpha-Beta"; //""; //"/../Trials/TrialsAll";
final String mainScriptName = "StateConcepts.sh";
final String folderName = "ConceptsAB";
final String jobName = "ABConcept";
try (final PrintWriter mainWriter = new UnixPrintWriter(new File(mainScriptName), "UTF-8"))
{
final String[] gameNames = FileHandling.listGames();
for (int index = 0; index < gameNames.length; index++)
{
final String gameName = gameNames[index];
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/pending/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/validation/"))
continue;
final Game game = GameLoader.loadGameFromName(gameName);
final String fileName = gameName.isEmpty() ? ""
: StringRoutines.cleanGameName(gameName.substring(gameName.lastIndexOf('/') + 1, gameName.length()));
final List<String> rulesetNames = new ArrayList<String>();
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Get all the rulesets of the game if it has some.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty()) // We check if the ruleset is implemented.
rulesetNames.add(ruleset.heading());
}
}
if(rulesetNames.isEmpty())
{
final String scriptName = "StateConcepts" + fileName + ".sh";
System.out.println(scriptName + " " + "created.");
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptName), "UTF-8"))
{
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -J " + jobName + fileName);
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -o /work/"+clusterLogin+"/result/Out" + fileName + "_%J.out");
writer.println("#SBATCH -e /work/"+clusterLogin+"/result/Err" + fileName + "_%J.err");
writer.println("#SBATCH -t " + maxTimeMinutesCluster);
writer.println("#SBATCH --mem-per-cpu="+(int)(allocatedMemoryJava*1.25));
writer.println("#SBATCH -A um_dke");
writer.println("unset JAVA_TOOL_OPTIONS");
writer.println(
"java -Xms"+allocatedMemoryJava+"M -Xmx"+allocatedMemoryJava+"M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/"+clusterLogin+"/ludii/" + folderName + "/ludii.jar\" --export-moveconcept-db "
+ numPlayout + " " + maxTime + " " + thinkingTime + " " + maxMove + " " + "\"" + agentName + "\"" + " " + "\"" + folder + "\"" + " " + "\"" + gameName.substring(1) + "\"");
mainWriter.println("sbatch " + scriptName);
}
}
else
{
for(final String rulesetName : rulesetNames)
{
final String scriptName = "StateConcepts" + fileName + "-" + StringRoutines.cleanGameName(rulesetName.substring(8)) + ".sh";
System.out.println(scriptName + " " + "created.");
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptName), "UTF-8"))
{
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -J " + jobName + fileName);
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -o /work/"+clusterLogin+"/result/Out" + fileName + "_%J.out");
writer.println("#SBATCH -e /work/"+clusterLogin+"/result/Err" + fileName + "_%J.err");
writer.println("#SBATCH -t " + maxTimeMinutesCluster);
writer.println("#SBATCH --mem-per-cpu="+(int)(allocatedMemoryJava*1.25));
writer.println("#SBATCH -A um_dke");
writer.println("unset JAVA_TOOL_OPTIONS");
writer.println(
"java -Xms"+allocatedMemoryJava+"M -Xmx"+allocatedMemoryJava+"M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/"+clusterLogin+"/ludii/" + folderName + "/ludii.jar\" --export-moveconcept-db "
+ numPlayout + " " + maxTime + " " + thinkingTime + " " + maxMove + " " + "\"" + agentName + "\"" + " " + "\"" + folder + "\"" + " " + "\"" + gameName.substring(1) + "\"" + " " + "\"" + rulesetName + "\"");
mainWriter.println("sbatch " + scriptName);
}
}
}
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
| 6,002 | 39.836735 | 234 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/concepts/script/CreateSneliusClusterConceptScript.java
|
package utils.concepts.script;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.FileHandling;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
/**
* Script to run the state concepts computation on the cluster.
*
* @author Eric.Piette
*/
public class CreateSneliusClusterConceptScript
{
public static void main(final String[] args)
{
final int numPlayout = 100;
final int maxTime = 175000;
final int maxMove = 5000; //250; //5000; // Constants.DEFAULT_MOVES_LIMIT;
final int thinkingTime = 1;
final String agentName = "Alpha-Beta"; //"Alpha-Beta"; // Can be "UCT", "Alpha-Beta", "Alpha-Beta-UCT", "AB-Odd-Even", "ABONEPLY", "UCTONEPLY", or "Random"
final String folder = "/../Trials/Trials"+agentName; //""; //"/../Trials/TrialsAll";
final String mainScriptName = "Concepts.sh";
final String folderName = "Concepts"+agentName;
final String jobName = agentName + "Concept";
final String clusterLogin = "cbrowne";
final ArrayList<String> rulesetNames = new ArrayList<String>();
try (final PrintWriter mainWriter = new UnixPrintWriter(new File(mainScriptName), "UTF-8"))
{
final String[] gameNames = FileHandling.listGames();
for (int index = 0; index < gameNames.length; index++)
{
final String gameName = gameNames[index];
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/pending/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/validation/"))
continue;
// For the museum game.
// if(!gameName.contains("Ludus Coriovalli"))
// continue;
final Game game = GameLoader.loadGameFromName(gameName);
// final String fileName = gameName.isEmpty() ? ""
// : StringRoutines.cleanGameName(gameName.substring(gameName.lastIndexOf('/') + 1, gameName.length()));
final List<String> gameRulesetNames = new ArrayList<String>();
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Get all the rulesets of the game if it has some.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty() && !ruleset.heading().contains("Incomplete")) // We check if the ruleset is implemented.
gameRulesetNames.add(ruleset.heading());
}
}
// We get the name of all the rulesets
if(gameRulesetNames.isEmpty())
{
rulesetNames.add(gameName.substring(1) + "\"");
System.out.println(gameName.substring(1));
}
else
{
for(final String rulesetName : gameRulesetNames)
{
rulesetNames.add(gameName.substring(1) + "\"" + " " + "\"" + rulesetName + "\"");
System.out.println(gameName.substring(1)+ "/"+ rulesetName);
}
}
}
System.out.println("***************************" + rulesetNames.size() + " rulesets ***************************");
int scriptId = 0;
for(int i = 0; i < (rulesetNames.size() / 42 + 1); i++)
{
final String scriptName = "Concepts" + scriptId + ".sh";
System.out.println(scriptName + " " + "created.");
mainWriter.println("sbatch " + scriptName);
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptName), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J GenConcepts" + jobName + "Script" + scriptId);
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/"+clusterLogin+"/Out/Out_%J.out");
writer.println("#SBATCH -e /home/"+clusterLogin+"/Out/Err_%J.err");
writer.println("#SBATCH -t 6000");
writer.println("#SBATCH -N 1");
writer.println("#SBATCH --cpus-per-task=128");
writer.println("#SBATCH --mem=224G");
writer.println("#SBATCH --exclusive");
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
for(int j = 0; j < 42; j++)
{
if((i*42+j) < rulesetNames.size())
{
String jobLine = "taskset -c ";
jobLine += (3*j) + "," + (3*j + 1) + "," + (3*j + 2) + " ";
jobLine += "java -Xms5120M -Xmx5120M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/"+ clusterLogin +"/ludii/" + folderName + "/Ludii.jar\" --export-moveconcept-db ";
jobLine += numPlayout + " " + maxTime + " " + thinkingTime + " " + maxMove + " " + "\"" + agentName + "\"" + " " + "\"" + folder + "\"" + " " + "\"";
jobLine += rulesetNames.get(i*42+j);
jobLine += " " + "> /home/"+ clusterLogin +"/Out/Out_${SLURM_JOB_ID}_"+ j +".out &";
writer.println(jobLine);
}
}
writer.println("wait");
// writer.println(
// "java -Xms"+allocatedMemoryJava+"M -Xmx"+allocatedMemoryJava+"M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/"+clusterLogin+"/ludii/" + folderName + "/ludii.jar\" --export-moveconcept-db "
// + numPlayout + " " + maxTime + " " + thinkingTime + " " + maxMove + " " + "\"" + agentName + "\"" + " " + "\"" + folder + "\"" + " " + "\"" + gameName.substring(1) + "\"");
// mainWriter.println("sbatch " + scriptName);
}
scriptId++;
}
// if(rulesetNames.isEmpty())
// {
// try (final PrintWriter writer = new UnixPrintWriter(new File(scriptName), "UTF-8"))
// {
// writer.println("#!/bin/bash");
// writer.println("#SBATCH -J GenConcepts"+jobName + fileName+"Script" + scriptId);
// writer.println("#SBATCH -p thin");
// writer.println("#SBATCH -o /home/piettee/Out/Out_%J.out");
// writer.println("#SBATCH -e /home/piettee/Out/Err_%J.err");
// writer.println("#SBATCH -t 6000");
// writer.println("#SBATCH -N 1");
// writer.println("#SBATCH --cpus-per-task=128");
// writer.println("#SBATCH --mem=234G");
// writer.println("#SBATCH --exclusive");
// writer.println("module load 2021");
// writer.println("module load Java/11.0.2");
// writer.println(
// "java -Xms"+allocatedMemoryJava+"M -Xmx"+allocatedMemoryJava+"M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/"+clusterLogin+"/ludii/" + folderName + "/ludii.jar\" --export-moveconcept-db "
// + numPlayout + " " + maxTime + " " + thinkingTime + " " + maxMove + " " + "\"" + agentName + "\"" + " " + "\"" + folder + "\"" + " " + "\"" + gameName.substring(1) + "\"");
// mainWriter.println("sbatch " + scriptName);
// }
// }
// else
// {
// for(final String rulesetName : rulesetNames)
// {
// final String scriptName = "StateConcepts" + fileName + "-" + StringRoutines.cleanGameName(rulesetName.substring(8)) + ".sh";
//
// System.out.println(scriptName + " " + "created.");
//
// try (final PrintWriter writer = new UnixPrintWriter(new File(scriptName), "UTF-8"))
// {
// writer.println("#!/bin/bash");
// writer.println("#SBATCH -J GenConcepts"+jobName + fileName+"Script" + scriptId);
// writer.println("#SBATCH -p thin");
// writer.println("#SBATCH -o /home/piettee/Out/Out_%J.out");
// writer.println("#SBATCH -e /home/piettee/Out/Err_%J.err");
// writer.println("#SBATCH -t 6000");
// writer.println("#SBATCH -N 1");
// writer.println("#SBATCH --cpus-per-task=128");
// writer.println("#SBATCH --mem=234G");
// writer.println("#SBATCH --exclusive");
// writer.println("module load 2021");
// writer.println("module load Java/11.0.2");
// writer.println(
// "java -Xms"+allocatedMemoryJava+"M -Xmx"+allocatedMemoryJava+"M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/"+clusterLogin+"/ludii/" + folderName + "/ludii.jar\" --export-moveconcept-db "
// + numPlayout + " " + maxTime + " " + thinkingTime + " " + maxMove + " " + "\"" + agentName + "\"" + " " + "\"" + folder + "\"" + " " + "\"" + gameName.substring(1) + "\"" + " " + "\"" + rulesetName + "\"");
// mainWriter.println("sbatch " + scriptName);
// }
// }
// }
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
| 8,938 | 40.771028 | 235 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/concepts/script/MergeDBResultCSV.java
|
package utils.concepts.script;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import main.UnixPrintWriter;
/**
* Script to merge all the csv results of many jobs in the cluster for the db
* and compute the ids of each line in the resulting csv.
*
* @author Eric.Piette
*/
public class MergeDBResultCSV
{
/** The path of the csv folder. */
private static final String FolderCSV = "C:\\Users\\eric.piette\\Ludii\\Ludii\\Mining\\res\\concepts\\input\\ToMerge";
public static void main(final String[] args) throws IOException
{
final File folder = new File(FolderCSV.replaceAll(Pattern.quote("\\"), "/"));
final List<File> csvFiles = new ArrayList<File>();
for (final File file : folder.listFiles())
csvFiles.add(file);
final String mainScriptName = "RulesetConcepts.csv";
int id = 1;
try (final PrintWriter mainWriter = new UnixPrintWriter(new File(mainScriptName), "UTF-8"))
{
for (final File csv : csvFiles)
{
try
(
final BufferedReader reader =
new BufferedReader
(
new FileReader(csv.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/"))
)
)
{
String line = reader.readLine();
while (line != null)
{
final String lineFromComa = line.substring(line.indexOf(','));
final String idRuleset = lineFromComa.substring(1, 3);
if (!idRuleset.equals("-1"))
{
mainWriter.println(id + lineFromComa);
id++;
}
line = reader.readLine();
}
reader.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
| 2,002 | 24.0375 | 119 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/concepts/script/MergeEdgesResultCSV.java
|
package utils.concepts.script;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;
import main.UnixPrintWriter;
/**
* Script to merge all the csv results of the edges results generated for all the rulesets of the museum game.
*
* @author Eric.Piette
*/
public class MergeEdgesResultCSV
{
/** The path of the csv folder. */
private static final String FolderCSV = "C:\\Users\\eric.piette\\Ludii\\Ludii\\Mining\\res\\concepts\\input\\ToMerge";
/** The names of the board. */
private static final String boardOne = "Both Extension Joined Diagonal";
private static final String boardTwo = "Both Extension No Joined Diagonal";
private static final String boardThree = "No Extension Joined Diagonal";
private static final String boardFour = "No Extension No Joined Diagonal";
private static final String boardFive = "Top Extension Joined Diagonal ";
private static final String boardSix = "Top Extension No Joined Diagonal";
public static void main(final String[] args) throws IOException
{
createMergeFile(boardOne);
createMergeFile(boardTwo);
createMergeFile(boardThree);
createMergeFile(boardFour);
createMergeFile(boardFive);
createMergeFile(boardSix);
}
/**
* To create a merged csv for the edges results.
* @param boardName
*/
public static void createMergeFile(final String boardName)
{
final File folder = new File(FolderCSV.replaceAll(Pattern.quote("\\"), "/"));
final String edgeResults = "EdgesResults" + boardName + ".csv";
try (final PrintWriter mainWriter = new UnixPrintWriter(new File(edgeResults), "UTF-8"))
{
for (final File agentFolder : folder.listFiles())
{
final String agentName = agentFolder.getName();
for (final File file : agentFolder.listFiles())
{
if(file.getName().contains(boardName))
{
String rulesetName = file.getName().substring(file.getName().indexOf('-') + 1);
rulesetName = rulesetName.substring(0,rulesetName.length()-4);
try
(
final BufferedReader reader =
new BufferedReader
(
new FileReader(file.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/"))
)
)
{
mainWriter.print(agentName + ",");
mainWriter.print(rulesetName + ",");
String line = reader.readLine();
while (line != null)
{
final double frequency = Double.parseDouble(line.substring(line.lastIndexOf(',') + 1 ));
mainWriter.print(frequency);
mainWriter.print(",");
line = reader.readLine();
}
reader.close();
mainWriter.println("");
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
| 3,046 | 28.582524 | 119 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/features/ExportFeaturesDB.java
|
package utils.features;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.list.array.TFloatArrayList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.collections.ListUtils;
import main.options.Option;
import main.options.Ruleset;
import other.GameLoader;
/**
* Code to export CSV files for features to database
*
* @author Dennis Soemers
*/
public class ExportFeaturesDB
{
//-------------------------------------------------------------------------
/** The path of the csv with the id of the rulesets for each game. */
private static final String GAME_RULESET_PATH = "/concepts/input/GameRulesets.csv";
/** The path of the csv with Feature strings and IDs */
private static final String FEATURES_CSV_PATH = "/features/Features.csv";
/** ID of Cross-Entropy objective in database */
private static final int CROSS_ENTROPY_ID = 1;
/** ID of the TSPG objective in database */
@SuppressWarnings("unused") // NOT USED YET, but probably will be used later!!!!
private static final int TSPG_ID = 2;
//-------------------------------------------------------------------------
/**
* Constructor
*/
private ExportFeaturesDB()
{
// No need to instantiate
}
//-------------------------------------------------------------------------
/**
* Export the CSVs
* @param argParse
*/
private static void exportCSVs(final CommandLineArgParse argParse)
{
final String[] allGameNames = FileHandling.listGames();
final List<String> games = new ArrayList<String>();
final List<String> rulesets = new ArrayList<String>();
final TIntArrayList ids = new TIntArrayList();
final InputStream inGameRulesets = ExportFeaturesDB.class.getResourceAsStream(GAME_RULESET_PATH);
try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(inGameRulesets)))
{
String line = rdr.readLine();
while (line != null)
{
String lineNoQuote = line.replaceAll(Pattern.quote("\""), "");
int separatorIndex = lineNoQuote.indexOf(',');
final String gameName = lineNoQuote.substring(0, separatorIndex);
games.add(gameName);
lineNoQuote = lineNoQuote.substring(gameName.length() + 1);
separatorIndex = lineNoQuote.indexOf(',');
final String rulesetName = lineNoQuote.substring(0, separatorIndex);
rulesets.add(rulesetName);
lineNoQuote = lineNoQuote.substring(rulesetName.length() + 1);
final int id = Integer.parseInt(lineNoQuote);
ids.add(id);
line = rdr.readLine();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
final TObjectIntHashMap<String> featureIDsMap = new TObjectIntHashMap<String>();
final List<String> featureStrings = new ArrayList<String>();
// First collect all the already-known features and their IDs
final InputStream inFeatures = ExportFeaturesDB.class.getResourceAsStream(FEATURES_CSV_PATH);
try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(inFeatures)))
{
String line = rdr.readLine();
while (line != null)
{
final String[] split = line.split(Pattern.quote(","));
final int featureID = Integer.parseInt(split[0]);
final String featureString = split[1];
if (featureIDsMap.containsKey(featureString))
{
if (featureIDsMap.get(featureString) != featureID)
System.err.println("ERROR: feature ID mismatch!");
System.err.println("ERROR: duplicate feature in old CSV");
}
else
{
featureIDsMap.put(featureString, featureID);
featureStrings.add(featureString);
}
line = rdr.readLine();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
final File outDir = new File(argParse.getValueString("--out-dir"));
outDir.mkdirs();
@SuppressWarnings("resource") // NOTE: not using try-with-resource because we need multiple writers, and pass them around functions
PrintWriter featuresWriter = null;
@SuppressWarnings("resource") // NOTE: not using try-with-resource because we need multiple writers, and pass them around functions
PrintWriter rulesetFeaturesWriter = null;
try
{
// First re-write the features we already know about
featuresWriter = new UnixPrintWriter(new File(argParse.getValueString("--out-dir") + "/Features.csv"), "UTF-8");
for (int i = 0; i < featureStrings.size(); ++i)
{
featuresWriter.println((i + 1) + "," + StringRoutines.quote(featureStrings.get(i)));
}
rulesetFeaturesWriter = new UnixPrintWriter(new File(argParse.getValueString("--out-dir") + "/RulesetFeatures.csv"), "UTF-8");
// Start processing training results
final File gamesDir = new File(argParse.getValueString("--games-dir"));
final File[] gameDirs = gamesDir.listFiles();
// First counter is Feature ID, second counter is Ruleset-Feature-ID
final int[] idCounters = new int[]{featureStrings.size() + 1, 1};
for (final File gameDir : gameDirs)
{
// We will either directly find features in here, or subdirectories of combinations of options
final File[] files = gameDir.listFiles();
if (files.length == 0)
continue;
if (files[0].isDirectory())
{
// Subdirectories for combinations of options
for (final File optionsCombDir : files)
{
System.out.println("Processing: " + gameDir.getName() + "/" + optionsCombDir.getName());
processTrainingResultsDir(
gameDir.getName(),
optionsCombDir.getName(),
optionsCombDir.listFiles(),
featureIDsMap,
allGameNames,
games,
ids,
rulesets,
featuresWriter,
rulesetFeaturesWriter,
idCounters
);
}
}
else
{
// Just a game-wide directory
System.out.println("Processing: " + gameDir.getName());
processTrainingResultsDir(
gameDir.getName(),
null,
files,
featureIDsMap,
allGameNames,
games,
ids,
rulesets,
featuresWriter,
rulesetFeaturesWriter,
idCounters
);
}
}
}
catch (final IOException e)
{
e.printStackTrace();
}
finally
{
if (featuresWriter != null)
featuresWriter.close();
if (rulesetFeaturesWriter != null)
rulesetFeaturesWriter.close();
}
}
//-------------------------------------------------------------------------
private static void processTrainingResultsDir
(
final String gameDirName,
final String optionsCombDirName,
final File[] trainingOutFiles,
final TObjectIntHashMap<String> knownFeaturesMap,
final String[] allGameNames,
final List<String> gameNames,
final TIntArrayList ids,
final List<String> rulesetNames,
final PrintWriter featuresWriter,
final PrintWriter rulesetFeaturesWriter,
final int[] idCounters // First counter is Feature ID, second counter is Ruleset-Feature-ID
)
{
// First figure out the proper name of the game we're dealing with
String gameName = "";
for (final String name : allGameNames)
{
final String[] gameNameSplit = name.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String cleanGameName = StringRoutines.cleanGameName(gameNameSplit[gameNameSplit.length - 1]);
if (gameDirName.equals(cleanGameName))
{
gameName = name;
break;
}
}
if (gameName.equals(""))
{
System.err.println("Can't recognise game: " + gameDirName);
return;
}
// Compile game without options
final Game gameDefault = GameLoader.loadGameFromName(gameName);
List<String> optionsToCompile = null;
if (optionsCombDirName == null)
{
optionsToCompile = new ArrayList<String>();
}
else
{
// Figure out all combinations of options
final List<List<String>> optionCategories = new ArrayList<List<String>>();
for (int o = 0; o < gameDefault.description().gameOptions().numCategories(); o++)
{
final List<Option> options = gameDefault.description().gameOptions().categories().get(o).options();
final List<String> optionCategory = new ArrayList<String>();
for (int i = 0; i < options.size(); i++)
{
final Option option = options.get(i);
final String categoryStr = StringRoutines.join("/", option.menuHeadings().toArray(new String[0]));
if
(
!categoryStr.contains("Board Size/") &&
!categoryStr.contains("Rows/") &&
!categoryStr.contains("Columns/")
)
{
optionCategory.add(categoryStr);
}
}
if (optionCategory.size() > 0)
optionCategories.add(optionCategory);
}
final List<List<String>> optionCombinations = ListUtils.generateTuples(optionCategories);
// Figure out which combination of options is the correct one that we wish to compile
for (final List<String> optionCombination : optionCombinations)
{
final String optionCombinationString =
StringRoutines.join("-", optionCombination)
.replaceAll(Pattern.quote(" "), "")
.replaceAll(Pattern.quote("/"), "_")
.replaceAll(Pattern.quote("("), "_")
.replaceAll(Pattern.quote(")"), "_")
.replaceAll(Pattern.quote(","), "_");
if (optionsCombDirName.equals(optionCombinationString))
{
optionsToCompile = optionCombination;
break;
}
}
if (optionsToCompile == null)
{
System.err.println("Couldn't find options to compile!");
return;
}
}
// See if we can find a ruleset that matches our list of options to compile with
final List<Ruleset> rulesetsInGame = gameDefault.description().rulesets();
int rulesetID = -1;
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
final List<String> specifiedOptions =
gameDefault.description().gameOptions().allOptionStrings(optionsToCompile);
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty())
{
final List<String> rulesetOptions =
gameDefault.description().gameOptions().allOptionStrings(ruleset.optionSettings());
if (rulesetOptions.equals(specifiedOptions))
{
final String rulesetHeading = ruleset.heading();
final String startString = "Ruleset/";
final String rulesetNameCSV = rulesetHeading.substring(startString.length(),
rulesetHeading.lastIndexOf('(') - 1);
for (int i = 0; i < gameNames.size(); i++)
{
if (gameNames.get(i).equals(gameDefault.name()) && rulesetNames.get(i).equals(rulesetNameCSV))
{
rulesetID = ids.getQuick(i);
break;
}
}
if (rulesetID != -1)
break;
}
}
}
}
else
{
// No rulesets; see if these options are just the default for the game
final List<String> defaultOptions =
gameDefault.description().gameOptions().allOptionStrings(new ArrayList<String>());
final List<String> specifiedOptions =
gameDefault.description().gameOptions().allOptionStrings(optionsToCompile);
if (defaultOptions.equals(specifiedOptions))
{
for (int i = 0; i < gameNames.size(); i++)
{
if (gameNames.get(i).equals(gameDefault.name()))
{
rulesetID = ids.getQuick(i);
break;
}
}
}
else
{
// We're skipping these options, they're not the default
return;
}
}
if (rulesetID == -1)
return; // Didn't find matching ruleset
final Game game = GameLoader.loadGameFromName(gameName, optionsToCompile);
final int numPlayers = game.players().count();
// Find latest FeatureSet and PolicyWeightsCE files per player
final File[] latestFeatureSetFiles = new File[numPlayers + 1];
final File[] latestPolicyWeightFiles = new File[numPlayers + 1];
final int[] latestCheckpoints = new int[numPlayers + 1];
Arrays.fill(latestCheckpoints, -1);
for (final File trainingOutFile : trainingOutFiles)
{
final String outFilename = trainingOutFile.getName();
if (!outFilename.startsWith("FeatureSet_"))
continue;
// We're dealing with a featureset file
final String[] outFilenameSplit = outFilename.split(Pattern.quote("_"));
final int player = Integer.parseInt(outFilenameSplit[1].substring(1));
final String checkpointStr = outFilenameSplit[2].replaceFirst(Pattern.quote(".fs"), "");
final int checkpoint = Integer.parseInt(checkpointStr);
if (checkpoint > latestCheckpoints[player])
{
// New latest checkpoint
latestCheckpoints[player] = checkpoint;
latestFeatureSetFiles[player] = trainingOutFile;
// Find matching CE weights file
final File weightsFile = new File(
trainingOutFile.getParentFile().getAbsolutePath() +
"/PolicyWeightsCE_P" + player + "_" + checkpointStr + ".txt");
latestPolicyWeightFiles[player] = weightsFile;
}
}
for (int p = 1; p <= numPlayers; ++p)
{
if (latestFeatureSetFiles[p] != null)
{
// Read the list of feature strings
final List<String> features = new ArrayList<String>();
try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(latestFeatureSetFiles[p]))))
{
String line = rdr.readLine();
while (line != null)
{
features.add(line);
line = rdr.readLine();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
// Read the list of feature weights
final TFloatArrayList weights = new TFloatArrayList();
try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(latestPolicyWeightFiles[p]))))
{
String line = rdr.readLine();
while (line != null)
{
if (line.startsWith("FeatureSet="))
break;
weights.add(Float.parseFloat(line));
line = rdr.readLine();
}
}
catch (final IOException e)
{
e.printStackTrace();
}
// Write results to CSVs
for (int i = 0; i < features.size(); ++i)
{
final String feature = features.get(i);
final float weight = weights.getQuick(i);
final int featureID;
if (!knownFeaturesMap.containsKey(feature))
{
featureID = idCounters[0]++;
knownFeaturesMap.put(feature, featureID);
featuresWriter.println(featureID + "," + StringRoutines.quote(feature));
}
else
{
featureID = knownFeaturesMap.get(feature);
}
rulesetFeaturesWriter.println(StringRoutines.join(",", new String[]{
Integer.toString(idCounters[1]++),
Integer.toString(rulesetID),
Integer.toString(featureID),
Integer.toString(CROSS_ENTROPY_ID),
Integer.toString(p),
Float.toString(weight)
}));
}
}
}
}
//-------------------------------------------------------------------------
/**
* Main method
* @param args
*/
public static void main(final String[] args)
{
// Define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Export CSVs for features in database."
);
argParse.addOption(new ArgOption()
.withNames("--games-dir")
.help("Directory that contains one subdirectory for every game.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
argParse.addOption(new ArgOption()
.withNames("--out-dir")
.help("Filepath for directory to write new CSVs to.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// Parse the args
if (!argParse.parseArguments(args))
return;
exportCSVs(argParse);
}
//-------------------------------------------------------------------------
}
| 16,130 | 28.598165 | 133 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/heuristics/GenerateBaseHeuristicScoresDatabaseCSVs.java
|
package utils.heuristics;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import gnu.trove.map.TObjectDoubleMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import main.CommandLineArgParse;
import main.CommandLineArgParse.ArgOption;
import main.CommandLineArgParse.OptionTypes;
import main.FileHandling;
import main.StringRoutines;
import main.options.Ruleset;
import other.GameLoader;
import utils.IdRuleset;
/**
* Generates CSV files for database, describing scores of all base heuristics
* for all games.
*
* @author Dennis Soemers
*/
public class GenerateBaseHeuristicScoresDatabaseCSVs
{
//-------------------------------------------------------------------------
/**
* Different types of heuristics for which we store data
*
* @author Dennis Soemers
*/
public enum HeuristicTypes
{
/** A standard, unparameterised heuristic */
Standard,
/** A parameterised heuristic with a specific parameter (e.g., region proximity for specific region ID) */
Unmerged,
/** Represents a collection of heuristics of the same type, but with different parameters */
Merged
}
//-------------------------------------------------------------------------
/**
* Constructor (don't need this)
*/
private GenerateBaseHeuristicScoresDatabaseCSVs()
{
// Do nothing
}
//-------------------------------------------------------------------------
/**
* Generates our CSV
* @param argParse
* @throws IOException
* @throws FileNotFoundException
*/
private static void generateCSVs(final CommandLineArgParse argParse) throws FileNotFoundException, IOException
{
String resultsDir = argParse.getValueString("--results-dir");
resultsDir = resultsDir.replaceAll(Pattern.quote("\\"), "/");
if (!resultsDir.endsWith("/"))
resultsDir += "/";
final String[] allGameNames = Arrays.stream(FileHandling.listGames()).filter(s -> (
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wishlist/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/reconstruction/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/simulation/")) &&
!(s.replaceAll(Pattern.quote("\\"), "/").contains("/lud/proprietary/"))
)).toArray(String[]::new);
final List<HeuristicData> heuristicsList = new ArrayList<HeuristicData>();
final List<ScoreData> scoreDataList = new ArrayList<ScoreData>();
for (final String fullGamePath : allGameNames)
{
final String[] gamePathParts = fullGamePath.replaceAll(Pattern.quote("\\"), "/").split(Pattern.quote("/"));
final String gameName = gamePathParts[gamePathParts.length - 1].replaceAll(Pattern.quote(".lud"), "");
final Game gameNoRuleset = GameLoader.loadGameFromName(gameName + ".lud");
final List<Ruleset> gameRulesets = new ArrayList<Ruleset>(gameNoRuleset.description().rulesets());
gameRulesets.add(null);
boolean foundRealRuleset = false;
for (final Ruleset ruleset : gameRulesets)
{
final Game game;
String fullRulesetName = "";
if (ruleset == null && foundRealRuleset)
{
// Skip this, don't allow game without ruleset if we do have real implemented ones
continue;
}
else if (ruleset != null && !ruleset.optionSettings().isEmpty())
{
fullRulesetName = ruleset.heading();
foundRealRuleset = true;
game = GameLoader.loadGameFromName(gameName + ".lud", fullRulesetName);
}
else if (ruleset != null && ruleset.optionSettings().isEmpty())
{
// Skip empty ruleset
continue;
}
else
{
game = gameNoRuleset;
}
if (game.isDeductionPuzzle())
continue;
if (game.isSimulationMoveGame())
continue;
if (!game.isAlternatingMoveGame())
continue;
if (game.hasSubgames())
continue;
final String filepathsGameName = StringRoutines.cleanGameName(gameName);
final String filepathsRulesetName = StringRoutines.cleanRulesetName(fullRulesetName.replaceAll(Pattern.quote("Ruleset/"), ""));
final File rulesetResultsDir = new File(resultsDir + filepathsGameName + filepathsRulesetName);
if (rulesetResultsDir.exists())
{
final int rulesetID = IdRuleset.get(game);
if (rulesetID >= 0)
{
// Map from heuristic names to sum of scores for this ruleset
final TObjectDoubleMap<String> heuristicScoreSums = new TObjectDoubleHashMap<String>();
// Map from heuristic names to how often we observed this heuristic in this ruleset
final TObjectIntMap<String> heuristicCounts = new TObjectIntHashMap<String>();
final File[] matchupDirs = rulesetResultsDir.listFiles();
for (final File matchupDir : matchupDirs)
{
if (matchupDir.isDirectory())
{
final String[] resultLines =
FileHandling.loadTextContentsFromFile(
matchupDir.getAbsolutePath() + "/alpha_rank_data.csv"
).split(Pattern.quote("\n"));
// Skip index 0, that's just the headings
for (int i = 1; i < resultLines.length; ++i)
{
final String line = resultLines[i];
final int idxQuote1 = 0;
final int idxQuote2 = line.indexOf("\"", idxQuote1 + 1);
final int idxQuote3 = line.indexOf("\"", idxQuote2 + 1);
final int idxQuote4 = line.indexOf("\"", idxQuote3 + 1);
final String heuristicsTuple =
line
.substring(idxQuote1 + 2, idxQuote2 - 1)
.replaceAll(Pattern.quote(" "), "")
.replaceAll(Pattern.quote("'"), "");
final String scoresTuple =
line
.substring(idxQuote3 + 2, idxQuote4 - 1)
.replaceAll(Pattern.quote(" "), "");
final String[] heuristicNames = heuristicsTuple.split(Pattern.quote(","));
final String[] scores = scoresTuple.split(Pattern.quote(","));
for (int j = 0; j < heuristicNames.length; ++j)
{
if (Double.parseDouble(scores[j]) < -1.0 || Double.parseDouble(scores[j]) > 1.0)
{
System.out.println(scores[j]);
System.out.println("Line " + i + " of " + matchupDir.getAbsolutePath() + "/alpha_rank_data.csv");
}
// Convert score to "win percentage"
final double score = ((Double.parseDouble(scores[j]) + 1.0) / 2.0) * 100.0;
heuristicScoreSums.adjustOrPutValue(heuristicNames[j], score, score);
heuristicCounts.adjustOrPutValue(heuristicNames[j], 1, 1);
}
}
}
}
final List<ScoreData> rulesetScoreData = new ArrayList<ScoreData>();
for (final String heuristic : heuristicScoreSums.keySet())
{
if (StringRoutines.isDigit(heuristic.charAt(heuristic.length() - 1)))
{
// Need to do both merged and unmerged
final String truncatedName = heuristic.substring(0, heuristic.lastIndexOf("_"));
// First do unmerged version
HeuristicData heuristicData = null;
for (final HeuristicData data : heuristicsList)
{
if (data.name.equals(heuristic))
{
heuristicData = data;
break;
}
}
if (heuristicData == null)
{
heuristicData = new HeuristicData(heuristic, HeuristicTypes.Unmerged);
heuristicsList.add(heuristicData);
}
final int heuristicID = heuristicData.id;
final double score = heuristicScoreSums.get(heuristic) / heuristicCounts.get(heuristic);
rulesetScoreData.add(new ScoreData(rulesetID, heuristicID, score));
// And now the merged version
heuristicData = null;
for (final HeuristicData data : heuristicsList)
{
if (data.name.equals(truncatedName))
{
heuristicData = data;
break;
}
}
if (heuristicData == null)
{
heuristicData = new HeuristicData(truncatedName, HeuristicTypes.Merged);
heuristicsList.add(heuristicData);
}
final int mergedHeuristicID = heuristicData.id;
// See if we need to update already-added score data, or add new data
boolean shouldAdd = true;
for (final ScoreData data : rulesetScoreData)
{
if (data.heuristicID == mergedHeuristicID)
{
if (score > data.score)
data.score = score;
shouldAdd = false;
break;
}
}
if (shouldAdd)
rulesetScoreData.add(new ScoreData(rulesetID, mergedHeuristicID, score));
}
else
{
// No merged version
HeuristicData heuristicData = null;
for (final HeuristicData data : heuristicsList)
{
if (data.name.equals(heuristic))
{
heuristicData = data;
break;
}
}
if (heuristicData == null)
{
heuristicData = new HeuristicData(heuristic, HeuristicTypes.Standard);
heuristicsList.add(heuristicData);
}
final int heuristicID = heuristicData.id;
final double score = heuristicScoreSums.get(heuristic) / heuristicCounts.get(heuristic);
rulesetScoreData.add(new ScoreData(rulesetID, heuristicID, score));
}
}
scoreDataList.addAll(rulesetScoreData);
}
}
}
}
try (final PrintWriter writer = new PrintWriter(new File("../Mining/res/heuristics/Heuristics.csv"), "UTF-8"))
{
for (final HeuristicData data : heuristicsList)
{
writer.println(data);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
try (final PrintWriter writer = new PrintWriter(new File("../Mining/res/heuristics/RulesetHeuristics.csv"), "UTF-8"))
{
for (final ScoreData data : scoreDataList)
{
writer.println(data);
}
}
catch (final FileNotFoundException | UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
/**
* Data for Heuristics table
*
* @author Dennis Soemers
*/
private static class HeuristicData
{
private static int nextID = 1;
protected final int id;
protected final String name;
protected final HeuristicTypes type;
public HeuristicData(final String name, final HeuristicTypes type)
{
this.id = nextID++;
this.name = name;
this.type = type;
}
@Override
public String toString()
{
return id + "," + name + "," + type.ordinal();
}
}
/**
* Data for the table of ruleset+heuristic scores
*
* @author Dennis Soemers
*/
private static class ScoreData
{
private static int nextID = 1;
protected final int id;
protected final int rulesetID;
protected final int heuristicID;
protected double score;
public ScoreData(final int rulesetID, final int heuristicID, final double score)
{
this.id = nextID++;
this.rulesetID = rulesetID;
this.heuristicID = heuristicID;
this.score = score;
}
@Override
public String toString()
{
return id + "," + rulesetID + "," + heuristicID + "," + score;
}
}
//-------------------------------------------------------------------------
/**
* Main method to generate all our scripts
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(final String[] args) throws FileNotFoundException, IOException
{
// define options for arg parser
final CommandLineArgParse argParse =
new CommandLineArgParse
(
true,
"Generates CSV files for database, describing scores of all base heuristics for all games."
);
argParse.addOption(new ArgOption()
.withNames("--results-dir")
.help("Filepath for directory with per-game subdirectories of matchup directories.")
.withNumVals(1)
.withType(OptionTypes.String)
.setRequired());
// parse the args
if (!argParse.parseArguments(args))
return;
generateCSVs(argParse);
}
//-------------------------------------------------------------------------
}
| 12,834 | 29.705742 | 131 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/trials/CreateAachenClusterTrialsScript.java
|
package utils.trials;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
/**
* Script to generate all the .sh to generate the different trials
*
* @author Eric.Piette
*/
public class CreateAachenClusterTrialsScript
{
public static void main(final String[] args)
{
final int numPlayout = 100;
final int maxMove = 5000; // Constants.DEFAULT_MOVES_LIMIT;
final int allocatedMemoryJava = 4096;
final int thinkingTime = 1;
final String agentName = "UCT"; // Can be "UCT", "Alpha-Beta", "Alpha-Beta-UCT", "AB-Odd-Even", or "Random"
final String clusterLogin = "ls670643";
final String mainScriptName = "GenTrials.sh";
try (final PrintWriter mainWriter = new UnixPrintWriter(new File(mainScriptName), "UTF-8"))
{
final String[] gameNames = FileHandling.listGames();
for (int index = 0; index < gameNames.length; index++)
{
final String gameName = gameNames[index];
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/pending/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/validation/"))
continue;
final Game game = GameLoader.loadGameFromName(gameName);
final String fileName = gameName.isEmpty() ? ""
: StringRoutines.cleanGameName(gameName.substring(gameName.lastIndexOf('/') + 1, gameName.length()));
final List<String> rulesetNames = new ArrayList<String>();
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Get all the rulesets of the game if it has some.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty()) // We check if the ruleset is implemented.
rulesetNames.add(ruleset.heading());
}
}
if(rulesetNames.isEmpty())
{
final String scriptName = "GenTrials" + fileName + ".sh";
System.out.println(scriptName + " " + "created.");
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptName), "UTF-8"))
{
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -J GenTrials" + agentName + fileName);
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -o /work/" + clusterLogin + "/result/Out" + agentName + fileName + "Gentrials_%J.out");
writer.println("#SBATCH -e /work/" + clusterLogin + "/result/Err" + agentName + fileName + "Gentrials_%J.err");
writer.println("#SBATCH -t 6000");
writer.println("#SBATCH --mem-per-cpu="+(int)(allocatedMemoryJava*1.25));
writer.println("#SBATCH -A um_dke");
writer.println("unset JAVA_TOOL_OPTIONS");
writer.println(
"java -Xms"+allocatedMemoryJava+"M -Xmx"+allocatedMemoryJava+"M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/"+clusterLogin+"/ludii/Trials/Trials"+ agentName +"/ludii.jar\" --generate-trials "
+ maxMove + " " + thinkingTime + " " + numPlayout + " " + "\"" + agentName + "\"" + " " + "\"" + gameName.substring(1) + "\"");
mainWriter.println("sbatch " + scriptName);
}
}
else
{
for(final String rulesetName : rulesetNames)
{
final String scriptName = "GenTrials" + fileName + "-" + StringRoutines.cleanGameName(rulesetName.substring(8)) + ".sh";
System.out.println(scriptName + " " + "created.");
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptName), "UTF-8"))
{
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -J GenTrials" + agentName + fileName);
writer.println("#!/usr/local_rwth/bin/zsh");
writer.println("#SBATCH -o /work/"+clusterLogin+"/result/Out" + agentName + fileName + "Gentrials_%J.out");
writer.println("#SBATCH -e /work/"+clusterLogin+"/result/Err" + agentName + fileName + "Gentrials_%J.err");
writer.println("#SBATCH -t 6000");
writer.println("#SBATCH --mem-per-cpu="+(int)(allocatedMemoryJava*1.25));
writer.println("#SBATCH -A um_dke");
writer.println("unset JAVA_TOOL_OPTIONS");
writer.println(
"java -Xms"+allocatedMemoryJava+"M -Xmx"+allocatedMemoryJava+"M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/"+clusterLogin+"/ludii/Trials//Trials"+ agentName +"/ludii.jar\" --generate-trials "
+ maxMove + " " + thinkingTime + " " + numPlayout + " " + "\"" + agentName + "\"" + " " + "\"" + gameName.substring(1) + "\"" + " " + "\"" + rulesetName + "\"");
mainWriter.println("sbatch " + scriptName);
}
}
}
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
| 5,681 | 39.014085 | 239 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/trials/CreateDSRIClusterTrialsScript.java
|
package utils.trials;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.FileHandling;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
/**
* Script to generate all the .sh to generate the different trials
*
* @author Eric.Piette
*/
public class CreateDSRIClusterTrialsScript
{
public static void main(final String[] args)
{
String bashName = "";
String jobName = "";
// For runAll.sh
// String deleteAll = "oc delete jobs --all\n"
// + "oc delete builds --all\n"
// + "oc delete buildconfigs --all\n\n";
String deleteAll ="";
// For Dockerfile
String beginDockerFile ="FROM ghcr.io/maastrichtu-ids/openjdk:18\n"
+ "RUN mkdir -p /app\n"
+ "WORKDIR /app\n"
+ "ENTRYPOINT [\"java\", \"-jar\", \"/data/ludii.jar\"]\n"
+ "CMD [";
String endDockerFile ="]";
// args //"--generate-trials", "5000", "1", "100", "Random", "lud/board/war/replacement/checkmate/chess/Chess.lud";
final int numPlayout = 100;
final int maxMove = 5000; // Constants.DEFAULT_MOVES_LIMIT;
//final int allocatedMemoryJava = 4096;
final int thinkingTime = 1;
final String agentName = "Random"; // Can be "UCT", "Alpha-Beta", "Alpha-Beta-UCT", "AB-Odd-Even", or "Random"
String folderGen = "Gen" + agentName + File.separator;
final String mainScriptName = folderGen + "allRun.sh";
final File genFolderFile = new File(folderGen + jobName);
if(!genFolderFile.exists())
genFolderFile.mkdirs();
try (final PrintWriter mainWriter = new UnixPrintWriter(new File(mainScriptName), "UTF-8"))
{
// Write the delete lines in the big bash.
mainWriter.println(deleteAll);
final String[] gameNames = FileHandling.listGames();
for (int index = 0; index < gameNames.length; index++)
{
final String gameName = gameNames[index];
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/pending/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/validation/"))
continue;
final Game game = GameLoader.loadGameFromName(gameName);
final String fileName = gameName.isEmpty() ? ""
: StringRoutines.cleanGameName(gameName.substring(gameName.lastIndexOf('/') + 1, gameName.length()));
final List<String> rulesetNames = new ArrayList<String>();
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Get all the rulesets of the game if it has some.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty()) // We check if the ruleset is implemented.
rulesetNames.add(ruleset.heading());
}
}
if(rulesetNames.isEmpty())
{
// Get the name of the bash file.
bashName = "job"+fileName;
// Get the name of the job.
jobName = bashName+agentName+"Trials";
jobName = jobName.toLowerCase();
jobName = jobName.replace("_", "");
// Write the line in the big bash
mainWriter.println(createBashJob(bashName));
// Write bash file for a specific ruleset
final String rulesetScriptName = folderGen + "run"+ bashName +".sh";
try (final PrintWriter rulesetWriter = new UnixPrintWriter(new File(rulesetScriptName), "UTF-8"))
{
rulesetWriter.println(createRulesetBashJob(jobName));
final File jobFolderFile = new File(folderGen + jobName);
if(!jobFolderFile.exists())
jobFolderFile.mkdirs();
}
// Write YML file for a specific ruleset
final String YMLName = folderGen + jobName + File.separator + jobName +".yml";
try (final PrintWriter ymlWriter = new UnixPrintWriter(new File(YMLName), "UTF-8"))
{
ymlWriter.println(createYML(jobName));
}
// Write Docker file for a specific ruleset
final String dockerName = folderGen + jobName + File.separator + "Dockerfile";
try (final PrintWriter dockerWriter = new UnixPrintWriter(new File(dockerName), "UTF-8"))
{
dockerWriter.print(beginDockerFile);
dockerWriter.print("\"--generate-trials\", ");
dockerWriter.print("\"" + maxMove + "\", ");
dockerWriter.print("\"" + thinkingTime + "\", ");
dockerWriter.print("\"" + numPlayout + "\", ");
dockerWriter.print("\"" + agentName + "\", ");
dockerWriter.print("\"" + gameName.substring(1) + "\"");
dockerWriter.println(endDockerFile);
}
System.out.println(createBashJob(bashName) + " " + "written.");
}
else
{
for(int idRuleset = 0; idRuleset < rulesetNames.size(); idRuleset++)
{
final String rulesetJobName = "Ruleset" + idRuleset; // Need to modify the name of the job bc DSRI has a limit of 58 chars
final String rulesetName = rulesetNames.get(idRuleset);
// Get the name of the bash file.
bashName = "job"+fileName + "-" + rulesetJobName;
// Get the name of the job.
jobName = "job"+fileName + "-" + rulesetJobName+agentName+"Trials";
jobName = jobName.toLowerCase();
jobName = jobName.replace("_", "");
// Write the line in the big bash
mainWriter.println(createBashJob(bashName));
// Write bash file for a specific ruleset
final String rulesetScriptName = folderGen + "run"+ bashName +".sh";
try (final PrintWriter rulesetWriter = new UnixPrintWriter(new File(rulesetScriptName), "UTF-8"))
{
rulesetWriter.println(createRulesetBashJob(jobName));
final File jobFolderFile = new File(folderGen + jobName);
if(!jobFolderFile.exists())
jobFolderFile.mkdirs();
}
// Write YML file for a specific ruleset
final String YMLName = folderGen + jobName + File.separator + jobName +".yml";
try (final PrintWriter ymlWriter = new UnixPrintWriter(new File(YMLName), "UTF-8"))
{
ymlWriter.println(createYML(jobName));
}
// Write Docker file for a specific ruleset
final String dockerName = folderGen + jobName + File.separator + "Dockerfile";
try (final PrintWriter dockerWriter = new UnixPrintWriter(new File(dockerName), "UTF-8"))
{
dockerWriter.print(beginDockerFile);
dockerWriter.print("\"--generate-trials\", ");
dockerWriter.print("\"" + maxMove + "\", ");
dockerWriter.print("\"" + thinkingTime + "\", ");
dockerWriter.print("\"" + numPlayout + "\", ");
dockerWriter.print("\"" + agentName + "\", ");
dockerWriter.print("\"" + gameName.substring(1) + "\", ");
dockerWriter.print("\"" + rulesetName + "\"");
dockerWriter.println(endDockerFile);
}
System.out.println(createBashJob(bashName) + " " + "written.");
}
}
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
/**
* @param jobName The name of the job.
* @return The bash line in runAll.sh to run the job.
*/
public static String createBashJob(final String jobName)
{
return "bash run"+jobName+".sh&";
}
/**
* @param jobName The name of the job.
* @return The bash file to run the job for a specific ruleset.
*/
public static String createRulesetBashJob(final String jobName)
{
return "cd "+jobName+"\n"
+ "oc new-build --name "+ jobName+ " --binary\n"
+ "oc start-build "+jobName+" --from-dir=. --follow --wait\n"
+ "oc apply -f "+jobName+".yml\n"
+ "cd ..";
}
/**
* @param jobName The name of the job.
* @return The YML file for a specific ruleset.
*/
public static String createYML(final String jobName)
{
return "apiVersion: batch/v1\n"
+ "kind: Job\n"
+ "metadata:\n"
+ " name: "+jobName+"\n"
+ " labels:\n"
+ " app: \""+jobName+"\"\n"
+ "spec:\n"
+ " template:\n"
+ " metadata:\n"
+ " name: " + jobName +"\n"
+ " spec:\n"
+ " serviceAccountName: anyuid\n"
+ " containers:\n"
+ " - name: " + jobName+"\n"
+ " image: image-registry.openshift-image-registry.svc:5000/ludii/"+jobName+":latest\n"
+ " imagePullPolicy: Always\n"
+ " # command: [\"--help\"] \n"
+ " volumeMounts:\n"
+ " - mountPath: /data\n"
+ " name: data\n"
+ " resources:\n"
+ " requests:\n"
+ " cpu: \"1\"\n"
+ " memory: \"4G\"\n"
+ " limits:\n"
+ " cpu: \"2\"\n"
+ " memory: \"8G\"\n"
+ " volumes:\n"
+ " - name: data\n"
+ " persistentVolumeClaim:\n"
+ " claimName: ludii-job-storage\n"
+ " restartPolicy: Never";
}
}
| 9,679 | 33.571429 | 128 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/trials/CreateSneliusClusterTrialsMuseumFeatures.java
|
package utils.trials;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.StringRoutines;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
/**
* Script to generate all the .sh to generate the different trials for the Snellius cluster on thin nodes.
*
* This is for the museum game rulesets with the features.
*
* @author Eric.Piette and Dennis Soemers
*/
public class CreateSneliusClusterTrialsMuseumFeatures
{
private static final String[] POLICIES =
new String[]
{
"Tree_1",
"Tree_2",
"Tree_3",
"Tree_4",
"Tree_5",
"TSPG"
};
public static void main(final String[] args)
{
final int numPlayout = 100;
final int maxMove = 250; // Constants.DEFAULT_MOVES_LIMIT;
//final int allocatedMemoryJava = 4096;
final int thinkingTime = 1;
//final String clusterLogin = "piettee";
final String mainScriptName = "GenTrials.sh";
final ArrayList<ProcessData> processDataList = new ArrayList<ProcessData>();
try (final PrintWriter mainWriter = new UnixPrintWriter(new File(mainScriptName), "UTF-8"))
{
final String gameName = "/Ludus Coriovalli.lud";
final Game game = GameLoader.loadGameFromName(gameName);
// final String fileName = gameName.isEmpty() ? ""
// : StringRoutines.cleanGameName(gameName.substring(gameName.lastIndexOf('/') + 1, gameName.length()));
final List<String> gameRulesetNames = new ArrayList<String>();
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Get all the rulesets of the game if it has some.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty()) // We check if the ruleset is implemented.
gameRulesetNames.add(ruleset.heading());
}
}
// We get the name of all the rulesets
for (final String rulesetName : gameRulesetNames)
{
for (int i = 0; i < POLICIES.length - 1; ++i)
{
for (int j = i + 1; j < POLICIES.length; ++j)
{
processDataList.add
(
new ProcessData
(
gameName.substring(1) + "\"" + " " + "\"" + rulesetName + "\"",
POLICIES[i],
POLICIES[j],
StringRoutines.cleanGameName(gameName.replaceAll(Pattern.quote(".lud"), "")),
StringRoutines.cleanRulesetName(rulesetName).replaceAll(Pattern.quote("/"), "_")
)
);
}
}
System.out.println(gameName.substring(1)+ "/"+ rulesetName);
}
int scriptId = 0;
for(int i = 0; i < (processDataList.size() / 42 + 1); i++)
{
final String scriptName = "GenTrial_" + scriptId + ".sh";
mainWriter.println("sbatch " + scriptName);
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptName), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J GenTrialsMuseumFeatures" + scriptId);
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/piettee/Out/Out_%J.out");
writer.println("#SBATCH -e /home/piettee/Out/Err_%J.err");
writer.println("#SBATCH -t 6000");
writer.println("#SBATCH -N 1");
writer.println("#SBATCH --cpus-per-task=128");
writer.println("#SBATCH --mem=234G");
writer.println("#SBATCH --exclusive");
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
for(int j = 0; j < 42; j++)
{
final int pIdx = i * 42 + j;
if (pIdx < processDataList.size())
{
final ProcessData processData = processDataList.get(pIdx);
final String agentString1;
final String agentString2;
// Build string for first agent
if (processData.agent1.equals("TSPG"))
{
final List<String> policyStrParts = new ArrayList<String>();
policyStrParts.add("algorithm=Softmax");
for (int p = 1; p <= 2; ++p)
{
policyStrParts.add
(
"policyweights" +
p +
"=/home/piettee/ludii/features" +
processData.cleanGameName + "_" + processData.cleanRulesetName +
"/PolicyWeightsTSPG_P" + p + "_00201.txt"
);
}
policyStrParts.add("friendly_name=TSPG");
policyStrParts.add("boosted=true");
agentString1 =
StringRoutines.join
(
";",
policyStrParts
);
}
else
{
agentString1 =
StringRoutines.join
(
";",
"algorithm=SoftmaxPolicyLogitTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
"piettee",
"ludii",
"features" + processData.cleanGameName + "_" + processData.cleanRulesetName,
"CE_Selection_Logit_" + processData.agent1 + ".txt"
),
"friendly_name=" + processData.agent1,
"greedy=false"
);
}
// Build string for second agent
if (processData.agent2.equals("TSPG"))
{
final List<String> policyStrParts = new ArrayList<String>();
policyStrParts.add("algorithm=Softmax");
for (int p = 1; p <= 2; ++p)
{
policyStrParts.add
(
"policyweights" +
p +
"=/home/piettee/ludii/features" +
processData.cleanGameName + "_" + processData.cleanRulesetName +
"/PolicyWeightsTSPG_P" + p + "_00201.txt"
);
}
policyStrParts.add("friendly_name=TSPG");
policyStrParts.add("boosted=true");
agentString2 =
StringRoutines.join
(
";",
policyStrParts
);
}
else
{
agentString2 =
StringRoutines.join
(
";",
"algorithm=SoftmaxPolicyLogitTree",
"policytrees=/" +
StringRoutines.join
(
"/",
"home",
"piettee",
"ludii",
"features" + processData.cleanGameName + "_" + processData.cleanRulesetName,
"CE_Selection_Logit_" + processData.agent2 + ".txt"
),
"friendly_name=" + processData.agent2,
"greedy=false"
);
}
String jobLine = "taskset -c ";
jobLine += (3*j) + "," + (3*j + 1) + "," + (3*j + 2) + " ";
jobLine += "java -Xms5120M -Xmx5120M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/piettee/ludii/Trials/Ludii.jar\" --generate-trials-parallel ";
jobLine += maxMove + " " + thinkingTime + " " + numPlayout + " " + "\"" + agentString1 + "\"" + " " + "\"";
jobLine += processData.rulesetName;
jobLine += " " + StringRoutines.quote(agentString2);
jobLine += " " + processData.agent1 + "_vs_" + processData.agent2;
jobLine += " " + "> /home/piettee/Out/Out_${SLURM_JOB_ID}_"+ j +".out &";
writer.println(jobLine);
}
}
writer.println("wait");
}
scriptId++;
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
/**
* Wrapper for data we need for an individual Java process (of which we run multiple per job)
*
* @author Dennis Soemers
*/
private static final class ProcessData
{
public final String rulesetName;
public final String agent1;
public final String agent2;
public final String cleanGameName;
public final String cleanRulesetName;
/**
* Constructor
* @param rulesetName
* @param agent1
* @param agent2
* @param cleanGameName
* @param cleanRulesetName
*/
public ProcessData
(
final String rulesetName,
final String agent1,
final String agent2,
final String cleanGameName,
final String cleanRulesetName
)
{
this.rulesetName = rulesetName;
this.agent1 = agent1;
this.agent2 = agent2;
this.cleanGameName = cleanGameName;
this.cleanRulesetName = cleanRulesetName;
}
}
}
| 8,407 | 28.093426 | 188 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/trials/CreateSneliusClusterTrialsScript.java
|
package utils.trials;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import game.Game;
import main.FileHandling;
import main.UnixPrintWriter;
import main.options.Ruleset;
import other.GameLoader;
/**
* Script to generate all the .sh to generate the different trials for the Snellius cluster on thin nodes.
*
* @author Eric.Piette
*/
public class CreateSneliusClusterTrialsScript
{
public static void main(final String[] args)
{
final int numPlayout = 100;
final int maxMove = 5000; // Constants.DEFAULT_MOVES_LIMIT;
//final int allocatedMemoryJava = 4096;
final int thinkingTime = 1;
final String agentName = "Alpha-Beta"; // Can be "UCT", "Alpha-Beta", "Alpha-Beta-UCT", "AB-Odd-Even", or "Random"
final String clusterLogin = "cbrowne";
final String mainScriptName = "GenTrials.sh";
final ArrayList<String> rulesetNames = new ArrayList<String>();
try (final PrintWriter mainWriter = new UnixPrintWriter(new File(mainScriptName), "UTF-8"))
{
final String[] gameNames = FileHandling.listGames();
for (int index = 0; index < gameNames.length; index++)
{
final String gameName = gameNames[index];
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/bad/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/wip/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/WishlistDLP/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("/lud/test/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("subgame"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/pending/"))
continue;
if (gameName.replaceAll(Pattern.quote("\\"), "/").contains("reconstruction/validation/"))
continue;
final Game game = GameLoader.loadGameFromName(gameName);
// final String fileName = gameName.isEmpty() ? ""
// : StringRoutines.cleanGameName(gameName.substring(gameName.lastIndexOf('/') + 1, gameName.length()));
final List<String> gameRulesetNames = new ArrayList<String>();
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Get all the rulesets of the game if it has some.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
if (!ruleset.optionSettings().isEmpty() && !ruleset.heading().contains("Incomplete")) // We check if the ruleset is implemented.
gameRulesetNames.add(ruleset.heading());
}
}
// We get the name of all the rulesets
if(gameRulesetNames.isEmpty())
{
rulesetNames.add(gameName.substring(1) + "\"");
System.out.println(gameName.substring(1));
}
else
{
for(final String rulesetName : gameRulesetNames)
{
rulesetNames.add(gameName.substring(1) + "\"" + " " + "\"" + rulesetName + "\"");
System.out.println(gameName.substring(1)+ "/"+ rulesetName);
}
}
}
System.out.println("***************************" + rulesetNames.size() + " rulesets ***************************");
int scriptId = 0;
for(int i = 0; i < (rulesetNames.size() / 42 + 1); i++)
{
final String scriptName = "GenTrial_" + scriptId + ".sh";
mainWriter.println("sbatch " + scriptName);
try (final PrintWriter writer = new UnixPrintWriter(new File(scriptName), "UTF-8"))
{
writer.println("#!/bin/bash");
writer.println("#SBATCH -J GenTrials"+agentName+"Script" + scriptId);
writer.println("#SBATCH -p thin");
writer.println("#SBATCH -o /home/" + clusterLogin + "/Out/Out_%J.out");
writer.println("#SBATCH -e /home/" + clusterLogin + "/Out/Err_%J.err");
writer.println("#SBATCH -t 6000");
writer.println("#SBATCH -N 1");
writer.println("#SBATCH --cpus-per-task=128");
writer.println("#SBATCH --mem=224G");
writer.println("#SBATCH --exclusive");
writer.println("module load 2021");
writer.println("module load Java/11.0.2");
for(int j = 0; j < 42; j++)
{
if((i*42+j) < rulesetNames.size())
{
String jobLine = "taskset -c ";
jobLine += (3*j) + "," + (3*j + 1) + "," + (3*j + 2) + " ";
jobLine += "java -Xms5120M -Xmx5120M -XX:+HeapDumpOnOutOfMemoryError -da -dsa -XX:+UseStringDeduplication -jar \"/home/" + clusterLogin + "/ludii/Trials/Ludii.jar\" --generate-trials-parallel ";
jobLine += maxMove + " " + thinkingTime + " " + numPlayout + " " + "\"" + agentName + "\"" + " " + "\"";
jobLine += rulesetNames.get(i*42+j);
jobLine += " " + "> /home/" + clusterLogin + "/Out/Out_${SLURM_JOB_ID}_"+ j +".out &";
writer.println(jobLine);
}
}
writer.println("wait");
}
scriptId++;
}
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
catch (final UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
| 5,205 | 33.939597 | 201 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/trials/GenerateTrialsCluster.java
|
package utils.trials;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import game.Game;
import main.Constants;
import main.FileHandling;
import main.options.Ruleset;
import other.AI;
import other.GameLoader;
import other.context.Context;
import other.model.Model;
import other.trial.Trial;
import search.minimax.AlphaBetaSearch;
import search.minimax.AlphaBetaSearch.AllowedSearchDepths;
import utils.AIFactory;
/**
* To generate, and store, trials for every game.
* Games for which trials are already stored will be skipped.
*
* @author Eric Piette
*/
public class GenerateTrialsCluster
{
/** Number of random trials to generate per game */
private static int NUM_TRIALS_PER_GAME;
/** The move limit to use to generate the trials. */
private static int moveLimit;
/** The move limit to use to generate the trials. */
private static String rootPath = File.separator + "data" + File.separator + "Trials" + File.separator;
//----------------------------------------------------------------
/**
* Generates trials.
*
* Arg 1 = Move Limit.
* Arg 2 = Thinking time for the agents.
* Arg 3 = Num trials to generate.
* Arg 4 = Name of the agent. // Can be "UCT", "Alpha-Beta", "Alpha-Beta-UCT", "AB-Odd-Even", or "Random"
* Arg 5 = Name of the game.
* Arg 6 = Name of the ruleset.
*/
public static void main(final String[] args)
{
moveLimit = args.length == 0 ? Constants.DEFAULT_MOVES_LIMIT : Integer.parseInt(args[0]);
final double thinkingTime = args.length < 2 ? 1 : Double.parseDouble(args[1]);
NUM_TRIALS_PER_GAME = args.length < 3 ? 100 : Integer.parseInt(args[2]);
final String agentName = args.length < 4 ? "Random" : args[3];
final String gameNameExpected = args.length < 5 ? "" : args[4];
final String rulesetExpected = args.length < 6 ? "" : args[5];
final File startFolder = new File("Ludii/lud/");
final List<File> gameDirs = new ArrayList<File>();
gameDirs.add(startFolder);
final String[] gamePaths = FileHandling.listGames();
int index = 0;
String gamePath = "";
System.out.println("Game looking for is " + gameNameExpected);
System.out.println("Ruleset looking for is " + rulesetExpected);
/** Check if the game path exits. */
for (; index < gamePaths.length; index++)
{
if (!gamePaths[index].contains(gameNameExpected))
continue;
gamePath = gamePaths[index];
break;
}
// Game not found !
if(index >= gamePaths.length)
System.err.println("ERROR GAME NOT FOUND");
else
System.out.println("GAME FOUND");
gamePath = gamePath.replaceAll(Pattern.quote("\\"), "/");
final Game game = GameLoader.loadGameFromName(gamePath);
game.setMaxMoveLimit(moveLimit);
game.start(new Context(game, new Trial(game)));
System.out.println("Loading game: " + game.name());
final String testPath = rootPath + "Trials" + agentName;
final File testfile = new File(testPath);
System.out.println(testPath);
if(!testfile.exists())
System.out.println("not existing :(");
final String gameFolderPath = rootPath + "Trials" + agentName + File.separator + game.name() ;
final File gameFolderFile = new File(gameFolderPath);
System.out.println(gameFolderFile);
if(!gameFolderFile.exists())
gameFolderFile.mkdirs();
// Check if the game has a ruleset.
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Has many rulesets.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
// We check if we want a specific ruleset.
if(!rulesetExpected.isEmpty() && !rulesetExpected.equals(ruleset.heading()))
continue;
if (!ruleset.optionSettings().isEmpty()) // We check if the ruleset is implemented.
{
final Game rulesetGame = GameLoader.loadGameFromName(gamePath, ruleset.optionSettings());
rulesetGame.setMaxMoveLimit(moveLimit);
final String rulesetFolderPath = gameFolderPath + File.separator + rulesetGame.getRuleset().heading().replace("/", "_");
final File rulesetFolderFile = new File(rulesetFolderPath);
if(!rulesetFolderFile.exists())
rulesetFolderFile.mkdirs();
System.out.println("Loading ruleset: " + rulesetGame.getRuleset().heading());
for (int i = 0; i < NUM_TRIALS_PER_GAME; ++i)
{
System.out.println("Starting playout for: ...");
final String trialFilepath = rulesetFolderPath + File.separator + agentName + "Trial_" + i + ".txt";
final File trialFile = new File(trialFilepath);
if(trialFile.exists())
continue;
// Set the agents.
final List<AI> ais = chooseAI(rulesetGame, agentName, i);
for(final AI ai : ais)
if(ai != null)
ai.setMaxSecondsPerMove(thinkingTime);
final Trial trial = new Trial(rulesetGame);
final Context context = new Context(rulesetGame, trial);
final byte[] startRNGState = ((RandomProviderDefaultState) context.rng().saveState()).getState();
rulesetGame.start(context);
// Init the ais.
for (int p = 1; p <= rulesetGame.players().count(); ++p)
ais.get(p).initAI(rulesetGame, p);
final Model model = context.model();
// Run the trial.
while (!trial.over())
model.startNewStep(context, ais, thinkingTime);
try
{
trial.saveTrialToTextFile(trialFile, gamePath, rulesetGame.getOptions(), new RandomProviderDefaultState(startRNGState));
System.out.println("Saved trial for " + rulesetGame.name() + "|" + rulesetGame.getRuleset().heading().replace("/", "_") +" to file: " + trialFilepath);
}
catch (final IOException e)
{
e.printStackTrace();
fail("Crashed when trying to save trial to file.");
}
}
}
}
}
else // Code for the default ruleset.
{
for (int i = 0; i < NUM_TRIALS_PER_GAME; ++i)
{
System.out.println("Starting playout for: ...");
final String trialFilepath = gameFolderPath + File.separator + agentName + "Trial_" + i + ".txt";
final File trialFile = new File(trialFilepath);
if(trialFile.exists())
continue;
// Set the agents.
final List<AI> ais = chooseAI(game, agentName, i);
for(final AI ai : ais)
if(ai != null)
ai.setMaxSecondsPerMove(thinkingTime);
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
final byte[] startRNGState = ((RandomProviderDefaultState) context.rng().saveState()).getState();
game.start(context);
// Init the ais.
for (int p = 1; p <= game.players().count(); ++p)
ais.get(p).initAI(game, p);
final Model model = context.model();
// Run the trial.
while (!trial.over())
model.startNewStep(context, ais, thinkingTime);
try
{
trial.saveTrialToTextFile(trialFile, gamePath, new ArrayList<String>(), new RandomProviderDefaultState(startRNGState));
System.out.println("Saved trial for " + game.name() +" to file: " + trialFilepath);
}
catch (final IOException e)
{
e.printStackTrace();
fail("Crashed when trying to save trial to file.");
}
}
}
}
/**
* @param game The game.
* @param agentName The name of the agent.
* @param indexPlayout The index of the playout.
* @return The list of AIs to play that playout.
*/
private static List<AI> chooseAI(final Game game, final String agentName, final int indexPlayout)
{
final List<AI> ais = new ArrayList<AI>();
ais.add(null);
for (int p = 1; p <= game.players().count(); ++p)
{
if(agentName.equals("UCT"))
{
final AI ai = AIFactory.createAI("UCT");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else if(agentName.equals("Alpha-Beta"))
{
AI ai = AIFactory.createAI("Alpha-Beta");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else if(agentName.equals("Alpha-Beta-UCT")) // AB/UCT/AB/UCT/...
{
if(indexPlayout % 2 == 0)
{
if(p % 2 == 1)
{
AI ai = AIFactory.createAI("Alpha-Beta");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AI ai = AIFactory.createAI("UCT");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if(p % 2 == 1)
{
final AI ai = AIFactory.createAI("UCT");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = AIFactory.createAI("Alpha-Beta");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else if(agentName.equals("AB-Odd-Even")) // Alternating between AB Odd and AB Even
{
if(indexPlayout % 2 == 0)
{
if(p % 2 == 1)
{
AI ai = new AlphaBetaSearch();
((AlphaBetaSearch)ai).setAllowedSearchDepths(AllowedSearchDepths.Odd);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AlphaBetaSearch ai = new AlphaBetaSearch();
ai.setAllowedSearchDepths(AllowedSearchDepths.Even);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if(p % 2 == 1)
{
final AlphaBetaSearch ai = new AlphaBetaSearch();
ai.setAllowedSearchDepths(AllowedSearchDepths.Even);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = new AlphaBetaSearch();
((AlphaBetaSearch)ai).setAllowedSearchDepths(AllowedSearchDepths.Odd);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else
{
ais.add(new utils.RandomAI());
}
}
return ais;
}
}
| 11,294 | 25.892857 | 158 |
java
|
Ludii
|
Ludii-master/Mining/src/utils/trials/GenerateTrialsClusterParallel.java
|
package utils.trials;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import game.Game;
import gnu.trove.list.array.TIntArrayList;
import main.Constants;
import main.FileHandling;
import main.collections.ListUtils;
import main.options.Ruleset;
import other.AI;
import other.GameLoader;
import other.RankUtils;
import other.context.Context;
import other.model.Model;
import other.trial.Trial;
import search.minimax.AlphaBetaSearch;
import search.minimax.AlphaBetaSearch.AllowedSearchDepths;
import utils.AIFactory;
import utils.experiments.ResultsSummary;
/**
* To generate, and store, trials for every game in parallel.
* Games for which trials are already stored will be skipped.
*
* @author Eric Piette
*/
public class GenerateTrialsClusterParallel
{
/** Number of random trials to generate per game */
private static int NUM_TRIALS_PER_GAME;
/** The move limit to use to generate the trials. */
private static int moveLimit;
/** The move limit to use to generate the trials. */
private static String rootPath = "." + File.separator; //""; (for local use this).
/** Number of parallel playouts we run */
private static final int NUM_PARALLEL = 3;
//----------------------------------------------------------------
/**
* Generates trials.
*
* Arg 1 = Move Limit.
* Arg 2 = Thinking time for the agents.
* Arg 3 = Num trials to generate.
* Arg 4 = Name of the agent. // Can be "UCT", "Alpha-Beta", "Alpha-Beta-UCT", "AB-Odd-Even", or "Random"
* Arg 5 = Name of the game.
* Arg 6 = Name of the ruleset.
* Arg 7 = Name of second agent (leave empty if we only want to use Arg 4).
* Arg 8 = Name we append to "Trials" to get name we save files in. Will use Arg 4 if left empty.
*/
public static void main(final String[] args)
{
moveLimit = args.length == 0 ? Constants.DEFAULT_MOVES_LIMIT : Integer.parseInt(args[0]);
final double thinkingTime = args.length < 2 ? 1 : Double.parseDouble(args[1]);
NUM_TRIALS_PER_GAME = args.length < 3 ? 100 : Integer.parseInt(args[2]);
final String agentName = args.length < 4 ? "Random" : args[3];
final String gameNameExpected = args.length < 5 ? "" : args[4];
final String rulesetExpected = args.length < 6 ? "" : args[5];
final String agentName2 = args.length < 7 ? "" : args[6];
final String trialsDirName = args.length < 8 ? agentName : args[7];
final File startFolder = new File("Ludii/lud/");
final List<File> gameDirs = new ArrayList<File>();
gameDirs.add(startFolder);
final String[] gamePaths = FileHandling.listGames();
int index = 0;
String gamePath = "";
System.out.println("Game looking for is " + gameNameExpected);
System.out.println("Ruleset looking for is " + rulesetExpected);
/** Check if the game path exits. */
for (; index < gamePaths.length; index++)
{
if (!gamePaths[index].contains(gameNameExpected))
continue;
gamePath = gamePaths[index];
break;
}
// Game not found !
if(index >= gamePaths.length)
System.err.println("ERROR GAME NOT FOUND");
else
System.out.println("GAME FOUND");
gamePath = gamePath.replaceAll(Pattern.quote("\\"), "/");
final Game game = GameLoader.loadGameFromName(gamePath);
game.setMaxMoveLimit(moveLimit);
game.start(new Context(game, new Trial(game)));
System.out.println("Loading game: " + game.name());
final String testPath = rootPath + "Trials" + trialsDirName;
final File testfile = new File(testPath);
System.out.println(testPath);
if(!testfile.exists())
System.out.println("not existing :(");
final String gameFolderPath = rootPath + "Trials" + trialsDirName + File.separator + game.name() ;
final File gameFolderFile = new File(gameFolderPath);
System.out.println(gameFolderFile);
if(!gameFolderFile.exists())
gameFolderFile.mkdirs();
// Check if the game has a ruleset.
final List<Ruleset> rulesetsInGame = game.description().rulesets();
// Has many rulesets.
if (rulesetsInGame != null && !rulesetsInGame.isEmpty())
{
for (int rs = 0; rs < rulesetsInGame.size(); rs++)
{
final Ruleset ruleset = rulesetsInGame.get(rs);
// We check if we want a specific ruleset.
if (!rulesetExpected.isEmpty() && !rulesetExpected.equals(ruleset.heading()))
continue;
if (!ruleset.optionSettings().isEmpty()) // We check if the ruleset is implemented.
{
final Game rulesetGame = GameLoader.loadGameFromName(gamePath, ruleset.optionSettings());
rulesetGame.setMaxMoveLimit(moveLimit);
final String rulesetFolderPath = gameFolderPath + File.separator + rulesetGame.getRuleset().heading().replace("/", "_");
final File rulesetFolderFile = new File(rulesetFolderPath);
if(!rulesetFolderFile.exists())
rulesetFolderFile.mkdirs();
System.out.println("Loading ruleset: " + rulesetGame.getRuleset().heading());
int beginTrialIndex = 0;
for (; beginTrialIndex < NUM_TRIALS_PER_GAME; ++beginTrialIndex)
{
final String trialFilepath = rulesetFolderPath + File.separator + trialsDirName + "Trial_" + beginTrialIndex + ".txt";
final File trialFile = new File(trialFilepath);
if (!trialFile.exists())
break;
}
if (beginTrialIndex < NUM_TRIALS_PER_GAME)
{
final int parallelNum = (NUM_TRIALS_PER_GAME - beginTrialIndex) > NUM_PARALLEL ? NUM_PARALLEL : (NUM_TRIALS_PER_GAME - beginTrialIndex);
final ExecutorService executorService = Executors.newFixedThreadPool(parallelNum, new TrialsThreadFactory());
final CountDownLatch latch = new CountDownLatch(NUM_TRIALS_PER_GAME - beginTrialIndex);
// For every thread, create a list of AIs to be used for all trials in that thread
final List<List<AI>> aisListPerThread = new ArrayList<List<AI>>(parallelNum);
for (int i = 0; i < parallelNum; ++i)
{
aisListPerThread.add(chooseAI(game, agentName, agentName2, 0));
for (final AI ai : aisListPerThread.get(i))
if (ai != null)
ai.setMaxSecondsPerMove(thinkingTime);
}
final int numPlayers = game.players().count();
final List<TIntArrayList> aiListPermutations;
if (numPlayers <= 5)
{
// Compute all possible permutations of indices for the list of AIs
aiListPermutations = ListUtils.generatePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()));
Collections.shuffle(aiListPermutations);
}
else
{
// Randomly generate some permutations of indices for the list of AIs
aiListPermutations = ListUtils.samplePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()), 120);
}
final List<String> agentStrings = new ArrayList<String>(numPlayers);
for (int p = 1; p <= numPlayers; ++p)
{
agentStrings.add(aisListPerThread.get(0).get(p - 1).friendlyName());
}
final ResultsSummary resultsSummary = new ResultsSummary(game, agentStrings);
for (int i = beginTrialIndex; i < NUM_TRIALS_PER_GAME; ++i)
{
final String trialFilepath = rulesetFolderPath + File.separator + trialsDirName + "Trial_" + i + ".txt";
final File trialFile = new File(trialFilepath);
try
{
final int numTrial = i ;
final String path = gamePath;
executorService.submit
(
() ->
{
try
{
System.out.println("Starting playout " + numTrial + ": ...");
// Figure out the 0-based index of our thread
final int threadIdx =
Integer.parseInt(Thread.currentThread().getName().substring("Trials Thread ".length()));
// Create re-ordered list of AIs for this particular trial
final List<AI> ais = new ArrayList<AI>();
ais.add(null);
final int currentAIsPermutation = numTrial % aiListPermutations.size();
final TIntArrayList currentPlayersPermutation = aiListPermutations.get(currentAIsPermutation);
for (int j = 0; j < currentPlayersPermutation.size(); ++j)
{
ais.add
(
aisListPerThread.get(threadIdx).get(currentPlayersPermutation.getQuick(j) % numPlayers)
);
}
final Trial trial = new Trial(rulesetGame);
final Context context = new Context(rulesetGame, trial);
final byte[] startRNGState = ((RandomProviderDefaultState) context.rng().saveState()).getState();
rulesetGame.start(context);
// Init the ais.
for (int p = 1; p <= rulesetGame.players().count(); ++p)
ais.get(p).initAI(rulesetGame, p);
final Model model = context.model();
// Run the trial.
while (!trial.over())
model.startNewStep(context, ais, thinkingTime);
try
{
trial.saveTrialToTextFile(trialFile, path, rulesetGame.getOptions(), new RandomProviderDefaultState(startRNGState));
System.out.println("Saved trial for " + rulesetGame.name() + "|" + rulesetGame.getRuleset().heading().replace("/", "_") +" to file: " + trialFilepath);
}
catch (final IOException e)
{
e.printStackTrace();
fail("Crashed when trying to save trial to file.");
}
// Record outcome
final double[] utilities = RankUtils.agentUtilities(context);
final int numMovesPlayed = context.trial().numMoves() - context.trial().numInitialPlacementMoves();
final int[] agentPermutation = new int[currentPlayersPermutation.size() + 1];
currentPlayersPermutation.toArray(agentPermutation, 0, 1, currentPlayersPermutation.size());
resultsSummary.recordResults(agentPermutation, utilities, numMovesPlayed);
}
catch (final Exception e)
{
e.printStackTrace();
}
finally
{
latch.countDown();
}
}
);
}
catch (final Exception e)
{
e.printStackTrace();
}
}
try
{
latch.await();
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
executorService.shutdown();
if (new HashSet<String>(agentStrings).size() > 1)
{
// We have more than one agent name, so print per-agent results
final File resultsFile = new File(rulesetFolderPath + File.separator + trialsDirName + "alpha_rank_data.csv");
resultsSummary.writeAlphaRankData(resultsFile);
}
}
}
}
}
else // Code for the default ruleset.
{
int beginTrialIndex = 0;
for (; beginTrialIndex < NUM_TRIALS_PER_GAME; ++beginTrialIndex)
{
final String trialFilepath = gameFolderPath + File.separator + trialsDirName + "Trial_" + beginTrialIndex + ".txt";
final File trialFile = new File(trialFilepath);
if(!trialFile.exists())
break;
}
if (beginTrialIndex < NUM_TRIALS_PER_GAME)
{
final int parallelNum = (NUM_TRIALS_PER_GAME - beginTrialIndex) > NUM_PARALLEL ? NUM_PARALLEL : (NUM_TRIALS_PER_GAME - beginTrialIndex);
final ExecutorService executorService = Executors.newFixedThreadPool(parallelNum, new TrialsThreadFactory());
final CountDownLatch latch = new CountDownLatch(NUM_TRIALS_PER_GAME - beginTrialIndex);
// For every thread, create a list of AIs to be used for all trials in that thread
final List<List<AI>> aisListPerThread = new ArrayList<List<AI>>(parallelNum);
for (int i = 0; i < parallelNum; ++i)
{
aisListPerThread.add(chooseAI(game, agentName, agentName2, 0));
for (final AI ai : aisListPerThread.get(i))
if (ai != null)
ai.setMaxSecondsPerMove(thinkingTime);
}
final int numPlayers = game.players().count();
final List<TIntArrayList> aiListPermutations;
if (numPlayers <= 5)
{
// Compute all possible permutations of indices for the list of AIs
aiListPermutations = ListUtils.generatePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()));
Collections.shuffle(aiListPermutations);
}
else
{
// Randomly generate some permutations of indices for the list of AIs
aiListPermutations = ListUtils.samplePermutations(
TIntArrayList.wrap(IntStream.range(0, numPlayers).toArray()), 120);
}
final List<String> agentStrings = new ArrayList<String>(numPlayers);
for (int p = 1; p <= numPlayers; ++p)
{
agentStrings.add(aisListPerThread.get(0).get(p - 1).friendlyName());
}
final ResultsSummary resultsSummary = new ResultsSummary(game, agentStrings);
for (int i = beginTrialIndex; i < NUM_TRIALS_PER_GAME; ++i)
{
final String trialFilepath = gameFolderPath + File.separator + trialsDirName + "Trial_" + i + ".txt";
final File trialFile = new File(trialFilepath);
try
{
final int numTrial = i;
final String path = gamePath;
executorService.submit
(
() ->
{
try
{
System.out.println("Starting playout " + numTrial + ": ...");
// Figure out the 0-based index of our thread
final int threadIdx =
Integer.parseInt(Thread.currentThread().getName().substring("Trials Thread ".length()));
// Create re-ordered list of AIs for this particular trial
final List<AI> ais = new ArrayList<AI>();
ais.add(null);
final int currentAIsPermutation = numTrial % aiListPermutations.size();
final TIntArrayList currentPlayersPermutation = aiListPermutations.get(currentAIsPermutation);
for (int j = 0; j < currentPlayersPermutation.size(); ++j)
{
ais.add
(
aisListPerThread.get(threadIdx).get(currentPlayersPermutation.getQuick(j) % numPlayers)
);
}
final Trial trial = new Trial(game);
final Context context = new Context(game, trial);
final byte[] startRNGState = ((RandomProviderDefaultState) context.rng().saveState()).getState();
game.start(context);
// Init the ais.
for (int p = 1; p <= game.players().count(); ++p)
ais.get(p).initAI(game, p);
final Model model = context.model();
// Run the trial.
while (!trial.over())
model.startNewStep(context, ais, thinkingTime);
try
{
trial.saveTrialToTextFile(trialFile, path, new ArrayList<String>(), new RandomProviderDefaultState(startRNGState));
System.out.println("Saved trial for " + game.name() +" to file: " + trialFilepath);
}
catch (final IOException e)
{
e.printStackTrace();
fail("Crashed when trying to save trial to file.");
}
// Record outcome
final double[] utilities = RankUtils.agentUtilities(context);
final int numMovesPlayed = context.trial().numMoves() - context.trial().numInitialPlacementMoves();
final int[] agentPermutation = new int[currentPlayersPermutation.size() + 1];
currentPlayersPermutation.toArray(agentPermutation, 0, 1, currentPlayersPermutation.size());
resultsSummary.recordResults(agentPermutation, utilities, numMovesPlayed);
}
catch (final Exception e)
{
e.printStackTrace();
}
finally
{
latch.countDown();
}
}
);
}
catch (final Exception e)
{
e.printStackTrace();
}
}
try
{
latch.await();
}
catch (final InterruptedException e)
{
e.printStackTrace();
}
executorService.shutdown();
if (new HashSet<String>(agentStrings).size() > 1)
{
// We have more than one agent name, so print per-agent results
final File resultsFile = new File(gameFolderPath + File.separator + trialsDirName + "alpha_rank_data.csv");
resultsSummary.writeAlphaRankData(resultsFile);
}
}
}
}
/**
* @param game The game.
* @param agentName The name of the agent.
* @param agentName2 The name of the second agent (can be empty string if not used).
* @param indexPlayout The index of the playout.
* @return The list of AIs to play that playout.
*/
private static List<AI> chooseAI(final Game game, final String agentName, final String agentName2, final int indexPlayout)
{
final List<AI> ais = new ArrayList<AI>();
//ais.add(null);
if (agentName2.length() > 0)
{
// Special case where we have provided two different names
if (game.players().count() == 2)
{
ais.add(AIFactory.createAI(agentName));
ais.add(AIFactory.createAI(agentName2));
return ais;
}
else
{
System.err.println("Provided 2 agent names, but not a 2-player game!");
}
}
// Continue with Eric's original implementation
for (int p = 1; p <= game.players().count(); ++p)
{
if(agentName.equals("UCT"))
{
final AI ai = AIFactory.createAI("UCT");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else if(agentName.equals("Alpha-Beta"))
{
AI ai = AIFactory.createAI("Alpha-Beta");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else if(agentName.equals("Alpha-Beta-UCT")) // AB/UCT/AB/UCT/...
{
if(indexPlayout % 2 == 0)
{
if(p % 2 == 1)
{
AI ai = AIFactory.createAI("Alpha-Beta");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AI ai = AIFactory.createAI("UCT");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if(p % 2 == 1)
{
final AI ai = AIFactory.createAI("UCT");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = AIFactory.createAI("Alpha-Beta");
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else if(agentName.equals("AB-Odd-Even")) // Alternating between AB Odd and AB Even
{
if(indexPlayout % 2 == 0)
{
if(p % 2 == 1)
{
AI ai = new AlphaBetaSearch();
((AlphaBetaSearch)ai).setAllowedSearchDepths(AllowedSearchDepths.Odd);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
final AlphaBetaSearch ai = new AlphaBetaSearch();
ai.setAllowedSearchDepths(AllowedSearchDepths.Even);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
else
{
if(p % 2 == 1)
{
final AlphaBetaSearch ai = new AlphaBetaSearch();
ai.setAllowedSearchDepths(AllowedSearchDepths.Even);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
else
{
AI ai = new AlphaBetaSearch();
((AlphaBetaSearch)ai).setAllowedSearchDepths(AllowedSearchDepths.Odd);
if(ai.supportsGame(game))
{
ais.add(ai);
}
else if (AIFactory.createAI("UCT").supportsGame(game))
{
ai = AIFactory.createAI("UCT");
ais.add(ai);
}
else
{
ais.add(new utils.RandomAI());
}
}
}
}
else
{
ais.add(new utils.RandomAI());
}
}
return ais;
}
/**
* Thread factory that gives us consecutive IDs, starting from 0, we can access from
* each thread in our pool.
*
* @author Dennis Soemers
*/
protected static class TrialsThreadFactory implements ThreadFactory
{
private int nextID = 0;
@Override
public Thread newThread(final Runnable r)
{
return new Thread(r, "Trials Thread " + nextID++);
}
}
}
| 21,531 | 29.804006 | 163 |
java
|
Ludii
|
Ludii-master/Player/src/app/PlayerApp.java
|
package app;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import app.move.MoveHandler;
import app.move.animation.AnimationType;
import app.move.animation.MoveAnimation;
import app.utils.AnimationVisualsType;
import app.utils.BufferedImageUtil;
import app.utils.ContextSnapshot;
import app.utils.GameUtil;
import app.utils.GraphicsCache;
import app.utils.RemoteDialogFunctionsPublic;
import app.utils.SVGUtil;
import app.utils.SettingsExhibition;
import app.utils.SettingsPlayer;
import app.utils.Sound;
import app.utils.UpdateTabMessages;
import app.views.View;
import bridge.Bridge;
import bridge.PlatformGraphics;
import game.equipment.container.board.Board;
import game.types.board.SiteType;
import main.Constants;
import main.collections.FastArrayList;
import manager.Manager;
import manager.PlayerInterface;
import metadata.graphics.util.PieceStackType;
import metadata.graphics.util.StackPropertyType;
import other.action.Action;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.move.Move;
import other.state.State;
import other.state.container.ContainerState;
import tournament.Tournament;
import util.HiddenUtil;
import util.ImageInfo;
import util.PlaneType;
import util.StringUtil;
/**
* Abstract PlayerApp class to be extended by each platform specific Player.
*
* @author Matthew.Stephenson
*/
public abstract class PlayerApp implements PlayerInterface, ActionListener, ItemListener, PlatformGraphics
{
private final Manager manager = new Manager(this);
private final Bridge bridge = new Bridge();
private final ContextSnapshot contextSnapshot = new ContextSnapshot();
private final SettingsPlayer settingsPlayer = new SettingsPlayer();
private final GraphicsCache graphicsCache = new GraphicsCache();
private final RemoteDialogFunctionsPublic remoteDialogFunctionsPublic = RemoteDialogFunctionsPublic.construct();
//-------------------------------------------------------------------------
public abstract Tournament tournament();
public abstract void setTournament(Tournament tournament);
public abstract void reportError(String error);
public abstract void repaintComponentBetweenPoints(Context context, Location moveFrom, Point startPoint, Point endPoint);
public abstract void showPuzzleDialog(final int site);
public abstract void showPossibleMovesDialog(final Context context, final FastArrayList<Move> possibleMoves);
public abstract void saveTrial();
public abstract void playSound(String soundName);
public abstract void setVolatileMessage(String text);
public abstract void writeTextToFile(String fileName, String log);
public abstract void resetMenuGUI();
public abstract void showSettingsDialog();
public abstract void showOtherDialog(FastArrayList<Move> otherPossibleMoves);
public abstract void showInfoDialog();
public abstract int width();
public abstract int height();
public abstract List<View> getPanels();
public abstract Rectangle[] playerSwatchList();
public abstract Rectangle[] playerNameList();
public abstract boolean[] playerSwatchHover();
public abstract boolean[] playerNameHover();
public abstract void repaint(Rectangle rect);
//-------------------------------------------------------------------------
public Manager manager()
{
return manager;
}
public Bridge bridge()
{
return bridge;
}
public SettingsPlayer settingsPlayer()
{
return settingsPlayer;
}
public ContextSnapshot contextSnapshot()
{
return contextSnapshot;
}
public GraphicsCache graphicsCache()
{
return graphicsCache;
}
public RemoteDialogFunctionsPublic remoteDialogFunctionsPublic()
{
return remoteDialogFunctionsPublic;
}
//-------------------------------------------------------------------------
@Override
public Location locationOfClickedImage(final Point pt)
{
final ArrayList<Location> overlappedLocations = new ArrayList<>();
for (int imageIndex = 0; imageIndex < graphicsCache().allDrawnComponents().size(); imageIndex++)
{
//check if pixel is on image
final BufferedImage image = graphicsCache().allDrawnComponents().get(imageIndex).pieceImage();
final Point imageDrawPosn = graphicsCache().allDrawnComponents().get(imageIndex).imageInfo().drawPosn();
if (BufferedImageUtil.pointOverlapsImage(pt, image, imageDrawPosn))
{
final int clickedIndex = graphicsCache().allDrawnComponents().get(imageIndex).imageInfo().site();
final int clickedLevel = graphicsCache().allDrawnComponents().get(imageIndex).imageInfo().level();
final SiteType clickedType = graphicsCache().allDrawnComponents().get(imageIndex).imageInfo().graphElementType();
overlappedLocations.add(new FullLocation(clickedIndex, clickedLevel, clickedType));
}
}
if (overlappedLocations.size() == 1)
{
return overlappedLocations.get(0);
}
else if (overlappedLocations.size() > 1)
{
Location highestLocation = null;
int highestLevel = -1;
for (final Location location : overlappedLocations)
{
if (location.level() > highestLevel)
{
highestLevel = location.level();
highestLocation = location;
}
}
return highestLocation;
}
return new FullLocation(-1, 0, SiteType.Cell);
}
//-----------------------------------------------------------------------------
@Override
public void drawSVG(final Context context, final Graphics2D g2d, final SVGGraphics2D svg, final ImageInfo imageInfo)
{
final BufferedImage componentImage = SVGUtil.createSVGImage(svg.getSVGElement(), imageInfo.imageSize(), imageInfo.imageSize());
g2d.drawImage(componentImage, imageInfo.drawPosn().x - imageInfo.imageSize()/2, imageInfo.drawPosn().y - imageInfo.imageSize()/2, null);
}
//-----------------------------------------------------------------------------
@Override
public void drawComponent(final Graphics2D g2d, final Context context, final ImageInfo imageInfo)
{
final State state = context.state();
final ContainerState cs = state.containerStates()[imageInfo.containerIndex()];
final int hiddenValue = HiddenUtil.siteHiddenBitsetInteger(context, cs, imageInfo.site(), imageInfo.level(), context.state().mover(), imageInfo.graphElementType());
final BufferedImage componentImage = graphicsCache().getComponentImage(bridge, imageInfo.containerIndex(), imageInfo.component(), imageInfo.component().owner(), imageInfo.localState(), imageInfo.value(), imageInfo.site(), imageInfo.level(), imageInfo.graphElementType(), imageInfo.imageSize(), context, hiddenValue, imageInfo.rotation(), false);
graphicsCache().drawPiece(g2d, context, componentImage, imageInfo.drawPosn(), imageInfo.site(), imageInfo.level(), imageInfo.graphElementType(), imageInfo.transparency());
drawPieceCount(g2d, context, imageInfo, cs);
}
//-----------------------------------------------------------------------------
private void drawPieceCount(final Graphics2D g2d, final Context context, final ImageInfo imageInfo, final ContainerState cs)
{
if (context.equipment().components()[cs.what(imageInfo.site(), imageInfo.level(), imageInfo.graphElementType())].isDomino())
return;
final int localState = cs.state(imageInfo.site(), imageInfo.level(), imageInfo.graphElementType());
final int value = cs.value(imageInfo.site(), imageInfo.level(), imageInfo.graphElementType());
final PieceStackType componentStackType = PieceStackType.getTypeFromValue((int) context.metadata().graphics().stackMetadata(context, context.equipment().containers()[imageInfo.containerIndex()], imageInfo.site(), imageInfo.graphElementType(), localState, value, StackPropertyType.Type));
if (imageInfo.count() < 0)
{
drawCountValue(context, g2d, imageInfo, "?", 1, 1);
}
if (imageInfo.count() > 1)
{
drawCountValue(context, g2d, imageInfo, Integer.toString(imageInfo.count()), 1, 1);
}
else if (componentStackType.equals(PieceStackType.Count) && cs.sizeStack(imageInfo.site(), imageInfo.graphElementType()) > 1)
{
drawCountValue(context, g2d, imageInfo, Integer.toString(cs.sizeStack(imageInfo.site(), imageInfo.graphElementType())), 1, 1);
}
else if (componentStackType.equals(PieceStackType.DefaultAndCount) && cs.sizeStack(imageInfo.site(), imageInfo.graphElementType()) > 1)
{
drawCountValue(context, g2d, imageInfo, Integer.toString(cs.sizeStack(imageInfo.site(), imageInfo.graphElementType())), 1, 1);
}
else if (componentStackType.equals(PieceStackType.CountColoured) && cs.sizeStack(imageInfo.site(), imageInfo.graphElementType()) > 1)
{
// Record the number of pieces owned by each player in this stack.
final int [] playerCountArray = new int[Constants.MAX_PLAYERS];
Arrays.fill(playerCountArray, 0);
for (int i = 0; i < Constants.MAX_STACK_HEIGHT; i++)
if (cs.what(imageInfo.site(), i, imageInfo.graphElementType()) != 0)
playerCountArray[cs.who(imageInfo.site(), i, imageInfo.graphElementType())]++;
// Record the total number of counts to be drawn.
int totalCountsDrawn = 0;
for (int i = 0; i < Constants.MAX_PLAYERS; i++)
if (playerCountArray[i] != 0)
totalCountsDrawn++;
// Display the counts for each player.
int numberCountsDrawn = 0;
for (int i = 0; i < Constants.MAX_PLAYERS; i++)
if (playerCountArray[i] != 0)
drawCountValue(context, g2d, imageInfo, Integer.toString(playerCountArray[i]), ++numberCountsDrawn, totalCountsDrawn);
}
}
//-----------------------------------------------------------------------------
/**
* For drawing a specific count value on an image, its position adjusted based on how many are to be drawn.
* @param g2d
* @param imageInfo
* @param count The count value.
* @param numberCountsDrawn The index of this count, out of the total counts to be drawn.
* @param totalCountsDrawn The total number of counts to be drawn.
* @param textColour The colour of the count string.
*/
private void drawCountValue(final Context context, final Graphics2D g2d, final ImageInfo imageInfo, final String count, final int numberCountsDrawn, final int totalCountsDrawn)
{
g2d.setFont(new Font("Arial", Font.PLAIN, Math.min(imageInfo.imageSize()/3, 20)));
if (imageInfo.containerIndex() > 0)
{
g2d.setColor(Color.BLACK);
if (SettingsExhibition.exhibitionVersion)
{
g2d.setColor(Color.white);
}
final Rectangle2D countRect = g2d.getFont().getStringBounds("x"+count, g2d.getFontRenderContext());
final int drawPosnX = (int)(imageInfo.drawPosn().x + imageInfo.imageSize()/2 - countRect.getWidth()/2);
final int drawPosnY = (int)(imageInfo.drawPosn().y + imageInfo.imageSize() + countRect.getHeight()/2 * 1.5);
g2d.drawString("x"+count,drawPosnX,drawPosnY);
}
else
{
g2d.setColor(bridge.getComponentStyle(imageInfo.component().index()).getSecondaryColour());
final Rectangle2D countRect = g2d.getFont().getStringBounds(count, g2d.getFontRenderContext());
final int drawPosnX = imageInfo.drawPosn().x + imageInfo.imageSize()/2;
final int drawPosnY = imageInfo.drawPosn().y + imageInfo.imageSize()/2;
StringUtil.drawStringAtPoint(g2d, count, null, new Point2D.Double(drawPosnX,drawPosnY+(numberCountsDrawn-1)*countRect.getHeight()-(totalCountsDrawn-1)*countRect.getHeight()/2), true);
}
}
//-----------------------------------------------------------------------------
@Override
public void drawBoard(final Context context, final Graphics2D g2d, final Rectangle2D boardDimensions)
{
if (graphicsCache().boardImage() == null)
{
final Board board = context.board();
bridge.getContainerStyle(board.index()).render(PlaneType.BOARD, context);
final String svg = bridge.getContainerStyle(board.index()).containerSVGImage();
if (svg == null || svg.equals(""))
return;
graphicsCache().setBoardImage(SVGUtil.createSVGImage(svg, boardDimensions.getWidth(), boardDimensions.getHeight()));
}
if (!context.game().metadata().graphics().boardHidden())
{
g2d.drawImage(graphicsCache().boardImage(), 0, 0, null);
}
}
//-----------------------------------------------------------------------------
@Override
public void drawGraph(final Context context, final Graphics2D g2d, final Rectangle2D boardDimensions)
{
if (graphicsCache().graphImage() == null || context.board().isBoardless())
{
final Board board = context.board();
bridge.getContainerStyle(board.index()).render(PlaneType.GRAPH, context);
final String svg = bridge.getContainerStyle(board.index()).graphSVGImage();
if (svg == null)
return;
graphicsCache().setGraphImage(SVGUtil.createSVGImage(svg, boardDimensions.getWidth(), boardDimensions.getHeight()));
}
g2d.drawImage(graphicsCache().graphImage(), 0, 0, null);
}
//-----------------------------------------------------------------------------
@Override
public void drawConnections(final Context context, final Graphics2D g2d, final Rectangle2D boardDimensions)
{
if (graphicsCache().connectionsImage() == null || context.board().isBoardless())
{
final Board board = context.board();
bridge.getContainerStyle(board.index()).render(PlaneType.CONNECTIONS, context);
final String svg = bridge.getContainerStyle(board.index()).dualSVGImage();
if (svg == null)
return;
graphicsCache().setConnectionsImage(SVGUtil.createSVGImage(svg, boardDimensions.getWidth(), boardDimensions.getHeight()));
}
g2d.drawImage(graphicsCache().connectionsImage(), 0, 0, null);
}
//-----------------------------------------------------------------------------
public void clearGraphicsCache()
{
graphicsCache().clearAllCachedImages();
}
@Override
public void restartGame()
{
GameUtil.resetGame(this, false);
}
//-----------------------------------------------------------------------------
// @Override
// public void postMoveUpdates(final Move move, final boolean noAnimation)
// {
// if (!noAnimation && settingsPlayer().showAnimation() && !bridge().settingsVC().pieceBeingDragged())
// {
// MoveAnimation.saveMoveAnimationDetails(this, move);
//
// new java.util.Timer().schedule
// (
// new java.util.TimerTask()
// {
// @Override
// public void run()
// {
// postAnimationUpdates(move);
// }
// },
// MoveAnimation.ANIMATION_WAIT_TIME
// );
// }
// else
// {
// postAnimationUpdates(move);
// }
// }
//-----------------------------------------------------------------------------
@Override
public void postMoveUpdates(final Move move, final boolean noAnimation)
{
if (!noAnimation && settingsPlayer().showAnimation() && !bridge().settingsVC().pieceBeingDragged() && !manager.ref().context().game().metadata().graphics().noAnimation())
{
if (settingsPlayer().animationType() == AnimationVisualsType.All)
{
// Animate all valid actions within the move.
final ArrayList<Move> singleActionMoves = new ArrayList<>();
for (final Action a : move.actions())
{
a.setDecision(true);
final Move singleActionMove = new Move(a);
singleActionMove.setFromNonDecision(a.from());
singleActionMove.setToNonDecision(a.to());
final AnimationType animationType = MoveAnimation.getMoveAnimationType(this, singleActionMove);
if (!animationType.equals(AnimationType.NONE))
singleActionMoves.add(singleActionMove);
}
if (singleActionMoves.size() > 0)
animateMoves(singleActionMoves);
}
else
{
// Animate just the first decision action within the move.
final ArrayList<Move> moves = new ArrayList<>();
moves.add(move);
animateMoves(moves);
}
}
else
{
postAnimationUpdates(move);
}
}
//-----------------------------------------------------------------------------
/**
* Animates a list of moves, one after the other.
*/
void animateMoves(final List<Move> moves)
{
final PlayerApp app = this;
final Move move = moves.get(0);
moves.remove(0);
MoveAnimation.saveMoveAnimationDetails(this, move);
if (SettingsExhibition.exhibitionVersion)
Sound.playSound("Ludemeljud5");
final Timer animationTimer = new Timer();
final TimerTask animationTask = new TimerTask()
{
@Override
public void run()
{
final Context snapshotContext = contextSnapshot().getContext(app);
move.apply(snapshotContext, false);
contextSnapshot().setContext(snapshotContext);
if (moves.size() == 0)
postAnimationUpdates(move);
else
animateMoves(moves);
}
};
animationTimer.schedule(animationTask, MoveAnimation.ANIMATION_WAIT_TIME);
}
//-----------------------------------------------------------------------------
/**
* Called after any animations for the moves have finished.
*/
public void postAnimationUpdates(final Move move)
{
UpdateTabMessages.postMoveUpdateStatusTab(this);
settingsPlayer().setComponentIsSelected(false);
bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED));
contextSnapshot().setContext(this);
final Context context = contextSnapshot().getContext(this);
GameUtil.gameOverTasks(this, move);
if (!context.game().isSimulationMoveGame())
MoveHandler.checkMoveWarnings(this);
if (move != null && manager().aiSelected()[manager.playerToAgent(move.mover())].ai() != null)
playSound("Pling-KevanGC-1485374730");
if (settingsPlayer().saveTrialAfterMove())
saveTrial();
if (context.game().metadata().graphics().needRedrawn())
graphicsCache().clearAllCachedImages();
MoveAnimation.resetAnimationValues(this);
updateFrameTitle(false);
repaint();
}
//-----------------------------------------------------------------------------
/**
* Load specific game preferences for the current game.
*/
public void loadGameSpecificPreferences()
{
final Context context = manager().ref().context();
bridge().settingsColour().resetColours();
for (int pid = 0; pid <= context.game().players().count()+1; pid++)
{
final Color colour = context.game().metadata().graphics().playerColour(context, pid);
if (pid > context.game().players().count())
pid = Constants.MAX_PLAYERS+1;
if (colour != null)
bridge().settingsColour().setPlayerColour(pid, colour);
}
manager().ref().context().game().setMaxTurns(manager().settingsManager().turnLimit(manager().ref().context().game().name()));
}
//-----------------------------------------------------------------------------
}
| 19,083 | 35.419847 | 347 |
java
|
Ludii
|
Ludii-master/Player/src/app/move/MouseHandler.java
|
package app.move;
import java.awt.Point;
import app.PlayerApp;
import app.utils.GUIUtil;
import app.utils.sandbox.SandboxUtil;
import main.Constants;
import other.action.move.ActionSelect;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.move.Move;
import util.LocationUtil;
/**
* Functions that handle any "mouse" actions.
*
* @author Matthew.Stephenson
*/
public class MouseHandler
{
//-------------------------------------------------------------------------
/**
* Code that is applied when a mouse is pressed.
*/
public static void mousePressedCode(final PlayerApp app, final Point pressedPoint)
{
if (!mouseChecks(app))
return;
final Context context = app.contextSnapshot().getContext(app);
if (app.bridge().settingsVC().selectedFromLocation().equals(new FullLocation(Constants.UNDEFINED)))
app.settingsPlayer().setComponentIsSelected(false);
// Can't select pieces if the AI is moving
if (app.manager().aiSelected()[app.manager().moverToAgent()].ai() != null && !app.manager().settingsManager().agentsPaused())
return;
// Get the nearest valid from location to the pressed point.
if (app.settingsPlayer().sandboxMode())
app.bridge().settingsVC().setSelectedFromLocation(LocationUtil.calculateNearestLocation(context, app.bridge(), pressedPoint, LocationUtil.getAllLocations(context, app.bridge())));
else if (!app.settingsPlayer().componentIsSelected())
app.bridge().settingsVC().setSelectedFromLocation(LocationUtil.calculateNearestLocation(context, app.bridge(), pressedPoint, LocationUtil.getLegalFromLocations(context)));
}
//-------------------------------------------------------------------------
/**
* Code that is applied when a mouse is released.
*/
public static void mouseReleasedCode(final PlayerApp app, final Point releasedPoint)
{
if (!mouseChecks(app))
return;
final Context context = app.contextSnapshot().getContext(app);
final Location selectedFromLocation = app.bridge().settingsVC().selectedFromLocation();
Location selectedToLocation;
if (app.bridge().settingsVC().selectingConsequenceMove() || app.settingsPlayer().sandboxMode())
selectedToLocation = LocationUtil.calculateNearestLocation(context, app.bridge(), releasedPoint, LocationUtil.getAllLocations(context, app.bridge()));
else
selectedToLocation = LocationUtil.calculateNearestLocation(context, app.bridge(), releasedPoint, LocationUtil.getLegalToLocations(app.bridge(), context));
// Account for any large component offsets
if
(
app.bridge().settingsVC().pieceBeingDragged()
&&
app.settingsPlayer().dragComponent() != null
&&
app.bridge().getComponentStyle(app.settingsPlayer().dragComponent().index()).getLargeOffsets().size() > app.settingsPlayer().dragComponentState()
)
{
final Point newPoint = releasedPoint;
newPoint.x = (int) (newPoint.x - app.bridge().getComponentStyle(app.settingsPlayer().dragComponent().index()).getLargeOffsets().get(app.settingsPlayer().dragComponentState()).getX());
newPoint.y = (int) (newPoint.y + app.bridge().getComponentStyle(app.settingsPlayer().dragComponent().index()).getLargeOffsets().get(app.settingsPlayer().dragComponentState()).getY());
selectedToLocation = LocationUtil.calculateNearestLocation(context, app.bridge(), newPoint, LocationUtil.getLegalToLocations(app.bridge(), context));
}
if (context.game().isDeductionPuzzle())
{
MoveHandler.tryPuzzleMove(app, selectedFromLocation, selectedToLocation);
}
else
{
if (app.settingsPlayer().sandboxMode())
{
SandboxUtil.makeSandboxDragMove(app, selectedFromLocation, selectedToLocation);
}
else if (!MoveHandler.tryGameMove(app, selectedFromLocation, selectedToLocation, false, -1))
{
// Remember the selected From location for next time.
if
(
!app.settingsPlayer().componentIsSelected()
&&
!app.settingsPlayer().usingMYOGApp()
&&
app.bridge().settingsVC().lastClickedSite().equals(selectedFromLocation)
)
{
app.settingsPlayer().setComponentIsSelected(true);
}
else
{
// Special exhibition code for making move piece to hands move / removing pieces.
if (app.settingsPlayer().usingMYOGApp())
{
if (GUIUtil.pointOverlapsRectangle(releasedPoint, app.settingsPlayer().boardMarginPlacement()))
{
for (final Move m : context.game().moves(context).moves())
{
if (selectedToLocation.site() == -1 || selectedToLocation.site() >= context.board().numSites())
{
if (m.from() == selectedFromLocation.site() && m.to() >= context.board().numSites())
{
app.manager().ref().applyHumanMoveToGame(app.manager(), m);
break;
}
}
}
}
else
{
for (final Move m : context.game().moves(context).moves())
{
if (m.from() == selectedFromLocation.site() && m.actions().get(0) instanceof ActionSelect && m.from() != m.to())
{
app.manager().ref().applyHumanMoveToGame(app.manager(), m);
break;
}
}
}
}
else
{
app.setVolatileMessage("That is not a valid move.");
}
app.settingsPlayer().setComponentIsSelected(false);
}
}
}
if (!app.settingsPlayer().componentIsSelected())
app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED));
app.bridge().settingsVC().setPieceBeingDragged(false);
app.settingsPlayer().setCurrentWalkExtra(0);
app.repaint();
}
//-------------------------------------------------------------------------
/**
* Code that is applied when a mouse is clicked.
*/
public static void mouseClickedCode(final PlayerApp app, final Point point)
{
if (!mouseChecks(app))
return;
// Store the last clicked location, used for dev display and selecting pieces.
final Context context = app.contextSnapshot().getContext(app);
// clickedLocation = LocationUtil.calculateNearestLocation(context, app.bridge(), point, LocationUtil.getAllLocations(context, app.bridge()));
Location clickedLocation;
if (app.settingsPlayer().componentIsSelected())
clickedLocation = LocationUtil.calculateNearestLocation(context, app.bridge(), point, LocationUtil.getLegalToLocations(app.bridge(), context));
else
clickedLocation = LocationUtil.calculateNearestLocation(context, app.bridge(), point, LocationUtil.getLegalFromLocations(context));
// If not valid legal location was found, just use the closest site to what they clicked.
if (clickedLocation.equals(new FullLocation(Constants.UNDEFINED)))
clickedLocation = LocationUtil.calculateNearestLocation(context, app.bridge(), point, LocationUtil.getAllLocations(context, app.bridge()));
app.bridge().settingsVC().setLastClickedSite(clickedLocation);
app.repaint();
}
//-------------------------------------------------------------------------
/**
* Code that is applied when a mouse is dragged.
*/
public static void mouseDraggedCode(final PlayerApp app, final Point point)
{
if (!mouseChecks(app))
return;
final Context context = app.contextSnapshot().getContext(app);
app.bridge().settingsVC().setSelectedFromLocation(app.bridge().settingsVC().selectedFromLocation());
// Can't drag pieces in a deduction puzzle.
if (context.game().isDeductionPuzzle())
return;
if (app.settingsPlayer().usingMYOGApp())
{
// repaint the whole view for exhibition mode.
app.repaint();
}
else if (!app.bridge().settingsVC().pieceBeingDragged())
{
// repaint the whole view when a piece starts to be dragged.
app.repaint();
}
else
{
// Repaint between the dragged points and update location of dragged piece.
app.repaintComponentBetweenPoints
(
context,
app.bridge().settingsVC().selectedFromLocation(),
app.settingsPlayer().oldMousePoint(),
point
);
}
app.bridge().settingsVC().setPieceBeingDragged(true);
app.settingsPlayer().setOldMousePoint(point);
}
//-------------------------------------------------------------------------
/**
* Checks that need to be made before any code specific to mouse actions is performed.
*/
private static boolean mouseChecks(final PlayerApp app)
{
if (app.manager().settingsNetwork().getActiveGameId() != 0)
{
if (app.contextSnapshot().getContext(app).state().mover() != app.manager().settingsNetwork().getNetworkPlayerNumber())
{
app.setVolatileMessage("Wait your turn!");
return false;
}
for (int i = 1; i <= app.contextSnapshot().getContext(app).game().players().count(); i++)
{
if (app.manager().aiSelected()[i].name().trim().equals(""))
{
app.setVolatileMessage("Not all players have joined yet.");
return false;
}
}
}
return true;
}
//-------------------------------------------------------------------------
}
| 8,960 | 33.598456 | 186 |
java
|
Ludii
|
Ludii-master/Player/src/app/move/MoveFormat.java
|
package app.move;
public enum MoveFormat
{
Full, // Full move format
Move, // Default move format
Short; // Short move format
}
| 137 | 14.333333 | 30 |
java
|
Ludii
|
Ludii-master/Player/src/app/move/MoveHandler.java
|
package app.move;
import java.awt.EventQueue;
import java.util.ArrayList;
import app.PlayerApp;
import app.utils.PuzzleSelectionType;
import game.equipment.component.Component;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import game.util.directions.AbsoluteDirection;
import main.Constants;
import main.collections.FastArrayList;
import other.action.Action;
import other.action.puzzle.ActionReset;
import other.action.puzzle.ActionSet;
import other.action.puzzle.ActionToggle;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.move.Move;
import other.state.container.ContainerState;
import other.topology.Vertex;
import util.ContainerUtil;
/**
* Functions for handling moves made by humans.
*
* @author Matthew.Stephenson
*/
public class MoveHandler
{
//-------------------------------------------------------------------------
/**
* Try to make a move for the specified From and To locations.
* If more than one possible move is found, the users is asked which they want.
* If one possible move is found, that move is applied.
* @return True if a matching legal move found, false otherwise
*/
public static boolean tryGameMove(final PlayerApp app, final Location locnFromInfo, final Location locnToInfo, final boolean passMove, final int selectPlayerMove)
{
final Context context = app.manager().ref().context();
final Moves legal = context.game().moves(context);
final FastArrayList<Move> possibleMoves = new FastArrayList<>();
// only used in web app, to force multiple possible moves in some cases.
boolean forceMultiplePossibleMoves = false;
// Check if de-selecting a previously selected piece
if (app.settingsPlayer().componentIsSelected() && app.bridge().settingsVC().lastClickedSite().equals(locnFromInfo))
return false;
if (app.bridge().settingsVC().selectingConsequenceMove())
{
applyConsequenceChosen(app, locnToInfo);
return true;
}
if (passMove)
{
for (final Move m : legal.moves())
{
if (m.isPass())
possibleMoves.add(m);
if (m.containsNextInstance())
possibleMoves.add(m);
}
}
else if (selectPlayerMove != -1)
{
for (final Move m : legal.moves())
{
if (m.playerSelected() == selectPlayerMove)
possibleMoves.add(m);
}
}
else
{
for (final Move move : legal.moves())
{
if (locnFromInfo.site() == -1)
return false;
// Check if any other legal moves have fromInfo as their from location.
if
(
locnFromInfo.equals(locnToInfo)
&&
move.getFromLocation().equals(locnFromInfo)
&&
!move.getToLocation().equals(locnToInfo)
&&
!app.settingsPlayer().componentIsSelected()
)
{
forceMultiplePossibleMoves = true;
}
// If move matches clickInfo, then store it as a possible move.
if (MoveHandler.moveMatchesLocation(app, move, locnFromInfo, locnToInfo, context))
{
boolean moveAlreadyAvailable = false;
for (final Move m : possibleMoves)
if (m.getActionsWithConsequences(context).equals(move.getActionsWithConsequences(context)))
moveAlreadyAvailable = true;
if (!moveAlreadyAvailable)
possibleMoves.add(move);
}
}
}
if (app.settingsPlayer().printMoveFeatures() || app.settingsPlayer().printMoveFeatureInstances())
{
printMoveFeatures(app, context, possibleMoves);
return false;
}
if (possibleMoves.size() > 1 || (possibleMoves.size() > 0 && forceMultiplePossibleMoves && !app.settingsPlayer().usingMYOGApp()))
{
// If several different moves are possible.
return handleMultiplePossibleMoves(app, possibleMoves, context);
}
else if (possibleMoves.size() == 1)
{
if (MoveHandler.moveChecks(app, possibleMoves.get(0)))
{
app.manager().ref().applyHumanMoveToGame(app.manager(), possibleMoves.get(0));
return true; // move found
}
}
return false; // move not found
}
//-------------------------------------------------------------------------
private static void printMoveFeatures(final PlayerApp app, final Context context, final FastArrayList<Move> possibleMoves)
{
// Not supported anymore because decision trees in metadata mess up the implementation
System.err.println("Printing move features is not currently supported.");
// Don't apply move, but print active features for all matching moves
// final SoftmaxFromMetadataSelection softmax = app.settingsPlayer().featurePrintingSoftmax();
// softmax.initIfNeeded(context.game(), context.state().mover());
//
// final BaseFeatureSet[] featureSets = softmax.featureSets();
// final BaseFeatureSet featureSet;
// if (featureSets[0] != null)
// featureSet = featureSets[0];
// else
// featureSet = featureSets[context.state().mover()];
//
// if (app.settingsPlayer().printMoveFeatures())
// {
// for (final Move move : possibleMoves)
// {
// final List<Feature> activeFeatures = featureSet.computeActiveFeatures(context, move);
// System.out.println("Listing active features for move: " + move);
//
// for (final Feature activeFeature : activeFeatures)
// System.out.println(activeFeature);
// }
// }
//
// if (app.settingsPlayer().printMoveFeatureInstances())
// {
// for (final Move move : possibleMoves)
// {
// final List<FeatureInstance> activeFeatureInstances =
// featureSet.getActiveSpatialFeatureInstances
// (
// context.state(),
// FeatureUtils.fromPos(context.trial().lastMove()),
// FeatureUtils.toPos(context.trial().lastMove()),
// FeatureUtils.fromPos(move),
// FeatureUtils.toPos(move),
// move.mover()
// );
// System.out.println("Listing active feature instances for move: " + move);
//
// for (final FeatureInstance activeFeatureInstance : activeFeatureInstances)
// System.out.println(activeFeatureInstance);
// }
// }
}
//-------------------------------------------------------------------------
/**
* Try and carry out a move for the puzzle.
*/
public static void tryPuzzleMove(final PlayerApp app, final Location locnFromInfo, final Location locnToInfo)
{
final Context context = app.contextSnapshot().getContext(app);
final Moves legal = context.game().moves(context);
for (final Move move : legal.moves())
{
if (moveMatchesLocation(app, move, locnFromInfo, locnToInfo, context))
{
final ContainerState cs = context.state().containerStates()[0];
final int site = move.from();
SiteType setType = move.fromType();
int maxValue = 0;
int puzzleValue = 0;
boolean valueResolved = false;
boolean valueFound = false;
maxValue = context.board().getRange(setType).max(context);
puzzleValue = cs.what(site, setType);
valueResolved = cs.isResolved(site, setType);
valueFound = false;
if (!valueResolved)
puzzleValue = -1;
for (int i = puzzleValue + 1; i < maxValue + 1; i++)
{
other.action.puzzle.ActionSet a = null;
a = new ActionSet(setType, site, i);
a.setDecision(true);
final Move m = new Move(a);
m.setFromNonDecision(move.from());
m.setToNonDecision(move.to());
m.setEdgeMove(site);
m.setDecision(true);
m.setOrientedMove(false);
if
(
context.game().moves(context).moves().contains(m)
||
(app.settingsPlayer().illegalMovesValid() && i > 0)
)
{
valueFound = true;
puzzleValue = i;
break;
}
}
if
(
app.settingsPlayer().puzzleDialogOption() == PuzzleSelectionType.Dialog
||
(
app.settingsPlayer().puzzleDialogOption() == PuzzleSelectionType.Automatic
&&
maxValue > 3
)
)
{
app.showPuzzleDialog(site);
}
else
{
if (!valueFound)
{
final Move resetMove = new Move(new ActionReset(context.board().defaultSite(), site, maxValue + 1));
resetMove.setDecision(true);
if (MoveHandler.moveChecks(app, resetMove))
app.manager().ref().applyHumanMoveToGame(app.manager(), resetMove);
}
else
{
puzzleMove(app, site, puzzleValue, true, setType);
// Set all unresolved edges, faces and vertices to the first value.
if (context.trial().over())
{
setType = SiteType.Edge;
for (int i = 0; i < context.board().topology().edges().size(); i++)
if (!cs.isResolvedEdges(i))
puzzleMove(app, i, 0, true, setType);
setType = SiteType.Cell;
for (int i = 0; i < context.board().topology().cells().size(); i++)
if (!cs.isResolvedVerts(i))
puzzleMove(app, i, 0, true, setType);
setType = SiteType.Vertex;
for (int i = 0; i < context.board().topology().vertices().size(); i++)
if (!cs.isResolvedCell(i))
puzzleMove(app, i, 0, true, setType);
}
}
}
break;
}
}
}
/**
* Move made specifically for a puzzle game.
* Involves either selecting a value or toggling a value for a site.
*/
public static void puzzleMove(final PlayerApp app, final int site, final int puzzleValue, final boolean leftClick, final SiteType type)
{
Action a = null;
if (leftClick)
a = new ActionSet(type, site, puzzleValue); // Set value
else
a = new ActionToggle(type, site, puzzleValue); // Toggle value
final Move m = new Move(a);
m.setDecision(true);
if (MoveHandler.moveChecks(app, m))
app.manager().ref().applyHumanMoveToGame(app.manager(), m);
}
//-------------------------------------------------------------------------
/**
* Handle the cases where several moves are possible for the same from/to ClickInfo.
*/
private static boolean handleMultiplePossibleMoves(final PlayerApp app, final FastArrayList<Move> possibleMoves, final Context context)
{
app.bridge().settingsVC().possibleConsequenceLocations().clear();
app.manager().settingsManager().possibleConsequenceMoves().clear();
app.bridge().settingsVC().setSelectingConsequenceMove(false);
int minMoveLength = 9999;
for (final Move m : possibleMoves)
if (m.getActionsWithConsequences(context).size() < minMoveLength)
minMoveLength = m.getActionsWithConsequences(context).size();
int differentAction = -1;
for (int i = 0; i < minMoveLength; i++)
{
Action sameAction = null;
boolean allSame = true;
for (final Move m : possibleMoves)
{
if (sameAction == null)
sameAction = m.getActionsWithConsequences(context).get(i);
else if (!sameAction.equals(m.getActionsWithConsequences(context).get(i)))
allSame = false;
}
if (!allSame)
{
differentAction = i;
break;
}
}
if (differentAction == -1)
{
app.showPossibleMovesDialog(context, possibleMoves);
return false;
}
else
{
for (final Move m : possibleMoves)
{
app.bridge().settingsVC().possibleConsequenceLocations()
.add(new FullLocation(m.getActionsWithConsequences(context).get(differentAction).to(),
m.getActionsWithConsequences(context).get(differentAction).levelTo(),
m.getActionsWithConsequences(context).get(differentAction).toType()));
// ** FIXME: Not thread-safe.
app.manager().settingsManager().possibleConsequenceMoves().add(m);
if (m.getActionsWithConsequences(context).get(differentAction).to() < 0)
{
app.showPossibleMovesDialog(context, possibleMoves);
return false;
}
}
// If any of the possibleToLocations are duplicates then need the dialog.
final ArrayList<Location> checkForDuplicates = new ArrayList<>();
boolean duplicateFound = false;
for (int i = 0; i < app.bridge().settingsVC().possibleConsequenceLocations().size(); i++)
{
for (final Location location : checkForDuplicates)
{
if (location.equals(app.bridge().settingsVC().possibleConsequenceLocations().get(i)))
{
duplicateFound = true;
break;
}
}
if (duplicateFound)
{
app.showPossibleMovesDialog(context, possibleMoves);
return false;
}
checkForDuplicates.add(app.bridge().settingsVC().possibleConsequenceLocations().get(i));
}
app.bridge().settingsVC().setSelectingConsequenceMove(true);
// Need to event queue this message so that it overrides the "invalid move" message.
app.setTemporaryMessage("Please select a consequence.");
return true;
}
}
//-------------------------------------------------------------------------
/**
* Applies the chosen consequence, corresponding with the selected location.
*/
private static void applyConsequenceChosen(final PlayerApp app, final Location location)
{
boolean moveMade = false;
for (int i = 0; i < app.bridge().settingsVC().possibleConsequenceLocations().size(); i++)
{
if (app.bridge().settingsVC().possibleConsequenceLocations().get(i).site() == location.site())
{
if (MoveHandler.moveChecks(app, app.manager().settingsManager().possibleConsequenceMoves().get(i)))
{
app.manager().ref().applyHumanMoveToGame(app.manager(), app.manager().settingsManager().possibleConsequenceMoves().get(i));
moveMade = true;
break;
}
}
}
if (!moveMade)
app.setVolatileMessage("That is not a valid move.");
app.bridge().settingsVC().setSelectingConsequenceMove(false);
app.bridge().settingsVC().possibleConsequenceLocations().clear();
app.manager().settingsManager().possibleConsequenceMoves().clear();
}
//-------------------------------------------------------------------------
/**
* Checks if Move matches the From and To location information.
*/
private static boolean moveMatchesLocation(final PlayerApp app, final Move move, final Location fromInfo, final Location toInfo, final Context context)
{
if (checkVertexMoveForEdge(move, fromInfo, toInfo, context))
return true;
if (move.matchesUserMove(fromInfo.site(), fromInfo.level(), fromInfo.siteType(), toInfo.site(), toInfo.level(), toInfo.siteType()))
return moveMatchesDraggedPieceRotation(app, move, fromInfo);
return false;
}
//-------------------------------------------------------------------------
/**
* @return Whether the player dragged between two vertices to indicate an edge move.
*/
private static boolean checkVertexMoveForEdge(final Move move, final Location fromInfo, final Location toInfo, final Context context)
{
// player can perform an edge move by dragging between its two vertices.
if (move.fromType() == SiteType.Edge && move.toType() == SiteType.Edge && move.getFromLocation().equals(move.getToLocation()))
{
// only works if dragging between vertices, and not dragging to the same vertex.
if (fromInfo.siteType() == SiteType.Vertex
&& fromInfo.siteType() == SiteType.Vertex
&& fromInfo.site() != toInfo.site())
{
if (move.from() == move.to())
{
final int edgeIndex = move.from();
final Vertex va = context.board().topology().edges().get(edgeIndex).vA();
final Vertex vb = context.board().topology().edges().get(edgeIndex).vB();
if (va.index() == fromInfo.site() && vb.index() == toInfo.site())
return true;
if (!move.isOrientedMove() && vb.index() == fromInfo.site() && va.index() == toInfo.site())
return true;
}
}
else
{
return false;
}
}
return false;
}
//-------------------------------------------------------------------------
/**
* returns true if the rotation of the dragged component matches the move specified.
*/
private static boolean moveMatchesDraggedPieceRotation(final PlayerApp app, final Move move, final Location fromInfo)
{
final Context context = app.contextSnapshot().getContext(app);
if (context.game().hasLargePiece() && app.bridge().settingsVC().pieceBeingDragged())
{
final int containerId = ContainerUtil.getContainerId(context, fromInfo.site(), fromInfo.siteType());
final int componentIndex = context.containerState(containerId).whatCell(fromInfo.site());
if
(
componentIndex > 0
&&
move.what() == Constants.NO_PIECE
&&
context.components()[componentIndex].isLargePiece()
&&
move.state() != app.settingsPlayer().dragComponentState()
)
return false;
}
return true;
}
//-------------------------------------------------------------------------
/**
* Applies the legal move that matches the direction (if only one match)
*/
public static void applyDirectionMove(final PlayerApp app, final AbsoluteDirection direction)
{
final Context context = app.manager().ref().context();
final Moves legal = context.game().moves(context);
// Find all valid moves for the specified direction.
final ArrayList<Move> validMovesfound = new ArrayList<>();
for (final Move m : legal.moves())
if (direction.equals(m.direction(context.topology())))
validMovesfound.add(m);
// If only one valid move found, apply it to the game.
if (validMovesfound.size() == 1)
{
if (moveChecks(app, validMovesfound.get(0)))
app.manager().ref().applyHumanMoveToGame(app.manager(), validMovesfound.get(0));
}
else
{
if (validMovesfound.size() == 0)
app.setVolatileMessage("No valid moves found for Direction " + direction.name());
else
app.setVolatileMessage("Too many valid moves found for Direction " + direction.name());
EventQueue.invokeLater(() ->
{
app.manager().getPlayerInterface().repaint();
});
}
}
//-------------------------------------------------------------------------
/**
* Checks if any of the legal moves are duplicates or not decisions.
*/
public static void checkMoveWarnings(final PlayerApp app)
{
final Context context = app.contextSnapshot().getContext(app);
final Moves legal = context.moves(context);
for (int i = 0; i < legal.moves().size(); i++)
{
final Move m1 = legal.moves().get(i);
if (!context.game().isSimulationMoveGame())
{
// Check if any moves are not decisions.
if (!m1.isDecision())
app.manager().getPlayerInterface().addTextToStatusPanel("WARNING: Move " + m1.getActionsWithConsequences(context) + " was not a decision move. If you see this in an official Ludii game, please report it to us.\n");
// Check if any moves have more than one decision.
int decisionCounter = 0;
for (final Action a : m1.actions())
if (a.isDecision())
decisionCounter++;
if (decisionCounter > 1)
app.manager().getPlayerInterface().addTextToStatusPanel("WARNING: Move " + m1.getActionsWithConsequences(context) + " has multiple decision actions. If you see this in an official Ludii game, please report it to us.\n");
// Check if any moves have an illegal mover.
if (m1.mover() <= 0 || m1.mover() > context.game().players().count())
app.manager().getPlayerInterface().addTextToStatusPanel("WARNING: Move " + m1.getActionsWithConsequences(context) + " has an illegal mover (" + m1.mover() + "). If you see this in an official Ludii game, please report it to us.\n");
// Check if more than one pass move.
int passMoveCounter = 0;
if (m1.isPass())
passMoveCounter++;
if (passMoveCounter > 1)
app.manager().getPlayerInterface().addTextToStatusPanel("WARNING: Multiple Pass moves detected in the legal moves.\n");
// Check if more than one swap move.
int swapMoveCounter = 0;
if (m1.isSwap())
swapMoveCounter++;
if (swapMoveCounter > 1)
app.manager().getPlayerInterface().addTextToStatusPanel("WARNING: Multiple Swap moves detected in the legal moves.\n");
}
}
}
//-------------------------------------------------------------------------
/**
* Checks that need to be made before any code specific to moves is performed.
*/
public static boolean moveChecks(final PlayerApp app, final Move move)
{
final Context context = app.manager().ref().context();
if (!move.isAlwaysGUILegal() && !context.model().verifyMoveLegal(context, move))
{
System.err.println("Selected illegal move: " + move.getActionsWithConsequences(context));
app.addTextToStatusPanel("Selected illegal move: " + move.getActionsWithConsequences(context) + "\n");
return false;
}
return true;
}
//-------------------------------------------------------------------------
/**
* Returns the component associated with the to position of the last move.
*/
public static Component getLastMovedPiece(final PlayerApp app)
{
final Context context = app.manager().ref().context();
final Move lastMove = context.trial().lastMove();
if (lastMove != null)
{
try
{
final int containerId = ContainerUtil.getContainerId(context, lastMove.getToLocation().site(), lastMove.getToLocation().siteType());
final int what = context.containerState(containerId).what(lastMove.getToLocation().site(), lastMove.getToLocation().siteType());
// TODO update exhib rules so that you can only drag to correct site on shared hand.s
if (containerId == 3)
return null;
if (context.trial().numberRealMoves() <= 0 || what == 0)
return null;
final Component lastMoveComponent = context.game().equipment().components()[what];
return lastMoveComponent;
}
catch (final Exception e)
{
return null;
}
}
return null;
}
//-------------------------------------------------------------------------
}
| 21,478 | 31.202399 | 237 |
java
|
Ludii
|
Ludii-master/Player/src/app/move/MoveUtil.java
|
package app.move;
import java.util.ArrayList;
import java.util.List;
import app.PlayerApp;
import game.types.play.ModeType;
import other.action.Action;
import other.context.Context;
import other.move.Move;
public class MoveUtil
{
//-------------------------------------------------------------------------
/**
* Gets the action string for a specified Action object.
*/
public static String getActionFormat(final Action action, final Context context, final boolean shortMoveFormat, final boolean useCoords)
{
if (shortMoveFormat)
return action.toTurnFormat(context.currentInstanceContext(), useCoords);
else
return action.toMoveFormat(context.currentInstanceContext(), useCoords);
}
//-------------------------------------------------------------------------
public static String getMoveFormat(final PlayerApp app, final Move move, final Context context)
{
final MoveFormat settingMoveFormat = app.settingsPlayer().moveFormat();
final boolean useCoords = app.settingsPlayer().isMoveCoord();
// Full move format
if (settingMoveFormat.equals(MoveFormat.Full))
{
final List<Action> actionsToPrint = new ArrayList<>(move.getActionsWithConsequences(context));
final StringBuilder completeActionLastMove = new StringBuilder();
for (final Action a : actionsToPrint)
{
if (completeActionLastMove.length() > 0)
completeActionLastMove.append(", ");
completeActionLastMove.append(a.toMoveFormat(context.currentInstanceContext(), useCoords));
}
if (actionsToPrint.size() > 1)
{
completeActionLastMove.insert(0, '[');
completeActionLastMove.append(']');
}
return completeActionLastMove.toString();
}
// Default/Short move format
else
{
final boolean shortMoveFormat = settingMoveFormat.equals(MoveFormat.Short);
if (context.game().mode().mode() == ModeType.Simultaneous)
{
String moveToPrint = "";
for (final Action action : move.actions())
if (action.isDecision())
moveToPrint += getActionFormat(action, context, shortMoveFormat, useCoords) + ", ";
if (moveToPrint.length() > 0)
return moveToPrint.substring(0, moveToPrint.length() - 2);
return ".\n";
}
else if (context.game().mode().mode() == ModeType.Simulation)
{
String moveToPrint = "";
for (final Action action : move.actions())
moveToPrint += getActionFormat(action, context, shortMoveFormat, useCoords) + ", ";
if (moveToPrint.length() > 0)
return moveToPrint.substring(0, moveToPrint.length() - 2);
return ".\n";
}
else
{
for (final Action action : move.actions())
if (action.isDecision())
return getActionFormat(action, context, shortMoveFormat, useCoords);
}
return ".\n";
}
}
//-------------------------------------------------------------------------
}
| 2,846 | 28.05102 | 137 |
java
|
Ludii
|
Ludii-master/Player/src/app/move/MoveVisuals.java
|
package app.move;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import app.PlayerApp;
import game.Game;
import game.rules.end.EndRule;
import game.rules.end.If;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import main.Constants;
import main.collections.FVector;
import main.collections.FastArrayList;
import other.AI;
import other.AI.AIVisualisationData;
import other.context.Context;
import other.location.Location;
import other.move.Move;
import util.ArrowUtil;
import util.ContainerUtil;
import util.HiddenUtil;
/**
* Functions that deal with specific visualisations of moves
*
* @author Matthew.Stephenson
*/
public class MoveVisuals
{
//-------------------------------------------------------------------------
/**
* Draw the last move that was performed.
*/
public static void drawLastMove(final PlayerApp app, final Graphics2D g2d, final Context context, final Rectangle passLocation, final Rectangle otherLocation)
{
final Move lastMove = context.currentInstanceContext().trial().lastMove();
drawMove(app, g2d, context, passLocation, otherLocation, lastMove, new Color(1.f, 1.f, 0.f, 0.5f));
}
//-------------------------------------------------------------------------
/**
* Draw all possible moves as a set of arrows. Used for tutorial visualisation.
*/
public static void drawTutorialVisualisatonArrows(final PlayerApp app, final Graphics2D g2d, final Context context, final Rectangle passLocation, final Rectangle otherLocation)
{
final Game game = context.game();
for (final Move legalMove: game.moves(context).moves())
for (final Move tutorialVisualisationMove: app.settingsPlayer().tutorialVisualisationMoves())
if (tutorialVisualisationMove.getMoveWithConsequences(context).equals(legalMove.getMoveWithConsequences(context)))
MoveVisuals.drawMove(app, g2d, context, passLocation, otherLocation, legalMove, new Color(1.f, 0.f, 0.f, 1.f));
}
//-------------------------------------------------------------------------
/**
* Draw the AI distribution.
*/
public static void drawAIDistribution(final PlayerApp app, final Graphics2D g2d, final Context context, final Rectangle passLocation, final Rectangle otherLocation)
{
if (!context.trial().over())
{
if (app.manager().liveAIs() == null)
return;
for (final AI visualisationAI : app.manager().liveAIs())
{
if (visualisationAI == null)
continue;
final AIVisualisationData visData = visualisationAI.aiVisualisationData();
if (visData != null)
{
final FVector aiDistribution = visData.searchEffort();
final FVector valueEstimates = visData.valueEstimates();
final FastArrayList<Move> moves = visData.moves();
final float maxVal = aiDistribution.max();
for (int i = 0; i < aiDistribution.dim(); ++i)
{
final float val = aiDistribution.get(i);
float probRatio = 0.05f + ((0.95f * val) / maxVal);
if (probRatio > 1)
probRatio = 1;
if (probRatio < -1)
probRatio = -1;
final Move move = moves.get(i);
final int from = move.from();
final int to = move.to();
final SiteType fromType = move.fromType();
final SiteType toType = move.toType();
final int fromContainerIdx = ContainerUtil.getContainerId(context, from, fromType);
final int toContainerIdx = ContainerUtil.getContainerId(context, to, toType);
if (from != to)
{
final Point2D fromPosnWorld = app.bridge().getContainerStyle(fromContainerIdx)
.drawnGraphElement(from, fromType).centroid();
final Point2D ToPosnWorld = app.bridge().getContainerStyle(toContainerIdx)
.drawnGraphElement(to, toType).centroid();
final Point fromPosnScreen = app.bridge().getContainerStyle(fromContainerIdx).screenPosn(fromPosnWorld);
final Point toPosnScreen = app.bridge().getContainerStyle(toContainerIdx).screenPosn(ToPosnWorld);
final int fromX = fromPosnScreen.x;
final int fromY = fromPosnScreen.y;
final int toX = toPosnScreen.x;
final int toY = toPosnScreen.y;
final int maxRadius = Math.max(app.bridge().getContainerStyle(fromContainerIdx).cellRadiusPixels(), app.bridge().getContainerStyle(toContainerIdx).cellRadiusPixels());
final int minRadius = maxRadius / 4;
final int arrowWidth = Math.max((int) ((minRadius + probRatio * (maxRadius - minRadius)) / 2.5), 1);
if (valueEstimates != null)
{
// interpolate between red (losing) and blue (winning)
g2d.setColor(new Color(0.5f - 0.5f * valueEstimates.get(i), 0.f,
0.5f + 0.5f * valueEstimates.get(i), 0.5f + 0.2f * probRatio * probRatio));
}
else
{
// just use red
g2d.setColor(new Color(1.f, 0.f, 0.f, 0.5f + 0.2f * probRatio * probRatio));
}
if (move.isOrientedMove())
{
// draw arrow with arrow head
ArrowUtil.drawArrow(g2d, fromX, fromY, toX, toY, arrowWidth, (Math.max(arrowWidth, 3)),
(int) (1.75 * (Math.max(arrowWidth, 5))));
}
else
{
// draw arrow with no head
ArrowUtil.drawArrow(g2d, fromX, fromY, toX, toY, arrowWidth, 0, 0);
}
}
else if (to != Constants.UNDEFINED)
{
final int maxRadius = app.bridge().getContainerStyle(toContainerIdx).cellRadiusPixels();
final int minRadius = maxRadius / 4;
final Point2D ToPosnWorld = app.bridge().getContainerStyle(toContainerIdx)
.drawnGraphElement(to, toType).centroid();
final Point toPosnScreen = app.bridge().getContainerStyle(toContainerIdx).screenPosn(ToPosnWorld);
final int midX = toPosnScreen.x;
final int midY = toPosnScreen.y;
final int radius = (int) (minRadius + probRatio * (maxRadius - minRadius));
if (valueEstimates != null)
{
// interpolate between red (losing) and blue (winning)
g2d.setColor(new Color(0.5f - 0.5f * valueEstimates.get(i), 0.f,
0.5f + 0.5f * valueEstimates.get(i), 0.5f + 0.2f * probRatio));
}
else
{
// just use red
g2d.setColor(new Color(1.f, 0.f, 0.f, 0.5f + 0.2f * probRatio));
}
g2d.fillOval(midX - radius, midY - radius, 2 * radius, 2 * radius);
}
else
{
// no positions
if (move.isPass() || move.isSwap() || move.isOtherMove() || move.containsNextInstance())
{
Rectangle position = null;
if (move.isPass() || move.containsNextInstance())
position = passLocation;
else
position = otherLocation;
if (position != null)
{
final int maxRadius = ((Math.min(position.width, position.height))) / 2;
final int minRadius = maxRadius / 4;
final int midX = (int) position.getCenterX();
final int midY = (int) position.getCenterY();
final int radius = (int) (minRadius + probRatio * (maxRadius - minRadius));
if (valueEstimates != null)
{
// Interpolate between red (losing) and blue (winning)
g2d.setColor(new Color(0.5f - 0.5f * valueEstimates.get(i), 0.f,
0.5f + 0.5f * valueEstimates.get(i), 0.5f + 0.2f * probRatio));
}
else
{
// Just use red
g2d.setColor(new Color(1.f, 0.f, 0.f, 0.5f + 0.2f * probRatio));
}
g2d.fillOval(midX - radius, midY - radius, 2 * radius, 2 * radius);
}
}
}
}
}
}
}
}
//-------------------------------------------------------------------------
/**
* Draws moves that would lead to a repeated state (Green = legal, Red = illegal).
*/
public static void drawRepeatedStateMove(final PlayerApp app, final Graphics2D g2d, final Context context, final Rectangle passLocation, final Rectangle otherLocation)
{
final Moves legal = context.moves(context);
// Moves that can be done, but lead to a repeated state (Green)
final ArrayList<Move> movesThatLeadToRepeatedStates = new ArrayList<>();
for (final Move m : legal.moves())
{
final Context newContext = new Context(context);
newContext.game().apply(newContext, m);
if (app.manager().settingsManager().storedGameStatesForVisuals().contains(Long.valueOf(newContext.state().stateHash())))
movesThatLeadToRepeatedStates.add(m);
}
for (final Move m : movesThatLeadToRepeatedStates)
drawMove(app, g2d, context, passLocation, otherLocation, m, new Color(0.f, 1.f, 0.f, 0.5f));
// Moves that cannot be done, because they lead to a repeated state (Red)
for (final Move m: app.manager().settingsManager().movesAllowedWithRepetition())
if (!legal.moves().contains(m))
drawMove(app, g2d, context, passLocation, otherLocation, m, new Color(1.f, 0.f, 0.f, 0.5f));
}
//-------------------------------------------------------------------------
/**
* Draws ending move when one was just made.
*/
public static void drawEndingMove(final PlayerApp app, final Graphics2D g2d, final Context context)
{
final Context copyContext = new Context(context);
copyContext.state().setMover(context.state().prev());
copyContext.state().setNext(context.state().mover());
for (final EndRule endRule : context.game().endRules().endRules())
{
if (endRule instanceof If)
{
if (((If) endRule).result() != null && ((If) endRule).result().result() != null)
{
final List<Location> endingLocations = ((If) endRule).endCondition().satisfyingSites(copyContext);
for (final Location location : endingLocations)
drawEndingMoveLocation(app, g2d, context, location);
if (endingLocations.size() > 0)
break;
}
}
}
}
//-------------------------------------------------------------------------
/**
* Draws a marker for representing an ending move at a given location, for a given result.
*/
private static void drawEndingMoveLocation(final PlayerApp app, final Graphics2D g2d, final Context context, final Location location)
{
final int lastMover = context.trial().getMove(context.trial().numMoves()-1).mover();
Color colour = null;
if (!context.trial().over())
{
if (context.active(lastMover))
colour = new Color(1.0f, 0.7f, 0.f, 0.7f);
else if (context.computeNextDrawRank() > context.trial().ranking()[lastMover])
colour = new Color(0.f, 1.f, 0.f, 0.7f);
else if (context.computeNextDrawRank() < context.trial().ranking()[lastMover])
colour = new Color(1.f, 0.f, 0.f, 0.7f);
}
else
{
if (context.winners().contains(lastMover))
colour = new Color(0.f, 1.f, 0.f, 0.7f);
else
colour = new Color(1.f, 0.f, 0.f, 0.7f);
}
final int site = location.site();
final SiteType type = location.siteType();
final int containerIdx = ContainerUtil.getContainerId(context, site, type);
final Point2D ToPosnWorld = app.bridge().getContainerStyle(containerIdx).drawnGraphElement(site, type).centroid();
final Point toPosnScreen = app.bridge().getContainerStyle(containerIdx).screenPosn(ToPosnWorld);
final int midX = toPosnScreen.x;
final int midY = toPosnScreen.y;
g2d.setColor(Color.BLACK);
int radius = (int) (app.bridge().getContainerStyle(containerIdx).cellRadiusPixels()/2 * 1.1) + 2;
g2d.fillOval(midX - radius, midY - radius, 2 * radius, 2 * radius);
g2d.setColor(colour);
radius = app.bridge().getContainerStyle(containerIdx).cellRadiusPixels()/2;
g2d.fillOval(midX - radius, midY - radius, 2 * radius, 2 * radius);
}
//-------------------------------------------------------------------------
/**
* Draw the specified move.
* Generic functionality, called by the other MoveVisuals functions.
*/
private static void drawMove(final PlayerApp app, final Graphics2D g2d, final Context context, final Rectangle passLocation, final Rectangle otherLocation, final Move move, final Color colour)
{
final int currentMover = context.state().mover();
g2d.setColor(colour);
if (move != null)
{
final int from = move.from();
final int to = move.to();
final int fromLevel = move.levelFrom();
final int toLevel = move.levelTo();
final SiteType fromType = move.fromType();
final SiteType toType = move.toType();
final int fromContainerIdx = ContainerUtil.getContainerId(context, from, fromType);
final int toContainerIdx = ContainerUtil.getContainerId(context, to, toType);
if (from != to)
{
// Move with two locations.
final Point2D fromPosnWorld = app.bridge().getContainerStyle(fromContainerIdx)
.drawnGraphElement(from, fromType).centroid();
final Point2D ToPosnWorld = app.bridge().getContainerStyle(toContainerIdx).drawnGraphElement(to, toType)
.centroid();
final Point fromPosnScreen = app.bridge().getContainerStyle(fromContainerIdx).screenPosn(fromPosnWorld);
final Point toPosnScreen = app.bridge().getContainerStyle(toContainerIdx).screenPosn(ToPosnWorld);
final int fromX = fromPosnScreen.x;
final int fromY = fromPosnScreen.y;
final int toX = toPosnScreen.x;
final int toY = toPosnScreen.y;
final int maxRadius = Math.max(app.bridge().getContainerStyle(fromContainerIdx).cellRadiusPixels(),
app.bridge().getContainerStyle(toContainerIdx).cellRadiusPixels());
final int arrowWidth = Math.max((int) (maxRadius / 3.5), 1);
boolean arrowHidden = false;
if (HiddenUtil.siteHiddenBitsetInteger(context, context.state().containerStates()[fromContainerIdx], from, fromLevel, currentMover, fromType) > 0
|| HiddenUtil.siteHiddenBitsetInteger(context, context.state().containerStates()[toContainerIdx], to, toLevel, currentMover, toType) > 0)
arrowHidden = true;
if (!arrowHidden)
{
if (move.isOrientedMove())
ArrowUtil.drawArrow(g2d, fromX, fromY, toX, toY, arrowWidth, (int) (1.75 * (Math.max(arrowWidth, 3))),
(int) (2.75 * (Math.max(arrowWidth, 5))));
else
ArrowUtil.drawArrow(g2d, fromX, fromY, toX, toY, arrowWidth, 0, 0);
}
}
else if (to != Constants.UNDEFINED)
{
// Move with just one location.
final Point2D ToPosnWorld = app.bridge().getContainerStyle(toContainerIdx).drawnGraphElement(to, toType)
.centroid();
final Point toPosnScreen = app.bridge().getContainerStyle(toContainerIdx).screenPosn(ToPosnWorld);
final int midX = toPosnScreen.x;
final int midY = toPosnScreen.y;
final int radius = app.bridge().getContainerStyle(toContainerIdx).cellRadiusPixels()/2;
g2d.fillOval(midX - radius, midY - radius, 2 * radius, 2 * radius);
}
else
{
// Move with no location.
Rectangle position = null;
if (move.isPass() || move.containsNextInstance())
position = passLocation;
else if (move.isOtherMove())
position = otherLocation;
if (position != null)
g2d.fillOval(position.x, position.y, position.width, position.height);
}
}
}
//-------------------------------------------------------------------------
}
| 15,171 | 35.825243 | 193 |
java
|
Ludii
|
Ludii-master/Player/src/app/move/animation/AnimationParameters.java
|
package app.move.animation;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
/**
* Parameters needed for animating a move.
*
* @author Matthew.Stephenson
*/
public class AnimationParameters
{
public final AnimationType animationType;
public final List<BufferedImage> pieceImages;
public final List<Point> fromLocations;
public final List<Point> toLocations;
public final long animationTimeMs;
public AnimationParameters()
{
animationType = AnimationType.NONE;
pieceImages = new ArrayList<>();
fromLocations = new ArrayList<>();
toLocations = new ArrayList<>();
animationTimeMs = 0;
}
public AnimationParameters(final AnimationType animationType, final List<BufferedImage> pieceImages, final List<Point> fromLocations, final List<Point> toLocations, final long animationWaitTime)
{
this.animationType = animationType;
this.pieceImages = pieceImages;
this.fromLocations = fromLocations;
this.toLocations = toLocations;
animationTimeMs = animationWaitTime;
}
}
| 1,063 | 26.282051 | 195 |
java
|
Ludii
|
Ludii-master/Player/src/app/move/animation/AnimationType.java
|
package app.move.animation;
/**
* Different types of animation.
*
* @author Matthew.Stephenson
*/
public enum AnimationType
{
// No animation.
NONE,
// Move between two locations.
DRAG,
// Pulse at a specified location.
PULSE
}
| 245 | 11.947368 | 34 |
java
|
Ludii
|
Ludii-master/Player/src/app/move/animation/MoveAnimation.java
|
package app.move.animation;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import app.PlayerApp;
import app.utils.BufferedImageUtil;
import app.utils.DrawnImageInfo;
import game.Game;
import game.equipment.container.Container;
import game.rules.play.moves.BaseMoves;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import metadata.graphics.util.PieceStackType;
import metadata.graphics.util.StackPropertyType;
import other.action.Action;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.move.Move;
import other.state.State;
import other.state.container.ContainerState;
import other.topology.TopologyElement;
import util.ContainerUtil;
import util.HiddenUtil;
import util.ImageInfo;
import util.StackVisuals;
/**
* Functions that deal with animating moves.
*
* @author Matthew.Stephenson
*/
public class MoveAnimation
{
/** Number of frames that an movement animation lasts for. */
public static final boolean SLOW_IN_SLOW_OUT = true;
/** Number of frames that an movement animation lasts for. */
public static int MOVE_PIECE_FRAMES = 30;
/** Number of frames that an add/remove animation lasts for. */
public static final int FLASH_LENGTH = 10;
/** Length of an animation frame in milliseconds. */
public static final int ANIMATION_FRAME_LENGTH = 15;
/** Length of time that an animation will last in milliseconds. */
public static final long ANIMATION_WAIT_TIME = ANIMATION_FRAME_LENGTH * (MOVE_PIECE_FRAMES - 1);
//-----------------------------------------------------------------------------
/**
* Store the required animation information about a move to be animated.
*/
public static void saveMoveAnimationDetails(final PlayerApp app, final Move move)
{
final AnimationType animationType = getMoveAnimationType(app, move);
if (!animationType.equals(AnimationType.NONE))
{
try
{
app.settingsPlayer().setDrawingMovingPieceTime(0);
app.bridge().settingsVC().setAnimationMove(move);
app.bridge().settingsVC().setThisFrameIsAnimated(true);
app.settingsPlayer().setAnimationParameters(getMoveAnimationParameters(app, move));
app.settingsPlayer().getAnimationTimer().cancel();
app.settingsPlayer().setAnimationTimer(new Timer());
app.settingsPlayer().getAnimationTimer().scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
app.settingsPlayer().setDrawingMovingPieceTime(app.settingsPlayer().getDrawingMovingPieceTime()+1);
}
}, 0, ANIMATION_FRAME_LENGTH);
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}
//-------------------------------------------------------------------------
/**
* Draw the move animated, based on the previously stored animation details.
*/
public static void moveAnimation(final PlayerApp app, final Graphics2D g2d)
{
final AnimationParameters aimationParameters = app.settingsPlayer().animationParameters();
for (int i = 0; i < aimationParameters.pieceImages.size(); i ++)
{
BufferedImage pieceImage = aimationParameters.pieceImages.get(i);
final int time = app.settingsPlayer().getDrawingMovingPieceTime();
final double transparency = getMoveAnimationTransparency(app, time, aimationParameters.animationType);
if (transparency > 0)
pieceImage = BufferedImageUtil.makeImageTranslucent(pieceImage, transparency);
final Point drawPoint = MoveAnimation.getMoveAnimationPoint(app, aimationParameters.fromLocations.get(i), aimationParameters.toLocations.get(i), time, aimationParameters.animationType);
g2d.drawImage(pieceImage, (int)drawPoint.getX(), (int)drawPoint.getY(), null);
}
}
//-------------------------------------------------------------------------
/**
* Get AnimationParameters of a provided move.
*/
public static AnimationParameters getMoveAnimationParameters(final PlayerApp app, final Move move)
{
final Context context = app.contextSnapshot().getContext(app);
final Location moveFrom = move.getFromLocation();
final Location moveTo = move.getToLocation();
final int containerIdFrom = ContainerUtil.getContainerId(context, moveFrom.site(), moveFrom.siteType());
final int containerIdTo = ContainerUtil.getContainerId(context, moveTo.site(), moveTo.siteType());
final Point2D graphPointStart = app.bridge().getContainerStyle(containerIdFrom).drawnGraphElement(moveFrom.site(), moveFrom.siteType()).centroid();
final Point2D graphEndStart = app.bridge().getContainerStyle(containerIdTo).drawnGraphElement(moveTo.site(), moveTo.siteType()).centroid();
final Point startPoint = app.bridge().getContainerStyle(containerIdFrom).screenPosn(graphPointStart);
final Point endPoint = app.bridge().getContainerStyle(containerIdTo).screenPosn(graphEndStart);
final List<DrawnImageInfo> startDrawnInfo = MoveAnimation.getMovingPieceImages(app, move, moveFrom, startPoint.x, startPoint.y, true);
final List<DrawnImageInfo> endDrawnInfo = MoveAnimation.getMovingPieceImages(app, move, moveFrom, endPoint.x, endPoint.y, true);
final List<BufferedImage> pieceImages = new ArrayList<>();
final List<Point> startPoints = new ArrayList<>();
final List<Point> endPoints = new ArrayList<>();
for (final DrawnImageInfo d : startDrawnInfo)
{
startPoints.add(d.imageInfo().drawPosn());
pieceImages.add(d.pieceImage());
}
for (final DrawnImageInfo d : endDrawnInfo)
{
endPoints.add(d.imageInfo().drawPosn());
}
// Placeholders in case no images/points found
if (startPoints.size() == 0)
startPoints.add(new Point(0,0));
if (endPoints.size() == 0)
endPoints.add(new Point(0,0));
if (pieceImages.size() == 0)
pieceImages.add(new BufferedImage(1,1,1));
return new AnimationParameters
(
MoveAnimation.getMoveAnimationType(app, move),
pieceImages,
startPoints,
endPoints,
MoveAnimation.ANIMATION_WAIT_TIME
);
}
//-------------------------------------------------------------------------
/**
* Get transparency value for a given animationType and time through the animation.
*/
private static double getMoveAnimationTransparency(final PlayerApp app, final int time, final AnimationType animationType)
{
if (animationType.equals(AnimationType.PULSE))
{
// How transparent the animated piece should be.
double currentflashValue = 0.0;
final int flashCycleValue = time
% (MoveAnimation.FLASH_LENGTH * 2);
if (flashCycleValue >= MoveAnimation.FLASH_LENGTH)
{
currentflashValue = 1.0 - (time % (MoveAnimation.FLASH_LENGTH)) / (double) (MoveAnimation.FLASH_LENGTH);
}
else
{
currentflashValue = (time % (MoveAnimation.FLASH_LENGTH)) / (double) (MoveAnimation.FLASH_LENGTH);
}
return 1.0 - currentflashValue;
}
return 0.0;
}
//-------------------------------------------------------------------------
/**
* Draw an animation for a move between two locations, at a given time frame.
*/
private static Point getMoveAnimationPoint(final PlayerApp app, final Point startPoint, final Point endPoint, final int time, final AnimationType animationType)
{
try
{
final Location moveFrom = app.bridge().settingsVC().getAnimationMove().getFromLocation();
// Piece is moving from one location to another.
if (animationType.equals(AnimationType.DRAG))
{
final Point2D.Double pointOnTimeLine = new Point2D.Double();
if (MoveAnimation.SLOW_IN_SLOW_OUT)
{
double multiplyFactor = (time/(double)(MoveAnimation.MOVE_PIECE_FRAMES));
multiplyFactor = (Math.cos(multiplyFactor*Math.PI + Math.PI) + 1) / 2;
pointOnTimeLine.x = (startPoint.x + ((endPoint.x - startPoint.x) * multiplyFactor));
pointOnTimeLine.y = (startPoint.y + ((endPoint.y - startPoint.y) * multiplyFactor));
}
else
{
final double multiplyFactor = (time/(double)(MoveAnimation.MOVE_PIECE_FRAMES));
pointOnTimeLine.x = (startPoint.x + ((endPoint.x - startPoint.x) * multiplyFactor));
pointOnTimeLine.y = (startPoint.y + ((endPoint.y - startPoint.y) * multiplyFactor));
}
app.repaintComponentBetweenPoints(app.contextSnapshot().getContext(app), moveFrom, startPoint, endPoint);
return new Point((int)pointOnTimeLine.x, (int) pointOnTimeLine.y);
}
// Piece is being added/removed/changed at a single site.
else if (animationType.equals(AnimationType.PULSE))
{
app.repaintComponentBetweenPoints(app.contextSnapshot().getContext(app), moveFrom, startPoint, endPoint);
return new Point(startPoint.x, startPoint.y);
}
}
catch (final Exception e)
{
// If something goes wrong, cancel the animation.
app.settingsPlayer().setDrawingMovingPieceTime(MoveAnimation.MOVE_PIECE_FRAMES);
}
return null;
}
//-------------------------------------------------------------------------
/**
* Get the type of animation for the move.
*/
public static AnimationType getMoveAnimationType(final PlayerApp app, final Move move)
{
final Context context = app.contextSnapshot().getContext(app);
final Game game = context.game();
if (move == null)
return AnimationType.NONE;
if (app.bridge().settingsVC().noAnimation())
return AnimationType.NONE;
if (game.isDeductionPuzzle())
return AnimationType.NONE;
if (game.hasLargePiece())
return AnimationType.NONE;
if (move.from() == -1)
return AnimationType.NONE;
if (move.to() == -1)
return AnimationType.NONE;
// if (app.settingsPlayer().animationType().equals(AnimationVisualsType.All) && move.actionType().equals(ActionType.Select))
// return AnimationType.NONE;
if (!move.getFromLocation().equals(move.getToLocation()))
return AnimationType.DRAG;
if (move.getFromLocation().equals(move.getToLocation()))
return AnimationType.PULSE;
return AnimationType.NONE; // manager.settingsManager().showAnimation();
}
//-------------------------------------------------------------------------
/**
* Reset all necessary animation variables to their defaults.
*/
public static void resetAnimationValues(final PlayerApp app)
{
app.settingsPlayer().setDrawingMovingPieceTime(MOVE_PIECE_FRAMES);
app.bridge().settingsVC().setAnimationMove(null);
app.bridge().settingsVC().setThisFrameIsAnimated(false);
app.settingsPlayer().getAnimationTimer().cancel();
app.settingsPlayer().setAnimationParameters(new AnimationParameters());
}
//-------------------------------------------------------------------------
/**
* Draw the piece being moved.
*/
public static List<DrawnImageInfo> getMovingPieceImages(final PlayerApp app, final Move move, final Location selectedLocation, final int x, final int y, final boolean drawingAnimation)
{
final List<DrawnImageInfo> allMovingPieceImages = new ArrayList<>();
final Context context = app.contextSnapshot().getContext(app);
final Moves legal = context.game().moves(context);
if (move != null)
{
// Replace legal moves with the specific move being done.
final Moves moves = new BaseMoves(null);
moves.moves().add(move);
}
// If all moves from this location involve the same level range, then use that level range.
final int[] levelMinMax = StackVisuals.getLevelMinAndMax(legal, selectedLocation);
for (int i = 0; i < context.numContainers(); i++)
{
final Container container = context.equipment().containers()[i];
final int containerIndex = container.index();
final List<TopologyElement> graphElements = app.bridge().getContainerStyle(containerIndex).drawnGraphElements();
final State state = app.contextSnapshot().getContext(app).state();
final ContainerState cs = state.containerStates()[i];
for (final TopologyElement graphElement : graphElements)
{
if
(
graphElement.index() == selectedLocation.site()
&&
graphElement.elementType() == selectedLocation.siteType()
)
{
int lowestSelectedLevel = -1;
for (int level = levelMinMax[0]; level <= levelMinMax[1]; level++)
{
final int localState = cs.state(selectedLocation.site(), level, selectedLocation.siteType());
final int value = cs.value(selectedLocation.site(), level, selectedLocation.siteType());
final PieceStackType componentStackType = PieceStackType.getTypeFromValue((int) context.metadata().graphics().stackMetadata(context, container, selectedLocation.site(), selectedLocation.siteType(), localState, value, StackPropertyType.Type));
// get the what of the component at the selected location
int what = cs.what(graphElement.index(), level, graphElement.elementType());
// If adding a piece at the site, get the what of the move (first action that matches selected location) instead.
if (what == 0)
{
if (move != null)
what = move.what();
for (final Move m : legal.moves())
{
if (m.getFromLocation().equals(selectedLocation))
{
for (final Action a : m.actions())
{
final Location actionLocationA = new FullLocation(a.from(), a.levelFrom(),
a.fromType());
final Location actionLocationB = new FullLocation(a.to(), a.levelTo(),
a.toType());
final Location testingLocation = new FullLocation(selectedLocation.site(), level, selectedLocation.siteType());
if (actionLocationA.equals(testingLocation) && actionLocationB.equals(testingLocation))
{
what = a.what();
break;
}
}
}
if (what != 0)
break;
}
}
// If a piece was found
if (what > 0)
{
app.settingsPlayer().setDragComponent
(
app.contextSnapshot().getContext(app).equipment().components()[what]
);
try
{
if (lowestSelectedLevel == -1)
lowestSelectedLevel = level;
if (drawingAnimation)
lowestSelectedLevel = 0;
BufferedImage pieceImage = null;
final int cellSize = app.bridge().getContainerStyle(0).cellRadiusPixels(); // This line uses the size of the piece where it current is when drawing it
final int hiddenValue = HiddenUtil.siteHiddenBitsetInteger(context, cs, graphElement.index(), level, context.state().mover(), graphElement.elementType());
int imageSize = cellSize*2;
try
{
imageSize = app.graphicsCache().getComponentImageSize(containerIndex, app.settingsPlayer().dragComponent().index(), cs.who(graphElement.index(), graphElement.elementType()), localState, cs.value(graphElement.index(), graphElement.elementType()), hiddenValue, cs.rotation(graphElement.index(), graphElement.elementType()));
}
catch (final Exception e)
{
// Component image doesn't exist yet.
}
if (app.settingsPlayer().dragComponent().isLargePiece())
{
// If the local state of the from is different from that of the move, the piece can be rotated.
for (final Move m : legal.moves())
if (cs.state(graphElement.index(), graphElement.elementType()) != m.state())
app.setVolatileMessage("You can rotate this piece by pressing 'r'");
// If we have rotated the piece all the way around to its starting walk.
if (cs.state(graphElement.index(), graphElement.elementType()) + app.settingsPlayer().currentWalkExtra() >= app.settingsPlayer().dragComponent().walk().length * (app.contextSnapshot().getContext(app).board().topology().supportedDirections(SiteType.Cell).size() / 2))
app.settingsPlayer().setCurrentWalkExtra(-cs.state(graphElement.index(), graphElement.elementType()));
pieceImage = app.graphicsCache().getComponentImage(app.bridge(), 0, app.settingsPlayer().dragComponent(), cs.who(graphElement.index(), graphElement.elementType()), cs.state(graphElement.index(), graphElement.elementType()) + app.settingsPlayer().currentWalkExtra(), cs.value(graphElement.index(), graphElement.elementType()), graphElement.index(), 0, graphElement.elementType(), cellSize*2, app.contextSnapshot().getContext(app), hiddenValue, cs.rotation(graphElement.index(), graphElement.elementType()), true);
app.settingsPlayer().setDragComponentState(cs.state(graphElement.index(), graphElement.elementType()) + app.settingsPlayer().currentWalkExtra());
}
else
{
pieceImage = app.graphicsCache().getComponentImage(app.bridge(), i, app.settingsPlayer().dragComponent(), cs.who(graphElement.index(), graphElement.elementType()), cs.state(graphElement.index(), graphElement.elementType()), cs.value(graphElement.index(), graphElement.elementType()), graphElement.index(), 0 , graphElement.elementType(), imageSize, app.contextSnapshot().getContext(app), hiddenValue, cs.rotation(graphElement.index(), graphElement.elementType()), true);
}
final Point2D.Double dragPosition = new Point2D.Double(x - (pieceImage.getWidth() / 2), y - (pieceImage.getHeight() / 2));
final int stackSize = cs.sizeStack(selectedLocation.site(), selectedLocation.siteType());
final Point2D.Double offsetDistance = StackVisuals.calculateStackOffset(app.bridge(), context, container, componentStackType, cellSize, level-lowestSelectedLevel, selectedLocation.site(), selectedLocation.siteType(), stackSize, localState, value);
allMovingPieceImages.add(new DrawnImageInfo(pieceImage, new ImageInfo(new Point((int)(dragPosition.x + offsetDistance.x), (int)(dragPosition.y + offsetDistance.y)), graphElement.index(), level, graphElement.elementType())));
if (!context.currentInstanceContext().game().isStacking())
return allMovingPieceImages;
}
catch (final NullPointerException e)
{
e.printStackTrace();
}
}
else
{
break;
}
}
return allMovingPieceImages;
}
}
}
return allMovingPieceImages;
}
//-------------------------------------------------------------------------
}
| 18,438 | 38.48394 | 521 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/AIPlayer.java
|
package app.utils;
import java.util.ArrayList;
import java.util.List;
import app.PlayerApp;
import game.Game;
import main.grammar.Report;
import metrics.Evaluation;
import metrics.Metric;
import supplementary.experiments.EvalGamesThread;
/**
* Utility to load AI players and launch the Evaluation dialog for the desktop player.
*
* @author matthew and cambolbro
*/
public class AIPlayer
{
//-------------------------------------------------------------------------
/**
* Evaluates a single specified game and option combination, based on the AI parameters passed in.
*/
public static void AIEvalution(final PlayerApp app, final Report report, final int numberTrials, final int maxTurns, final double thinkTime, final String AIName, final List<Metric> metricsToEvaluate, final ArrayList<Double> weights, final boolean useDatabaseGames)
{
final Evaluation evaluation = new Evaluation();
final Game game = app.manager().ref().context().game();
final List<String> options = app.manager().settingsManager().userSelections().selectedOptionStrings();
if (options.size() > 0)
app.addTextToAnalysisPanel("Analysing " + game.name() + " " + options + "\n\n");
else
app.addTextToAnalysisPanel("Analysing " + game.name() + "\n\n");
final EvalGamesThread evalThread = EvalGamesThread.construct
(
evaluation, report, game, options, AIName,
numberTrials, thinkTime, maxTurns,
metricsToEvaluate, weights, useDatabaseGames
);
evalThread.setDaemon(true);
evalThread.start();
}
//-------------------------------------------------------------------------
}
| 1,648 | 31.98 | 265 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/AnimationVisualsType.java
|
package app.utils;
/**
* Different ways that moves can be animated
*
* @author Matthew.Stephenson
*/
public enum AnimationVisualsType
{
None, // No piece animation.
Single, // Single action animation.
All; // All action animation.
//-------------------------------------------------------------------------
/**
* Returns the AnimationVisualsType who's value matches the provided name.
*/
public static AnimationVisualsType getAnimationVisualsType(final String name)
{
for (final AnimationVisualsType animationVisualsType : AnimationVisualsType.values())
if (animationVisualsType.name().equals(name))
return animationVisualsType;
return None;
}
//-------------------------------------------------------------------------
}
| 809 | 24.3125 | 93 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/BufferedImageUtil.java
|
package app.utils;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import app.PlayerApp;
/**
* Functions for helping out with image manipulation and rendering.
*
* @author Matthew Stephenson
*/
public class BufferedImageUtil
{
//-------------------------------------------------------------------------
/**
* Makes a buffered image translucent.
*/
public static BufferedImage makeImageTranslucent(final BufferedImage source, final double alpha)
{
if (source == null)
return null;
final BufferedImage target = new BufferedImage(source.getWidth(),
source.getHeight(), java.awt.Transparency.TRANSLUCENT);
// Get the images graphics
final Graphics2D g = target.createGraphics();
// Set the Graphics composite to Alpha
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
(float) alpha));
// Draw the image into the prepared receiver image
g.drawImage(source, null, 0, 0);
// let go of all system resources in this Graphics
g.dispose();
// Return the image
return target;
}
//-------------------------------------------------------------------------
/**
* Flips a buffered image vertically.
*/
public static BufferedImage createFlippedVertically(final BufferedImage image)
{
if (image == null)
return null;
final AffineTransform at = new AffineTransform();
at.concatenate(AffineTransform.getScaleInstance(1, -1));
at.concatenate(AffineTransform.getTranslateInstance(0, -image.getHeight()));
return createTransformed(image, at);
}
//-------------------------------------------------------------------------
/**
* Flips a buffered image horizontally.
*/
public static BufferedImage createFlippedHorizontally(final BufferedImage image)
{
if (image == null)
return null;
final AffineTransform at = new AffineTransform();
at.concatenate(AffineTransform.getScaleInstance(-1, 1));
at.concatenate(AffineTransform.getTranslateInstance(-image.getWidth(), 0));
return createTransformed(image, at);
}
//-------------------------------------------------------------------------
/**
* Transforms a buffered image.
*/
public static BufferedImage createTransformed(final BufferedImage image, final AffineTransform at)
{
if (image == null)
return null;
final BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = newImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.transform(at);
g.drawImage(image, 0, 0, null);
g.dispose();
return newImage;
}
//-------------------------------------------------------------------------
/**
* Rotates a buffered image.
*/
public static BufferedImage rotateImageByDegrees(final BufferedImage img, final double angle)
{
if (img == null)
return null;
final double rads = Math.toRadians(angle);
final int w = img.getWidth();
final int h = img.getHeight();
final BufferedImage rotated = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2d = rotated.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
final AffineTransform at = new AffineTransform();
at.translate(0, 0);
final int x = w / 2;
final int y = h / 2;
at.rotate(rads, x, y);
g2d.setTransform(at);
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
return rotated;
}
//-------------------------------------------------------------------------
/**
* Resizes a buffered image.
*/
public static BufferedImage resize(final BufferedImage img, final int newW, final int newH)
{
if (img == null)
return null;
int width = newW;
int height = newH;
if (newW < 1)
width = 1;
if (newH < 1)
height = 1;
final Image tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
final BufferedImage dimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
//-------------------------------------------------------------------------
/**
* Sets all pixels of an image to a certain colour (masked pieces).
* Use componentStyle.createPieceImageColourSVG instead when possible.
*/
public static BufferedImage setPixelsToColour(final BufferedImage image, final Color colour)
{
if (image == null)
return null;
for (int y = 0; y < image.getHeight(); ++y)
{
for (int x = 0; x < image.getWidth(); ++x)
{
if(image.getRGB(x,y) != 0x00)
{
image.setRGB(x, y, colour.getRGB());
}
}
}
return image;
}
//-------------------------------------------------------------------------
/**
* Deep copies a buffered image.
*/
public static BufferedImage deepCopy(final BufferedImage image)
{
final ColorModel cm = image.getColorModel();
final boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
final WritableRaster raster = image.copyData(null);
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
//-------------------------------------------------------------------------
/**
* Combines two bufferedImage objects together.
*/
public static BufferedImage joinBufferedImages(final BufferedImage img1, final BufferedImage img2)
{
return joinBufferedImages(img1, img2, 0, 0);
}
//-------------------------------------------------------------------------
/**
* Combines two bufferedImage objects together, with specified offsets.
*/
public static BufferedImage joinBufferedImages(final BufferedImage img1,final BufferedImage img2, final int offsetX, final int offsetY)
{
final int w = Math.max(img1.getWidth(), img2.getWidth());
final int h = Math.max(img1.getHeight(), img2.getHeight());
final BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
final Graphics2D g = combined.createGraphics();
g.drawImage(img1, 0, 0, null);
g.drawImage(img2, offsetX, offsetY, null);
return combined;
}
//-------------------------------------------------------------------------
// /**
// * Returns a bufferedImage of an SVG file.
// */
// public static BufferedImage getImageFromSVGName(final String svgName, final int imageSize)
// {
// final String SVGPath = ImageUtil.getImageFullPath(svgName);
// SVGGraphics2D g2d = new SVGGraphics2D(imageSize, imageSize);
// g2d = new SVGGraphics2D(imageSize, imageSize);
// SVGtoImage.loadFromString
// (
// g2d, SVGPath, imageSize, imageSize, 0, 0,
// Color.BLACK, Color.BLACK, true, 0
// );
// return SVGUtil.createSVGImage(g2d.getSVGDocument(), imageSize, imageSize);
// }
//-------------------------------------------------------------------------
/**
* Determines if a specified point overlaps an image in the graphics cache.
*/
public static boolean pointOverlapsImage(final Point p, final BufferedImage image, final Point imageDrawPosn)
{
try
{
final int imageWidth = image.getWidth();
final int imageHeight = image.getHeight();
final int pixelOnImageX = p.x - imageDrawPosn.x;
final int pixelOnImageY = p.y - imageDrawPosn.y;
if (pixelOnImageX < 0 || pixelOnImageY < 0 || pixelOnImageY > imageHeight || pixelOnImageX > imageWidth)
{
return false;
}
final int pixelClicked = image.getRGB(pixelOnImageX, pixelOnImageY);
if( (pixelClicked>>24) != 0x00 )
{
return true;
}
}
catch (final Exception E)
{
return false;
}
return false;
}
//-------------------------------------------------------------------------
/**
* Draws a String on top of a bufferedImage
*/
public static BufferedImage createImageWithText(final PlayerApp app, final BufferedImage image, final String string)
{
final Graphics2D g2d = image.createGraphics();
g2d.setFont(app.bridge().settingsVC().displayFont());
g2d.setColor(Color.RED);
g2d.drawString(string, image.getWidth()/2, image.getHeight()/2);
return image; // but return the second
}
//-------------------------------------------------------------------------
}
| 8,941 | 29.209459 | 137 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/ContextSnapshot.java
|
package app.utils;
import app.PlayerApp;
import other.context.Context;
import other.context.InformationContext;
/**
* A snapshot of the last recorded context.
* Updated and frozen whenever painting to avoid threading issues.
*
* @author Matthew.Stephenson
*/
public class ContextSnapshot
{
private Context copyOfCurrentContext = null;
//-------------------------------------------------------------------------
/**
* Don't instantiate me.
*/
public ContextSnapshot()
{
// Do Nothing
}
//-------------------------------------------------------------------------
private static int getInformationContextPlayerNumber(final PlayerApp app)
{
final Context context = app.manager().ref().context();
int mover = context.state().mover();
if (context.game().isDeductionPuzzle())
return mover;
if (app.manager().settingsNetwork().getNetworkPlayerNumber() > 0)
{
mover = app.manager().settingsNetwork().getNetworkPlayerNumber();
}
else if (app.settingsPlayer().hideAiMoves())
{
int humansFound = 0;
int humanIndex = 0;
for (int i = 1; i <= context.game().players().count(); i++)
{
if (app.manager().aiSelected()[app.manager().playerToAgent(i)].ai() == null)
{
humansFound++;
humanIndex = i;
}
}
if (humansFound == 1)
mover = humanIndex;
}
return mover;
}
//-------------------------------------------------------------------------
public void setContext(final Context context)
{
copyOfCurrentContext = context;
}
public void setContext(final PlayerApp app)
{
copyOfCurrentContext = new InformationContext(app.manager().ref().context(), getInformationContextPlayerNumber(app));
}
//-------------------------------------------------------------------------
public Context getContext(final PlayerApp app)
{
if (copyOfCurrentContext == null)
setContext(app);
return copyOfCurrentContext;
}
//-------------------------------------------------------------------------
}
| 2,009 | 22.103448 | 119 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/DrawnImageInfo.java
|
package app.utils;
import java.awt.image.BufferedImage;
import util.ImageInfo;
/**
* Object that links a drawn bufferedImage to other useful information about it.
*
* @author Matthew Stephenson
*/
public class DrawnImageInfo
{
private final BufferedImage pieceImage;
private final ImageInfo imageInfo;
//-------------------------------------------------------------------------
public DrawnImageInfo(final BufferedImage pieceImage, final ImageInfo imageInfo)
{
this.pieceImage = pieceImage;
this.imageInfo = imageInfo;
}
//-------------------------------------------------------------------------
public BufferedImage pieceImage()
{
return pieceImage;
}
public ImageInfo imageInfo()
{
return imageInfo;
}
//-------------------------------------------------------------------------
}
| 828 | 19.219512 | 81 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/EnglishSwedishTranslations.java
|
package app.utils;
public enum EnglishSwedishTranslations
{
// Menu Text
MYOGTITLE("Make Your Own Game", "Gor Ditt Eget Spel"), //"Gör Ditt Eget Spel"),
INTRO_A("Ludemes are the elements that make up games.", "Spel består av beståndsdelar som kallas ludemes."),
INTRO_B("Here you can mix and match ludemes to make your own game!", "Här kan du mixa och matcha ludemes och göra ditt eget spel!"),
MAKE_YOUR_GAME("Make Your Game", "Gor Ditt Spel"),
PLAY_YOUR_GAME("Play Your Game", "Spela Ditt Spel"),
HOME("Home", "Home"),
ENGLISH("EN", "EN"),
SWEDISH("SV", "SV"),
CHOOSEBOARD("Choose a board", "Välj ett spelbräde"),
DRAGPIECES("Drag pieces onto the board", "Dra pjäser till brädet"),
MOVEMENT("Piece moves", "Hur man flyttar"),
CAPTURE("How to capture", "Hur man fångar"),
GOAL("How to win", "Hur man vinner"),
// Button Text
START("Start", "Starta"),
RESET("Reset", "Återställ"),
PLAY("Play", "Spela"),
PLAYAGAIN("Play Again", "Spela igen"),
EDIT("Edit Rules", "Redigera regler"),
HUMANVSHUMAN("vs Human", "vs Person"),
HUMANVSAI("vs AI", "vs AI"),
PRINT("Print", "Skriva ut"),
// Goal Options
LINE3("Line of 3", "Tre i rad"),
LINE4("Line of 4", "Fyra i rad"),
ELIMINATE("Eliminate", "Eliminera"),
BLOCK("Block", "Blockera"),
SURROUND("Surround", "Omringa"),
// Move Options
STEP("Step", "Steg"),
SLIDE("Slide", "Glida"),
KNIGHT("Knight", "Riddare"),
ADD("Add", "Tillsätta"),
ANY("Anywhere", "Överallt"),
// Capture Options
REPLACE("Replace", "Ersätta"),
HOP("Hop", "Hoppa"),
FLANK("Flank", "Flankera"),
NEIGHBOR("Neighbor", "Angränsa"),
;
//-------------------------------------------------------------------------
private String english;
private String swedish;
// Change this to use english or swedish words.
private static boolean inEnglish = true;
//--------------------------------------------------------------------------
EnglishSwedishTranslations(final String english, final String swedish)
{
this.english = english;
this.swedish = swedish;
}
//-------------------------------------------------------------------------
public static boolean inEnglish()
{
return inEnglish;
}
public static void setInEnglish(final boolean inEnglish)
{
EnglishSwedishTranslations.inEnglish = inEnglish;
}
@Override
public String toString()
{
return inEnglish ? english : swedish;
}
}
| 2,385 | 25.21978 | 133 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/GUIUtil.java
|
package app.utils;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.List;
import app.views.View;
/**
* Utility functions for the GUI.
*
* @author Matthew Stephenson
*/
public class GUIUtil
{
//-------------------------------------------------------------------------
/**
* Checks if point overlaps the rectangle
*/
public static boolean pointOverlapsRectangle(final Point p, final Rectangle rectangle)
{
return pointOverlapsRectangles(p, new Rectangle[]{rectangle});
}
/**
* Checks if point overlaps any rectangle in the list
*/
public static boolean pointOverlapsRectangles(final Point p, final Rectangle[] rectangleList)
{
final int bufferDistance = 2;
for (final Rectangle r : rectangleList)
if (r != null)
if
(
p.x > r.x - bufferDistance
&&
p.x < r.x+r.width + bufferDistance
&&
p.y > r.y - bufferDistance
&&
p.y < r.y+r.height + bufferDistance
)
return true;
return false;
}
//-------------------------------------------------------------------------
/**
* Returns the ViewPanel that the point is on
*/
public static View calculateClickedPanel(final List<View> panels, final Point pt)
{
View clickedPanel = null;
for (final View p : panels)
{
final Rectangle placement = p.placement();
if (placement.contains(pt))
{
clickedPanel = p;
break;
}
}
return clickedPanel;
}
//-----------------------------------------------------------------------------
}
| 1,528 | 18.857143 | 94 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/GameSetup.java
|
package app.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.rng.core.RandomProviderDefaultState;
import app.PlayerApp;
import compiler.Compiler;
import game.Game;
import main.Constants;
import main.grammar.Description;
import main.grammar.Report;
import manager.ai.AIDetails;
import util.StringUtil;
/**
* Functions to assist with setting up games.
*
* @author Matthew.Stephenson
*/
public class GameSetup
{
//-------------------------------------------------------------------------
/**
* Compile and display the specified description with the corresponding menu options.
*/
public static void compileAndShowGame(final PlayerApp app, final String desc, final boolean debug)
{
final Description gameDescription = new Description(desc);
final Report report = new Report();
report.setReportMessageFunctions(new ReportMessengerGUI(app));
try
{
final Game game = (Game)Compiler.compile(gameDescription, app.manager().settingsManager().userSelections(), report, debug);
app.manager().ref().setGame(app.manager(), game);
printCompilationMessages(app, game, debug, report);
// Reset all AI objects to null to free memory space.
for (int i = 0; i < app.manager().aiSelected().length; i++)
app.manager().aiSelected()[i].setAI(null);
app.loadGameSpecificPreferences();
GameUtil.resetGame(app, false);
}
catch (final Exception e)
{
e.printStackTrace();
app.reportError(e.getMessage());
}
// Try to make Java run GC in case previous game occupied a lot of memory
System.gc();
}
//-------------------------------------------------------------------------
private static void printCompilationMessages(final PlayerApp app, final Game game, final boolean debug, final Report report)
{
app.addTextToStatusPanel("-------------------------------------------------\n");
app.addTextToStatusPanel("Compiled " + game.name() + " successfully.\n");
if (report.isWarning())
{
for (final String warning : report.warnings())
app.reportError("Warning: " + warning);
}
if (game.hasMissingRequirement())
{
app.reportError("");
app.reportError("Requirement Warning: ");
final List<String> missingRequirements = game.requirementReport();
for (final String missingRequirement : missingRequirements)
app.reportError("--> " + missingRequirement);
app.reportError("");
}
if (game.willCrash())
{
app.reportError("");
app.reportError("Crash Warning: ");
final List<String> crashes = game.crashReport();
for (final String crash : crashes)
app.reportError("--> " + crash);
app.reportError("");
}
if (game.equipmentWithStochastic())
{
app.addTextToStatusPanel("Warning: This game uses stochastic equipment, automatic trial saving is disabled.\n");
}
if (debug)
{
app.writeTextToFile("debug_log.txt", report.log());
}
}
//-------------------------------------------------------------------------
public static void setupNetworkGame(final PlayerApp app, final String gameName, final List<String> gameOptions, final String inputLinePlayerNumber, final boolean aiAllowed, final int selectedGameID, final int turnLimit)
{
app.manager().settingsNetwork().setLoadingNetworkGame(true);
try
{
if (!inputLinePlayerNumber.equals("") && StringUtil.isInteger(inputLinePlayerNumber))
{
// Disable features which are not allowed in network games.
app.settingsPlayer().setCursorTooltipDev(false);
app.settingsPlayer().setSwapRule(false);
app.settingsPlayer().setNoRepetition(false);
app.settingsPlayer().setNoRepetitionWithinTurn(false);
app.settingsPlayer().setSandboxMode(false);
final int playerNumber = Integer.parseInt(inputLinePlayerNumber);
app.manager().settingsNetwork().setActiveGameId(selectedGameID);
app.manager().settingsNetwork().setNetworkPlayerNumber(playerNumber);
// Format the stored string into the syntax needed for loading the game.
final List<String> formattedGameOptions = new ArrayList<>();
for (int i = 0; i < gameOptions.size(); i++)
{
String formattedString = gameOptions.get(i);
formattedString = formattedString.replaceAll("_", " ");
formattedString = formattedString.replaceAll("\\|", "/");
formattedGameOptions.add(formattedString);
}
if (!formattedGameOptions.get(0).equals("-") && !formattedGameOptions.get(0).equals(""))
app.loadGameFromName(gameName, formattedGameOptions, false);
else
app.loadGameFromName(gameName, new ArrayList<String>(), false);
if (playerNumber > Constants.MAX_PLAYERS)
app.addTextToStatusPanel("Joined game as a spectator\n");
else
app.addTextToStatusPanel("Joined game as player number " + playerNumber + "\n");
app.manager().ref().context().game().setMaxTurns(turnLimit);
final String gameRNG = app.manager().databaseFunctionsPublic().getRNG(app.manager());
final String[] byteStrings = gameRNG.split(Pattern.quote(","));
final byte[] bytes = new byte[byteStrings.length];
for (int i = 0; i < byteStrings.length; ++i)
bytes[i] = Byte.parseByte(byteStrings[i]);
final RandomProviderDefaultState rngState = new RandomProviderDefaultState(bytes);
app.manager().ref().context().rng().restoreState(rngState);
GameUtil.startGame(app);
app.manager().setCurrGameStartRngState(rngState);
for (int i = 0; i < app.manager().aiSelected().length; i++)
{
if (app.manager().aiSelected()[i].ai() != null)
app.manager().aiSelected()[i].ai().closeAI();
app.manager().aiSelected()[i] = new AIDetails(app.manager(), null, i, "Human");
}
app.manager().settingsNetwork().setOnlineAIAllowed(aiAllowed);
}
else
{
app.addTextToStatusPanel(inputLinePlayerNumber);
}
}
catch (final Exception e)
{
e.printStackTrace();
}
app.manager().settingsNetwork().setLoadingNetworkGame(false);
}
//-------------------------------------------------------------------------
}
| 6,200 | 33.071429 | 220 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/GameUtil.java
|
package app.utils;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import app.PlayerApp;
import app.move.MoveHandler;
import app.move.animation.MoveAnimation;
import compiler.Compiler;
import game.Game;
import game.equipment.container.Container;
import game.types.board.SiteType;
import game.types.play.RoleType;
import main.Constants;
import main.grammar.Report;
import main.options.Ruleset;
import manager.Referee;
import manager.ai.AIUtil;
import other.context.Context;
import other.location.FullLocation;
import other.move.Move;
import tournament.TournamentUtil;
/**
* Utility functions for games.
*
* @author Matthew.Stephenson
*/
public class GameUtil
{
//-------------------------------------------------------------------------
/**
* All function calls needed to restart the game.
*/
public static void resetGame(final PlayerApp app, final boolean keepSameTrial)
{
final Referee ref = app.manager().ref();
final Context context = ref.context();
Game game = context.game();
app.manager().undoneMoves().clear();
ref.interruptAI(app.manager());
AIUtil.checkAISupported(app.manager(), context);
// Web Player settings
app.settingsPlayer().setWebGameResultValid(true);
for (int i = 0; i <= game.players().count(); i++)
{
if (app.manager().aiSelected()[app.manager().playerToAgent(i)].ai() != null)
app.settingsPlayer().setAgentArray(i, true);
else
app.settingsPlayer().setAgentArray(i, false);
}
// If game has stochastic equipment, need to recompile the whole game from scratch.
if (game.equipmentWithStochastic())
{
game = (Game)Compiler.compile
(
game.description(),
app.manager().settingsManager().userSelections(),
new Report(), //null,
false
);
app.manager().ref().setGame(app.manager(), game);
}
if (keepSameTrial)
{
// Reset all necessary information about the context.
context.rng().restoreState(app.manager().currGameStartRngState());
context.reset();
context.state().initialise(context.currentInstanceContext().game());
context.trial().setStatus(null);
}
else
{
app.manager().ref().setGame(app.manager(), game);
UpdateTabMessages.postMoveUpdateStatusTab(app);
}
// Start the game
GameUtil.startGame(app);
updateRecentGames(app, app.manager().ref().context().game().name());
resetUIVariables(app);
}
//-------------------------------------------------------------------------
public static void resetUIVariables(final PlayerApp app)
{
app.contextSnapshot().setContext(app);
MVCSetup.setMVC(app);
app.bridge().setGraphicsRenderer(app);
app.manager().ref().interruptAI(app.manager());
app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED));
app.bridge().settingsVC().setSelectingConsequenceMove(false);
app.settingsPlayer().setCurrentWalkExtra(0);
MoveAnimation.resetAnimationValues(app);
app.manager().settingsManager().movesAllowedWithRepetition().clear();
app.manager().settingsManager().storedGameStatesForVisuals().clear();
app.manager().settingsManager().storedGameStatesForVisuals().add(Long.valueOf(app.manager().ref().context().state().stateHash()));
app.settingsPlayer().setComponentIsSelected(false);
app.bridge().settingsVC().setPieceBeingDragged(false);
app.settingsPlayer().setDragComponent(null);
app.setTemporaryMessage("");
app.manager().settingsNetwork().resetNetworkPlayers();
app.updateFrameTitle(true);
AIUtil.pauseAgentsIfNeeded(app.manager());
if (app.manager().isWebApp())
{
final Context context = app.manager().ref().context();
// Check if that game contains a shared hand (above the board)
boolean hasSharedHand = false;
for (final Container container : context.equipment().containers())
if (container.role().equals(RoleType.Shared))
hasSharedHand = true;
// Check if the game has custom hand placement
boolean hasCustomHandPlacement = false;
for (int i = 0; i <= Constants.MAX_PLAYERS; i++)
if (context.game().metadata().graphics().handPlacement(context, i) != null)
hasCustomHandPlacement = true;
final boolean boardBackground = context.game().metadata().graphics().boardBackground(context).size() > 0;
// Make the margins around the board thinner
if (context.board().defaultSite().equals(SiteType.Cell) && !hasSharedHand && !boardBackground && !hasCustomHandPlacement)
app.bridge().getContainerStyle(0).setDefaultBoardScale(0.95);
}
MoveHandler.checkMoveWarnings(app);
EventQueue.invokeLater(() ->
{
app.repaint();
});
}
//-------------------------------------------------------------------------
/**
* various tasks that are performed when a normal game ends.
*/
public static void gameOverTasks(final PlayerApp app, final Move move)
{
final Context context = app.manager().ref().context();
final int moveNumber = context.currentInstanceContext().trial().numMoves() - 1;
if (context.trial().over() && context.trial().lastMove().equals(move))
{
app.addTextToStatusPanel(UpdateTabMessages.gameOverMessage(app.manager().ref().context(), context.trial()));
app.manager().databaseFunctionsPublic().sendResultToDatabase(app.manager(), context);
TournamentUtil.saveTournamentResults(app.manager(), app.manager().ref().context());
if (app.manager().isWebApp())
app.setTemporaryMessage(UpdateTabMessages.gameOverMessage(app.manager().ref().context(), app.manager().ref().context().trial()));
else if (!app.settingsPlayer().usingMYOGApp())
app.setTemporaryMessage("Choose Game > Restart to play again.");
}
else if (context.isAMatch() && moveNumber < context.currentInstanceContext().trial().numInitialPlacementMoves())
{
resetUIVariables(app);
}
}
//-------------------------------------------------------------------------
public static void startGame(final PlayerApp app)
{
final Context context = app.manager().ref().context();
context.game().start(context);
context.game().incrementGameStartCount();
final int numPlayers = context.game().players().count();
for (int p = 0; p < app.manager().aiSelected().length; ++p)
{
// Close AI players that may have had data from previous game
if (app.manager().aiSelected()[p].ai() != null)
app.manager().aiSelected()[p].ai().closeAI();
// Initialise AI players (only if player ID relevant)
if (p <= numPlayers && app.manager().aiSelected()[p].ai() != null)
app.manager().aiSelected()[p].ai().initIfNeeded(context.game(), p);
}
}
//-------------------------------------------------------------------------
/**
* Add gameName to the list of recent games, or update its position in this list.
* These games can then be selected from the menu bar
* @param gameName
*/
private static void updateRecentGames(final PlayerApp app, final String gameName)
{
String GameMenuName = gameName;
final String[] recentGames = app.settingsPlayer().recentGames();
if (!app.settingsPlayer().loadedFromMemory())
GameMenuName = app.manager().savedLudName();
int gameAlreadyIncluded = -1;
// Check if the game is already included in our recent games list, and record its position.
for (int i = 0; i < recentGames.length; i++)
if (recentGames[i] != null && recentGames[i].equals(GameMenuName))
gameAlreadyIncluded = i;
// If game was not already in recent games list, record the last position on the list
if (gameAlreadyIncluded == -1)
gameAlreadyIncluded = recentGames.length-1;
// Shift all games ahead of the record position down a spot.
for (int i = gameAlreadyIncluded; i > 0; i--)
recentGames[i] = recentGames[i-1];
// Add game at front of recent games list.
recentGames[0] = GameMenuName;
}
//-------------------------------------------------------------------------
public static boolean checkMatchingRulesets(final PlayerApp app, final Game game, final String rulesetName)
{
final List<Ruleset> rulesets = game.description().rulesets();
boolean rulesetSelected = false;
if (rulesets != null && !rulesets.isEmpty())
{
for (int rs = 0; rs < rulesets.size(); rs++)
{
final Ruleset ruleset = rulesets.get(rs);
if (ruleset.heading().equals(rulesetName))
{
// Match!
app.manager().settingsManager().userSelections().setRuleset(rs);
// Set the game options according to the chosen ruleset
app.manager().settingsManager().userSelections().setSelectOptionStrings(new ArrayList<String>(ruleset.optionSettings()));
rulesetSelected = true;
try
{
GameSetup.compileAndShowGame(app, game.description().raw(), false);
}
catch (final Exception exception)
{
GameUtil.resetGame(app, false);
}
break;
}
}
}
return rulesetSelected;
}
}
| 8,891 | 31.452555 | 133 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/GenerateAliasesFile.java
|
package app.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import main.FileHandling;
import main.StringRoutines;
/**
* Small class with main method to generate our resource file
* containing aliases of games.
*
* @author Dennis Soemers
*/
public class GenerateAliasesFile
{
/** Filepath to which we'll write the file containing data on aliases */
private static final String ALIASES_FILEPATH = "../Common/res/help/Aliases.txt";
//-------------------------------------------------------------------------
/**
* Constructor
*/
private GenerateAliasesFile()
{
// Do not instantiate
}
//-------------------------------------------------------------------------
/**
* Our main method
* @param args
* @throws IOException
*/
public static void main(final String[] args) throws IOException
{
final File startFolder = new File("../Common/res/lud/");
final List<File> gameDirs = new ArrayList<>();
gameDirs.add(startFolder);
// We compute the .lud files (and not the ludemeplex).
final List<File> entries = new ArrayList<>();
for (int i = 0; i < gameDirs.size(); ++i)
{
final File gameDir = gameDirs.get(i);
for (final File fileEntry : gameDir.listFiles())
{
if (fileEntry.isDirectory())
{
final String path = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/");
if (path.equals("../Common/res/lud/plex"))
continue;
if (path.equals("../Common/res/lud/wishlist"))
continue;
if (path.equals("../Common/res/lud/WishlistDLP"))
continue;
if (path.equals("../Common/res/lud/wip"))
continue;
if (path.equals("../Common/res/lud/test"))
continue;
if (path.equals("../Common/res/lud/bad"))
continue;
if (path.equals("../Common/res/lud/bad_playout"))
continue;
if (path.equals("../Common/res/lud/subgame"))
continue;
if (path.equals("../Common/res/lud/reconstruction"))
continue;
gameDirs.add(fileEntry);
}
else if (fileEntry.getName().contains(".lud"))
{
entries.add(fileEntry);
}
}
}
try
(
final PrintWriter writer =
new PrintWriter(new OutputStreamWriter(new FileOutputStream(ALIASES_FILEPATH), StandardCharsets.UTF_8))
)
{
for (final File fileEntry : entries)
{
System.out.println("Processing: " + fileEntry.getAbsolutePath() + "...");
final String fileContents = FileHandling.loadTextContentsFromFile(fileEntry.getAbsolutePath());
final int metadataStart = fileContents.indexOf("(metadata");
final int metadataEnd = StringRoutines.matchingBracketAt(fileContents, metadataStart);
final String metadataString = fileContents.substring(metadataStart, metadataEnd);
final List<String> aliases = new ArrayList<String>();
final int aliasesStart = metadataString.indexOf("(aliases {") + "(aliases ".length();
if (aliasesStart >= "(aliases ".length())
{
final int aliasesEnd = StringRoutines.matchingBracketAt(metadataString, aliasesStart);
final String aliasStrings = metadataString.substring(aliasesStart + 1, aliasesEnd);
int nextOpenQuoteIdx = aliasStrings.indexOf("\"", 0);
while (nextOpenQuoteIdx >= 0)
{
final int nextClosingQuoteIdx = StringRoutines.matchingQuoteAt(aliasStrings, nextOpenQuoteIdx);
if (nextClosingQuoteIdx >= 0)
{
aliases.add(aliasStrings.substring(nextOpenQuoteIdx + 1, nextClosingQuoteIdx));
}
nextOpenQuoteIdx = aliasStrings.indexOf("\"", nextClosingQuoteIdx + 1);
}
}
if (aliases.size() > 0)
{
// First print the game path
final String fileEntryPath = fileEntry.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/");
final int ludPathStartIdx = fileEntryPath.indexOf("/lud/");
writer.println(fileEntryPath.substring(ludPathStartIdx));
// Now print the aliases
for (final String alias : aliases)
{
writer.println(alias);
}
}
}
System.out.println("Finished processing aliases.");
System.out.println("Wrote to file: " + new File(ALIASES_FILEPATH).getAbsolutePath());
}
catch (final FileNotFoundException e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
}
| 4,589 | 26.987805 | 106 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/GraphicsCache.java
|
package app.utils;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import org.jfree.graphics2d.svg.SVGGraphics2D;
import bridge.Bridge;
import game.equipment.component.Component;
import game.equipment.container.other.Dice;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import main.Constants;
import other.action.Action;
import other.action.die.ActionUpdateDice;
import other.action.die.ActionUseDie;
import other.context.Context;
import other.move.Move;
import util.ImageInfo;
import view.component.ComponentStyle;
/**
* GraphicsCache for storing all the images we need.
*
* @author Matthew.Stephenson
*/
public class GraphicsCache
{
// All component images and sizes for use on the containers.
private cacheStorage allComponentImages = new cacheStorage();
// All component images and sizes for use on other GUI elements without a container.
private cacheStorage allComponentImagesSecondary = new cacheStorage();
// Other images we want to store
private BufferedImage boardImage = null;
private BufferedImage graphImage = null;
private BufferedImage connectionsImage = null;
private BufferedImage[] allToolButtons = new BufferedImage[9];
private final ArrayList<DrawnImageInfo> allDrawnComponents = new ArrayList<>();
//-------------------------------------------------------------------------
/**
* Get the image of a component.
*/
public BufferedImage getComponentImage
(
final Bridge bridge,
final int containerId,
final Component component,
final int owner,
final int localState,
final int value,
final int site,
final int level,
final SiteType type,
final int imageSize,
final Context context,
final int hiddenValue,
final int rotation,
final boolean secondary
)
{
final int componentId = component.index();
final ComponentStyle componentStyle = bridge.getComponentStyle(component.index());
// Retrieve and initialise the correct graphics cache object.
cacheStorage componentImageArray;
if (secondary && component.isTile())
componentImageArray = allComponentImagesSecondary().setupCache(containerId, componentId, owner, localState, value, hiddenValue, rotation, secondary);
else
componentImageArray = allComponentImages().setupCache(containerId, componentId, owner, localState, value, hiddenValue, rotation, secondary);
// Fetch the image and size stored in the graphics cache.
BufferedImage cacheImage = componentImageArray.getCacheImage(containerId, componentId, owner, localState, value, hiddenValue, rotation);
int cacheImageSize = componentImageArray.getCacheImageSize(containerId, componentId, owner, localState, value, hiddenValue, rotation).intValue();
// If the component does not have a stored image for the provided local state, then create one from its SVG string
if (cacheImage == null || cacheImageSize != imageSize)
{
// create the image for the given local state value
if (containerId > 0 && component.isLargePiece())
componentStyle.renderImageSVG(context, containerId, bridge.getContainerStyle(0).cellRadiusPixels()*2, localState, value, true, hiddenValue, rotation);
else if (containerId > 0 && component.isTile())
componentStyle.renderImageSVG(context, containerId, imageSize, localState, value, true, hiddenValue, rotation);
else
componentStyle.renderImageSVG(context, containerId, imageSize, localState, value, secondary, hiddenValue, rotation);
final SVGGraphics2D svg = componentStyle.getImageSVG(localState);
final BufferedImage componentImage = getComponentBufferedImage(svg, component, componentStyle, context, containerId, imageSize, localState, secondary);
componentImageArray.setCacheImage(componentImage, containerId, componentId, owner, localState, value, hiddenValue, rotation);
componentImageArray.setCacheImageSize(imageSize, containerId, componentId, owner, localState, value, hiddenValue, rotation);
cacheImage = componentImage;
cacheImageSize = imageSize;
}
// Check if the component is a die, if so then if the die is used make it transparent.
if (component.isDie())
return getDiceImage(containerId, component, localState, site, context, componentId, cacheImage);
return cacheImage;
}
//-------------------------------------------------------------------------
/**
* Creates the (basic) image of the component from its SVG.
*/
private static BufferedImage getComponentBufferedImage(final SVGGraphics2D svg, final Component component, final ComponentStyle componentStyle, final Context context, final int containerId, final int imageSize, final int localState, final boolean secondary)
{
// create the BufferedImage based on this SVG image.
BufferedImage componentImage = null;
if (svg != null)
{
if (component.isLargePiece())
{
componentImage = SVGUtil.createSVGImage(svg.getSVGDocument(), componentStyle.largePieceSize().x, componentStyle.largePieceSize().y);
if (containerId != 0)
{
final int maxSize = Math.max(componentStyle.largePieceSize().x, componentStyle.largePieceSize().y);
final double scaleFactor = 0.9 * imageSize / maxSize;
componentImage = BufferedImageUtil.resize(componentImage, (int)(scaleFactor * componentStyle.largePieceSize().x), (int)(scaleFactor * componentStyle.largePieceSize().y));
}
}
else
{
componentImage = SVGUtil.createSVGImage(svg.getSVGDocument(), imageSize, imageSize);
}
}
return componentImage;
}
//-------------------------------------------------------------------------
/**
* Gets the image of the component if it's a dice (transparent if already used).
*/
private static BufferedImage getDiceImage
(
final int containerId,
final Component component,
final int localState,
final int site,
final Context context,
final int componentId,
final BufferedImage cacheImage
)
{
// get the index of the dice container (usually just one)
int handDiceIndex = -1;
for (int j = 0; j < context.handDice().size(); j++)
{
final Dice dice = context.handDice().get(j);
if (dice.index() == containerId)
{
handDiceIndex = j;
break;
}
}
// Only grey out dice if they are in a dice hand.
// TODO ERIC REWRITE THIS INTO INFORMATION CONTEXT
if (handDiceIndex != -1)
{
// Previous value of the dice (looking for if this is zero) (before to apply the prior (now do) moves).
int previousValue = context.state().currentDice()[handDiceIndex][site - context.sitesFrom()[containerId]];
int stateValue = localState;
//final Context fullContext = ((InformationContext) context).originalContext();
final Moves moves = context.moves(context);
boolean useDieDetected = false;
if (moves.moves().size() > 0)
{
// Keep only actions that are the same across all moves.
final ArrayList<Action> allSameActions = new ArrayList<Action>(moves.moves().get(0).actions());
for (final Move m : moves.moves())
{
boolean differentAction = false;
for (int j = allSameActions.size()-1; j >= 0; j--)
{
if (m.actions().size() <= j)
break;
if (allSameActions.get(j) != m.actions().get(j))
differentAction = true;
if (differentAction)
allSameActions.remove(j);
}
}
// We check if the moves used an ActionUseDie to know if we need to grey them or not.
for (final Move m : moves.moves())
{
for (final Action action : m.actions())
if (action instanceof ActionUseDie)
{
useDieDetected = true;
break;
}
if (useDieDetected)
break;
}
// We keep only the same actions equal to ActionSetStateAndUpdateDice.
for (int j = 0; j < allSameActions.size(); j++)
{
if (!(allSameActions.get(j) instanceof ActionUpdateDice))
allSameActions.remove(j);
}
final int loc = context.sitesFrom()[containerId] + site;
for (final Action a : allSameActions)
{
if (a.from() == loc && stateValue != Constants.UNDEFINED)
{
stateValue = a.state();
previousValue = context.components()[component.index()].getFaces()[stateValue];
}
}
}
// Grey the die if the previous value was 0 and this is the same turn and the action useDieDetected is used.
if (context.state().mover() == context.state().prev() && previousValue == 0 && useDieDetected)
return BufferedImageUtil.makeImageTranslucent(cacheImage, 0.2);
}
return cacheImage;
}
//-------------------------------------------------------------------------
/**
* Draws the image onto the view, and also saves its information for selection use later.
*/
public void drawPiece(final Graphics2D g2d, final Context context, final BufferedImage pieceImage, final Point posn, final int site, final int level, final SiteType type, final double transparency)
{
BufferedImage imageToDraw = pieceImage;
if (transparency != 0)
{
imageToDraw = BufferedImageUtil.makeImageTranslucent(pieceImage, transparency);
}
final ImageInfo imageInfo = new ImageInfo(posn, site, level, type);
allDrawnComponents().add(new DrawnImageInfo(pieceImage,imageInfo));
g2d.drawImage(imageToDraw, posn.x, posn.y, null);
}
//-------------------------------------------------------------------------
/**
* Clear the graphics cache.
*/
public void clearAllCachedImages()
{
setAllComponentImages(new cacheStorage());
setAllComponentImagesSecondary(new cacheStorage());
setBoardImage(null);
setGraphImage(null);
setConnectionsImage(null);
setAllToolButtons(new BufferedImage[Constants.MAX_PLAYERS+1]);
allDrawnComponents().clear();
}
//-------------------------------------------------------------------------
/**
* Gets the size of the image for a component.
*/
public int getComponentImageSize(final int containerId, final int componentId, final int owner, final int localState, final int value, final int hiddenValue, final int rotation)
{
return allComponentImages().getCacheImageSize(containerId, componentId, owner, localState, value, hiddenValue, rotation).intValue();
}
//-------------------------------------------------------------------------
/**
* Nested class for storing the bufferedImages from the component SVGs.
* [Container, Component, State, Value, HiddenValue, Rotation]
*/
protected static class cacheStorage
{
/** All component images for use on the containers (BufferedImages). */
protected final ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<BufferedImage>>>>>>> cacheStorageImages = new ArrayList<>();
/** All component image sizes for use on the containers (Integer). */
protected final ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<Integer>>>>>>> cacheStorageSizes = new ArrayList<>();
//-------------------------------------------------------------------------
protected BufferedImage getCacheImage(final int containerId, final int componentId, final int owner, final int localState, final int value, final int hiddenValue, final int rotation)
{
return cacheStorageImages.get(containerId).get(componentId).get(owner).get(localState).get(value).get(hiddenValue).get(rotation);
}
protected Integer getCacheImageSize(final int containerId, final int componentId, final int owner, final int localState, final int value, final int hiddenValue, final int rotation)
{
return cacheStorageSizes.get(containerId).get(componentId).get(owner).get(localState).get(value).get(hiddenValue).get(rotation);
}
//-------------------------------------------------------------------------
protected BufferedImage setCacheImage(final BufferedImage image, final int containerId, final int componentId, final int owner, final int localState, final int value, final int hiddenValue, final int rotation)
{
return cacheStorageImages.get(containerId).get(componentId).get(owner).get(localState).get(value).get(hiddenValue).set(rotation, image);
}
protected Integer setCacheImageSize(final int size, final int containerId, final int componentId, final int owner, final int localState, final int value, final int hiddenValue, final int rotation)
{
return cacheStorageSizes.get(containerId).get(componentId).get(owner).get(localState).get(value).get(hiddenValue).set(rotation, Integer.valueOf(size));
}
//-------------------------------------------------------------------------
/**
* Adds additional empty arrayLists and default values to the graphics cache, for the intermediary values.
*/
protected final cacheStorage setupCache
(
final int containerId,
final int componentId,
final int owner,
final int localState,
final int value,
final int hiddenValue,
final int rotation,
final boolean secondary
)
{
while (cacheStorageImages.size() <= containerId)
{
cacheStorageImages.add(new ArrayList<>());
cacheStorageSizes.add(new ArrayList<>());
}
while (cacheStorageImages.get(containerId).size() <= componentId)
{
cacheStorageImages.get(containerId).add(new ArrayList<>());
cacheStorageSizes.get(containerId).add(new ArrayList<>());
}
while (cacheStorageImages.get(containerId).get(componentId).size() <= owner)
{
cacheStorageImages.get(containerId).get(componentId).add(new ArrayList<>());
cacheStorageSizes.get(containerId).get(componentId).add(new ArrayList<>());
}
while (cacheStorageImages.get(containerId).get(componentId).get(owner).size() <= localState)
{
cacheStorageImages.get(containerId).get(componentId).get(owner).add(new ArrayList<>());
cacheStorageSizes.get(containerId).get(componentId).get(owner).add(new ArrayList<>());
}
while (cacheStorageImages.get(containerId).get(componentId).get(owner).get(localState).size() <= value)
{
cacheStorageImages.get(containerId).get(componentId).get(owner).get(localState).add(new ArrayList<>());
cacheStorageSizes.get(containerId).get(componentId).get(owner).get(localState).add(new ArrayList<>());
}
while (cacheStorageImages.get(containerId).get(componentId).get(owner).get(localState).get(value).size() <= hiddenValue)
{
cacheStorageImages.get(containerId).get(componentId).get(owner).get(localState).get(value).add(new ArrayList<>());
cacheStorageSizes.get(containerId).get(componentId).get(owner).get(localState).get(value).add(new ArrayList<>());
}
while (cacheStorageImages.get(containerId).get(componentId).get(owner).get(localState).get(value).get(hiddenValue).size() <= rotation)
{
cacheStorageImages.get(containerId).get(componentId).get(owner).get(localState).get(value).get(hiddenValue).add(null);
cacheStorageSizes.get(containerId).get(componentId).get(owner).get(localState).get(value).get(hiddenValue).add(Integer.valueOf(0));
}
return this;
}
}
//-------------------------------------------------------------------------
public BufferedImage boardImage()
{
return boardImage;
}
public void setBoardImage(final BufferedImage boardImage)
{
this.boardImage = boardImage;
}
public BufferedImage graphImage()
{
return graphImage;
}
public void setGraphImage(final BufferedImage graphImage)
{
this.graphImage = graphImage;
}
public BufferedImage connectionsImage()
{
return connectionsImage;
}
public void setConnectionsImage(final BufferedImage connectionsImage)
{
this.connectionsImage = connectionsImage;
}
public BufferedImage[] allToolButtons()
{
return allToolButtons;
}
public void setAllToolButtons(final BufferedImage[] allToolButtons)
{
this.allToolButtons = allToolButtons;
}
public ArrayList<DrawnImageInfo> allDrawnComponents()
{
return allDrawnComponents;
}
private cacheStorage allComponentImages()
{
return allComponentImages;
}
private void setAllComponentImages(final cacheStorage allComponentImages)
{
this.allComponentImages = allComponentImages;
}
private cacheStorage allComponentImagesSecondary()
{
return allComponentImagesSecondary;
}
private void setAllComponentImagesSecondary(final cacheStorage allComponentImagesSecondary)
{
this.allComponentImagesSecondary = allComponentImagesSecondary;
}
//-------------------------------------------------------------------------
}
| 16,356 | 35.268293 | 258 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/MVCSetup.java
|
package app.utils;
import app.PlayerApp;
import bridge.ViewControllerFactory;
import game.equipment.component.Component;
import game.equipment.container.Container;
import metadata.Metadata;
import other.context.Context;
/**
* Functions for setting up the Model-View-Controller within the Bridge.
*
* @author Matthew.Stephenson and cambolbro
*/
public class MVCSetup
{
//-------------------------------------------------------------------------
/**
* Set the Bridge MVC objects to the correct Styles for each container and component.
*/
public static void setMVC(final PlayerApp app)
{
final Context context = app.manager().ref().context();
final Metadata metadata = context.metadata();
// Game metadata can be used to disable animation.
app.bridge().settingsVC().setNoAnimation(context.game().metadata().graphics().noAnimation());
// Container style
if (metadata != null && metadata.graphics().boardStyle() != null)
context.board().setStyle(metadata.graphics().boardStyle());
for (final Container c : context.equipment().containers())
{
app.bridge().addContainerStyle(ViewControllerFactory.createStyle(app.bridge(), c, c.style(), context), c.index());
app.bridge().addContainerController(ViewControllerFactory.createController(app.bridge(), c, c.controller()), c.index());
}
// Component style
for (final Component c : context.equipment().components())
{
if (c != null)
{
// Override the component's default style with that specified in metadata
if (metadata != null && metadata.graphics().componentStyle(context, c.owner(), c.name()) != null)
c.setStyle( metadata.graphics().componentStyle(context, c.owner(), c.name()));
app.bridge().addComponentStyle(ViewControllerFactory.createStyle(app.bridge(), c, c.style()), c.index());
}
}
app.clearGraphicsCache();
}
//-------------------------------------------------------------------------
}
| 1,948 | 31.483333 | 123 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/PuzzleSelectionType.java
|
package app.utils;
/**
* Different ways that values can be selected for deduction puzzles.
*
* @author Matthew.Stephenson
*/
public enum PuzzleSelectionType
{
Automatic, // Pick from the others based on the # possible values.
Dialog, // Show a dialog with all possible values.
Cycle; // Cycle through to the next possible value.
//-------------------------------------------------------------------------
/**
* Returns the PuzzleSelectionType who's value matches the provided name.
*/
public static PuzzleSelectionType getPuzzleSelectionType(final String name)
{
for (final PuzzleSelectionType puzzleSelectionType : PuzzleSelectionType.values())
if (puzzleSelectionType.name().equals(name))
return puzzleSelectionType;
return Automatic;
}
//-------------------------------------------------------------------------
}
| 903 | 27.25 | 90 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/QrCodeGeneration.java
|
package app.utils;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import game.Game;
import graphics.qr_codes.QrCode;
import graphics.qr_codes.ToImage;
import main.DatabaseInformation;
/**
* QR code generation functions.
*
* @author cambolbro and matthew.stephenson
*/
public class QrCodeGeneration
{
/**
* Saves a QR code png for the specified game. Will use the ruleset is available.
* @param game
*/
public static void makeQRCode(final Game game)
{
makeQRCode(game, 10, 4, true);
}
public static void makeQRCode(final Game game, final int scale, final int border, final boolean includeRuleset)
{
// Determine the file name
String fileName = "qr-" + game.name();
if (game.getRuleset() != null && includeRuleset)
{
fileName += "-" + game.getRuleset().heading();
fileName = fileName.replaceAll("Ruleset/", ""); // remove keyword
}
//fileName = fileName.replaceAll(" ", "-"); // remove empty spaces
//fileName = fileName.replaceAll("/", "-"); // remove slashes spaces
fileName += ".png";
// Determine URL to encode
String url = "https://ludii.games/details.php?keyword=" + game.name();
if (game.getRuleset() != null && includeRuleset)
{
// Format: https://ludii.games/variantDetails.php?keyword=Achi&variant=563
final int variant = DatabaseInformation.getRulesetId(game.name(), game.getRuleset().heading());
url = "https://ludii.games/variantDetails.php?keyword=" + game.name() +
"&variant=" + variant;
}
url = url.replaceAll(" ", "%20"); // make URL valid HTML (yuck)
final QrCode qr = QrCode.encodeText(url, QrCode.Ecc.MEDIUM);
// Make the image
final BufferedImage img = ToImage.toLudiiCodeImage(qr, scale, border);
try
{
ImageIO.write(img, "png", new File(fileName));
}
catch (final IOException e1)
{
e1.printStackTrace();
}
}
/**
* To be used only for exhibition QR codes.
*/
// public static void main(String[] args)
// {
// final File startFolder = new File("../Common/res/lud");
// final List<File> gameDirs = new ArrayList<File>();
// gameDirs.add(startFolder);
//
// final List<File> entries = new ArrayList<File>();
//
// //final String moreSpecificFolder = "../Common/res/lud/board/war/leaping/diagonal";
// final String moreSpecificFolder = "";
//
// for (int i = 0; i < gameDirs.size(); ++i)
// {
// final File gameDir = gameDirs.get(i);
//
// for (final File fileEntry : gameDir.listFiles())
// {
// if (fileEntry.isDirectory())
// {
// final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/");
//
// if (fileEntryPath.equals("../Common/res/lud/plex"))
// continue;
//
// if (fileEntryPath.equals("../Common/res/lud/wip"))
// continue;
//
// if (fileEntryPath.equals("../Common/res/lud/wishlist"))
// continue;
//
// if (fileEntryPath.equals("../Common/res/lud/WishlistDLP"))
// continue;
//
// if (fileEntryPath.equals("../Common/res/lud/test"))
// continue;
//
// if (fileEntryPath.equals("../Common/res/lud/bad"))
// continue;
//
// if (fileEntryPath.equals("../Common/res/lud/bad_playout"))
// continue;
//
// gameDirs.add(fileEntry);
// }
// else
// {
// final String fileEntryPath = fileEntry.getPath().replaceAll(Pattern.quote("\\"), "/");
// if (moreSpecificFolder.equals("") || fileEntryPath.contains(moreSpecificFolder))
// entries.add(fileEntry);
// }
// }
// }
//
// for (File file : entries)
// {
// String gameName = file.getPath().substring(file.getPath().lastIndexOf('\\')+1);
// gameName = gameName.substring(0, gameName.length()-4);
//
// // Determine the file name
// String fileName = "qr-" + gameName;
//
// //fileName = fileName.replaceAll(" ", "-"); // remove empty spaces
// //fileName = fileName.replaceAll("/", "-"); // remove slashes spaces
// fileName += ".png";
//
// // Determine URL to encode
// String url = "https://ludii.games/details.php?keyword=" + gameName;
// url = url.replaceAll(" ", "%20"); // make URL valid HTML (yuck)
//
// final QrCode qr = QrCode.encodeText(url, QrCode.Ecc.MEDIUM);
//
// // Make the image
// final BufferedImage img = ToImage.toLudiiCodeImage(qr, 5, 2);
// try
// {
// ImageIO.write(img, "png", new File(fileName));
// }
// catch (final IOException e1)
// {
// e1.printStackTrace();
// }
// }
// }
}
| 4,489 | 27.967742 | 112 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/RemoteDialogFunctionsPublic.java
|
package app.utils;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import app.PlayerApp;
import manager.Manager;
/**
* Public class for calling remote dialog functions.
* Fake function calls. Remote dialog functionality is not available in the source code.
*
* @author Matthew.Stephenson and Dennis Soemers
*/
public class RemoteDialogFunctionsPublic
{
//-------------------------------------------------------------------------
/** Class loader used to load private network code if available (not included in public source code repo) */
private static URLClassLoader privateNetworkCodeClassLoader = null;
// Static block to initialise classloader
static
{
final File networkPrivateBin = new File("../../LudiiPrivate/NetworkPrivate/bin");
if (networkPrivateBin.exists())
{
try
{
privateNetworkCodeClassLoader = new URLClassLoader(new URL[]{networkPrivateBin.toURI().toURL()});
}
catch (final MalformedURLException e)
{
// If this fails, that's fine, just means we don't have private code available
}
}
}
//-------------------------------------------------------------------------
/**
* @return Constructs a wrapper around the remote dialog functions functions.
*/
public static RemoteDialogFunctionsPublic construct()
{
// See if we can find private code first
final ClassLoader classLoader =
privateNetworkCodeClassLoader != null ? privateNetworkCodeClassLoader : RemoteDialogFunctionsPublic.class.getClassLoader();
try
{
final Class<?> privateClass = Class.forName("app.display.dialogs.remote.util.RemoteDialogFunctionsPrivate", true, classLoader);
if (privateClass != null)
{
// Found private network code, use its zero-args constructor
return (RemoteDialogFunctionsPublic) privateClass.getConstructor().newInstance();
}
}
catch (final Exception e)
{
// Nothing to do
}
// Failed to load the private class, so we're probably working just with public source code
return new RemoteDialogFunctionsPublic();
}
//-------------------------------------------------------------------------
/**
* Show the remote dialog.
*/
@SuppressWarnings("static-method")
public void showRemoteDialog(final PlayerApp app)
{
app.addTextToStatusPanel("Sorry. Remote play functionality is not available from the source code.\n");
}
/**
* Refresh the remote dialog display.
*/
public void refreshNetworkDialog()
{
// Do nothing.
}
/**
* Leave current online game and update all required GUI elements.
*/
public void leaveGameUpdateGui(final Manager manager)
{
// Do nothing.
}
//-------------------------------------------------------------------------
}
| 2,766 | 26.39604 | 130 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/ReportMessengerGUI.java
|
package app.utils;
import java.awt.EventQueue;
import app.PlayerApp;
import main.grammar.Report.ReportMessenger;
/**
* Report Messenger implementation for the GUI.
*
* @author Matthew.Stephenson
*/
public class ReportMessengerGUI implements ReportMessenger
{
private final PlayerApp app;
//-------------------------------------------------------------------------
public ReportMessengerGUI(final PlayerApp app)
{
super();
this.app = app;
}
//-------------------------------------------------------------------------
@Override
public void printMessageInStatusPanel(final String s)
{
try
{
EventQueue.invokeLater(() ->
{
app.addTextToStatusPanel(s);
});
}
catch (final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
@Override
public void printMessageInAnalysisPanel(final String s)
{
try
{
EventQueue.invokeLater(() ->
{
app.addTextToAnalysisPanel(s);
});
}
catch (final Exception e)
{
e.printStackTrace();
}
}
//-------------------------------------------------------------------------
}
| 1,157 | 16.815385 | 76 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/SVGUtil.java
|
package app.utils;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.batik.gvt.renderer.ImageRenderer;
import org.apache.batik.transcoder.SVGAbstractTranscoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.ImageTranscoder;
/**
* Functions for helping out the SVG rendering
*
* @author Matthew Stephenson
*/
public class SVGUtil
{
//-------------------------------------------------------------------------
public static BufferedImage createSVGImage(final String imageEntry, final double width, final double height)
{
final BufferedImage[] imagePointer = new BufferedImage[1];
// Need this check in case of boardless board.
if (imageEntry.length() > 0)
{
try
{
final InputStream inputStream = new ByteArrayInputStream(imageEntry.getBytes(StandardCharsets.UTF_8));
final TranscoderInput input = new TranscoderInput(inputStream);
final ImageTranscoder t = new ImageTranscoder()
{
@Override
protected ImageRenderer createRenderer() {
final ImageRenderer r = super.createRenderer();
final RenderingHints rh = r.getRenderingHints();
rh.add(new RenderingHints(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY));
rh.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC));
rh.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
rh.add(new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_QUALITY));
rh.add(new RenderingHints(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_DISABLE));
rh.add(new RenderingHints(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY));
rh.add(new RenderingHints(RenderingHints.KEY_STROKE_CONTROL,
RenderingHints.VALUE_STROKE_PURE));
rh.add(new RenderingHints(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON));
rh.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
r.setRenderingHints(rh);
return r;
}
@Override
public BufferedImage createImage(final int w, final int h)
{
return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
}
@Override
public void writeImage(final BufferedImage img, final TranscoderOutput output)
{
imagePointer[0] = img;
}
};
t.addTranscodingHint(ImageTranscoder.KEY_FORCE_TRANSPARENT_WHITE, Boolean.FALSE);
if (width > 0 && height > 0)
{
t.addTranscodingHint(SVGAbstractTranscoder.KEY_WIDTH, Float.valueOf((float)width));
t.addTranscodingHint(SVGAbstractTranscoder.KEY_HEIGHT, Float.valueOf((float)height));
}
t.transcode(input, null);
}
catch (final TranscoderException ex)
{
// ex.printStackTrace();
}
}
return imagePointer[0];
}
//-------------------------------------------------------------------------
}
| 4,181 | 38.45283 | 115 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/SettingsExhibition.java
|
package app.utils;
/**
* Exhibition (in-depth) application settings
*
* @author Matthew.Stephenson
*/
public class SettingsExhibition
{
/** If the app should be loaded in the exhibition display
* format. */
public static final boolean exhibitionVersion = false;
/** The resolution of the app (some aspects may be hard-coded to this size). */
public static final int exhibitionDisplayWidth = 1920;
public static final int exhibitionDisplayHeight = 1080;
/** If Player 2 should be controlled by an AI agent. */
public static final boolean againstAI = true;
public static final double thinkingTime = 2.0;
/** The game to load (there exists both an English and Swedish version of each game). */
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Baghchal Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Hnefatafl Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Mu Torere Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Mweso Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Nard Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Papan Dakon Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Sahkku Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Senet Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Shatranj Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Shodra Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Toguz Kumalak Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Wari Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Weiqi Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Xiangqi Exhibition English.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Baghchal Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Hnefatafl Exhibition Swedish.lud";
public static final String exhibitionGamePath = "/lud/wip/exhibition/Mu Torere Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Mweso Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Nard Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Papan Dakon Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Sahkku Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Senet Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Shatranj Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Shodra Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Toguz Kumalak Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Wari Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Weiqi Exhibition Swedish.lud";
// public static final String exhibitionGamePath = "/lud/wip/exhibition/Xiangqi Exhibition Swedish.lud";
}
| 3,662 | 68.113208 | 110 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/SettingsPlayer.java
|
package app.utils;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import app.move.MoveFormat;
import app.move.animation.AnimationParameters;
import app.move.animation.MoveAnimation;
import game.equipment.component.Component;
import other.move.Move;
import policies.softmax.SoftmaxFromMetadataSelection;
/**
* Settings for the current player.
*
* @author Matthew and cambolbro
*/
public class SettingsPlayer
{
/** Default X and Y values for placing the frame (loaded from preferences). */
private int defaultX = -1;
private int defaultY = -1;
/** Whether the fame should be maximised (loaded from preferences). */
private boolean frameMaximised = false;
/** True if the Developer cursor tooltip is to be shown. */
private boolean cursorTooltipDev = false;
/** True if we should play a sound effect after each move. */
private boolean moveSoundEffect = false;
/** Font size for the text area. */
private int tabFontSize = 13;
/** Font size for the text area. */
private int editorFontSize = 13;
private boolean editorParseText = true;
/** Format for printing moves (Move, Full, Short). */
private MoveFormat moveFormat = MoveFormat.Move;
/** Strings entered into the TestLudemeDialog, to be saved in preferences. */
private String testLudeme1 = "";
private String testLudeme2 = "";
private String testLudeme3 = "";
private String testLudeme4 = "";
/** If the zoomBox (magnifying glass) should be shown. */
private boolean showZoomBox = false;
/** If we should display moves using coord rather than index */
private boolean moveCoord = true;
/** number of walks to increment the drag piece image by when rotating. */
private int currentWalkExtra = 0;
/** Show the board. */
private boolean showBoard = true;
/** Show the pieces. */
private boolean showPieces = true;
/** Show the graph. */
private boolean showGraph = false;
/** Show the dual. */
private boolean showConnections = false;
/** Show the board axes. */
private boolean showAxes = false;
/** Tab currently selected. */
private int tabSelected = 0;
//-------------------------------------------------------------------------
// Web player settings
/** Store the results of this game in the DB */
private boolean webGameResultValid = true;
/** If played index has always been an agent */
private final boolean[] agentArray = {false,false,false,false,false,false,false,false,false,false,
false,false,false,false,false,false,false,false,false,false};
//-------------------------------------------------------------------------
// MYOG player settings
// If the exhibition app if being used
private boolean usingExhibitionApp = false;
// Placement of the board and its white margin. Used for detecting whether move to hands is done.
private Rectangle boardPlacement = new Rectangle();
private Rectangle boardMarginPlacement = new Rectangle();
private String lastGeneratedGameEnglishRules = "";
//-------------------------------------------------------------------------
// User settings
/** For puzzles whether to show the dialog, cycle through, or decide automatically. */
private PuzzleSelectionType puzzleDialogOption = PuzzleSelectionType.Automatic;
/** Visualize AI's distribution over moves on the game board */
private boolean showAIDistribution = false;
/** Visualize the last move made on the game board */
private boolean showLastMove = false;
/** Visualize any ending moves made on the game board */
private boolean showEndingMove = true;
private boolean swapRule = false;
private boolean noRepetition = false;
private boolean noRepetitionWithinTurn = false;
/** Hide the moves of the AI if this is a hidden information game.
Only applied in games where just one of the players is a human. */
private boolean hideAiMoves = true;
/** If true, whenever we save a trial, we also save a CSV file with heuristic evaluations of game states */
private boolean saveHeuristics = false;
/** If true, whenever the user clicks (or drags between) one or two sites, we print active features for matching moves */
private boolean printMoveFeatures = false;
/** If true, whenever the user clicks (or drags between) one or two sites, we print active feature instances for matching moves */
private boolean printMoveFeatureInstances = false;
/** Object we can use to compute active features for printing purposes */
private final SoftmaxFromMetadataSelection featurePrintingSoftmax = new SoftmaxFromMetadataSelection(0.0);
private boolean devMode = false;
private AnimationVisualsType animationType = AnimationVisualsType.None;
/** Shows the name of the phase in the frame title. */
private boolean showPhaseInTitle = false;
//-------------------------------------------------------------------------
// Editor settings
/** Whether the editor should show possible autocomplete options. */
private boolean editorAutocomplete = true;
//-------------------------------------------------------------------------
// Animation settings
private AnimationParameters animationParameters = null;
/** Timer object used for animating moves. */
private Timer animationTimer = new Timer();
/** The number of frames still to go for the current animation. */
private int drawingMovingPieceTime = MoveAnimation.MOVE_PIECE_FRAMES;
//-------------------------------------------------------------------------
// Information about the component being dragged.
/** Component currently being dragged. */
private Component dragComponent = null;
/** State of the dragged component. */
private int dragComponentState = 1;
/** Original mouse position at the start of the drag. */
private Point oldMousePoint = new Point(0,0);
/** If a component is currently selected. */
private boolean componentIsSelected = false;
//-------------------------------------------------------------------------
// Tutorial visualisation
private boolean performingTutorialVisualisation = false;
/** Only used for tutorial generation purposes. */
private List<Move> tutorialVisualisationMoves = new ArrayList<>();
//-------------------------------------------------------------------------
// Other
/** Whether illegal moves are allowed to be made. */
private boolean illegalMovesValid = false;
/** The last error message that was reported. Stored to prevent the same error message being repeated multiple times. */
private String lastErrorMessage = "";
/** If the trial should be saved after every move. */
private boolean saveTrialAfterMove = false;
/** whether or not the preferences have been loaded successfully. */
private boolean preferencesLoaded = false;
/** most recent games that have been loaded, used for menu option. */
private String[] recentGames = {null,null,null,null,null,null,null,null,null,null};
/** If the last game was loaded from memory. */
private boolean loadedFromMemory = false;
private String savedStatusTabString = "";
private boolean sandboxMode = false;
//-------------------------------------------------------------------------
public boolean isMoveCoord()
{
return moveCoord;
}
public void setMoveCoord(final boolean moveCoord)
{
this.moveCoord = moveCoord;
}
public int defaultX()
{
return defaultX;
}
public void setDefaultX(final int x)
{
defaultX = x;
}
public int defaultY()
{
return defaultY;
}
public void setDefaultY(final int y)
{
defaultY = y;
}
public boolean frameMaximised()
{
return frameMaximised;
}
public void setFrameMaximised(final boolean max)
{
frameMaximised = max;
}
public boolean cursorTooltipDev()
{
return cursorTooltipDev;
}
public void setCursorTooltipDev(final boolean value)
{
cursorTooltipDev = value;
}
public int tabFontSize()
{
return tabFontSize;
}
public void setTabFontSize(final int size)
{
tabFontSize = size;
}
public int editorFontSize()
{
return editorFontSize;
}
public void setEditorFontSize(final int size)
{
editorFontSize = size;
}
public MoveFormat moveFormat()
{
return moveFormat;
}
public void setMoveFormat(final MoveFormat format)
{
moveFormat = format;
}
public String testLudeme1()
{
return testLudeme1;
}
public void setTestLudeme1(final String test1)
{
testLudeme1 = test1;
}
public String testLudeme2()
{
return testLudeme2;
}
public void setTestLudeme2(final String test2)
{
testLudeme2 = test2;
}
public String testLudeme3()
{
return testLudeme3;
}
public void setTestLudeme3(final String test3)
{
testLudeme3 = test3;
}
public String testLudeme4()
{
return testLudeme4;
}
public void setTestLudeme4(final String test4)
{
testLudeme4 = test4;
}
public boolean showZoomBox()
{
return showZoomBox;
}
public void setShowZoomBox(final boolean show)
{
showZoomBox = show;
}
public int currentWalkExtra()
{
return currentWalkExtra;
}
public void setCurrentWalkExtra(final int currentWalkExtra)
{
this.currentWalkExtra = currentWalkExtra;
}
public boolean showBoard()
{
return showBoard;
}
public void setShowBoard(final boolean show)
{
showBoard = show;
}
public boolean showPieces()
{
return showPieces;
}
public void setShowPieces(final boolean show)
{
showPieces = show;
}
public boolean showGraph()
{
return showGraph;
}
public void setShowGraph(final boolean show)
{
showGraph = show;
}
public boolean showConnections()
{
return showConnections;
}
public void setShowConnections(final boolean show)
{
showConnections = show;
}
public boolean showAxes()
{
return showAxes;
}
public void setShowAxes(final boolean show)
{
showAxes = show;
}
public PuzzleSelectionType puzzleDialogOption()
{
return puzzleDialogOption;
}
public void setPuzzleDialogOption(final PuzzleSelectionType puzzleDialogOption)
{
this.puzzleDialogOption = puzzleDialogOption;
}
public boolean showAIDistribution()
{
return showAIDistribution;
}
public void setShowAIDistribution(final boolean show)
{
showAIDistribution = show;
}
public boolean showLastMove()
{
return showLastMove;
}
public void setShowLastMove(final boolean show)
{
showLastMove = show;
}
public boolean showEndingMove()
{
return showEndingMove;
}
public void setShowEndingMove(final boolean show)
{
showEndingMove = show;
}
public boolean swapRule()
{
return swapRule;
}
public void setSwapRule(final boolean swap)
{
swapRule = swap;
}
public boolean noRepetition()
{
return noRepetition;
}
public void setNoRepetition(final boolean no)
{
noRepetition = no;
}
public boolean noRepetitionWithinTurn()
{
return noRepetitionWithinTurn;
}
public void setNoRepetitionWithinTurn(final boolean no)
{
noRepetitionWithinTurn = no;
}
public boolean hideAiMoves()
{
return hideAiMoves;
}
public void setHideAiMoves(final boolean hide)
{
hideAiMoves = hide;
}
public boolean saveHeuristics()
{
return saveHeuristics;
}
public void setSaveHeuristics(final boolean save)
{
saveHeuristics = save;
}
/**
* @return Do we want to print move features?
*/
public boolean printMoveFeatures()
{
return printMoveFeatures;
}
/**
* @return Do we want to print move feature instances?
*/
public boolean printMoveFeatureInstances()
{
return printMoveFeatureInstances;
}
/**
* Sets whether we want to print move features
* @param val
*/
public void setPrintMoveFeatures(final boolean val)
{
printMoveFeatures = val;
}
/**
* Sets whether we want to print move feature instances
* @param val
*/
public void setPrintMoveFeatureInstances(final boolean val)
{
printMoveFeatureInstances = val;
}
/**
* @return The softmax object we can use for computing features to print
*/
public SoftmaxFromMetadataSelection featurePrintingSoftmax()
{
return featurePrintingSoftmax;
}
public boolean devMode()
{
return devMode;
}
public void setDevMode(final boolean value)
{
devMode = value;
}
public Component dragComponent()
{
return dragComponent;
}
public void setDragComponent(final Component drag)
{
dragComponent = drag;
}
public int dragComponentState()
{
return dragComponentState;
}
public void setDragComponentState(final int drag)
{
dragComponentState = drag;
}
public Point oldMousePoint()
{
return oldMousePoint;
}
public void setOldMousePoint(final Point old)
{
oldMousePoint = old;
}
public boolean illegalMovesValid()
{
return illegalMovesValid;
}
public void setIllegalMovesValid(final boolean illegal)
{
illegalMovesValid = illegal;
}
public String lastErrorMessage()
{
return lastErrorMessage;
}
public void setLastErrorMessage(final String last)
{
lastErrorMessage = last;
}
public boolean editorAutocomplete()
{
return editorAutocomplete;
}
public void setEditorAutocomplete(final boolean editor)
{
editorAutocomplete = editor;
}
public boolean componentIsSelected()
{
return componentIsSelected;
}
public void setComponentIsSelected(final boolean componentIsSelected)
{
this.componentIsSelected = componentIsSelected;
}
public boolean isMoveSoundEffect()
{
return moveSoundEffect;
}
public void setMoveSoundEffect(final boolean moveSoundEffect)
{
this.moveSoundEffect = moveSoundEffect;
}
public AnimationVisualsType animationType()
{
return animationType;
}
public void setAnimationType(final AnimationVisualsType animationType)
{
this.animationType = animationType;
}
public boolean showAnimation()
{
return animationType != AnimationVisualsType.None;
}
public Timer getAnimationTimer()
{
return animationTimer;
}
public void setAnimationTimer(final Timer animationTimer)
{
this.animationTimer = animationTimer;
}
public int getDrawingMovingPieceTime()
{
return drawingMovingPieceTime;
}
public void setDrawingMovingPieceTime(final int drawingMovingPieceTime)
{
this.drawingMovingPieceTime = drawingMovingPieceTime;
}
public boolean saveTrialAfterMove()
{
return saveTrialAfterMove;
}
public void setSaveTrialAfterMove(final boolean saveTrialAfterMove)
{
this.saveTrialAfterMove = saveTrialAfterMove;
}
public boolean preferencesLoaded()
{
return preferencesLoaded;
}
public void setPreferencesLoaded(final boolean preferencesLoaded)
{
this.preferencesLoaded = preferencesLoaded;
}
public String[] recentGames()
{
return recentGames;
}
public void setRecentGames(final String[] recentGames)
{
this.recentGames = recentGames;
}
public boolean loadedFromMemory()
{
return loadedFromMemory;
}
public void setLoadedFromMemory(final boolean loadedFromMemory)
{
this.loadedFromMemory = loadedFromMemory;
}
public String savedStatusTabString()
{
return savedStatusTabString;
}
public void setSavedStatusTabString(final String savedStatusTabString)
{
this.savedStatusTabString = savedStatusTabString;
}
public AnimationParameters animationParameters()
{
return animationParameters;
}
public void setAnimationParameters(final AnimationParameters animationParameters)
{
this.animationParameters = animationParameters;
}
public int tabSelected()
{
return tabSelected;
}
public void setTabSelected(final int tabSelected)
{
this.tabSelected = tabSelected;
}
public boolean sandboxMode()
{
return sandboxMode;
}
public void setSandboxMode(final boolean sandboxMode)
{
this.sandboxMode = sandboxMode;
}
public boolean isPerformingTutorialVisualisation()
{
return performingTutorialVisualisation;
}
public void setPerformingTutorialVisualisation(final boolean performingTutorialVisualisation)
{
this.performingTutorialVisualisation = performingTutorialVisualisation;
}
public List<Move> tutorialVisualisationMoves()
{
return tutorialVisualisationMoves;
}
public void setTutorialVisualisationMoves(final List<Move> tutorialVisualisationMoves)
{
this.tutorialVisualisationMoves = tutorialVisualisationMoves;
}
public boolean showPhaseInTitle()
{
return showPhaseInTitle;
}
public void setShowPhaseInTitle(final boolean showPhaseInTitle)
{
this.showPhaseInTitle = showPhaseInTitle;
}
public boolean isEditorParseText()
{
return editorParseText;
}
public void setEditorParseText(final boolean editorParseText)
{
this.editorParseText = editorParseText;
}
public boolean[] agentArray()
{
return agentArray;
}
public void setAgentArray(final int i, final boolean b)
{
agentArray[i] = b;
}
public boolean isWebGameResultValid()
{
return webGameResultValid;
}
public void setWebGameResultValid(final boolean webGameResultValid)
{
this.webGameResultValid = webGameResultValid;
}
public boolean usingMYOGApp()
{
return usingExhibitionApp;
}
public void setUsingExhibitionApp(final boolean usingExhibitionApp)
{
this.usingExhibitionApp = usingExhibitionApp;
}
public Rectangle boardPlacement()
{
return boardPlacement;
}
public void setBoardPlacement(final Rectangle boardPlacement)
{
this.boardPlacement = boardPlacement;
}
public Rectangle boardMarginPlacement()
{
return boardMarginPlacement;
}
public void setBoardMarginPlacement(final Rectangle boardMarginPlacement)
{
this.boardMarginPlacement = boardMarginPlacement;
}
public String lastGeneratedGameEnglishRules()
{
return lastGeneratedGameEnglishRules;
}
public void setLastGeneratedGameEnglishRules(final String lastGeneratedGameEnglishRules)
{
this.lastGeneratedGameEnglishRules = lastGeneratedGameEnglishRules;
}
//-------------------------------------------------------------------------
}
| 17,783 | 20.272727 | 131 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/Sound.java
|
package app.utils;
import java.io.BufferedInputStream;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
/**
* Functions relating to the playing of sounds/music.
*
* @author Matthew.Stephenson
*/
public class Sound
{
//-------------------------------------------------------------------------
// /**
// * Play a specific sound once.
// */
// public static synchronized void playSound(final String soundName)
// {
// final String soundPath = "../Common/res/audio/" + soundName + ".wav";
//
// new Thread(new Runnable()
// {
// // Audio playing doesn't work with standard try-with-resource approach.
// // https://stackoverflow.com/questions/25564980/java-use-a-clip-and-a-try-with-resources-block-which-results-with-no-sound
// @SuppressWarnings("resource")
// @Override
// public void run()
// {
// try
// {
// final AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(soundPath));
// final DataLine.Info info = new DataLine.Info(Clip.class, inputStream.getFormat());
// final Clip clip = (Clip)AudioSystem.getLine(info);
// clip.open(inputStream);
// clip.start();
// }
// catch (final Exception e)
// {
// e.printStackTrace();
// }
// }
// }).start();
// }
/**
* Play a specific sound once.
*/
public static synchronized void playSound(final String soundName)
{
final String soundPath = "/" + soundName + ".wav";
new Thread(new Runnable()
{
// Audio playing doesn't work with standard try-with-resource approach.
// https://stackoverflow.com/questions/25564980/java-use-a-clip-and-a-try-with-resources-block-which-results-with-no-sound
@SuppressWarnings("resource")
@Override
public void run()
{
try
{
final Clip clip = AudioSystem.getClip();
final InputStream is = Sound.class.getResourceAsStream(soundPath);
final BufferedInputStream bufferedIS = new BufferedInputStream(is);
final AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(bufferedIS);
clip.open(audioInputStream);
clip.start();
bufferedIS.close();
audioInputStream.close();
// Close the clip only once it has finished playing.
clip.addLineListener(new LineListener()
{
@Override
public void update(final LineEvent event)
{
if (event.getType() == LineEvent.Type.STOP)
clip.close();
}
});
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}).start();
}
}
| 2,766 | 26.949495 | 127 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/Spinner.java
|
package app.utils;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Arc2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Timer;
/**
* Functions for the spinner graphic
*
* @author cambolbro and matthew.stephenson
*/
public class Spinner
{
//-------------------------------------------------------------------------
// parameters relating to the spinning loading icon.
private int numPts = 12;
private double dotRadius = 1.5;
private Rectangle2D.Double originalRect = new Rectangle2D.Double();
private final Rectangle spinRect = new Rectangle();
private final List<Point2D.Double> spinPts = new ArrayList<>();
private Timer spinTimer = null;
int spinTicks = -1;
//-------------------------------------------------------------------------
public Spinner(final Rectangle2D.Double bounds)
{
originalRect = bounds;
final int r = (int) (bounds.getWidth()/2);
final int cx = (int) (bounds.getX() + r);
final int cy = (int) (bounds.getY() + r);
for (int n = 0; n < numPts-1; n++)
{
final double t = n / (double)(numPts - 1);
final double x = cx + r * Math.sin(t * 2 * Math.PI);
final double y = cy - r * Math.cos(t * 2 * Math.PI);
spinPts.add(new Point2D.Double(x, y));
}
spinRect.setBounds(cx - 2*r, cy - 2*r, 4 * r , 4 * r);
}
//-------------------------------------------------------------------------
public void startSpinner()
{
if (spinTimer != null)
return;
spinTicks = 0;
final int ms = (int)(1.0 / numPts * 1000);
spinTimer = new Timer(ms, spinTimerAction);
spinTimer.start();
}
//-------------------------------------------------------------------------
public void stopSpinner()
{
if (spinTimer != null)
{
spinTimer.stop();
spinTimer = null;
}
spinTicks = -1;
}
//-------------------------------------------------------------------------
public void drawSpinner(final Graphics2D g2d)
{
if (spinTicks < 0)
return;
for (int n = 0; n < numPts; n++)
{
final int dotAt = spinTicks - n;
if (dotAt < 0)
continue;
final Point2D.Double pt = spinPts.get(dotAt % spinPts.size());
final java.awt.Shape dot = new Arc2D.Double(pt.x-dotRadius, pt.y-dotRadius, 2*dotRadius+1, 2*dotRadius+1, 0, 360, 0);
final double t = Math.pow((numPts - n) / (double)numPts, 3);
final int alpha = (int)(t * 255);
final Color dotColour = new Color(160, 160, 160, alpha);
g2d.setColor(dotColour);
g2d.fill(dot);
}
}
//-------------------------------------------------------------------------
ActionListener spinTimerAction = new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e)
{
spinTicks++;
}
};
//-------------------------------------------------------------------------
public Rectangle2D.Double originalRect()
{
return originalRect;
}
public void setDotRadius(double dotRadius)
{
this.dotRadius = dotRadius;
}
public void setNumPts(int numPts)
{
this.numPts = numPts;
}
//-------------------------------------------------------------------------
}
| 3,325 | 22.757143 | 120 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/TrialUtil.java
|
package app.utils;
import java.util.List;
import manager.Manager;
import other.context.Context;
import other.move.Move;
/**
* Functions to help with Trials.
*
* @author Matthew.Stephenson
*/
public class TrialUtil
{
//-------------------------------------------------------------------------
/**
* Returns the index of the start of the current trial, within the complete game trial (used for matches).
*/
public static int getInstanceStartIndex(final Context context)
{
final int numInitialPlacementMoves = context.currentInstanceContext().trial().numInitialPlacementMoves();
final int startIndex = context.trial().numMoves() - context.currentInstanceContext().trial().numMoves() + numInitialPlacementMoves;
return startIndex;
}
//-------------------------------------------------------------------------
/**
* Returns the index of the end of the current trial, within the complete game trial (used for matches).
*/
public static int getInstanceEndIndex(final Manager manager, final Context context)
{
final List<Move> allMoves = manager.ref().context().trial().generateCompleteMovesList();
allMoves.addAll(manager.undoneMoves());
if (context.isAMatch())
{
int endOfInstance = context.trial().numMoves();
while (endOfInstance < allMoves.size())
{
if (allMoves.get(endOfInstance).containsNextInstance())
break;
endOfInstance++;
}
return endOfInstance;
}
return allMoves.size();
}
//-------------------------------------------------------------------------
}
| 1,555 | 25.827586 | 133 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/UpdateTabMessages.java
|
package app.utils;
import app.PlayerApp;
import game.Game;
import game.equipment.component.Component;
import game.functions.booleans.is.component.IsThreatened;
import game.functions.ints.IntConstant;
import other.action.Action;
import other.context.Context;
import other.move.Move;
import other.topology.TopologyElement;
import other.trial.Trial;
public class UpdateTabMessages
{
public static void postMoveUpdateStatusTab(final PlayerApp app)
{
final Context context = app.manager().ref().context();
final Trial trial = context.trial();
final Game game = context.game();
final int moveNumber = context.trial().numMoves()-1;
final Move lastMove = (moveNumber >= 0) ? trial.getMove(moveNumber) : null;
int nextMover = context.state().mover();
if (trial.numMoves() > moveNumber + 1)
nextMover = trial.getMove(moveNumber + 1).mover();
String statusString = "";
// Display check message
if (!game.isDeductionPuzzle())
{
final int indexMover = context.state().mover();
for (final TopologyElement element : context.board().topology().getAllGraphElements())
{
final int indexPiece = context.containerState(0).what(element.index(), element.elementType());
if (indexPiece != 0)
{
final Component component = context.components()[indexPiece];
if (game.metadata().graphics().checkUsed(context, indexMover, component.name()))
{
boolean check = false;
final IsThreatened threat = new IsThreatened(new IntConstant(indexPiece), element.elementType(),
new IntConstant(element.index()), null, null);
threat.preprocess(context.game());
check = threat.eval(context);
if (check)
app.setTemporaryMessage("Check.");
}
}
}
}
// Display Note action message
if (lastMove != null)
for (final Action action : lastMove.actions())
if (action.message() != null)
if (action.who() == context.state().mover())
statusString += "Note for Player " + action.who() + ": " + action.message() + ".\n";
if (lastMove != null && lastMove.isSwap())
app.setTemporaryMessage("Player " + lastMove.mover() + " made a swap move.");
// Check if any player has just lost or won
for (int i = 1; i <= game.players().count(); i++)
{
// Network
if (!(context.active(i)) && app.manager().settingsNetwork().activePlayers()[i])
{
app.manager().settingsNetwork().activePlayers()[i] = false;
if (app.manager().settingsNetwork().getActiveGameId() != 0)
{
final double[] tempRanking = new double[trial.ranking().length];
for (int j = 0; j < trial.ranking().length; j++)
tempRanking[j] = trial.ranking()[j];
for (int player = 1; player < trial.ranking().length; player++)
if (trial.ranking()[player] == 0.0)
tempRanking[player] = 1000;
app.manager().databaseFunctionsPublic().sendGameRankings(app.manager(), tempRanking);
}
}
// Local
if (!context.trial().over() && !context.active(i) && app.contextSnapshot().getContext(app).active(i))
{
if (context.computeNextDrawRank() > trial.ranking()[i])
statusString += context.getPlayerName(i) + " has achieved a win.\n";
else if (context.computeNextDrawRank() < context.trial().ranking()[i])
statusString += context.getPlayerName(i) + " has sufferred a loss.\n";
else
statusString += context.getPlayerName(i) + " has been given a draw.\n";
}
}
// Show next player to move
if (!context.trial().over() && nextMover < game.players().size())
statusString += app.manager().aiSelected()[app.manager().playerToAgent(nextMover)].name() + " to move.\n";
app.addTextToStatusPanel(statusString);
}
//-----------------------------------------------------------------------------
public static String gameOverMessage(final Context context, final Trial trial)
{
final Game game = context.game();
// This move wins the game
final int winner = trial.status().winner();
final int nbPlayers = context.game().players().count();
String str = "";
if (winner == 0)// DRAW
{
final double[] ranks = trial.ranking();
boolean allWin = true;
for (int i = 1; i < ranks.length; i++)
if (ranks[i] != 1.0)
allWin = false;
if (nbPlayers == 1 && allWin)
str += "Congratulations, puzzle solved!\n";
else if (nbPlayers == 1)
str += "Game Over, you lose!\n";
else
str += "Game won by no one" + ".\n";
if (game.checkMaxTurns(context))
str += "Maximum number of moves reached" + ".\n";
}
else if (winner == -1) // ABORT
str += "Game aborted" + ".\n";
else if (winner > game.players().count()) // TIE
str += "Game won by everyone" + ".\n";
else // WIN
{
if (nbPlayers == 1)
str += "Congratulations, puzzle solved!\n";
else
{
if (game.requiresTeams())
str += "Game won by team " + context.state().getTeam(winner) + ".\n";
else
str += "Game won by " + context.getPlayerName(winner) + ".\n";
}
}
if (game.players().count() >= 3) // Rankings
{
for (int i = 1; i <= game.players().count(); i++)
{
boolean anyPlayers = false;
str += "Rank " + (i) + ": ";
for (int j = 1; j <= game.players().count(); j++)
{
final double rank = trial.ranking()[j];
if (Math.floor(rank) == i)
{
if (!anyPlayers)
{
str += context.getPlayerName(j);
anyPlayers = true;
}
else
{
str += ", " + context.getPlayerName(j);
}
}
}
if (!anyPlayers)
str += "No one\n";
else
str += "\n";
}
}
return str;
}
//-----------------------------------------------------------------------------
}
| 5,686 | 28.015306 | 109 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/sandbox/SandboxUtil.java
|
package app.utils.sandbox;
import java.awt.EventQueue;
import app.PlayerApp;
import game.equipment.component.Component;
import game.rules.play.moves.BaseMoves;
import game.rules.play.moves.Moves;
import game.types.board.SiteType;
import main.Constants;
import other.action.Action;
import other.action.move.ActionAdd;
import other.action.move.ActionInsert;
import other.action.move.move.ActionMove;
import other.action.move.remove.ActionRemove;
import other.action.state.ActionSetCount;
import other.action.state.ActionSetNextPlayer;
import other.action.state.ActionSetRotation;
import other.action.state.ActionSetState;
import other.action.state.ActionSetValue;
import other.context.Context;
import other.location.FullLocation;
import other.location.Location;
import other.move.Move;
import other.state.container.ContainerState;
import util.ContainerUtil;
/**
* Various util functions to do with the sandbox.
*
* @author Matthew.Stephenson
*/
public class SandboxUtil
{
//-------------------------------------------------------------------------
/**
* Returns an error message if sandbox is not allowed for the specified component.
*/
public static boolean isSandboxAllowed(final PlayerApp app, final Location selectedLocation)
{
final Context context = app.manager().ref().context();
final int locnUpSite = selectedLocation.site();
final SiteType locnType = selectedLocation.siteType();
final int containerId = ContainerUtil.getContainerId(context, locnUpSite, locnType);
final Component componentAtSite = context.components()[(context.containerState(containerId)).what(locnUpSite,locnType)];
if (componentAtSite != null)
{
if (componentAtSite.isDie())
{
app.setVolatileMessage("Setting dice not supported yet.");
return false;
}
if (componentAtSite.isLargePiece())
{
app.setVolatileMessage("Setting large pieces is not supported yet.");
return false;
}
}
return true;
}
//-------------------------------------------------------------------------
/**
* @return the number of buttons needed for the sandbox dialog.
*/
public static int numSandboxButtonsNeeded(final PlayerApp app, final SandboxValueType sandboxValueType)
{
final Context context = app.manager().ref().context();
int numButtonsNeeded = 0;
if (sandboxValueType == SandboxValueType.Component)
{
numButtonsNeeded = context.components().length;
}
else if (sandboxValueType == SandboxValueType.LocalState)
{
numButtonsNeeded = context.game().maximalLocalStates();
}
else if (sandboxValueType == SandboxValueType.Count)
{
numButtonsNeeded = context.game().maxCount();
}
else if (sandboxValueType == SandboxValueType.Rotation)
{
numButtonsNeeded = context.game().maximalRotationStates();
}
else if (sandboxValueType == SandboxValueType.Value)
{
numButtonsNeeded = context.game().maximalValue();
}
return numButtonsNeeded;
}
//-------------------------------------------------------------------------
/**
* Move a piece from one location to another.
*/
public static void makeSandboxDragMove(final PlayerApp app, final Location selectedFromLocation, final Location selectedToLocation)
{
final Context context = app.manager().ref().context();
try
{
final int currentMover = context.state().mover();
final int nextMover = context.state().next();
final int previousMover = context.state().prev();
final Action actionRemove = ActionMove.construct(selectedFromLocation.siteType(), selectedFromLocation.site(), selectedFromLocation.level(), selectedToLocation.siteType(), selectedToLocation.site(), selectedToLocation.level(), Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, false);
actionRemove.setDecision(true);
final Move moveToApply = new Move(actionRemove);
final Moves csq = new BaseMoves(null);
final Move nextMove = new Move(new ActionSetNextPlayer(context.state().mover()));
csq.moves().add(nextMove);
moveToApply.then().add(csq);
moveToApply.apply(context, true);
context.state().setMover(currentMover);
context.state().setNext(nextMover);
context.state().setPrev(previousMover);
}
catch (final Exception e)
{
// An invalid drag location.
}
EventQueue.invokeLater(() ->
{
app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED));
app.repaint();
});
}
//-------------------------------------------------------------------------
/**
* @return Move object corresponding to removing a piece at a specified location.
*/
public static Move getSandboxRemoveMove(final PlayerApp app, final Location selectedLocation)
{
final Context context = app.manager().ref().context();
final Action actionRemove = ActionRemove.construct(selectedLocation.siteType(), selectedLocation.site(), selectedLocation.level(), true);
actionRemove.setDecision(true);
final Move moveToApply = new Move(actionRemove);
final Moves csq = new BaseMoves(null);
final Move nextMove = new Move(new ActionSetNextPlayer(context.state().mover()));
csq.moves().add(nextMove);
moveToApply.then().add(csq);
return moveToApply;
}
//-------------------------------------------------------------------------
/**
* @return Move object corresponding to adding a piece at a specified location.
*/
public static Move getSandboxAddMove(final PlayerApp app, final Location selectedLocation, final int componentIndex)
{
final Context context = app.manager().ref().context();
final Action actionAdd = new ActionAdd(selectedLocation.siteType(), selectedLocation.site(), componentIndex, 1, Constants.UNDEFINED, Constants.UNDEFINED, Constants.UNDEFINED, null);
actionAdd.setDecision(true);
final Move moveToApply = new Move(actionAdd);
final Moves csq = new BaseMoves(null);
final Move nextMove = new Move(new ActionSetNextPlayer(context.state().mover()));
csq.moves().add(nextMove);
moveToApply.then().add(csq);
return moveToApply;
}
//-------------------------------------------------------------------------
/**
* @return Move object corresponding to inserting a piece at a specified location.
*/
public static Move getSandboxInsertMove(final PlayerApp app, final Location selectedLocation, final int componentIndex)
{
final Context context = app.manager().ref().context();
final Action actionInsert = new ActionInsert(selectedLocation.siteType(), selectedLocation.site(), selectedLocation.level()+1, componentIndex, 1);
actionInsert.setDecision(true);
final Move moveToApply = new Move(actionInsert);
final Moves csq = new BaseMoves(null);
final Move nextMove = new Move(new ActionSetNextPlayer(context.state().mover()));
csq.moves().add(nextMove);
moveToApply.then().add(csq);
return moveToApply;
}
//-------------------------------------------------------------------------
/**
* @return Move object corresponding to setting a piece's variable at a specified location.
*/
public static Move getSandboxVariableMove(final PlayerApp app, final Location selectedLocation, final SandboxValueType sandboxValueType, final int value)
{
final Context context = app.manager().ref().context();
final int locnUpSite = selectedLocation.site();
final int locnLevel = selectedLocation.level();
final SiteType locnType = selectedLocation.siteType();
final int containerId = ContainerUtil.getContainerId(context, locnUpSite, locnType);
final ContainerState cs = context.state().containerStates()[containerId];
// Determine the action based on the type.
Action action = null;
if (sandboxValueType == SandboxValueType.LocalState)
{
action = new ActionSetState(locnType, locnUpSite, locnLevel, value);
}
else if (sandboxValueType == SandboxValueType.Count)
{
action = new ActionSetCount(locnType, locnUpSite, cs.what(locnUpSite, locnLevel, locnType), value);
}
else if (sandboxValueType == SandboxValueType.Value)
{
action = new ActionSetValue(locnType, locnUpSite, locnLevel, value);
}
else if (sandboxValueType == SandboxValueType.Rotation)
{
action = new ActionSetRotation(locnType, locnUpSite, value);
}
action.setDecision(true);
final Move moveToApply = new Move(action);
final Moves csq = new BaseMoves(null);
final Move nextMove = new Move(new ActionSetNextPlayer(context.state().mover()));
csq.moves().add(nextMove);
moveToApply.then().add(csq);
return moveToApply;
}
//-------------------------------------------------------------------------
}
| 8,551 | 33.345382 | 300 |
java
|
Ludii
|
Ludii-master/Player/src/app/utils/sandbox/SandboxValueType.java
|
package app.utils.sandbox;
/**
* All the types of values that can be altered by the Sandbox dialog.
*
* @author Matthew.Stephenson
*/
public enum SandboxValueType
{
Component,
LocalState,
Value,
Count,
Rotation;
}
| 225 | 13.125 | 69 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/BoardView.java
|
package app.views;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import app.PlayerApp;
import app.move.MoveVisuals;
import app.utils.SettingsExhibition;
import other.context.Context;
import util.PlaneType;
//-----------------------------------------------------------------------------
/**
* Panel showing the game board.
*
* @author Matthew.Stephenson and cambolbro
*/
public final class BoardView extends View
{
// maximum percentage of application display width that board can take up
private final double boardToSizeRatio = 1.0;
/** Size of the board. */
private final int boardSize;
//-------------------------------------------------------------------------
public BoardView(final PlayerApp app, final boolean exhibitionMode)
{
super(app);
if (exhibitionMode)
{
boardSize = Math.min(app.height(), (int) (app.width() * boardToSizeRatio));
placement = new Rectangle(app.width()-boardSize + 30, 30, boardSize, boardSize);
app.bridge().getContainerStyle(0).setDefaultBoardScale(0.7);
}
else if (SettingsExhibition.exhibitionVersion)
{
boardSize = (int) (app.width() * 0.65);
placement = new Rectangle(0, 0, boardSize, boardSize);
}
else
{
boardSize = Math.min(app.height(), (int) (app.width() * boardToSizeRatio));
placement = new Rectangle(0, 0, boardSize, boardSize);
}
}
//-------------------------------------------------------------------------
@Override
public void paint(final Graphics2D g2d)
{
// Add border around board for exhibition app.
if (app.settingsPlayer().usingMYOGApp())
{
g2d.setColor(Color.black);
g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER));
g2d.fillRoundRect(placement.x + 50, placement.y + 50, placement.width - 100, placement.height - 100, 40, 40);
app.settingsPlayer().setBoardPlacement(new Rectangle(placement.x + 120, placement.y + 120, placement.width - 240, placement.height - 240));
app.settingsPlayer().setBoardMarginPlacement(new Rectangle(placement.x + 50, placement.y + 50, placement.width - 100, placement.height - 100));
}
final Context context = app.contextSnapshot().getContext(app);
app.bridge().getContainerStyle(context.board().index()).setPlacement(context, placement);
if (app.settingsPlayer().showBoard() || context.board().isBoardless())
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.BOARD, context);
if (app.settingsPlayer().showGraph())
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.GRAPH, context);
if (app.settingsPlayer().showConnections())
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.CONNECTIONS, context);
if (app.settingsPlayer().showAxes())
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.AXES, context);
if (app.settingsPlayer().showPieces())
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.COMPONENTS, context);
if (context.game().isDeductionPuzzle())
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.HINTS, context);
if (app.bridge().settingsVC().showCandidateValues() && context.game().isDeductionPuzzle())
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.CANDIDATES, context);
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.TRACK, context);
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.PREGENERATION, context);
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.INDICES, context);
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.COSTS, context);
app.bridge().getContainerStyle(context.board().index()).draw(g2d, PlaneType.POSSIBLEMOVES, context);
// Originally in the overlay view, but moved here to work with web app.
if (
app.settingsPlayer().showEndingMove()
&&
context.currentInstanceContext().trial().moveNumber() > 0
&&
context.game().endRules() != null
&&
!app.settingsPlayer().sandboxMode()
)
MoveVisuals.drawEndingMove(app, g2d, context);
paintDebug(g2d, Color.CYAN);
}
//-------------------------------------------------------------------------
@Override
public int containerIndex()
{
return app.contextSnapshot().getContext(app).board().index();
}
public int boardSize()
{
return boardSize;
}
}
| 4,525 | 34.359375 | 146 |
java
|
Ludii
|
Ludii-master/Player/src/app/views/View.java
|
package app.views;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import app.PlayerApp;
//-----------------------------------------------------------------------------
/**
* Abstract View concept for defining different sections of the Main Window
*
* @author Matthew.Stephenson and cambolbro
*/
public abstract class View
{
/** Panel's placement. */
public Rectangle placement;
private final boolean debug = false;
protected final PlayerApp app;
//-------------------------------------------------------------------------
/**
* Constructor.
*/
public View(final PlayerApp app)
{
placement = new Rectangle(0,0,app.width(),app.height());
this.app= app;
}
//-------------------------------------------------------------------------
/**
* @return Panel's placement.
*/
public Rectangle placement()
{
return placement;
}
/**
* @param rect
*/
public void setPlacement(final Rectangle rect)
{
placement = (Rectangle) rect.clone();
}
//-------------------------------------------------------------------------
/**
* Paint this panel.
*/
public abstract void paint(Graphics2D g2d);
/**
* Paint a debug rectangle around this panel.
*/
public void paintDebug(final Graphics2D g2d, final Color colour)
{
if (debug)
{
g2d.setColor(colour);
g2d.setStroke(new BasicStroke(5, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER));
g2d.drawRect(placement.x, placement.y, placement.width, placement.height);
}
}
//-------------------------------------------------------------------------
/**
* @return Index of the container associated with this view.
*/
@SuppressWarnings("static-method")
public int containerIndex()
{
return -1;
}
//-------------------------------------------------------------------------
/**
* Perform necessary functionality for cursor being on this View
*/
public void mouseOverAt(final Point pt)
{
// By default, do nothing.
}
}
| 2,035 | 19.77551 | 85 |
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.