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/AI/src/training/feature_discovery/CorrelationBasedExpander.java
package training.feature_discovery; import java.io.PrintWriter; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import features.FeatureVector; import features.feature_sets.BaseFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.impl.Constants; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TObjectDoubleHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import main.collections.FVector; import main.collections.FastArrayList; import main.collections.ListUtils; import other.move.Move; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.gradients.Gradients; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import utils.experiments.InterruptableExperiment; /** * Correlation-based Feature Set Expander. Mostly the same as the one proposed in our * CEC 2019 paper (https://arxiv.org/abs/1903.08942), possibly with some small * changes implemented since then. * * @author Dennis Soemers */ public class CorrelationBasedExpander implements FeatureSetExpander { @Override public BaseFeatureSet expandFeatureSet ( final List<? extends ExperienceSample> batch, final BaseFeatureSet featureSet, final SoftmaxPolicyLinear policy, final Game game, final int featureDiscoveryMaxNumFeatureInstances, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TDoubleArrayList featureActiveRatios, final PrintWriter logWriter, final InterruptableExperiment experiment ) { // we need a matrix C_f with, at every entry (i, j), // the sum of cases in which features i and j are both active // // we also need a similar matrix C_e with, at every entry (i, j), // the sum of errors in cases where features i and j are both active // // NOTE: both of the above are symmetric matrices // // we also need a vector X_f with, for every feature i, the sum of // cases where feature i is active. (we would need a similar vector // with sums of squares, but that can be omitted because our features // are binary) // // NOTE: in writing it is easier to mention X_f as described above as // a separate vector, but actually we don't need it; we can simply // use the main diagonal of C_f instead // // we need a scalar S which is the sum of all errors, // and a scalar SS which is the sum of all squared errors // // Given a candidate pair of features (i, j), we can compute the // correlation of that pair of features with the errors (an // indicator of the candidate pair's potential to be useful) as // (where n = the number of cases = number of state-action pairs): // // // n * C_e(i, j) - C_f(i, j) * S //------------------------------------------------------------ // SQRT( n * C_f(i, j) - C_f(i, j)^2 ) * SQRT( n * SS - S^2 ) // // // For numeric stability with extremely large batch sizes, // it is better to compute this as: // // n * C_e(i, j) - C_f(i, j) * S //------------------------------------------------------------ // SQRT( C_f(i, j) * (n - C_f(i, j)) ) * SQRT( n * SS - S^2 ) // // // We can similarly compare the correlation between any candidate pair // of features (i, j) and either of its constituents i (an indicator // of redundancy of the candidate pair) as: // // // n * C_f(i, j) - C_f(i, j) * X_f(i) //-------------------------------------------------------------------- // SQRT( n * C_f(i, j) - C_f(i, j)^2 ) * SQRT( n * X_f(i) - X_f(i)^2 ) // // // For numeric stability with extremely large batch sizes, // it is better to compute this as: // // C_f(i, j) * (n - X_f(i)) //-------------------------------------------------------------------- // SQRT( C_f(i, j) * (n - C_f(i, j)) ) * SQRT( X_f(i) * (n - X_f(i)) ) // // // (note; even better would be if we could compute correlation between // candidate pair and ANY other feature, rather than just its // constituents, but that would probably become too expensive) // // We want to maximise the absolute value of the first (correlation // between candidate feature pair and distribution error), but minimise // the worst-case absolute value of the second (correlation between // candidate feature pair and either of its constituents). // // // NOTE: in all of the above, when we say "feature", we actually // refer to a particular instantiation of a feature. This is important, // because otherwise we wouldn't be able to merge different // instantiations of the same feature into a more complex new feature // // Due to the large amount of possible pairings when considering // feature instances, we implement our "matrices" using hash tables, // and automatically ignore entries that would be 0 (they won't // be created if such pairs are never observed activating together) // System.out.println("-------------------------------------------------------------------"); int numCases = 0; // we'll increment this as we go // this is our C_f matrix final TObjectIntHashMap<CombinableFeatureInstancePair> featurePairActivations = new TObjectIntHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0); // this is our C_e matrix final TObjectDoubleHashMap<CombinableFeatureInstancePair> errorSums = new TObjectDoubleHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0.0); // these are our S and SS scalars double sumErrors = 0.0; double sumSquaredErrors = 0.0; // Create a Hash Set of features already in Feature Set; we won't // have to consider combinations that are already in final Set<SpatialFeature> existingFeatures = new HashSet<SpatialFeature> ( (int) Math.ceil(featureSet.getNumSpatialFeatures() / 0.75f), 0.75f ); for (final SpatialFeature feature : featureSet.spatialFeatures()) { existingFeatures.add(feature); } // For every sample in batch, first compute apprentice policies, errors, and sum of absolute errors final FVector[] apprenticePolicies = new FVector[batch.size()]; final FVector[] errorVectors = new FVector[batch.size()]; final float[] absErrorSums = new float[batch.size()]; final TDoubleArrayList[] errorsPerActiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; final TDoubleArrayList[] errorsPerInactiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; for (int i = 0; i < errorsPerActiveFeature.length; ++i) { errorsPerActiveFeature[i] = new TDoubleArrayList(); errorsPerInactiveFeature[i] = new TDoubleArrayList(); } double avgActionError = 0.0; for (int i = 0; i < batch.size(); ++i) { final ExperienceSample sample = batch.get(i); final FeatureVector[] featureVectors = sample.generateFeatureVectors(featureSet); final FVector apprenticePolicy = policy.computeDistribution(featureVectors, sample.gameState().mover()); final FVector errors = Gradients.computeDistributionErrors ( apprenticePolicy, sample.expertDistribution() ); for (int a = 0; a < featureVectors.length; ++a) { final float actionError = errors.get(a); final TIntArrayList sparseFeatureVector = featureVectors[a].activeSpatialFeatureIndices(); sparseFeatureVector.sort(); int sparseIdx = 0; for (int featureIdx = 0; featureIdx < featureSet.getNumSpatialFeatures(); ++featureIdx) { if (sparseIdx < sparseFeatureVector.size() && sparseFeatureVector.getQuick(sparseIdx) == featureIdx) { // This spatial feature is active errorsPerActiveFeature[featureIdx].add(actionError); // We've used the sparse index, so increment it ++sparseIdx; } else { // This spatial feature is not active errorsPerInactiveFeature[featureIdx].add(actionError); } } avgActionError += (actionError - avgActionError) / (numCases + 1); ++numCases; } final FVector absErrors = errors.copy(); absErrors.abs(); apprenticePolicies[i] = apprenticePolicy; errorVectors[i] = errors; absErrorSums[i] = absErrors.sum(); } // For every feature, compute sample correlation coefficient between its activity level (0 or 1) // and errors // final double[] featureErrorCorrelations = new double[featureSet.getNumSpatialFeatures()]; // For every feature, compute expectation of absolute value of error given that feature is active final double[] expectedAbsErrorGivenFeature = new double[featureSet.getNumSpatialFeatures()]; // For every feature, computed expected value of feature activity times absolute error // final double[] expectedFeatureTimesAbsError = new double[featureSet.getNumSpatialFeatures()]; for (int fIdx = 0; fIdx < featureSet.getNumSpatialFeatures(); ++fIdx) { final TDoubleArrayList errorsWhenActive = errorsPerActiveFeature[fIdx]; // final TDoubleArrayList errorsWhenInactive = errorsPerInactiveFeature[fIdx]; // final double avgFeatureVal = // (double) errorsWhenActive.size() // / // (errorsWhenActive.size() + errorsPerInactiveFeature[fIdx].size()); // double dErrorSquaresSum = 0.0; // double numerator = 0.0; for (int i = 0; i < errorsWhenActive.size(); ++i) { final double error = errorsWhenActive.getQuick(i); // final double dError = error - avgActionError; // numerator += (1.0 - avgFeatureVal) * dError; // dErrorSquaresSum += (dError * dError); expectedAbsErrorGivenFeature[fIdx] += (Math.abs(error) - expectedAbsErrorGivenFeature[fIdx]) / (i + 1); // expectedFeatureTimesAbsError[fIdx] += (Math.abs(error) - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } // for (int i = 0; i < errorsWhenInactive.size(); ++i) // { // final double error = errorsWhenInactive.getQuick(i); // final double dError = error - avgActionError; // numerator += (0.0 - avgFeatureVal) * dError; // dErrorSquaresSum += (dError * dError); // expectedFeatureTimesAbsError[fIdx] += (0.0 - expectedFeatureTimesAbsError[fIdx]) / (i + 1); // } // final double dFeatureSquaresSum = // errorsWhenActive.size() * ((1.0 - avgFeatureVal) * (1.0 - avgFeatureVal)) // + // errorsWhenInactive.size() * ((0.0 - avgFeatureVal) * (0.0 - avgFeatureVal)); // // final double denominator = Math.sqrt(dFeatureSquaresSum * dErrorSquaresSum); // featureErrorCorrelations[fIdx] = numerator / denominator; // if (Double.isNaN(featureErrorCorrelations[fIdx])) // featureErrorCorrelations[fIdx] = 0.f; } // Create list of indices that we can use to index into batch, sorted in descending order // of sums of absolute errors. // This means that we prioritise looking at samples in the batch for which we have big policy // errors, and hence also focus on them when dealing with a cap in the number of active feature // instances we can look at final List<Integer> batchIndices = new ArrayList<Integer>(batch.size()); for (int i = 0; i < batch.size(); ++i) { batchIndices.add(Integer.valueOf(i)); } Collections.sort(batchIndices, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { final float deltaAbsErrorSums = absErrorSums[o1.intValue()] - absErrorSums[o2.intValue()]; if (deltaAbsErrorSums > 0.f) return -1; else if (deltaAbsErrorSums < 0.f) return 1; else return 0; } }); // Set of feature instances that we have already preserved (and hence must continue to preserve) final Set<CombinableFeatureInstancePair> preservedInstances = new HashSet<CombinableFeatureInstancePair>(); // Set of feature instances that we have already chosen to discard once (and hence must continue to discard) final Set<CombinableFeatureInstancePair> discardedInstances = new HashSet<CombinableFeatureInstancePair>(); // Loop through all samples in batch for (int bi = 0; bi < batchIndices.size(); ++bi) { final int batchIndex = batchIndices.get(bi).intValue(); final ExperienceSample sample = batch.get(batchIndex); final FVector errors = errorVectors[batchIndex]; final float minError = errors.min(); final float maxError = errors.max(); final FastArrayList<Move> moves = sample.moves(); final TIntArrayList sortedActionIndices = new TIntArrayList(); // Want to start looking at winning moves final BitSet winningMoves = sample.winningMoves(); for (int i = winningMoves.nextSetBit(0); i >= 0; i = winningMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // Look at losing moves next final BitSet losingMoves = sample.losingMoves(); for (int i = losingMoves.nextSetBit(0); i >= 0; i = losingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // And finally anti-defeating moves final BitSet antiDefeatingMoves = sample.antiDefeatingMoves(); for (int i = antiDefeatingMoves.nextSetBit(0); i >= 0; i = antiDefeatingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // if (antiDefeatingMoves.cardinality() > 0) // System.out.println("Winning -- Losing -- AntiDefeating : " + winningMoves.cardinality() + " -- " + losingMoves.cardinality() + " -- " + antiDefeatingMoves.cardinality()); final TIntArrayList unsortedActionIndices = new TIntArrayList(); for (int a = 0; a < moves.size(); ++a) { if (!winningMoves.get(a) && !losingMoves.get(a) && !antiDefeatingMoves.get(a)) unsortedActionIndices.add(a); } // Finally, randomly fill up with the remaining actions while (!unsortedActionIndices.isEmpty()) { final int r = ThreadLocalRandom.current().nextInt(unsortedActionIndices.size()); final int a = unsortedActionIndices.getQuick(r); ListUtils.removeSwap(unsortedActionIndices, r); sortedActionIndices.add(a); } // Every action in the sample is a new "case" (state-action pair) for (int aIdx = 0; aIdx < sortedActionIndices.size(); ++aIdx) { final int a = sortedActionIndices.getQuick(aIdx); // keep track of pairs we've already seen in this "case" final Set<CombinableFeatureInstancePair> observedCasePairs = new HashSet<CombinableFeatureInstancePair>(256, .75f); // list --> set --> list to get rid of duplicates final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(new HashSet<FeatureInstance>( featureSet.getActiveSpatialFeatureInstances ( sample.gameState(), sample.lastFromPos(), sample.lastToPos(), FeatureUtils.fromPos(moves.get(a)), FeatureUtils.toPos(moves.get(a)), moves.get(a).mover() ))); // Save a copy of the above list, which we leave unmodified final List<FeatureInstance> origActiveInstances = new ArrayList<FeatureInstance>(activeInstances); // Start out by keeping all feature instances that have already been marked as having to be // preserved, and discarding those that have already been discarded before final List<FeatureInstance> instancesToKeep = new ArrayList<FeatureInstance>(); // For every instance in activeInstances, also keep track of a combined-self version final List<CombinableFeatureInstancePair> activeInstancesCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // And same for instancesToKeep final List<CombinableFeatureInstancePair> instancesToKeepCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // int numRelevantConstituents = 0; for (int i = 0; i < activeInstances.size(); /**/) { final FeatureInstance instance = activeInstances.get(i); final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instance, instance); if (preservedInstances.contains(combinedSelf)) { // if (instancesToKeepCombinedSelfs.contains(combinedSelf)) // { // System.out.println("already contains: " + combinedSelf); // System.out.println("instance: " + instance); // } instancesToKeepCombinedSelfs.add(combinedSelf); instancesToKeep.add(instance); ListUtils.removeSwap(activeInstances, i); } else if (discardedInstances.contains(combinedSelf)) { ListUtils.removeSwap(activeInstances, i); } else if (featureActiveRatios.getQuick(instance.feature().spatialFeatureSetIndex()) == 1.0) { ListUtils.removeSwap(activeInstances, i); } else { activeInstancesCombinedSelfs.add(combinedSelf); ++i; } } // if (activeInstances.size() > 0) // System.out.println(activeInstances.size() + "/" + origActiveInstances.size() + " left"); // This action is allowed to pick at most this many extra instances int numInstancesAllowedThisAction = Math.min ( Math.min ( 50, featureDiscoveryMaxNumFeatureInstances - preservedInstances.size() ), activeInstances.size() ); if (numInstancesAllowedThisAction > 0) { // System.out.println("allowed to add " + numInstancesAllowedThisAction + " instances"); // Create distribution over active instances proportional to scores that reward // features that correlate strongly with errors, as well as features that, when active, // imply expectations of high absolute errors, as well as features that are often active // when absolute errors are high, as well as features that have high absolute weights final FVector distr = new FVector(activeInstances.size()); for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); distr.set ( i, (float) ( // featureErrorCorrelations[fIdx] + expectedAbsErrorGivenFeature[fIdx] //+ // expectedFeatureTimesAbsError[fIdx] + // Math.abs // ( // policy.linearFunction // ( // sample.gameState().mover() // ).effectiveParams().allWeights().get(fIdx + featureSet.getNumAspatialFeatures()) // ) ) ); } distr.softmax(2.0); // For every instance, divide its probability by the number of active instances for the same // feature (because that feature is sort of "overrepresented") for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); int featureCount = 0; for (int j = 0; j < origActiveInstances.size(); ++j) { if (origActiveInstances.get(j).feature().spatialFeatureSetIndex() == fIdx) ++featureCount; } distr.set(i, distr.get(i) / featureCount); } distr.normalise(); // for (int i = 0; i < activeInstances.size(); ++i) // { // System.out.println("prob = " + distr.get(i) + " for " + activeInstances.get(i)); // } while (numInstancesAllowedThisAction > 0) { // Sample another instance final int sampledIdx = distr.sampleFromDistribution(); final CombinableFeatureInstancePair combinedSelf = activeInstancesCombinedSelfs.get(sampledIdx); final FeatureInstance keepInstance = activeInstances.get(sampledIdx); instancesToKeep.add(keepInstance); instancesToKeepCombinedSelfs.add(combinedSelf); preservedInstances.add(combinedSelf); // Remember to preserve this one forever now distr.updateSoftmaxInvalidate(sampledIdx); // Don't want to pick the same index again --numInstancesAllowedThisAction; // Maybe now have to auto-pick several other instances if they lead to equal combinedSelf for (int i = 0; i < distr.dim(); ++i) { if (distr.get(0) != 0.f) { if (combinedSelf.equals(activeInstancesCombinedSelfs.get(i))) { //System.out.println("auto-picking " + activeInstances.get(i) + " after " + keepInstance); instancesToKeep.add(activeInstances.get(i)); instancesToKeepCombinedSelfs.add(activeInstancesCombinedSelfs.get(i)); distr.updateSoftmaxInvalidate(i); // Don't want to pick the same index again --numInstancesAllowedThisAction; } } } } } // Mark all the instances that haven't been marked as preserved yet as discarded instead for (int i = 0; i < activeInstances.size(); ++i) { final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, activeInstances.get(i), activeInstances.get(i)); if (!preservedInstances.contains(combinedSelf)) discardedInstances.add(combinedSelf); } final int numActiveInstances = instancesToKeep.size(); //System.out.println("numActiveInstances = " + numActiveInstances); float error = errors.get(a); if (winningMoves.get(a)) { error = minError; // Reward correlation with winning moves } else if (losingMoves.get(a)) { error = maxError; // Reward correlation with losing moves } else if (antiDefeatingMoves.get(a)) { error = Math.min(error, minError + 0.1f); // Reward correlation with anti-defeating moves } sumErrors += error; sumSquaredErrors += error * error; for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance instanceI = instancesToKeep.get(i); // increment entries on ''main diagonals'' final CombinableFeatureInstancePair combinedSelf = instancesToKeepCombinedSelfs.get(i); // boolean relevantConstituent = false; // if (!combinedSelf.combinedFeature.isReactive()) // { // if (combinedSelf.combinedFeature.pattern().featureElements().length == 1) // { // relevantConstituent = true; // final FeatureElement element = combinedSelf.combinedFeature.pattern().featureElements()[0]; // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // relevantConstituent = false; // } // } // } // if (relevantConstituent) // { // System.out.println("relevant constituent " + i + ": " + instanceI); // ++numRelevantConstituents; // } if (observedCasePairs.add(combinedSelf)) { featurePairActivations.adjustOrPutValue(combinedSelf, 1, 1); errorSums.adjustOrPutValue(combinedSelf, error, error); // if (relevantConstituent) // System.out.println("incremented for constituent " + i); } // else if (relevantConstituent) // { // System.out.println("Already observed for this action, so no increment for constituent " + i); // } for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance instanceJ = instancesToKeep.get(j); // increment off-diagonal entries final CombinableFeatureInstancePair combined = new CombinableFeatureInstancePair(game, instanceI, instanceJ); // boolean relevantCombined = false; // if (!combined.combinedFeature.isReactive() && combined.combinedFeature.pattern().featureElements().length == 2) // { // boolean onlyFriendElements = true; // for (final FeatureElement element : combined.combinedFeature.pattern().featureElements()) // { // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // onlyFriendElements = false; // break; // } // } // // if (onlyFriendElements) // relevantCombined = true; // } // if (relevantCombined) // { // System.out.println("relevant combined feature: " + combined.combinedFeature); // System.out.println("from constituent " + i + " = " + instanceI); // System.out.println("from constituent " + j + " = " + instanceJ); // } if (!existingFeatures.contains(combined.combinedFeature)) { if (observedCasePairs.add(combined)) { featurePairActivations.adjustOrPutValue(combined, 1, 1); errorSums.adjustOrPutValue(combined, error, error); // // if (relevantCombined) // System.out.println("incremented for combined"); } // else if (relevantCombined) // { // System.out.println("didn't add combined because already observed for this action "); // } } // else if (relevantCombined) // { // System.out.println("didn't add combined because feature already exists"); // } } } // if (numRelevantConstituents == 1) // System.out.println("origActiveInstances = " + origActiveInstances); } } if (sumErrors == 0.0 || sumSquaredErrors == 0.0) { // incredibly rare case but appears to be possible sometimes // we have nothing to guide our feature growing, so let's // just refuse to add a feature return null; } // Construct all possible pairs and scores; one priority queue for proactive features, // and one for reactive features // // In priority queues, we want highest scores at the head, hence "reversed" implementation // of comparator final Comparator<ScoredFeatureInstancePair> comparator = new Comparator<ScoredFeatureInstancePair>() { @Override public int compare(final ScoredFeatureInstancePair o1, final ScoredFeatureInstancePair o2) { if (o1.score < o2.score) return 1; else if (o1.score > o2.score) return -1; else return 0; } }; final PriorityQueue<ScoredFeatureInstancePair> proactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); final PriorityQueue<ScoredFeatureInstancePair> reactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // Randomly pick a minimum required sample size in [3, 5] final int requiredSampleSize = 3 + ThreadLocalRandom.current().nextInt(3); for (final CombinableFeatureInstancePair pair : featurePairActivations.keySet()) { // int numFriendElements = 0; // for (final FeatureElement element : ((RelativeFeature) pair.combinedFeature).pattern().featureElements()) // { // if (element.type() == ElementType.Friend && !element.not()) // ++numFriendElements; // } // final boolean couldBeWinFeature = (numFriendElements >= 3); // final boolean couldBeLossFeature = (numFriendElements == 2); if (!pair.a.equals(pair.b)) // Only interested in combinations of different instances { // if (pair.combinedFeature.toString().equals("rel:to=<{}>:pat=<els=[f{-1/6,1/6}, f{0,-1/6}]>")) // { // final int pairActs = featurePairActivations.get(pair); // final int actsI = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); // final int actsJ = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); // // if (pairActs != actsI || pairActs != actsJ || actsI != actsJ) // { // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("already contains = " + existingFeatures.contains(pair.combinedFeature)); // System.out.println("pair = " + pair); // System.out.println("errorSumsI = " + errorSums.get(new CombinableFeatureInstancePair(game, pair.a, pair.a))); // System.out.println("errorSumsJ = " + errorSums.get(new CombinableFeatureInstancePair(game, pair.b, pair.b))); // for (final CombinableFeatureInstancePair key : featurePairActivations.keySet()) // { // if (featurePairActivations.get(key) <= actsI && !key.combinedFeature.isReactive()) // { // boolean onlyFriendElements = true; // for (final FeatureElement element : key.combinedFeature.pattern().featureElements()) // { // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // onlyFriendElements = false; // break; // } // } // // if (onlyFriendElements) // System.out.println("Num activations for " + key + " = " + featurePairActivations.get(key)); // } // } // System.exit(0); // } // } final int pairActs = featurePairActivations.get(pair); if (pairActs == numCases || numCases < 4) { // Perfect correlation, so we should just skip this one // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of correlation: " + pair); continue; } if (pairActs < requiredSampleSize) { // Need a bigger sample size // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of sample size (" + pairActs + " < " + requiredSampleSize + "): " + pair); continue; } final int actsI = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); final int actsJ = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); if (actsI == numCases || actsJ == numCases || pairActs == actsI || pairActs == actsJ) { // Perfect correlation, so we should just skip this one // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of perfect correlation: " + pair); continue; } final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - featureDiscoveryParams.criticalValueCorrConf * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + featureDiscoveryParams.criticalValueCorrConf * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (pairActs * (numCases - actsI)) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(actsI * (numCases - actsI)) ) ); final double featureCorrJ = ( (pairActs * (numCases - actsJ)) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(actsJ * (numCases - actsJ)) ) ); final double worstFeatureCorr = Math.max ( Math.abs(featureCorrI), Math.abs(featureCorrJ) ); final double score; if (errorCorr >= 0.0) score = Math.max(0.0, lbErrorCorr) * (1.0 - worstFeatureCorr*worstFeatureCorr); else score = -Math.min(0.0, ubErrorCorr) * (1.0 - worstFeatureCorr*worstFeatureCorr); if (Double.isNaN(score)) { // System.err.println("numCases = " + numCases); // System.err.println("pairActs = " + pairActs); // System.err.println("actsI = " + actsI); // System.err.println("actsJ = " + actsJ); // System.err.println("sumErrors = " + sumErrors); // System.err.println("sumSquaredErrors = " + sumSquaredErrors); // if (couldBeWinFeature) // System.out.println("Skipping because of NaN score: " + pair); continue; } // if (couldBeWinFeature) // { // System.out.println("Might be win feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } // else if (couldBeLossFeature) // { // System.out.println("Might be loss feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } if (pair.combinedFeature.isReactive()) reactivePairs.add(new ScoredFeatureInstancePair(pair, score)); else proactivePairs.add(new ScoredFeatureInstancePair(pair, score)); } } // System.out.println("--------------------------------------------------------"); // final PriorityQueue<ScoredFeatureInstancePair> allPairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // allPairs.addAll(proactivePairs); // allPairs.addAll(reactivePairs); // while (!allPairs.isEmpty()) // { // final ScoredFeatureInstancePair pair = allPairs.poll(); // // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.b, pair.pair.b) // ); // // final int pairActs = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double pairErrorSum = // errorSums.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // System.out.println("score = " + pair.score); // System.out.println("correlation with errors = " + errorCorr); // System.out.println("lower bound correlation with errors = " + lbErrorCorr); // System.out.println("upper bound correlation with errors = " + ubErrorCorr); // System.out.println("correlation with first constituent = " + featureCorrI); // System.out.println("correlation with second constituent = " + featureCorrJ); // System.out.println("active feature A = " + pair.pair.a.feature()); // System.out.println("rot A = " + pair.pair.a.rotation()); // System.out.println("ref A = " + pair.pair.a.reflection()); // System.out.println("anchor A = " + pair.pair.a.anchorSite()); // System.out.println("active feature B = " + pair.pair.b.feature()); // System.out.println("rot B = " + pair.pair.b.rotation()); // System.out.println("ref B = " + pair.pair.b.reflection()); // System.out.println("anchor B = " + pair.pair.b.anchorSite()); // System.out.println("observed pair of instances " + pairActs + " times"); // System.out.println("observed first constituent " + actsI + " times"); // System.out.println("observed second constituent " + actsJ + " times"); // System.out.println(); // } // System.out.println("--------------------------------------------------------"); // Keep trying to add a proactive feature, until we succeed (almost always // this should be on the very first iteration) BaseFeatureSet currFeatureSet = featureSet; // TODO pretty much duplicate code of block below, should refactor into method while (!proactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = proactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); final int pairActs = featurePairActivations.get(pair); final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (numCases * pairActs - pairActs * actsI) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsI - actsI * actsI) ) ); final double featureCorrJ = ( (numCases * pairActs - pairActs * actsJ) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsJ - actsJ * actsJ) ) ); experiment.logLine(logWriter, "New proactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); experiment.logLine(logWriter, "score = " + bestPair.score); experiment.logLine(logWriter, "correlation with errors = " + errorCorr); experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); // System.out.println("BEST SCORE: " + bestPair.score); currFeatureSet = newFeatureSet; break; } } // Keep trying to add a reactive feature, until we succeed (almost always // this should be on the very first iteration) while (!reactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = reactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); final int pairActs = featurePairActivations.get(pair); final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (numCases * pairActs - pairActs * actsI) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsI - actsI * actsI) ) ); final double featureCorrJ = ( (numCases * pairActs - pairActs * actsJ) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsJ - actsJ * actsJ) ) ); experiment.logLine(logWriter, "New reactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); experiment.logLine(logWriter, "score = " + bestPair.score); experiment.logLine(logWriter, "correlation with errors = " + errorCorr); experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } return currFeatureSet; } }
51,422
38.678241
176
java
Ludii
Ludii-master/AI/src/training/feature_discovery/CorrelationErrorSignExpander.java
package training.feature_discovery; import java.io.PrintWriter; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import features.FeatureVector; import features.feature_sets.BaseFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.impl.Constants; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TObjectDoubleHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import main.collections.FVector; import main.collections.FastArrayList; import main.collections.ListUtils; import other.move.Move; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.gradients.Gradients; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import utils.experiments.InterruptableExperiment; /** * Correlation-based Feature Set Expander. Only uses signs of errors, * not the magnitudes of errors. * * @author Dennis Soemers */ public class CorrelationErrorSignExpander implements FeatureSetExpander { @Override public BaseFeatureSet expandFeatureSet ( final List<? extends ExperienceSample> batch, final BaseFeatureSet featureSet, final SoftmaxPolicyLinear policy, final Game game, final int featureDiscoveryMaxNumFeatureInstances, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TDoubleArrayList featureActiveRatios, final PrintWriter logWriter, final InterruptableExperiment experiment ) { // we need a matrix C_f with, at every entry (i, j), // the sum of cases in which features i and j are both active // // we also need a similar matrix C_e with, at every entry (i, j), // the sum of errors in cases where features i and j are both active // // NOTE: both of the above are symmetric matrices // // we also need a vector X_f with, for every feature i, the sum of // cases where feature i is active. (we would need a similar vector // with sums of squares, but that can be omitted because our features // are binary) // // NOTE: in writing it is easier to mention X_f as described above as // a separate vector, but actually we don't need it; we can simply // use the main diagonal of C_f instead // // we need a scalar S which is the sum of all errors, // and a scalar SS which is the sum of all squared errors // // Given a candidate pair of features (i, j), we can compute the // correlation of that pair of features with the errors (an // indicator of the candidate pair's potential to be useful) as // (where n = the number of cases = number of state-action pairs): // // // n * C_e(i, j) - C_f(i, j) * S //------------------------------------------------------------ // SQRT( n * C_f(i, j) - C_f(i, j)^2 ) * SQRT( n * SS - S^2 ) // // // For numeric stability with extremely large batch sizes, // it is better to compute this as: // // n * C_e(i, j) - C_f(i, j) * S //------------------------------------------------------------ // SQRT( C_f(i, j) * (n - C_f(i, j)) ) * SQRT( n * SS - S^2 ) // // // We can similarly compare the correlation between any candidate pair // of features (i, j) and either of its constituents i (an indicator // of redundancy of the candidate pair) as: // // // n * C_f(i, j) - C_f(i, j) * X_f(i) //-------------------------------------------------------------------- // SQRT( n * C_f(i, j) - C_f(i, j)^2 ) * SQRT( n * X_f(i) - X_f(i)^2 ) // // // For numeric stability with extremely large batch sizes, // it is better to compute this as: // // C_f(i, j) * (n - X_f(i)) //-------------------------------------------------------------------- // SQRT( C_f(i, j) * (n - C_f(i, j)) ) * SQRT( X_f(i) * (n - X_f(i)) ) // // // (note; even better would be if we could compute correlation between // candidate pair and ANY other feature, rather than just its // constituents, but that would probably become too expensive) // // We want to maximise the absolute value of the first (correlation // between candidate feature pair and distribution error), but minimise // the worst-case absolute value of the second (correlation between // candidate feature pair and either of its constituents). // // // NOTE: in all of the above, when we say "feature", we actually // refer to a particular instantiation of a feature. This is important, // because otherwise we wouldn't be able to merge different // instantiations of the same feature into a more complex new feature // // Due to the large amount of possible pairings when considering // feature instances, we implement our "matrices" using hash tables, // and automatically ignore entries that would be 0 (they won't // be created if such pairs are never observed activating together) // System.out.println("-------------------------------------------------------------------"); int numCases = 0; // we'll increment this as we go // this is our C_f matrix final TObjectIntHashMap<CombinableFeatureInstancePair> featurePairActivations = new TObjectIntHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0); // this is our C_e matrix final TObjectDoubleHashMap<CombinableFeatureInstancePair> errorSums = new TObjectDoubleHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0.0); // these are our S and SS scalars double sumErrors = 0.0; double sumSquaredErrors = 0.0; // Create a Hash Set of features already in Feature Set; we won't // have to consider combinations that are already in final Set<SpatialFeature> existingFeatures = new HashSet<SpatialFeature> ( (int) Math.ceil(featureSet.getNumSpatialFeatures() / 0.75f), 0.75f ); for (final SpatialFeature feature : featureSet.spatialFeatures()) { existingFeatures.add(feature); } // For every sample in batch, first compute apprentice policies, errors, and sum of absolute errors final FVector[] apprenticePolicies = new FVector[batch.size()]; final FVector[] errorVectors = new FVector[batch.size()]; final float[] absErrorSums = new float[batch.size()]; final TDoubleArrayList[] errorsPerActiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; // final TDoubleArrayList[] errorsPerInactiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; for (int i = 0; i < errorsPerActiveFeature.length; ++i) { errorsPerActiveFeature[i] = new TDoubleArrayList(); // errorsPerInactiveFeature[i] = new TDoubleArrayList(); } double avgActionError = 0.0; for (int i = 0; i < batch.size(); ++i) { final ExperienceSample sample = batch.get(i); final FeatureVector[] featureVectors = sample.generateFeatureVectors(featureSet); final FVector apprenticePolicy = policy.computeDistribution(featureVectors, sample.gameState().mover()); final FVector errors = Gradients.computeDistributionErrors ( apprenticePolicy, sample.expertDistribution() ); // This is used just for sorting, don't want to lose magnitudes and only keep signs here final FVector absErrors = errors.copy(); absErrors.abs(); // In errors vector, only preserve signs errors.sign(); for (int a = 0; a < featureVectors.length; ++a) { final float actionError = errors.get(a); final TIntArrayList sparseFeatureVector = featureVectors[a].activeSpatialFeatureIndices(); sparseFeatureVector.sort(); int sparseIdx = 0; for (int featureIdx = 0; featureIdx < featureSet.getNumSpatialFeatures(); ++featureIdx) { if (sparseIdx < sparseFeatureVector.size() && sparseFeatureVector.getQuick(sparseIdx) == featureIdx) { // This spatial feature is active errorsPerActiveFeature[featureIdx].add(actionError); // We've used the sparse index, so increment it ++sparseIdx; } // else // { // // This spatial feature is not active // errorsPerInactiveFeature[featureIdx].add(actionError); // } } avgActionError += (actionError - avgActionError) / (numCases + 1); ++numCases; } apprenticePolicies[i] = apprenticePolicy; errorVectors[i] = errors; absErrorSums[i] = absErrors.sum(); } // For every feature, compute sample correlation coefficient between its activity level (0 or 1) // and errors // final double[] featureErrorCorrelations = new double[featureSet.getNumSpatialFeatures()]; // For every feature, compute expectation of absolute value of error given that feature is active final double[] expectedAbsErrorGivenFeature = new double[featureSet.getNumSpatialFeatures()]; // For every feature, computed expected value of feature activity times absolute error // final double[] expectedFeatureTimesAbsError = new double[featureSet.getNumSpatialFeatures()]; for (int fIdx = 0; fIdx < featureSet.getNumSpatialFeatures(); ++fIdx) { final TDoubleArrayList errorsWhenActive = errorsPerActiveFeature[fIdx]; // final TDoubleArrayList errorsWhenInactive = errorsPerInactiveFeature[fIdx]; // final double avgFeatureVal = // (double) errorsWhenActive.size() // / // (errorsWhenActive.size() + errorsPerInactiveFeature[fIdx].size()); // double dErrorSquaresSum = 0.0; // double numerator = 0.0; for (int i = 0; i < errorsWhenActive.size(); ++i) { final double error = errorsWhenActive.getQuick(i); // final double dError = error - avgActionError; // numerator += (1.0 - avgFeatureVal) * dError; // dErrorSquaresSum += (dError * dError); expectedAbsErrorGivenFeature[fIdx] += (Math.abs(error) - expectedAbsErrorGivenFeature[fIdx]) / (i + 1); // expectedFeatureTimesAbsError[fIdx] += (Math.abs(error) - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } // for (int i = 0; i < errorsWhenInactive.size(); ++i) // { // final double error = errorsWhenInactive.getQuick(i); // final double dError = error - avgActionError; // numerator += (0.0 - avgFeatureVal) * dError; // dErrorSquaresSum += (dError * dError); // expectedFeatureTimesAbsError[fIdx] += (0.0 - expectedFeatureTimesAbsError[fIdx]) / (i + 1); // } // final double dFeatureSquaresSum = // errorsWhenActive.size() * ((1.0 - avgFeatureVal) * (1.0 - avgFeatureVal)) // + // errorsWhenInactive.size() * ((0.0 - avgFeatureVal) * (0.0 - avgFeatureVal)); // // final double denominator = Math.sqrt(dFeatureSquaresSum * dErrorSquaresSum); // featureErrorCorrelations[fIdx] = numerator / denominator; // if (Double.isNaN(featureErrorCorrelations[fIdx])) // featureErrorCorrelations[fIdx] = 0.f; } // Create list of indices that we can use to index into batch, sorted in descending order // of sums of absolute errors. // This means that we prioritise looking at samples in the batch for which we have big policy // errors, and hence also focus on them when dealing with a cap in the number of active feature // instances we can look at final List<Integer> batchIndices = new ArrayList<Integer>(batch.size()); for (int i = 0; i < batch.size(); ++i) { batchIndices.add(Integer.valueOf(i)); } Collections.sort(batchIndices, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { final float deltaAbsErrorSums = absErrorSums[o1.intValue()] - absErrorSums[o2.intValue()]; if (deltaAbsErrorSums > 0.f) return -1; else if (deltaAbsErrorSums < 0.f) return 1; else return 0; } }); // Set of feature instances that we have already preserved (and hence must continue to preserve) final Set<CombinableFeatureInstancePair> preservedInstances = new HashSet<CombinableFeatureInstancePair>(); // Set of feature instances that we have already chosen to discard once (and hence must continue to discard) final Set<CombinableFeatureInstancePair> discardedInstances = new HashSet<CombinableFeatureInstancePair>(); // Loop through all samples in batch for (int bi = 0; bi < batchIndices.size(); ++bi) { final int batchIndex = batchIndices.get(bi).intValue(); final ExperienceSample sample = batch.get(batchIndex); final FVector errors = errorVectors[batchIndex]; // final float minError = errors.min(); // final float maxError = errors.max(); final FastArrayList<Move> moves = sample.moves(); final TIntArrayList sortedActionIndices = new TIntArrayList(); // Want to start looking at winning moves final BitSet winningMoves = sample.winningMoves(); for (int i = winningMoves.nextSetBit(0); i >= 0; i = winningMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // Look at losing moves next final BitSet losingMoves = sample.losingMoves(); for (int i = losingMoves.nextSetBit(0); i >= 0; i = losingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // And finally anti-defeating moves final BitSet antiDefeatingMoves = sample.antiDefeatingMoves(); for (int i = antiDefeatingMoves.nextSetBit(0); i >= 0; i = antiDefeatingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // if (antiDefeatingMoves.cardinality() > 0) // System.out.println("Winning -- Losing -- AntiDefeating : " + winningMoves.cardinality() + " -- " + losingMoves.cardinality() + " -- " + antiDefeatingMoves.cardinality()); final TIntArrayList unsortedActionIndices = new TIntArrayList(); for (int a = 0; a < moves.size(); ++a) { if (!winningMoves.get(a) && !losingMoves.get(a) && !antiDefeatingMoves.get(a)) unsortedActionIndices.add(a); } // Finally, randomly fill up with the remaining actions while (!unsortedActionIndices.isEmpty()) { final int r = ThreadLocalRandom.current().nextInt(unsortedActionIndices.size()); final int a = unsortedActionIndices.getQuick(r); ListUtils.removeSwap(unsortedActionIndices, r); sortedActionIndices.add(a); } // Every action in the sample is a new "case" (state-action pair) for (int aIdx = 0; aIdx < sortedActionIndices.size(); ++aIdx) { final int a = sortedActionIndices.getQuick(aIdx); // keep track of pairs we've already seen in this "case" final Set<CombinableFeatureInstancePair> observedCasePairs = new HashSet<CombinableFeatureInstancePair>(256, .75f); // list --> set --> list to get rid of duplicates final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(new HashSet<FeatureInstance>( featureSet.getActiveSpatialFeatureInstances ( sample.gameState(), sample.lastFromPos(), sample.lastToPos(), FeatureUtils.fromPos(moves.get(a)), FeatureUtils.toPos(moves.get(a)), moves.get(a).mover() ))); // Save a copy of the above list, which we leave unmodified final List<FeatureInstance> origActiveInstances = new ArrayList<FeatureInstance>(activeInstances); // Start out by keeping all feature instances that have already been marked as having to be // preserved, and discarding those that have already been discarded before final List<FeatureInstance> instancesToKeep = new ArrayList<FeatureInstance>(); // For every instance in activeInstances, also keep track of a combined-self version final List<CombinableFeatureInstancePair> activeInstancesCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // And same for instancesToKeep final List<CombinableFeatureInstancePair> instancesToKeepCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // int numRelevantConstituents = 0; for (int i = 0; i < activeInstances.size(); /**/) { final FeatureInstance instance = activeInstances.get(i); final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instance, instance); if (preservedInstances.contains(combinedSelf)) { // if (instancesToKeepCombinedSelfs.contains(combinedSelf)) // { // System.out.println("already contains: " + combinedSelf); // System.out.println("instance: " + instance); // } instancesToKeepCombinedSelfs.add(combinedSelf); instancesToKeep.add(instance); ListUtils.removeSwap(activeInstances, i); } else if (discardedInstances.contains(combinedSelf)) { ListUtils.removeSwap(activeInstances, i); } else if (featureActiveRatios.getQuick(instance.feature().spatialFeatureSetIndex()) == 1.0) { ListUtils.removeSwap(activeInstances, i); } else { activeInstancesCombinedSelfs.add(combinedSelf); ++i; } } // if (activeInstances.size() > 0) // System.out.println(activeInstances.size() + "/" + origActiveInstances.size() + " left"); // This action is allowed to pick at most this many extra instances int numInstancesAllowedThisAction = Math.min ( Math.min ( 50, featureDiscoveryMaxNumFeatureInstances - preservedInstances.size() ), activeInstances.size() ); if (numInstancesAllowedThisAction > 0) { // System.out.println("allowed to add " + numInstancesAllowedThisAction + " instances"); // Create distribution over active instances proportional to scores that reward // features that correlate strongly with errors, as well as features that, when active, // imply expectations of high absolute errors, as well as features that are often active // when absolute errors are high, as well as features that have high absolute weights final FVector distr = new FVector(activeInstances.size()); for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); distr.set ( i, (float) ( // featureErrorCorrelations[fIdx] + expectedAbsErrorGivenFeature[fIdx] //+ // expectedFeatureTimesAbsError[fIdx] + // Math.abs // ( // policy.linearFunction // ( // sample.gameState().mover() // ).effectiveParams().allWeights().get(fIdx + featureSet.getNumAspatialFeatures()) // ) ) ); } distr.softmax(2.0); // For every instance, divide its probability by the number of active instances for the same // feature (because that feature is sort of "overrepresented") for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); int featureCount = 0; for (int j = 0; j < origActiveInstances.size(); ++j) { if (origActiveInstances.get(j).feature().spatialFeatureSetIndex() == fIdx) ++featureCount; } distr.set(i, distr.get(i) / featureCount); } distr.normalise(); // for (int i = 0; i < activeInstances.size(); ++i) // { // System.out.println("prob = " + distr.get(i) + " for " + activeInstances.get(i)); // } while (numInstancesAllowedThisAction > 0) { // Sample another instance final int sampledIdx = distr.sampleFromDistribution(); final CombinableFeatureInstancePair combinedSelf = activeInstancesCombinedSelfs.get(sampledIdx); final FeatureInstance keepInstance = activeInstances.get(sampledIdx); instancesToKeep.add(keepInstance); instancesToKeepCombinedSelfs.add(combinedSelf); preservedInstances.add(combinedSelf); // Remember to preserve this one forever now distr.updateSoftmaxInvalidate(sampledIdx); // Don't want to pick the same index again --numInstancesAllowedThisAction; // Maybe now have to auto-pick several other instances if they lead to equal combinedSelf for (int i = 0; i < distr.dim(); ++i) { if (distr.get(0) != 0.f) { if (combinedSelf.equals(activeInstancesCombinedSelfs.get(i))) { //System.out.println("auto-picking " + activeInstances.get(i) + " after " + keepInstance); instancesToKeep.add(activeInstances.get(i)); instancesToKeepCombinedSelfs.add(activeInstancesCombinedSelfs.get(i)); distr.updateSoftmaxInvalidate(i); // Don't want to pick the same index again --numInstancesAllowedThisAction; } } } } } // Mark all the instances that haven't been marked as preserved yet as discarded instead for (int i = 0; i < activeInstances.size(); ++i) { final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, activeInstances.get(i), activeInstances.get(i)); if (!preservedInstances.contains(combinedSelf)) discardedInstances.add(combinedSelf); } final int numActiveInstances = instancesToKeep.size(); //System.out.println("numActiveInstances = " + numActiveInstances); float error = errors.get(a); // if (winningMoves.get(a)) // { // error = minError; // Reward correlation with winning moves // } // else if (losingMoves.get(a)) // { // error = maxError; // Reward correlation with losing moves // } // else if (antiDefeatingMoves.get(a)) // { // error = Math.min(error, minError + 0.1f); // Reward correlation with anti-defeating moves // } sumErrors += error; sumSquaredErrors += error * error; for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance instanceI = instancesToKeep.get(i); // increment entries on ''main diagonals'' final CombinableFeatureInstancePair combinedSelf = instancesToKeepCombinedSelfs.get(i); // boolean relevantConstituent = false; // if (!combinedSelf.combinedFeature.isReactive()) // { // if (combinedSelf.combinedFeature.pattern().featureElements().length == 1) // { // relevantConstituent = true; // final FeatureElement element = combinedSelf.combinedFeature.pattern().featureElements()[0]; // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // relevantConstituent = false; // } // } // } // if (relevantConstituent) // { // System.out.println("relevant constituent " + i + ": " + instanceI); // ++numRelevantConstituents; // } if (observedCasePairs.add(combinedSelf)) { featurePairActivations.adjustOrPutValue(combinedSelf, 1, 1); errorSums.adjustOrPutValue(combinedSelf, error, error); // if (relevantConstituent) // System.out.println("incremented for constituent " + i); } // else if (relevantConstituent) // { // System.out.println("Already observed for this action, so no increment for constituent " + i); // } for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance instanceJ = instancesToKeep.get(j); // increment off-diagonal entries final CombinableFeatureInstancePair combined = new CombinableFeatureInstancePair(game, instanceI, instanceJ); // boolean relevantCombined = false; // if (!combined.combinedFeature.isReactive() && combined.combinedFeature.pattern().featureElements().length == 2) // { // boolean onlyFriendElements = true; // for (final FeatureElement element : combined.combinedFeature.pattern().featureElements()) // { // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // onlyFriendElements = false; // break; // } // } // // if (onlyFriendElements) // relevantCombined = true; // } // if (relevantCombined) // { // System.out.println("relevant combined feature: " + combined.combinedFeature); // System.out.println("from constituent " + i + " = " + instanceI); // System.out.println("from constituent " + j + " = " + instanceJ); // } if (!existingFeatures.contains(combined.combinedFeature)) { if (observedCasePairs.add(combined)) { featurePairActivations.adjustOrPutValue(combined, 1, 1); errorSums.adjustOrPutValue(combined, error, error); // // if (relevantCombined) // System.out.println("incremented for combined"); } // else if (relevantCombined) // { // System.out.println("didn't add combined because already observed for this action "); // } } // else if (relevantCombined) // { // System.out.println("didn't add combined because feature already exists"); // } } } // if (numRelevantConstituents == 1) // System.out.println("origActiveInstances = " + origActiveInstances); } } if (sumErrors == 0.0 || sumSquaredErrors == 0.0) { // incredibly rare case but appears to be possible sometimes // we have nothing to guide our feature growing, so let's // just refuse to add a feature return null; } // Construct all possible pairs and scores; one priority queue for proactive features, // and one for reactive features // // In priority queues, we want highest scores at the head, hence "reversed" implementation // of comparator final Comparator<ScoredFeatureInstancePair> comparator = new Comparator<ScoredFeatureInstancePair>() { @Override public int compare(final ScoredFeatureInstancePair o1, final ScoredFeatureInstancePair o2) { if (o1.score < o2.score) return 1; else if (o1.score > o2.score) return -1; else return 0; } }; final PriorityQueue<ScoredFeatureInstancePair> proactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); final PriorityQueue<ScoredFeatureInstancePair> reactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // Randomly pick a minimum required sample size in [3, 5] final int requiredSampleSize = 3 + ThreadLocalRandom.current().nextInt(3); for (final CombinableFeatureInstancePair pair : featurePairActivations.keySet()) { // int numFriendElements = 0; // for (final FeatureElement element : ((RelativeFeature) pair.combinedFeature).pattern().featureElements()) // { // if (element.type() == ElementType.Friend && !element.not()) // ++numFriendElements; // } // final boolean couldBeWinFeature = (numFriendElements >= 3); // final boolean couldBeLossFeature = (numFriendElements == 2); if (!pair.a.equals(pair.b)) // Only interested in combinations of different instances { // if (pair.combinedFeature.toString().equals("rel:to=<{}>:pat=<els=[f{-1/6,1/6}, f{0,-1/6}]>")) // { // final int pairActs = featurePairActivations.get(pair); // final int actsI = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); // final int actsJ = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); // // if (pairActs != actsI || pairActs != actsJ || actsI != actsJ) // { // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("already contains = " + existingFeatures.contains(pair.combinedFeature)); // System.out.println("pair = " + pair); // System.out.println("errorSumsI = " + errorSums.get(new CombinableFeatureInstancePair(game, pair.a, pair.a))); // System.out.println("errorSumsJ = " + errorSums.get(new CombinableFeatureInstancePair(game, pair.b, pair.b))); // for (final CombinableFeatureInstancePair key : featurePairActivations.keySet()) // { // if (featurePairActivations.get(key) <= actsI && !key.combinedFeature.isReactive()) // { // boolean onlyFriendElements = true; // for (final FeatureElement element : key.combinedFeature.pattern().featureElements()) // { // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // onlyFriendElements = false; // break; // } // } // // if (onlyFriendElements) // System.out.println("Num activations for " + key + " = " + featurePairActivations.get(key)); // } // } // System.exit(0); // } // } final int pairActs = featurePairActivations.get(pair); if (pairActs == numCases || numCases < 4) { // Perfect correlation, so we should just skip this one // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of correlation: " + pair); continue; } if (pairActs < requiredSampleSize) { // Need a bigger sample size // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of sample size (" + pairActs + " < " + requiredSampleSize + "): " + pair); continue; } final int actsI = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); final int actsJ = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); if (actsI == numCases || actsJ == numCases || pairActs == actsI || pairActs == actsJ) { // Perfect correlation, so we should just skip this one // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of perfect correlation: " + pair); continue; } final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - featureDiscoveryParams.criticalValueCorrConf * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + featureDiscoveryParams.criticalValueCorrConf * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (pairActs * (numCases - actsI)) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(actsI * (numCases - actsI)) ) ); final double featureCorrJ = ( (pairActs * (numCases - actsJ)) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(actsJ * (numCases - actsJ)) ) ); final double worstFeatureCorr = Math.max ( Math.abs(featureCorrI), Math.abs(featureCorrJ) ); final double score; if (errorCorr >= 0.0) score = Math.max(0.0, lbErrorCorr) * (1.0 - worstFeatureCorr*worstFeatureCorr); else score = -Math.min(0.0, ubErrorCorr) * (1.0 - worstFeatureCorr*worstFeatureCorr); if (Double.isNaN(score)) { // System.err.println("numCases = " + numCases); // System.err.println("pairActs = " + pairActs); // System.err.println("actsI = " + actsI); // System.err.println("actsJ = " + actsJ); // System.err.println("sumErrors = " + sumErrors); // System.err.println("sumSquaredErrors = " + sumSquaredErrors); // if (couldBeWinFeature) // System.out.println("Skipping because of NaN score: " + pair); continue; } // if (couldBeWinFeature) // { // System.out.println("Might be win feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } // else if (couldBeLossFeature) // { // System.out.println("Might be loss feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } if (pair.combinedFeature.isReactive()) reactivePairs.add(new ScoredFeatureInstancePair(pair, score)); else proactivePairs.add(new ScoredFeatureInstancePair(pair, score)); } } // System.out.println("--------------------------------------------------------"); // final PriorityQueue<ScoredFeatureInstancePair> allPairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // allPairs.addAll(proactivePairs); // allPairs.addAll(reactivePairs); // while (!allPairs.isEmpty()) // { // final ScoredFeatureInstancePair pair = allPairs.poll(); // // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.b, pair.pair.b) // ); // // final int pairActs = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double pairErrorSum = // errorSums.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // System.out.println("score = " + pair.score); // System.out.println("correlation with errors = " + errorCorr); // System.out.println("lower bound correlation with errors = " + lbErrorCorr); // System.out.println("upper bound correlation with errors = " + ubErrorCorr); // System.out.println("correlation with first constituent = " + featureCorrI); // System.out.println("correlation with second constituent = " + featureCorrJ); // System.out.println("active feature A = " + pair.pair.a.feature()); // System.out.println("rot A = " + pair.pair.a.rotation()); // System.out.println("ref A = " + pair.pair.a.reflection()); // System.out.println("anchor A = " + pair.pair.a.anchorSite()); // System.out.println("active feature B = " + pair.pair.b.feature()); // System.out.println("rot B = " + pair.pair.b.rotation()); // System.out.println("ref B = " + pair.pair.b.reflection()); // System.out.println("anchor B = " + pair.pair.b.anchorSite()); // System.out.println("observed pair of instances " + pairActs + " times"); // System.out.println("observed first constituent " + actsI + " times"); // System.out.println("observed second constituent " + actsJ + " times"); // System.out.println(); // } // System.out.println("--------------------------------------------------------"); // Keep trying to add a proactive feature, until we succeed (almost always // this should be on the very first iteration) BaseFeatureSet currFeatureSet = featureSet; // TODO pretty much duplicate code of block below, should refactor into method while (!proactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = proactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); final int pairActs = featurePairActivations.get(pair); final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (numCases * pairActs - pairActs * actsI) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsI - actsI * actsI) ) ); final double featureCorrJ = ( (numCases * pairActs - pairActs * actsJ) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsJ - actsJ * actsJ) ) ); experiment.logLine(logWriter, "New proactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); experiment.logLine(logWriter, "score = " + bestPair.score); experiment.logLine(logWriter, "correlation with errors = " + errorCorr); experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); // System.out.println("BEST SCORE: " + bestPair.score); currFeatureSet = newFeatureSet; break; } } // Keep trying to add a reactive feature, until we succeed (almost always // this should be on the very first iteration) while (!reactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = reactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); final int pairActs = featurePairActivations.get(pair); final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (numCases * pairActs - pairActs * actsI) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsI - actsI * actsI) ) ); final double featureCorrJ = ( (numCases * pairActs - pairActs * actsJ) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsJ - actsJ * actsJ) ) ); experiment.logLine(logWriter, "New reactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); experiment.logLine(logWriter, "score = " + bestPair.score); experiment.logLine(logWriter, "correlation with errors = " + errorCorr); experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } return currFeatureSet; } }
51,532
38.671286
176
java
Ludii
Ludii-master/AI/src/training/feature_discovery/ErrorReductionExpander.java
package training.feature_discovery; import java.io.PrintWriter; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import features.FeatureVector; import features.feature_sets.BaseFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import main.collections.FVector; import main.collections.FastArrayList; import main.collections.ListUtils; import other.move.Move; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.gradients.Gradients; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import utils.experiments.InterruptableExperiment; /** * Feature Set expander based on estimated reduction in error * * @author Dennis Soemers */ public class ErrorReductionExpander implements FeatureSetExpander { @Override public BaseFeatureSet expandFeatureSet ( final List<? extends ExperienceSample> batch, final BaseFeatureSet featureSet, final SoftmaxPolicyLinear policy, final Game game, final int featureDiscoveryMaxNumFeatureInstances, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TDoubleArrayList featureActiveRatios, final PrintWriter logWriter, final InterruptableExperiment experiment ) { int numCases = 0; // we'll increment this as we go final Map<CombinableFeatureInstancePair, TDoubleArrayList> errorLists = new HashMap<CombinableFeatureInstancePair, TDoubleArrayList>(); // Create a Hash Set of features already in Feature Set; we won't // have to consider combinations that are already in final Set<SpatialFeature> existingFeatures = new HashSet<SpatialFeature> ( (int) Math.ceil(featureSet.getNumSpatialFeatures() / 0.75f), 0.75f ); for (final SpatialFeature feature : featureSet.spatialFeatures()) { existingFeatures.add(feature); } // For every sample in batch, first compute apprentice policies, errors, and sum of absolute errors final FVector[] apprenticePolicies = new FVector[batch.size()]; final FVector[] errorVectors = new FVector[batch.size()]; final float[] absErrorSums = new float[batch.size()]; final TDoubleArrayList[] errorsPerActiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; final TDoubleArrayList[] errorsPerInactiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; for (int i = 0; i < errorsPerActiveFeature.length; ++i) { errorsPerActiveFeature[i] = new TDoubleArrayList(); errorsPerInactiveFeature[i] = new TDoubleArrayList(); } double avgActionError = 0.0; for (int i = 0; i < batch.size(); ++i) { final ExperienceSample sample = batch.get(i); final FeatureVector[] featureVectors = sample.generateFeatureVectors(featureSet); final FVector apprenticePolicy = policy.computeDistribution(featureVectors, sample.gameState().mover()); final FVector errors = Gradients.computeDistributionErrors ( apprenticePolicy, sample.expertDistribution() ); for (int a = 0; a < featureVectors.length; ++a) { final float actionError = errors.get(a); final TIntArrayList sparseFeatureVector = featureVectors[a].activeSpatialFeatureIndices(); sparseFeatureVector.sort(); int sparseIdx = 0; for (int featureIdx = 0; featureIdx < featureSet.getNumSpatialFeatures(); ++featureIdx) { if (sparseIdx < sparseFeatureVector.size() && sparseFeatureVector.getQuick(sparseIdx) == featureIdx) { // This spatial feature is active errorsPerActiveFeature[featureIdx].add(actionError); // We've used the sparse index, so increment it ++sparseIdx; } else { // This spatial feature is not active errorsPerInactiveFeature[featureIdx].add(actionError); } } avgActionError += (actionError - avgActionError) / (numCases + 1); ++numCases; } final FVector absErrors = errors.copy(); absErrors.abs(); apprenticePolicies[i] = apprenticePolicy; errorVectors[i] = errors; absErrorSums[i] = absErrors.sum(); } // For every feature, compute sample correlation coefficient between its activity level (0 or 1) // and errors final double[] featureErrorCorrelations = new double[featureSet.getNumSpatialFeatures()]; // For every feature, compute expectation of absolute value of error given that feature is active final double[] expectedAbsErrorGivenFeature = new double[featureSet.getNumSpatialFeatures()]; // For every feature, computed expected value of feature activity times absolute error final double[] expectedFeatureTimesAbsError = new double[featureSet.getNumSpatialFeatures()]; for (int fIdx = 0; fIdx < featureSet.getNumSpatialFeatures(); ++fIdx) { final TDoubleArrayList errorsWhenActive = errorsPerActiveFeature[fIdx]; final TDoubleArrayList errorsWhenInactive = errorsPerInactiveFeature[fIdx]; final double avgFeatureVal = (double) errorsWhenActive.size() / (errorsWhenActive.size() + errorsPerInactiveFeature[fIdx].size()); double dErrorSquaresSum = 0.0; double numerator = 0.0; for (int i = 0; i < errorsWhenActive.size(); ++i) { final double error = errorsWhenActive.getQuick(i); final double dError = error - avgActionError; numerator += (1.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); expectedAbsErrorGivenFeature[fIdx] += (Math.abs(error) - expectedAbsErrorGivenFeature[fIdx]) / (i + 1); expectedFeatureTimesAbsError[fIdx] += (Math.abs(error) - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } for (int i = 0; i < errorsWhenInactive.size(); ++i) { final double error = errorsWhenInactive.getQuick(i); final double dError = error - avgActionError; numerator += (0.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); expectedFeatureTimesAbsError[fIdx] += (0.0 - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } final double dFeatureSquaresSum = errorsWhenActive.size() * ((1.0 - avgFeatureVal) * (1.0 - avgFeatureVal)) + errorsWhenInactive.size() * ((0.0 - avgFeatureVal) * (0.0 - avgFeatureVal)); final double denominator = Math.sqrt(dFeatureSquaresSum * dErrorSquaresSum); featureErrorCorrelations[fIdx] = numerator / denominator; if (Double.isNaN(featureErrorCorrelations[fIdx])) featureErrorCorrelations[fIdx] = 0.f; } // Create list of indices that we can use to index into batch, sorted in descending order // of sums of absolute errors. // This means that we prioritise looking at samples in the batch for which we have big policy // errors, and hence also focus on them when dealing with a cap in the number of active feature // instances we can look at final List<Integer> batchIndices = new ArrayList<Integer>(batch.size()); for (int i = 0; i < batch.size(); ++i) { batchIndices.add(Integer.valueOf(i)); } Collections.sort(batchIndices, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { final float deltaAbsErrorSums = absErrorSums[o1.intValue()] - absErrorSums[o2.intValue()]; if (deltaAbsErrorSums > 0.f) return -1; else if (deltaAbsErrorSums < 0.f) return 1; else return 0; } }); // Set of feature instances that we have already preserved (and hence must continue to preserve) final Set<CombinableFeatureInstancePair> preservedInstances = new HashSet<CombinableFeatureInstancePair>(); // Set of feature instances that we have already chosen to discard once (and hence must continue to discard) final Set<CombinableFeatureInstancePair> discardedInstances = new HashSet<CombinableFeatureInstancePair>(); // Loop through all samples in batch for (int bi = 0; bi < batchIndices.size(); ++bi) { final int batchIndex = batchIndices.get(bi).intValue(); final ExperienceSample sample = batch.get(batchIndex); final FVector errors = errorVectors[batchIndex]; final float minError = errors.min(); final float maxError = errors.max(); final FastArrayList<Move> moves = sample.moves(); final TIntArrayList sortedActionIndices = new TIntArrayList(); // Want to start looking at winning moves final BitSet winningMoves = sample.winningMoves(); for (int i = winningMoves.nextSetBit(0); i >= 0; i = winningMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // Look at losing moves next final BitSet losingMoves = sample.losingMoves(); for (int i = losingMoves.nextSetBit(0); i >= 0; i = losingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // And finally anti-defeating moves final BitSet antiDefeatingMoves = sample.antiDefeatingMoves(); for (int i = antiDefeatingMoves.nextSetBit(0); i >= 0; i = antiDefeatingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } final TIntArrayList unsortedActionIndices = new TIntArrayList(); for (int a = 0; a < moves.size(); ++a) { if (!winningMoves.get(a) && !losingMoves.get(a) && !antiDefeatingMoves.get(a)) unsortedActionIndices.add(a); } // Finally, randomly fill up with the remaining actions while (!unsortedActionIndices.isEmpty()) { final int r = ThreadLocalRandom.current().nextInt(unsortedActionIndices.size()); final int a = unsortedActionIndices.getQuick(r); ListUtils.removeSwap(unsortedActionIndices, r); sortedActionIndices.add(a); } // Every action in the sample is a new "case" (state-action pair) for (int aIdx = 0; aIdx < sortedActionIndices.size(); ++aIdx) { final int a = sortedActionIndices.getQuick(aIdx); // keep track of pairs we've already seen in this "case" final Set<CombinableFeatureInstancePair> observedCasePairs = new HashSet<CombinableFeatureInstancePair>(256, .75f); // list --> set --> list to get rid of duplicates final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(new HashSet<FeatureInstance>( featureSet.getActiveSpatialFeatureInstances ( sample.gameState(), sample.lastFromPos(), sample.lastToPos(), FeatureUtils.fromPos(moves.get(a)), FeatureUtils.toPos(moves.get(a)), moves.get(a).mover() ))); // Save a copy of the above list, which we leave unmodified final List<FeatureInstance> origActiveInstances = new ArrayList<FeatureInstance>(activeInstances); // Start out by keeping all feature instances that have already been marked as having to be // preserved, and discarding those that have already been discarded before final List<FeatureInstance> instancesToKeep = new ArrayList<FeatureInstance>(); // For every instance in activeInstances, also keep track of a combined-self version final List<CombinableFeatureInstancePair> activeInstancesCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // And same for instancesToKeep final List<CombinableFeatureInstancePair> instancesToKeepCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); for (int i = 0; i < activeInstances.size(); /**/) { final FeatureInstance instance = activeInstances.get(i); final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instance, instance); if (preservedInstances.contains(combinedSelf)) { // if (instancesToKeepCombinedSelfs.contains(combinedSelf)) // { // System.out.println("already contains: " + combinedSelf); // System.out.println("instance: " + instance); // } instancesToKeepCombinedSelfs.add(combinedSelf); instancesToKeep.add(instance); activeInstances.remove(i); } else if (discardedInstances.contains(combinedSelf)) { activeInstances.remove(i); } else { activeInstancesCombinedSelfs.add(combinedSelf); ++i; } } // This action is allowed to pick at most this many extra instances int numInstancesAllowedThisAction = Math.min ( Math.min ( 15, featureDiscoveryMaxNumFeatureInstances - preservedInstances.size() ), activeInstances.size() ); if (numInstancesAllowedThisAction > 0) { // boolean wantPrint = (numInstancesAllowedThisAction > 0); // if (wantPrint) // System.out.println("allowing " + numInstancesAllowedThisAction + " instances for " + moves.get(a) + " --- " + errors.get(a) + " --- " + // Arrays.toString(new boolean[] {winningMoves.get(a), losingMoves.get(a), antiDefeatingMoves.get(a)})); // Create distribution over active instances proportional to scores that reward // features that correlate strongly with errors, as well as features that, when active, // imply expectations of high absolute errors, as well as features that are often active // when absolute errors are high final FVector distr = new FVector(activeInstances.size()); for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); distr.set(i, (float) (featureErrorCorrelations[fIdx] + expectedAbsErrorGivenFeature[fIdx] + expectedFeatureTimesAbsError[fIdx])); } distr.softmax(1.0); // For every instance, divide its probability by the number of active instances for the same // feature (because that feature is sort of "overrepresented") for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); int featureCount = 0; for (int j = 0; j < origActiveInstances.size(); ++j) { if (origActiveInstances.get(j).feature().spatialFeatureSetIndex() == fIdx) ++featureCount; } distr.set(i, distr.get(i) / featureCount); } distr.normalise(); // for (int i = 0; i < activeInstances.size(); ++i) // { // System.out.println("prob = " + distr.get(i) + " for " + activeInstances.get(i)); // } // if (wantPrint) // System.out.println("activeInstancesCombinedSelfs = " + activeInstancesCombinedSelfs); // if (wantPrint) // System.out.println("distr = " + distr); while (numInstancesAllowedThisAction > 0) { // Sample another instance final int sampledIdx = distr.sampleFromDistribution(); // System.out.println("sampledIdx = " + sampledIdx); final CombinableFeatureInstancePair combinedSelf = activeInstancesCombinedSelfs.get(sampledIdx); final FeatureInstance keepInstance = activeInstances.get(sampledIdx); // System.out.println("keepInstance = " + keepInstance); instancesToKeep.add(keepInstance); instancesToKeepCombinedSelfs.add(combinedSelf); preservedInstances.add(combinedSelf); // Remember to preserve this one forever now distr.updateSoftmaxInvalidate(sampledIdx); // Don't want to pick the same index again --numInstancesAllowedThisAction; } // if (wantPrint) // System.out.println("num preserved instances = " + preservedInstances.size()); } // Mark all the instances that haven't been marked as preserved yet as discarded instead for (int i = 0; i < activeInstances.size(); ++i) { final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, activeInstances.get(i), activeInstances.get(i)); if (!preservedInstances.contains(combinedSelf)) discardedInstances.add(combinedSelf); } final int numActiveInstances = instancesToKeep.size(); float error = errors.get(a); if (winningMoves.get(a)) { error = minError; // Reward correlation with winning moves } else if (losingMoves.get(a)) { error = maxError; // Reward correlation with losing moves } else if (antiDefeatingMoves.get(a)) { error = Math.min(error, minError + 0.1f); // Reward correlation with anti-defeating moves } for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance instanceI = instancesToKeep.get(i); // increment entries on ''main diagonals'' final CombinableFeatureInstancePair combinedSelf = instancesToKeepCombinedSelfs.get(i); if (observedCasePairs.add(combinedSelf)) { TDoubleArrayList errorsList = errorLists.get(combinedSelf); if (errorsList == null) { errorsList = new TDoubleArrayList(); errorLists.put(combinedSelf, errorsList); } errorsList.add(error); } for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance instanceJ = instancesToKeep.get(j); // increment off-diagonal entries final CombinableFeatureInstancePair combined = new CombinableFeatureInstancePair(game, instanceI, instanceJ); if (!existingFeatures.contains(combined.combinedFeature)) { TDoubleArrayList errorsList = errorLists.get(combined); if (errorsList == null) { errorsList = new TDoubleArrayList(); errorLists.put(combined, errorsList); } errorsList.add(error); } } } } } // Construct all possible pairs and scores; one priority queue for proactive features, // and one for reactive features // // In priority queues, we want highest scores at the head, hence "reversed" implementation // of comparator final Comparator<ScoredFeatureInstancePair> comparator = new Comparator<ScoredFeatureInstancePair>() { @Override public int compare(final ScoredFeatureInstancePair o1, final ScoredFeatureInstancePair o2) { if (o1.score < o2.score) return 1; else if (o1.score > o2.score) return -1; else return 0; } }; final PriorityQueue<ScoredFeatureInstancePair> proactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); final PriorityQueue<ScoredFeatureInstancePair> reactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); for (final CombinableFeatureInstancePair pair : errorLists.keySet()) { // int numFriendElements = 0; // for (final FeatureElement element : ((RelativeFeature) pair.combinedFeature).pattern().featureElements()) // { // if (element.type() == ElementType.Friend && !element.not()) // ++numFriendElements; // } // final boolean couldBeWinFeature = (numFriendElements >= 3); if (!pair.a.equals(pair.b)) // Only interested in combinations of different instances { final double pairErrorReduction = computeMaxErrorReduction(errorLists.get(pair)); final CombinableFeatureInstancePair selfA = new CombinableFeatureInstancePair(game, pair.a, pair.a); final CombinableFeatureInstancePair selfB = new CombinableFeatureInstancePair(game, pair.b, pair.b); final double errorReductionA = computeMaxErrorReduction(errorLists.get(selfA)); final double errorReductionB = computeMaxErrorReduction(errorLists.get(selfB)); double score = pairErrorReduction - errorReductionA - errorReductionB; // if (couldBeWinFeature) // { // System.out.println("Might be win feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } if (pair.combinedFeature.isReactive()) reactivePairs.add(new ScoredFeatureInstancePair(pair, score)); else proactivePairs.add(new ScoredFeatureInstancePair(pair, score)); } } // System.out.println("--------------------------------------------------------"); // final PriorityQueue<ScoredFeatureInstancePair> allPairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // allPairs.addAll(proactivePairs); // allPairs.addAll(reactivePairs); // while (!allPairs.isEmpty()) // { // final ScoredFeatureInstancePair pair = allPairs.poll(); // // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.b, pair.pair.b) // ); // // final int pairActs = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double pairErrorSum = // errorSums.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // System.out.println("score = " + pair.score); // System.out.println("correlation with errors = " + errorCorr); // System.out.println("lower bound correlation with errors = " + lbErrorCorr); // System.out.println("upper bound correlation with errors = " + ubErrorCorr); // System.out.println("correlation with first constituent = " + featureCorrI); // System.out.println("correlation with second constituent = " + featureCorrJ); // System.out.println("active feature A = " + pair.pair.a.feature()); // System.out.println("rot A = " + pair.pair.a.rotation()); // System.out.println("ref A = " + pair.pair.a.reflection()); // System.out.println("anchor A = " + pair.pair.a.anchorSite()); // System.out.println("active feature B = " + pair.pair.b.feature()); // System.out.println("rot B = " + pair.pair.b.rotation()); // System.out.println("ref B = " + pair.pair.b.reflection()); // System.out.println("anchor B = " + pair.pair.b.anchorSite()); // System.out.println("observed pair of instances " + pairActs + " times"); // System.out.println("observed first constituent " + actsI + " times"); // System.out.println("observed second constituent " + actsJ + " times"); // System.out.println(); // } // System.out.println("--------------------------------------------------------"); // Keep trying to add a proactive feature, until we succeed (almost always // this should be on the very first iteration) BaseFeatureSet currFeatureSet = featureSet; // TODO pretty much duplicate code of block below, should refactor into method while (!proactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = proactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) // ); // // final CombinableFeatureInstancePair pair = // new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); // // final int pairActs = featurePairActivations.get(pair); // final double pairErrorSum = errorSums.get(pair); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // experiment.logLine(logWriter, "New proactive feature added!"); // experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); // experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); // experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); // experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); // experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); // experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); // experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); // experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); // experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); // experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); // experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); // experiment.logLine(logWriter, "score = " + bestPair.score); // experiment.logLine(logWriter, "correlation with errors = " + errorCorr); // experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); // experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); // experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); // experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); // experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); // experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); // experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } // Keep trying to add a reactive feature, until we succeed (almost always // this should be on the very first iteration) while (!reactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = reactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) // ); // // final CombinableFeatureInstancePair pair = // new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); // // final int pairActs = featurePairActivations.get(pair); // final double pairErrorSum = errorSums.get(pair); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // experiment.logLine(logWriter, "New reactive feature added!"); // experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); // experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); // experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); // experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); // experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); // experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); // experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); // experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); // experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); // experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); // experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); // experiment.logLine(logWriter, "score = " + bestPair.score); // experiment.logLine(logWriter, "correlation with errors = " + errorCorr); // experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); // experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); // experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); // experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); // experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); // experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); // experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } return currFeatureSet; } /** * @param errorsList * @return Estimate of maximum error reduction we can get from a single feature with * a given list of errors. */ private static final double computeMaxErrorReduction(final TDoubleArrayList errorsList) { errorsList.sort(); final int midIndex = (errorsList.size() - 1) / 2; final double median; if (errorsList.size() % 2 == 0) median = (errorsList.getQuick(midIndex) + errorsList.getQuick(midIndex + 1)) / 2.0; else median = errorsList.getQuick(midIndex); double origAbsErrorSum = 0.0; double newAbsErrorSum = 0.0; for (int i = 0; i < errorsList.size(); ++i) { origAbsErrorSum += Math.abs(errorsList.getQuick(i)); newAbsErrorSum += Math.abs(errorsList.getQuick(i) - median); } final double errorReduction = origAbsErrorSum - newAbsErrorSum; if (errorReduction < 0.0) System.err.println("ERROR: NEGATIVE ERROR REDUCTION!"); return errorReduction; } }
34,565
38.279545
144
java
Ludii
Ludii-master/AI/src/training/feature_discovery/FeatureSetExpander.java
package training.feature_discovery; import java.io.PrintWriter; import java.util.List; import features.feature_sets.BaseFeatureSet; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.list.array.TDoubleArrayList; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import utils.experiments.InterruptableExperiment; /** * Interface for an object that can create expanded versions of feature sets. * * @author Dennis Soemers */ public interface FeatureSetExpander { /** * @param batch Batch of samples of experience * @param featureSet Feature set to expand * @param policy Current policy with current weights for predictions * @param game * @param featureDiscoveryMaxNumFeatureInstances * @param objectiveParams * @param featureDiscoveryParams * @param featureActiveRatios * @param logWriter * @param experiment Experiment in which this is being used * @return Expanded version of given feature set, or null if no expanded version * was constructed. */ public BaseFeatureSet expandFeatureSet ( final List<? extends ExperienceSample> batch, final BaseFeatureSet featureSet, final SoftmaxPolicyLinear policy, final Game game, final int featureDiscoveryMaxNumFeatureInstances, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TDoubleArrayList featureActiveRatios, final PrintWriter logWriter, final InterruptableExperiment experiment ); //------------------------------------------------------------------------- /** * Wrapper class for a pair of combined feature instances and a score * * @author Dennis Soemers */ public static final class ScoredFeatureInstancePair { /** First int */ public final CombinableFeatureInstancePair pair; /** Score */ public final double score; /** * Constructor * @param pair * @param score */ public ScoredFeatureInstancePair(final CombinableFeatureInstancePair pair, final double score) { this.pair = pair; this.score = score; } } //------------------------------------------------------------------------- /** * Wrapper class for two feature instances that could be combined, with * hashCode() and equals() implementations that should be invariant to * small differences in instantiations (such as different anchor positions) * that would result in equal combined features. * * @author Dennis Soemers */ final class CombinableFeatureInstancePair { /** First feature instance */ public final FeatureInstance a; /** Second feature instance */ public final FeatureInstance b; /** Feature obtained by combining the two instances */ protected final SpatialFeature combinedFeature; /** Cached hash code */ private int cachedHash = Integer.MIN_VALUE; /** * Constructor * @param game * @param a * @param b */ public CombinableFeatureInstancePair ( final Game game, final FeatureInstance a, final FeatureInstance b ) { this.a = a; this.b = b; if (a == b) { combinedFeature = a.feature(); } else { // We don't just arbitrarily combine a with b, but want to make // sure to do so in a consistent, reproducible order if (a.feature().spatialFeatureSetIndex() < b.feature().spatialFeatureSetIndex()) { combinedFeature = SpatialFeature.combineFeatures(game, a, b); } else if (b.feature().spatialFeatureSetIndex() < a.feature().spatialFeatureSetIndex()) { combinedFeature = SpatialFeature.combineFeatures(game, b, a); } else { if (a.reflection() > b.reflection()) { combinedFeature = SpatialFeature.combineFeatures(game, a, b); } else if (b.reflection() > a.reflection()) { combinedFeature = SpatialFeature.combineFeatures(game, b, a); } else { if (a.rotation() < b.rotation()) { combinedFeature = SpatialFeature.combineFeatures(game, a, b); } else if (b.rotation() < a.rotation()) { combinedFeature = SpatialFeature.combineFeatures(game, b, a); } else { if (a.anchorSite() < b.anchorSite()) combinedFeature = SpatialFeature.combineFeatures(game, a, b); else if (b.anchorSite() < a.anchorSite()) combinedFeature = SpatialFeature.combineFeatures(game, b, a); else combinedFeature = SpatialFeature.combineFeatures(game, a, b); } } } } } @Override public boolean equals(final Object other) { if (!(other instanceof CombinableFeatureInstancePair)) return false; return combinedFeature.equals(((CombinableFeatureInstancePair) other).combinedFeature); } @Override public int hashCode() { if (cachedHash == Integer.MIN_VALUE) cachedHash = combinedFeature.hashCode(); return cachedHash; } @Override public String toString() { return combinedFeature + " (from " + a + " and " + b + ")"; } } /** * Wrapper class for a single feature instance, with equals() and * hashCode() implementations that ignore differences in anchor * position (and resulting differences in exactly which positions * we place requirements on). * * @author Dennis Soemers */ // final class AnchorInvariantFeatureInstance // { // // /** The feature instance */ // public final FeatureInstance instance; // // /** Cached hash code */ // private int cachedHash = Integer.MIN_VALUE; // // /** // * Constructor // * @param instance // */ // public AnchorInvariantFeatureInstance(final FeatureInstance instance) // { // this.instance = instance; // } // // @Override // public boolean equals(final Object other) // { // if (!(other instanceof AnchorInvariantFeatureInstance)) // return false; // // return instance.equalsIgnoreAnchor(((AnchorInvariantFeatureInstance) other).instance); // } // // @Override // public int hashCode() // { // if (cachedHash == Integer.MIN_VALUE) // cachedHash = instance.hashCodeIgnoreAnchor(); // // return cachedHash; // } // // @Override // public String toString() // { // return "[Anchor-invariant instance (from: " + instance + ")]"; // } // } //------------------------------------------------------------------------- }
6,469
24.983936
96
java
Ludii
Ludii-master/AI/src/training/feature_discovery/KolmogorovSmirnovExpander.java
package training.feature_discovery; import java.io.PrintWriter; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import features.FeatureVector; import features.feature_sets.BaseFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import main.collections.FVector; import main.collections.FastArrayList; import main.collections.ListUtils; import main.math.MathRoutines; import main.math.statistics.KolmogorovSmirnov; import main.math.statistics.Sampling; import other.move.Move; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.gradients.Gradients; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import utils.experiments.InterruptableExperiment; /** * Expands feature sets based on Kolmogorov-Smirnov statistics between distributions * of errors. * * @author Dennis Soemers */ public class KolmogorovSmirnovExpander implements FeatureSetExpander { @Override public BaseFeatureSet expandFeatureSet ( final List<? extends ExperienceSample> batch, final BaseFeatureSet featureSet, final SoftmaxPolicyLinear policy, final Game game, final int featureDiscoveryMaxNumFeatureInstances, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TDoubleArrayList featureActiveRatios, final PrintWriter logWriter, final InterruptableExperiment experiment ) { int numCases = 0; // we'll increment this as we go final Map<CombinableFeatureInstancePair, TDoubleArrayList> errorLists = new HashMap<CombinableFeatureInstancePair, TDoubleArrayList>(); // Create a Hash Set of features already in Feature Set; we won't // have to consider combinations that are already in final Set<SpatialFeature> existingFeatures = new HashSet<SpatialFeature> ( (int) Math.ceil(featureSet.getNumSpatialFeatures() / 0.75f), 0.75f ); for (final SpatialFeature feature : featureSet.spatialFeatures()) { existingFeatures.add(feature); } // For every sample in batch, first compute apprentice policies, errors, and sum of absolute errors final FVector[] apprenticePolicies = new FVector[batch.size()]; final FVector[] errorVectors = new FVector[batch.size()]; final float[] absErrorSums = new float[batch.size()]; final TDoubleArrayList[] errorsPerActiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; final TDoubleArrayList[] errorsPerInactiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; for (int i = 0; i < errorsPerActiveFeature.length; ++i) { errorsPerActiveFeature[i] = new TDoubleArrayList(); errorsPerInactiveFeature[i] = new TDoubleArrayList(); } double avgActionError = 0.0; for (int i = 0; i < batch.size(); ++i) { final ExperienceSample sample = batch.get(i); final FeatureVector[] featureVectors = sample.generateFeatureVectors(featureSet); final FVector apprenticePolicy = policy.computeDistribution(featureVectors, sample.gameState().mover()); final FVector errors = Gradients.computeDistributionErrors ( apprenticePolicy, sample.expertDistribution() ); for (int a = 0; a < featureVectors.length; ++a) { final float actionError = errors.get(a); final TIntArrayList sparseFeatureVector = featureVectors[a].activeSpatialFeatureIndices(); sparseFeatureVector.sort(); int sparseIdx = 0; for (int featureIdx = 0; featureIdx < featureSet.getNumSpatialFeatures(); ++featureIdx) { if (sparseIdx < sparseFeatureVector.size() && sparseFeatureVector.getQuick(sparseIdx) == featureIdx) { // This spatial feature is active errorsPerActiveFeature[featureIdx].add(actionError); // We've used the sparse index, so increment it ++sparseIdx; } else { // This spatial feature is not active errorsPerInactiveFeature[featureIdx].add(actionError); } } avgActionError += (actionError - avgActionError) / (numCases + 1); ++numCases; } final FVector absErrors = errors.copy(); absErrors.abs(); apprenticePolicies[i] = apprenticePolicy; errorVectors[i] = errors; absErrorSums[i] = absErrors.sum(); } // For every feature, compute sample correlation coefficient between its activity level (0 or 1) // and errors final double[] featureErrorCorrelations = new double[featureSet.getNumSpatialFeatures()]; // For every feature, compute expectation of absolute value of error given that feature is active final double[] expectedAbsErrorGivenFeature = new double[featureSet.getNumSpatialFeatures()]; // For every feature, computed expected value of feature activity times absolute error final double[] expectedFeatureTimesAbsError = new double[featureSet.getNumSpatialFeatures()]; for (int fIdx = 0; fIdx < featureSet.getNumSpatialFeatures(); ++fIdx) { final TDoubleArrayList errorsWhenActive = errorsPerActiveFeature[fIdx]; final TDoubleArrayList errorsWhenInactive = errorsPerInactiveFeature[fIdx]; final double avgFeatureVal = (double) errorsWhenActive.size() / (errorsWhenActive.size() + errorsPerInactiveFeature[fIdx].size()); double dErrorSquaresSum = 0.0; double numerator = 0.0; for (int i = 0; i < errorsWhenActive.size(); ++i) { final double error = errorsWhenActive.getQuick(i); final double dError = error - avgActionError; numerator += (1.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); expectedAbsErrorGivenFeature[fIdx] += (Math.abs(error) - expectedAbsErrorGivenFeature[fIdx]) / (i + 1); expectedFeatureTimesAbsError[fIdx] += (Math.abs(error) - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } for (int i = 0; i < errorsWhenInactive.size(); ++i) { final double error = errorsWhenInactive.getQuick(i); final double dError = error - avgActionError; numerator += (0.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); expectedFeatureTimesAbsError[fIdx] += (0.0 - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } final double dFeatureSquaresSum = errorsWhenActive.size() * ((1.0 - avgFeatureVal) * (1.0 - avgFeatureVal)) + errorsWhenInactive.size() * ((0.0 - avgFeatureVal) * (0.0 - avgFeatureVal)); final double denominator = Math.sqrt(dFeatureSquaresSum * dErrorSquaresSum); featureErrorCorrelations[fIdx] = numerator / denominator; if (Double.isNaN(featureErrorCorrelations[fIdx])) featureErrorCorrelations[fIdx] = 0.f; } // Create list of indices that we can use to index into batch, sorted in descending order // of sums of absolute errors. // This means that we prioritise looking at samples in the batch for which we have big policy // errors, and hence also focus on them when dealing with a cap in the number of active feature // instances we can look at final List<Integer> batchIndices = new ArrayList<Integer>(batch.size()); for (int i = 0; i < batch.size(); ++i) { batchIndices.add(Integer.valueOf(i)); } Collections.sort(batchIndices, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { final float deltaAbsErrorSums = absErrorSums[o1.intValue()] - absErrorSums[o2.intValue()]; if (deltaAbsErrorSums > 0.f) return -1; else if (deltaAbsErrorSums < 0.f) return 1; else return 0; } }); // Set of feature instances that we have already preserved (and hence must continue to preserve) final Set<CombinableFeatureInstancePair> preservedInstances = new HashSet<CombinableFeatureInstancePair>(); // Set of feature instances that we have already chosen to discard once (and hence must continue to discard) final Set<CombinableFeatureInstancePair> discardedInstances = new HashSet<CombinableFeatureInstancePair>(); // Loop through all samples in batch for (int bi = 0; bi < batchIndices.size(); ++bi) { final int batchIndex = batchIndices.get(bi).intValue(); final ExperienceSample sample = batch.get(batchIndex); final FVector errors = errorVectors[batchIndex]; final float minError = errors.min(); final float maxError = errors.max(); final FastArrayList<Move> moves = sample.moves(); final TIntArrayList sortedActionIndices = new TIntArrayList(); // Want to start looking at winning moves final BitSet winningMoves = sample.winningMoves(); for (int i = winningMoves.nextSetBit(0); i >= 0; i = winningMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // Look at losing moves next final BitSet losingMoves = sample.losingMoves(); for (int i = losingMoves.nextSetBit(0); i >= 0; i = losingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // And finally anti-defeating moves final BitSet antiDefeatingMoves = sample.antiDefeatingMoves(); for (int i = antiDefeatingMoves.nextSetBit(0); i >= 0; i = antiDefeatingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } final TIntArrayList unsortedActionIndices = new TIntArrayList(); for (int a = 0; a < moves.size(); ++a) { if (!winningMoves.get(a) && !losingMoves.get(a) && !antiDefeatingMoves.get(a)) unsortedActionIndices.add(a); } // Finally, randomly fill up with the remaining actions while (!unsortedActionIndices.isEmpty()) { final int r = ThreadLocalRandom.current().nextInt(unsortedActionIndices.size()); final int a = unsortedActionIndices.getQuick(r); ListUtils.removeSwap(unsortedActionIndices, r); sortedActionIndices.add(a); } // Every action in the sample is a new "case" (state-action pair) for (int aIdx = 0; aIdx < sortedActionIndices.size(); ++aIdx) { final int a = sortedActionIndices.getQuick(aIdx); // keep track of pairs we've already seen in this "case" final Set<CombinableFeatureInstancePair> observedCasePairs = new HashSet<CombinableFeatureInstancePair>(256, .75f); // list --> set --> list to get rid of duplicates final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(new HashSet<FeatureInstance>( featureSet.getActiveSpatialFeatureInstances ( sample.gameState(), sample.lastFromPos(), sample.lastToPos(), FeatureUtils.fromPos(moves.get(a)), FeatureUtils.toPos(moves.get(a)), moves.get(a).mover() ))); // Save a copy of the above list, which we leave unmodified final List<FeatureInstance> origActiveInstances = new ArrayList<FeatureInstance>(activeInstances); // Start out by keeping all feature instances that have already been marked as having to be // preserved, and discarding those that have already been discarded before final List<FeatureInstance> instancesToKeep = new ArrayList<FeatureInstance>(); // For every instance in activeInstances, also keep track of a combined-self version final List<CombinableFeatureInstancePair> activeInstancesCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // And same for instancesToKeep final List<CombinableFeatureInstancePair> instancesToKeepCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); for (int i = 0; i < activeInstances.size(); /**/) { final FeatureInstance instance = activeInstances.get(i); final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instance, instance); if (preservedInstances.contains(combinedSelf)) { // if (instancesToKeepCombinedSelfs.contains(combinedSelf)) // { // System.out.println("already contains: " + combinedSelf); // System.out.println("instance: " + instance); // } instancesToKeepCombinedSelfs.add(combinedSelf); instancesToKeep.add(instance); activeInstances.remove(i); } else if (discardedInstances.contains(combinedSelf)) { activeInstances.remove(i); } else if (featureActiveRatios.getQuick(instance.feature().spatialFeatureSetIndex()) == 1.0) { activeInstances.remove(i); } else { activeInstancesCombinedSelfs.add(combinedSelf); ++i; } } // This action is allowed to pick at most this many extra instances int numInstancesAllowedThisAction = Math.min ( Math.min ( 50, featureDiscoveryMaxNumFeatureInstances - preservedInstances.size() ), activeInstances.size() ); if (numInstancesAllowedThisAction > 0) { // Create distribution over active instances proportional to scores that reward // features that correlate strongly with errors, as well as features that, when active, // imply expectations of high absolute errors, as well as features that are often active // when absolute errors are high, as well as features that have high absolute weights final FVector distr = new FVector(activeInstances.size()); for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); distr.set ( i, (float) ( featureErrorCorrelations[fIdx] + expectedAbsErrorGivenFeature[fIdx] + expectedFeatureTimesAbsError[fIdx] + Math.abs ( policy.linearFunction ( sample.gameState().mover() ).effectiveParams().allWeights().get(fIdx + featureSet.getNumAspatialFeatures()) ) ) ); } distr.softmax(1.0); // For every instance, divide its probability by the number of active instances for the same // feature (because that feature is sort of "overrepresented") for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); int featureCount = 0; for (int j = 0; j < origActiveInstances.size(); ++j) { if (origActiveInstances.get(j).feature().spatialFeatureSetIndex() == fIdx) ++featureCount; } distr.set(i, distr.get(i) / featureCount); } distr.normalise(); // for (int i = 0; i < activeInstances.size(); ++i) // { // System.out.println("prob = " + distr.get(i) + " for " + activeInstances.get(i)); // } while (numInstancesAllowedThisAction > 0) { // Sample another instance final int sampledIdx = distr.sampleFromDistribution(); final CombinableFeatureInstancePair combinedSelf = activeInstancesCombinedSelfs.get(sampledIdx); final FeatureInstance keepInstance = activeInstances.get(sampledIdx); instancesToKeep.add(keepInstance); instancesToKeepCombinedSelfs.add(combinedSelf); preservedInstances.add(combinedSelf); // Remember to preserve this one forever now distr.updateSoftmaxInvalidate(sampledIdx); // Don't want to pick the same index again --numInstancesAllowedThisAction; } } // Mark all the instances that haven't been marked as preserved yet as discarded instead for (int i = 0; i < activeInstances.size(); ++i) { final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, activeInstances.get(i), activeInstances.get(i)); if (!preservedInstances.contains(combinedSelf)) discardedInstances.add(combinedSelf); } final int numActiveInstances = instancesToKeep.size(); float error = errors.get(a); if (winningMoves.get(a)) { error = minError; // Reward correlation with winning moves } else if (losingMoves.get(a)) { error = maxError; // Reward correlation with losing moves } else if (antiDefeatingMoves.get(a)) { error = Math.min(error, minError + 0.1f); // Reward correlation with anti-defeating moves } for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance instanceI = instancesToKeep.get(i); // increment entries on ''main diagonals'' final CombinableFeatureInstancePair combinedSelf = instancesToKeepCombinedSelfs.get(i); if (observedCasePairs.add(combinedSelf)) { TDoubleArrayList errorsList = errorLists.get(combinedSelf); if (errorsList == null) { errorsList = new TDoubleArrayList(); errorLists.put(combinedSelf, errorsList); } errorsList.add(error); } for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance instanceJ = instancesToKeep.get(j); // increment off-diagonal entries final CombinableFeatureInstancePair combined = new CombinableFeatureInstancePair(game, instanceI, instanceJ); if (!existingFeatures.contains(combined.combinedFeature)) { if (observedCasePairs.add(combined)) { TDoubleArrayList errorsList = errorLists.get(combined); if (errorsList == null) { errorsList = new TDoubleArrayList(); errorLists.put(combined, errorsList); } errorsList.add(error); } } } } } } // Construct all possible pairs and scores; one priority queue for proactive features, // and one for reactive features // // In priority queues, we want highest scores at the head, hence "reversed" implementation // of comparator final Comparator<ScoredFeatureInstancePair> comparator = new Comparator<ScoredFeatureInstancePair>() { @Override public int compare(final ScoredFeatureInstancePair o1, final ScoredFeatureInstancePair o2) { if (o1.score < o2.score) return 1; else if (o1.score > o2.score) return -1; else return 0; } }; final PriorityQueue<ScoredFeatureInstancePair> proactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); final PriorityQueue<ScoredFeatureInstancePair> reactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); for (final CombinableFeatureInstancePair pair : errorLists.keySet()) { // int numFriendElements = 0; // for (final FeatureElement element : ((RelativeFeature) pair.combinedFeature).pattern().featureElements()) // { // if (element.type() == ElementType.Friend && !element.not()) // ++numFriendElements; // } // final boolean couldBeWinFeature = (numFriendElements >= 3); if (!pair.a.equals(pair.b)) // Only interested in combinations of different instances { final TDoubleArrayList pairErrors = errorLists.get(pair); final TDoubleArrayList errorsA = errorLists.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); final TDoubleArrayList errorsB = errorLists.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); pairErrors.sort(); errorsA.sort(); errorsB.sort(); if (pairErrors.equals(errorsA) || pairErrors.equals(errorsB)) continue; final int minSampleSize = 50; // Synthetically create more samples if we don't have at least this many final int numRealPairSamples = pairErrors.size(); while (pairErrors.size() < minSampleSize) { // Add a new sample drawn from a gaussian around a real sample final double realSample = pairErrors.getQuick(ThreadLocalRandom.current().nextInt(numRealPairSamples)); final double syntheticSample = MathRoutines.clip(ThreadLocalRandom.current().nextGaussian() * 0.1 + realSample, -1.0, 1.0); pairErrors.add(syntheticSample); } final int numRealSamplesA = errorsA.size(); while (errorsA.size() < minSampleSize) { // Add a new sample drawn from a gaussian around a real sample final double realSample = errorsA.getQuick(ThreadLocalRandom.current().nextInt(numRealSamplesA)); final double syntheticSample = MathRoutines.clip(ThreadLocalRandom.current().nextGaussian() * 0.1 + realSample, -1.0, 1.0); errorsA.add(syntheticSample); } final int numRealSamplesB = errorsB.size(); while (errorsB.size() < minSampleSize) { // Add a new sample drawn from a gaussian around a real sample final double realSample = errorsB.getQuick(ThreadLocalRandom.current().nextInt(numRealSamplesB)); final double syntheticSample = MathRoutines.clip(ThreadLocalRandom.current().nextGaussian() * 0.1 + realSample, -1.0, 1.0); errorsB.add(syntheticSample); } final int numBootstrapsPerConstituent = 10; double minKolmogorovSmirnovDistance = 0.0; for (int i = 0; i < numBootstrapsPerConstituent; ++i) { final TDoubleArrayList bootstrapA = Sampling.sampleWithReplacement(Math.min(150, pairErrors.size()), errorsA); final TDoubleArrayList bootstrapB = Sampling.sampleWithReplacement(Math.min(150, pairErrors.size()), errorsB); final TDoubleArrayList bootstrapPair = Sampling.sampleWithReplacement(Math.min(150, pairErrors.size()), pairErrors); final double ksA = KolmogorovSmirnov.kolmogorovSmirnovStatistic(bootstrapPair, bootstrapA); final double ksB = KolmogorovSmirnov.kolmogorovSmirnovStatistic(bootstrapPair, bootstrapB); if (ksA < minKolmogorovSmirnovDistance) minKolmogorovSmirnovDistance = ksA; if (ksB < minKolmogorovSmirnovDistance) minKolmogorovSmirnovDistance = ksB; } final double score = minKolmogorovSmirnovDistance; // if (couldBeWinFeature) // { // System.out.println("Might be win feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } if (pair.combinedFeature.isReactive()) reactivePairs.add(new ScoredFeatureInstancePair(pair, score)); else proactivePairs.add(new ScoredFeatureInstancePair(pair, score)); } } // System.out.println("--------------------------------------------------------"); // final PriorityQueue<ScoredFeatureInstancePair> allPairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // allPairs.addAll(proactivePairs); // allPairs.addAll(reactivePairs); // while (!allPairs.isEmpty()) // { // final ScoredFeatureInstancePair pair = allPairs.poll(); // // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.b, pair.pair.b) // ); // // final int pairActs = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double pairErrorSum = // errorSums.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // System.out.println("score = " + pair.score); // System.out.println("correlation with errors = " + errorCorr); // System.out.println("lower bound correlation with errors = " + lbErrorCorr); // System.out.println("upper bound correlation with errors = " + ubErrorCorr); // System.out.println("correlation with first constituent = " + featureCorrI); // System.out.println("correlation with second constituent = " + featureCorrJ); // System.out.println("active feature A = " + pair.pair.a.feature()); // System.out.println("rot A = " + pair.pair.a.rotation()); // System.out.println("ref A = " + pair.pair.a.reflection()); // System.out.println("anchor A = " + pair.pair.a.anchorSite()); // System.out.println("active feature B = " + pair.pair.b.feature()); // System.out.println("rot B = " + pair.pair.b.rotation()); // System.out.println("ref B = " + pair.pair.b.reflection()); // System.out.println("anchor B = " + pair.pair.b.anchorSite()); // System.out.println("observed pair of instances " + pairActs + " times"); // System.out.println("observed first constituent " + actsI + " times"); // System.out.println("observed second constituent " + actsJ + " times"); // System.out.println(); // } // System.out.println("--------------------------------------------------------"); // Keep trying to add a proactive feature, until we succeed (almost always // this should be on the very first iteration) BaseFeatureSet currFeatureSet = featureSet; // TODO pretty much duplicate code of block below, should refactor into method while (!proactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = proactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) // ); // // final CombinableFeatureInstancePair pair = // new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); // // final int pairActs = featurePairActivations.get(pair); // final double pairErrorSum = errorSums.get(pair); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // experiment.logLine(logWriter, "New proactive feature added!"); // experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); // experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); // experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); // experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); // experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); // experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); // experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); // experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); // experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); // experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); // experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); // experiment.logLine(logWriter, "score = " + bestPair.score); // experiment.logLine(logWriter, "correlation with errors = " + errorCorr); // experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); // experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); // experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); // experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); // experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); // experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); // experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } // Keep trying to add a reactive feature, until we succeed (almost always // this should be on the very first iteration) while (!reactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = reactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) // ); // // final CombinableFeatureInstancePair pair = // new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); // // final int pairActs = featurePairActivations.get(pair); // final double pairErrorSum = errorSums.get(pair); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // experiment.logLine(logWriter, "New reactive feature added!"); // experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); // experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); // experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); // experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); // experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); // experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); // experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); // experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); // experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); // experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); // experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); // experiment.logLine(logWriter, "score = " + bestPair.score); // experiment.logLine(logWriter, "correlation with errors = " + errorCorr); // experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); // experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); // experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); // experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); // experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); // experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); // experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } return currFeatureSet; } }
35,898
38.23388
144
java
Ludii
Ludii-master/AI/src/training/feature_discovery/RandomExpander.java
package training.feature_discovery; import java.io.PrintWriter; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import features.FeatureVector; import features.feature_sets.BaseFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.impl.Constants; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TObjectIntHashMap; import main.collections.FVector; import main.collections.FastArrayList; import main.collections.ListUtils; import other.move.Move; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.gradients.Gradients; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import utils.experiments.InterruptableExperiment; /** * Random Feature Set Expander. * * @author Dennis Soemers */ public class RandomExpander implements FeatureSetExpander { @Override public BaseFeatureSet expandFeatureSet ( final List<? extends ExperienceSample> batch, final BaseFeatureSet featureSet, final SoftmaxPolicyLinear policy, final Game game, final int featureDiscoveryMaxNumFeatureInstances, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TDoubleArrayList featureActiveRatios, final PrintWriter logWriter, final InterruptableExperiment experiment ) { // System.out.println("-------------------------------------------------------------------"); int numCases = 0; // we'll increment this as we go // this is our C_f matrix final TObjectIntHashMap<CombinableFeatureInstancePair> featurePairActivations = new TObjectIntHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0); // Create a Hash Set of features already in Feature Set; we won't // have to consider combinations that are already in final Set<SpatialFeature> existingFeatures = new HashSet<SpatialFeature> ( (int) Math.ceil(featureSet.getNumSpatialFeatures() / 0.75f), 0.75f ); for (final SpatialFeature feature : featureSet.spatialFeatures()) { existingFeatures.add(feature); } // For every sample in batch, first compute apprentice policies, errors, and sum of absolute errors final FVector[] apprenticePolicies = new FVector[batch.size()]; final FVector[] errorVectors = new FVector[batch.size()]; final float[] absErrorSums = new float[batch.size()]; final TDoubleArrayList[] errorsPerActiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; final TDoubleArrayList[] errorsPerInactiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; for (int i = 0; i < errorsPerActiveFeature.length; ++i) { errorsPerActiveFeature[i] = new TDoubleArrayList(); errorsPerInactiveFeature[i] = new TDoubleArrayList(); } double avgActionError = 0.0; for (int i = 0; i < batch.size(); ++i) { final ExperienceSample sample = batch.get(i); final FeatureVector[] featureVectors = sample.generateFeatureVectors(featureSet); final FVector apprenticePolicy = policy.computeDistribution(featureVectors, sample.gameState().mover()); final FVector errors = Gradients.computeDistributionErrors ( apprenticePolicy, sample.expertDistribution() ); for (int a = 0; a < featureVectors.length; ++a) { final float actionError = errors.get(a); final TIntArrayList sparseFeatureVector = featureVectors[a].activeSpatialFeatureIndices(); sparseFeatureVector.sort(); int sparseIdx = 0; for (int featureIdx = 0; featureIdx < featureSet.getNumSpatialFeatures(); ++featureIdx) { if (sparseIdx < sparseFeatureVector.size() && sparseFeatureVector.getQuick(sparseIdx) == featureIdx) { // This spatial feature is active errorsPerActiveFeature[featureIdx].add(actionError); // We've used the sparse index, so increment it ++sparseIdx; } else { // This spatial feature is not active errorsPerInactiveFeature[featureIdx].add(actionError); } } avgActionError += (actionError - avgActionError) / (numCases + 1); ++numCases; } final FVector absErrors = errors.copy(); absErrors.abs(); apprenticePolicies[i] = apprenticePolicy; errorVectors[i] = errors; absErrorSums[i] = absErrors.sum(); } // For every feature, compute expectation of absolute value of error given that feature is active final double[] expectedAbsErrorGivenFeature = new double[featureSet.getNumSpatialFeatures()]; // For every feature, computed expected value of feature activity times absolute error // final double[] expectedFeatureTimesAbsError = new double[featureSet.getNumSpatialFeatures()]; for (int fIdx = 0; fIdx < featureSet.getNumSpatialFeatures(); ++fIdx) { final TDoubleArrayList errorsWhenActive = errorsPerActiveFeature[fIdx]; for (int i = 0; i < errorsWhenActive.size(); ++i) { final double error = errorsWhenActive.getQuick(i); expectedAbsErrorGivenFeature[fIdx] += (Math.abs(error) - expectedAbsErrorGivenFeature[fIdx]) / (i + 1); } } // Create list of indices that we can use to index into batch, sorted in descending order // of sums of absolute errors. // This means that we prioritise looking at samples in the batch for which we have big policy // errors, and hence also focus on them when dealing with a cap in the number of active feature // instances we can look at final List<Integer> batchIndices = new ArrayList<Integer>(batch.size()); for (int i = 0; i < batch.size(); ++i) { batchIndices.add(Integer.valueOf(i)); } Collections.sort(batchIndices, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { final float deltaAbsErrorSums = absErrorSums[o1.intValue()] - absErrorSums[o2.intValue()]; if (deltaAbsErrorSums > 0.f) return -1; else if (deltaAbsErrorSums < 0.f) return 1; else return 0; } }); // Set of feature instances that we have already preserved (and hence must continue to preserve) final Set<CombinableFeatureInstancePair> preservedInstances = new HashSet<CombinableFeatureInstancePair>(); // Set of feature instances that we have already chosen to discard once (and hence must continue to discard) final Set<CombinableFeatureInstancePair> discardedInstances = new HashSet<CombinableFeatureInstancePair>(); // Loop through all samples in batch for (int bi = 0; bi < batchIndices.size(); ++bi) { final int batchIndex = batchIndices.get(bi).intValue(); final ExperienceSample sample = batch.get(batchIndex); final FastArrayList<Move> moves = sample.moves(); final TIntArrayList sortedActionIndices = new TIntArrayList(); // Want to start looking at winning moves final BitSet winningMoves = sample.winningMoves(); for (int i = winningMoves.nextSetBit(0); i >= 0; i = winningMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // Look at losing moves next final BitSet losingMoves = sample.losingMoves(); for (int i = losingMoves.nextSetBit(0); i >= 0; i = losingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // And finally anti-defeating moves final BitSet antiDefeatingMoves = sample.antiDefeatingMoves(); for (int i = antiDefeatingMoves.nextSetBit(0); i >= 0; i = antiDefeatingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } final TIntArrayList unsortedActionIndices = new TIntArrayList(); for (int a = 0; a < moves.size(); ++a) { if (!winningMoves.get(a) && !losingMoves.get(a) && !antiDefeatingMoves.get(a)) unsortedActionIndices.add(a); } // Finally, randomly fill up with the remaining actions while (!unsortedActionIndices.isEmpty()) { final int r = ThreadLocalRandom.current().nextInt(unsortedActionIndices.size()); final int a = unsortedActionIndices.getQuick(r); ListUtils.removeSwap(unsortedActionIndices, r); sortedActionIndices.add(a); } // Every action in the sample is a new "case" (state-action pair) for (int aIdx = 0; aIdx < sortedActionIndices.size(); ++aIdx) { final int a = sortedActionIndices.getQuick(aIdx); // keep track of pairs we've already seen in this "case" final Set<CombinableFeatureInstancePair> observedCasePairs = new HashSet<CombinableFeatureInstancePair>(256, .75f); // list --> set --> list to get rid of duplicates final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(new HashSet<FeatureInstance>( featureSet.getActiveSpatialFeatureInstances ( sample.gameState(), sample.lastFromPos(), sample.lastToPos(), FeatureUtils.fromPos(moves.get(a)), FeatureUtils.toPos(moves.get(a)), moves.get(a).mover() ))); // Save a copy of the above list, which we leave unmodified final List<FeatureInstance> origActiveInstances = new ArrayList<FeatureInstance>(activeInstances); // Start out by keeping all feature instances that have already been marked as having to be // preserved, and discarding those that have already been discarded before final List<FeatureInstance> instancesToKeep = new ArrayList<FeatureInstance>(); // For every instance in activeInstances, also keep track of a combined-self version final List<CombinableFeatureInstancePair> activeInstancesCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // And same for instancesToKeep final List<CombinableFeatureInstancePair> instancesToKeepCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // int numRelevantConstituents = 0; for (int i = 0; i < activeInstances.size(); /**/) { final FeatureInstance instance = activeInstances.get(i); final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instance, instance); if (preservedInstances.contains(combinedSelf)) { // if (instancesToKeepCombinedSelfs.contains(combinedSelf)) // { // System.out.println("already contains: " + combinedSelf); // System.out.println("instance: " + instance); // } instancesToKeepCombinedSelfs.add(combinedSelf); instancesToKeep.add(instance); ListUtils.removeSwap(activeInstances, i); } else if (discardedInstances.contains(combinedSelf)) { ListUtils.removeSwap(activeInstances, i); } else if (featureActiveRatios.getQuick(instance.feature().spatialFeatureSetIndex()) == 1.0) { ListUtils.removeSwap(activeInstances, i); } else { activeInstancesCombinedSelfs.add(combinedSelf); ++i; } } // if (activeInstances.size() > 0) // System.out.println(activeInstances.size() + "/" + origActiveInstances.size() + " left"); // This action is allowed to pick at most this many extra instances int numInstancesAllowedThisAction = Math.min ( Math.min ( 50, featureDiscoveryMaxNumFeatureInstances - preservedInstances.size() ), activeInstances.size() ); if (numInstancesAllowedThisAction > 0) { // System.out.println("allowed to add " + numInstancesAllowedThisAction + " instances"); // Create distribution over active instances proportional to scores that reward // features that correlate strongly with errors, as well as features that, when active, // imply expectations of high absolute errors, as well as features that are often active // when absolute errors are high, as well as features that have high absolute weights final FVector distr = new FVector(activeInstances.size()); for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); distr.set ( i, (float) ( expectedAbsErrorGivenFeature[fIdx] ) ); } distr.softmax(2.0); // For every instance, divide its probability by the number of active instances for the same // feature (because that feature is sort of "overrepresented") for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); int featureCount = 0; for (int j = 0; j < origActiveInstances.size(); ++j) { if (origActiveInstances.get(j).feature().spatialFeatureSetIndex() == fIdx) ++featureCount; } distr.set(i, distr.get(i) / featureCount); } distr.normalise(); while (numInstancesAllowedThisAction > 0) { // Sample another instance final int sampledIdx = distr.sampleFromDistribution(); final CombinableFeatureInstancePair combinedSelf = activeInstancesCombinedSelfs.get(sampledIdx); final FeatureInstance keepInstance = activeInstances.get(sampledIdx); instancesToKeep.add(keepInstance); instancesToKeepCombinedSelfs.add(combinedSelf); preservedInstances.add(combinedSelf); // Remember to preserve this one forever now distr.updateSoftmaxInvalidate(sampledIdx); // Don't want to pick the same index again --numInstancesAllowedThisAction; // Maybe now have to auto-pick several other instances if they lead to equal combinedSelf for (int i = 0; i < distr.dim(); ++i) { if (distr.get(0) != 0.f) { if (combinedSelf.equals(activeInstancesCombinedSelfs.get(i))) { //System.out.println("auto-picking " + activeInstances.get(i) + " after " + keepInstance); instancesToKeep.add(activeInstances.get(i)); instancesToKeepCombinedSelfs.add(activeInstancesCombinedSelfs.get(i)); distr.updateSoftmaxInvalidate(i); // Don't want to pick the same index again --numInstancesAllowedThisAction; } } } } } // Mark all the instances that haven't been marked as preserved yet as discarded instead for (int i = 0; i < activeInstances.size(); ++i) { final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, activeInstances.get(i), activeInstances.get(i)); if (!preservedInstances.contains(combinedSelf)) discardedInstances.add(combinedSelf); } final int numActiveInstances = instancesToKeep.size(); //System.out.println("numActiveInstances = " + numActiveInstances); for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance instanceI = instancesToKeep.get(i); // increment entries on ''main diagonals'' final CombinableFeatureInstancePair combinedSelf = instancesToKeepCombinedSelfs.get(i); if (observedCasePairs.add(combinedSelf)) { featurePairActivations.adjustOrPutValue(combinedSelf, 1, 1); } for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance instanceJ = instancesToKeep.get(j); // increment off-diagonal entries final CombinableFeatureInstancePair combined = new CombinableFeatureInstancePair(game, instanceI, instanceJ); if (!existingFeatures.contains(combined.combinedFeature)) { if (observedCasePairs.add(combined)) { featurePairActivations.adjustOrPutValue(combined, 1, 1); } } } } } } final List<CombinableFeatureInstancePair> proactivePairs = new ArrayList<CombinableFeatureInstancePair>(); final List<CombinableFeatureInstancePair> reactivePairs = new ArrayList<CombinableFeatureInstancePair>(); // Randomly pick a minimum required sample size in [3, 5] final int requiredSampleSize = 3 + ThreadLocalRandom.current().nextInt(3); for (final CombinableFeatureInstancePair pair : featurePairActivations.keySet()) { if (!pair.a.equals(pair.b)) // Only interested in combinations of different instances { final int pairActs = featurePairActivations.get(pair); if (pairActs == numCases || numCases < 4) { // Perfect correlation, so we should just skip this one continue; } if (pairActs < requiredSampleSize) { // Need a bigger sample size continue; } final int actsI = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); final int actsJ = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); if (actsI == numCases || actsJ == numCases || pairActs == actsI || pairActs == actsJ) { // Perfect correlation, so we should just skip this one continue; } if (pair.combinedFeature.isReactive()) reactivePairs.add(pair); else proactivePairs.add(pair); } } // Shuffle lists for random feature combination Collections.shuffle(proactivePairs); Collections.shuffle(reactivePairs); // Keep trying to add a proactive feature, until we succeed (almost always // this should be on the very first iteration) BaseFeatureSet currFeatureSet = featureSet; // TODO pretty much duplicate code of block below, should refactor into method while (!proactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final CombinableFeatureInstancePair bestPair = proactivePairs.remove(proactivePairs.size() - 1); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.a, bestPair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.b, bestPair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.a, bestPair.b); final int pairActs = featurePairActivations.get(pair); experiment.logLine(logWriter, "New proactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.b.anchorSite()); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } // Keep trying to add a reactive feature, until we succeed (almost always // this should be on the very first iteration) while (!reactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final CombinableFeatureInstancePair bestPair = reactivePairs.remove(reactivePairs.size() - 1); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.a, bestPair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.b, bestPair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.a, bestPair.b); final int pairActs = featurePairActivations.get(pair); experiment.logLine(logWriter, "New reactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.b.anchorSite()); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } return currFeatureSet; } }
21,679
36.37931
144
java
Ludii
Ludii-master/AI/src/training/feature_discovery/SpecialMovesCorrelationExpander.java
package training.feature_discovery; import java.io.PrintWriter; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import features.FeatureVector; import features.feature_sets.BaseFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.impl.Constants; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TObjectDoubleHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import main.collections.FVector; import main.collections.FastArrayList; import main.collections.ListUtils; import other.move.Move; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import utils.experiments.InterruptableExperiment; /** * Feature Set Expander that simply likes correlations with special moves * (winning moves, losing moves, anti-defeating moves). * * @author Dennis Soemers */ public class SpecialMovesCorrelationExpander implements FeatureSetExpander { @Override public BaseFeatureSet expandFeatureSet ( final List<? extends ExperienceSample> batch, final BaseFeatureSet featureSet, final SoftmaxPolicyLinear policy, final Game game, final int featureDiscoveryMaxNumFeatureInstances, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TDoubleArrayList featureActiveRatios, final PrintWriter logWriter, final InterruptableExperiment experiment ) { // we need a matrix C_f with, at every entry (i, j), // the sum of cases in which features i and j are both active // // we also need a similar matrix C_e with, at every entry (i, j), // the sum of errors in cases where features i and j are both active // // NOTE: both of the above are symmetric matrices // // we also need a vector X_f with, for every feature i, the sum of // cases where feature i is active. (we would need a similar vector // with sums of squares, but that can be omitted because our features // are binary) // // NOTE: in writing it is easier to mention X_f as described above as // a separate vector, but actually we don't need it; we can simply // use the main diagonal of C_f instead // // we need a scalar S which is the sum of all errors, // and a scalar SS which is the sum of all squared errors // // Given a candidate pair of features (i, j), we can compute the // correlation of that pair of features with the errors (an // indicator of the candidate pair's potential to be useful) as // (where n = the number of cases = number of state-action pairs): // // // n * C_e(i, j) - C_f(i, j) * S //------------------------------------------------------------ // SQRT( n * C_f(i, j) - C_f(i, j)^2 ) * SQRT( n * SS - S^2 ) // // // For numeric stability with extremely large batch sizes, // it is better to compute this as: // // n * C_e(i, j) - C_f(i, j) * S //------------------------------------------------------------ // SQRT( C_f(i, j) * (n - C_f(i, j)) ) * SQRT( n * SS - S^2 ) // // // We can similarly compare the correlation between any candidate pair // of features (i, j) and either of its constituents i (an indicator // of redundancy of the candidate pair) as: // // // n * C_f(i, j) - C_f(i, j) * X_f(i) //-------------------------------------------------------------------- // SQRT( n * C_f(i, j) - C_f(i, j)^2 ) * SQRT( n * X_f(i) - X_f(i)^2 ) // // // For numeric stability with extremely large batch sizes, // it is better to compute this as: // // C_f(i, j) * (n - X_f(i)) //-------------------------------------------------------------------- // SQRT( C_f(i, j) * (n - C_f(i, j)) ) * SQRT( X_f(i) * (n - X_f(i)) ) // // // (note; even better would be if we could compute correlation between // candidate pair and ANY other feature, rather than just its // constituents, but that would probably become too expensive) // // We want to maximise the absolute value of the first (correlation // between candidate feature pair and distribution error), but minimise // the worst-case absolute value of the second (correlation between // candidate feature pair and either of its constituents). // // // NOTE: in all of the above, when we say "feature", we actually // refer to a particular instantiation of a feature. This is important, // because otherwise we wouldn't be able to merge different // instantiations of the same feature into a more complex new feature // // Due to the large amount of possible pairings when considering // feature instances, we implement our "matrices" using hash tables, // and automatically ignore entries that would be 0 (they won't // be created if such pairs are never observed activating together) // System.out.println("-------------------------------------------------------------------"); int numCases = 0; // we'll increment this as we go // this is our C_f matrix final TObjectIntHashMap<CombinableFeatureInstancePair> featurePairActivations = new TObjectIntHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0); // this is our C_e matrix final TObjectDoubleHashMap<CombinableFeatureInstancePair> errorSums = new TObjectDoubleHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0.0); // these are our S and SS scalars double sumErrors = 0.0; double sumSquaredErrors = 0.0; // Create a Hash Set of features already in Feature Set; we won't // have to consider combinations that are already in final Set<SpatialFeature> existingFeatures = new HashSet<SpatialFeature> ( (int) Math.ceil(featureSet.getNumSpatialFeatures() / 0.75f), 0.75f ); for (final SpatialFeature feature : featureSet.spatialFeatures()) { existingFeatures.add(feature); } // For every sample in batch, first compute apprentice policies, errors, and sum of absolute errors final FVector[] errorVectors = new FVector[batch.size()]; final float[] absErrorSums = new float[batch.size()]; final TDoubleArrayList[] errorsPerActiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; final TDoubleArrayList[] errorsPerInactiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; for (int i = 0; i < errorsPerActiveFeature.length; ++i) { errorsPerActiveFeature[i] = new TDoubleArrayList(); errorsPerInactiveFeature[i] = new TDoubleArrayList(); } double avgActionError = 0.0; for (int i = 0; i < batch.size(); ++i) { final ExperienceSample sample = batch.get(i); final FeatureVector[] featureVectors = sample.generateFeatureVectors(featureSet); final FVector errors = new FVector(featureVectors.length); for (int a = 0; a < featureVectors.length; ++a) { final float actionError; if (sample.winningMoves().get(a)) { actionError = -1.f; } else if (sample.losingMoves().get(a)) { actionError = 1.f; } else if (sample.antiDefeatingMoves().get(a)) { actionError = 0.75f; // TODO can we do better by explicitly tracking win-corr, loss-corr, and antidefeat-corr? } else { actionError = 0.f; } errors.set(a, actionError); final TIntArrayList sparseFeatureVector = featureVectors[a].activeSpatialFeatureIndices(); sparseFeatureVector.sort(); int sparseIdx = 0; for (int featureIdx = 0; featureIdx < featureSet.getNumSpatialFeatures(); ++featureIdx) { if (sparseIdx < sparseFeatureVector.size() && sparseFeatureVector.getQuick(sparseIdx) == featureIdx) { // This spatial feature is active errorsPerActiveFeature[featureIdx].add(actionError); // We've used the sparse index, so increment it ++sparseIdx; } else { // This spatial feature is not active errorsPerInactiveFeature[featureIdx].add(actionError); } } avgActionError += (actionError - avgActionError) / (numCases + 1); ++numCases; } final FVector absErrors = errors.copy(); absErrors.abs(); errorVectors[i] = errors; absErrorSums[i] = absErrors.sum(); } // For every feature, compute sample correlation coefficient between its activity level (0 or 1) // and errors final double[] featureErrorCorrelations = new double[featureSet.getNumSpatialFeatures()]; // For every feature, compute expectation of absolute value of error given that feature is active final double[] expectedAbsErrorGivenFeature = new double[featureSet.getNumSpatialFeatures()]; // For every feature, computed expected value of feature activity times absolute error final double[] expectedFeatureTimesAbsError = new double[featureSet.getNumSpatialFeatures()]; for (int fIdx = 0; fIdx < featureSet.getNumSpatialFeatures(); ++fIdx) { final TDoubleArrayList errorsWhenActive = errorsPerActiveFeature[fIdx]; final TDoubleArrayList errorsWhenInactive = errorsPerInactiveFeature[fIdx]; final double avgFeatureVal = (double) errorsWhenActive.size() / (errorsWhenActive.size() + errorsPerInactiveFeature[fIdx].size()); double dErrorSquaresSum = 0.0; double numerator = 0.0; for (int i = 0; i < errorsWhenActive.size(); ++i) { final double error = errorsWhenActive.getQuick(i); final double dError = error - avgActionError; numerator += (1.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); expectedAbsErrorGivenFeature[fIdx] += (Math.abs(error) - expectedAbsErrorGivenFeature[fIdx]) / (i + 1); expectedFeatureTimesAbsError[fIdx] += (Math.abs(error) - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } for (int i = 0; i < errorsWhenInactive.size(); ++i) { final double error = errorsWhenInactive.getQuick(i); final double dError = error - avgActionError; numerator += (0.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); expectedFeatureTimesAbsError[fIdx] += (0.0 - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } final double dFeatureSquaresSum = errorsWhenActive.size() * ((1.0 - avgFeatureVal) * (1.0 - avgFeatureVal)) + errorsWhenInactive.size() * ((0.0 - avgFeatureVal) * (0.0 - avgFeatureVal)); final double denominator = Math.sqrt(dFeatureSquaresSum * dErrorSquaresSum); featureErrorCorrelations[fIdx] = numerator / denominator; if (Double.isNaN(featureErrorCorrelations[fIdx])) featureErrorCorrelations[fIdx] = 0.f; } // Create list of indices that we can use to index into batch, sorted in descending order // of sums of absolute errors. // This means that we prioritise looking at samples in the batch for which we have big policy // errors, and hence also focus on them when dealing with a cap in the number of active feature // instances we can look at final List<Integer> batchIndices = new ArrayList<Integer>(batch.size()); for (int i = 0; i < batch.size(); ++i) { batchIndices.add(Integer.valueOf(i)); } Collections.sort(batchIndices, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { final float deltaAbsErrorSums = absErrorSums[o1.intValue()] - absErrorSums[o2.intValue()]; if (deltaAbsErrorSums > 0.f) return -1; else if (deltaAbsErrorSums < 0.f) return 1; else return 0; } }); // Set of feature instances that we have already preserved (and hence must continue to preserve) final Set<CombinableFeatureInstancePair> preservedInstances = new HashSet<CombinableFeatureInstancePair>(); // Set of feature instances that we have already chosen to discard once (and hence must continue to discard) final Set<CombinableFeatureInstancePair> discardedInstances = new HashSet<CombinableFeatureInstancePair>(); // Loop through all samples in batch for (int bi = 0; bi < batchIndices.size(); ++bi) { final int batchIndex = batchIndices.get(bi).intValue(); final ExperienceSample sample = batch.get(batchIndex); final FVector errors = errorVectors[batchIndex]; final FastArrayList<Move> moves = sample.moves(); final TIntArrayList sortedActionIndices = new TIntArrayList(); // Want to start looking at winning moves final BitSet winningMoves = sample.winningMoves(); for (int i = winningMoves.nextSetBit(0); i >= 0; i = winningMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // Look at losing moves next final BitSet losingMoves = sample.losingMoves(); for (int i = losingMoves.nextSetBit(0); i >= 0; i = losingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // And finally anti-defeating moves final BitSet antiDefeatingMoves = sample.antiDefeatingMoves(); for (int i = antiDefeatingMoves.nextSetBit(0); i >= 0; i = antiDefeatingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // if (antiDefeatingMoves.cardinality() > 0) // System.out.println("Winning -- Losing -- AntiDefeating : " + winningMoves.cardinality() + " -- " + losingMoves.cardinality() + " -- " + antiDefeatingMoves.cardinality()); final TIntArrayList unsortedActionIndices = new TIntArrayList(); for (int a = 0; a < moves.size(); ++a) { if (!winningMoves.get(a) && !losingMoves.get(a) && !antiDefeatingMoves.get(a)) unsortedActionIndices.add(a); } // Finally, randomly fill up with the remaining actions while (!unsortedActionIndices.isEmpty()) { final int r = ThreadLocalRandom.current().nextInt(unsortedActionIndices.size()); final int a = unsortedActionIndices.getQuick(r); ListUtils.removeSwap(unsortedActionIndices, r); sortedActionIndices.add(a); } // Every action in the sample is a new "case" (state-action pair) for (int aIdx = 0; aIdx < sortedActionIndices.size(); ++aIdx) { final int a = sortedActionIndices.getQuick(aIdx); // keep track of pairs we've already seen in this "case" final Set<CombinableFeatureInstancePair> observedCasePairs = new HashSet<CombinableFeatureInstancePair>(256, .75f); // list --> set --> list to get rid of duplicates final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(new HashSet<FeatureInstance>( featureSet.getActiveSpatialFeatureInstances ( sample.gameState(), sample.lastFromPos(), sample.lastToPos(), FeatureUtils.fromPos(moves.get(a)), FeatureUtils.toPos(moves.get(a)), moves.get(a).mover() ))); // Save a copy of the above list, which we leave unmodified final List<FeatureInstance> origActiveInstances = new ArrayList<FeatureInstance>(activeInstances); // Start out by keeping all feature instances that have already been marked as having to be // preserved, and discarding those that have already been discarded before final List<FeatureInstance> instancesToKeep = new ArrayList<FeatureInstance>(); // For every instance in activeInstances, also keep track of a combined-self version final List<CombinableFeatureInstancePair> activeInstancesCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // And same for instancesToKeep final List<CombinableFeatureInstancePair> instancesToKeepCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // int numRelevantConstituents = 0; for (int i = 0; i < activeInstances.size(); /**/) { final FeatureInstance instance = activeInstances.get(i); final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instance, instance); if (preservedInstances.contains(combinedSelf)) { // if (instancesToKeepCombinedSelfs.contains(combinedSelf)) // { // System.out.println("already contains: " + combinedSelf); // System.out.println("instance: " + instance); // } instancesToKeepCombinedSelfs.add(combinedSelf); instancesToKeep.add(instance); ListUtils.removeSwap(activeInstances, i); } else if (discardedInstances.contains(combinedSelf)) { ListUtils.removeSwap(activeInstances, i); } else if (featureActiveRatios.getQuick(instance.feature().spatialFeatureSetIndex()) == 1.0) { ListUtils.removeSwap(activeInstances, i); } else { activeInstancesCombinedSelfs.add(combinedSelf); ++i; } } // if (activeInstances.size() > 0) // System.out.println(activeInstances.size() + "/" + origActiveInstances.size() + " left"); // This action is allowed to pick at most this many extra instances int numInstancesAllowedThisAction = Math.min ( Math.min ( 50, featureDiscoveryMaxNumFeatureInstances - preservedInstances.size() ), activeInstances.size() ); if (numInstancesAllowedThisAction > 0) { // System.out.println("allowed to add " + numInstancesAllowedThisAction + " instances"); // Create distribution over active instances proportional to scores that reward // features that correlate strongly with errors, as well as features that, when active, // imply expectations of high absolute errors, as well as features that are often active // when absolute errors are high, as well as features that have high absolute weights final FVector distr = new FVector(activeInstances.size()); for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); distr.set ( i, (float) ( // featureErrorCorrelations[fIdx] + expectedAbsErrorGivenFeature[fIdx] //+ // expectedFeatureTimesAbsError[fIdx] + // Math.abs // ( // policy.linearFunction // ( // sample.gameState().mover() // ).effectiveParams().allWeights().get(fIdx + featureSet.getNumAspatialFeatures()) // ) ) ); } distr.softmax(2.0); // For every instance, divide its probability by the number of active instances for the same // feature (because that feature is sort of "overrepresented") for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); int featureCount = 0; for (int j = 0; j < origActiveInstances.size(); ++j) { if (origActiveInstances.get(j).feature().spatialFeatureSetIndex() == fIdx) ++featureCount; } distr.set(i, distr.get(i) / featureCount); } distr.normalise(); // for (int i = 0; i < activeInstances.size(); ++i) // { // System.out.println("prob = " + distr.get(i) + " for " + activeInstances.get(i)); // } while (numInstancesAllowedThisAction > 0) { // Sample another instance final int sampledIdx = distr.sampleFromDistribution(); final CombinableFeatureInstancePair combinedSelf = activeInstancesCombinedSelfs.get(sampledIdx); final FeatureInstance keepInstance = activeInstances.get(sampledIdx); instancesToKeep.add(keepInstance); instancesToKeepCombinedSelfs.add(combinedSelf); preservedInstances.add(combinedSelf); // Remember to preserve this one forever now distr.updateSoftmaxInvalidate(sampledIdx); // Don't want to pick the same index again --numInstancesAllowedThisAction; // Maybe now have to auto-pick several other instances if they lead to equal combinedSelf for (int i = 0; i < distr.dim(); ++i) { if (distr.get(0) != 0.f) { if (combinedSelf.equals(activeInstancesCombinedSelfs.get(i))) { //System.out.println("auto-picking " + activeInstances.get(i) + " after " + keepInstance); instancesToKeep.add(activeInstances.get(i)); instancesToKeepCombinedSelfs.add(activeInstancesCombinedSelfs.get(i)); distr.updateSoftmaxInvalidate(i); // Don't want to pick the same index again --numInstancesAllowedThisAction; } } } } } // Mark all the instances that haven't been marked as preserved yet as discarded instead for (int i = 0; i < activeInstances.size(); ++i) { final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, activeInstances.get(i), activeInstances.get(i)); if (!preservedInstances.contains(combinedSelf)) discardedInstances.add(combinedSelf); } final int numActiveInstances = instancesToKeep.size(); //System.out.println("numActiveInstances = " + numActiveInstances); float error = errors.get(a); sumErrors += error; sumSquaredErrors += error * error; for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance instanceI = instancesToKeep.get(i); // increment entries on ''main diagonals'' final CombinableFeatureInstancePair combinedSelf = instancesToKeepCombinedSelfs.get(i); // boolean relevantConstituent = false; // if (!combinedSelf.combinedFeature.isReactive()) // { // if (combinedSelf.combinedFeature.pattern().featureElements().length == 1) // { // relevantConstituent = true; // final FeatureElement element = combinedSelf.combinedFeature.pattern().featureElements()[0]; // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // relevantConstituent = false; // } // } // } // if (relevantConstituent) // { // System.out.println("relevant constituent " + i + ": " + instanceI); // ++numRelevantConstituents; // } if (observedCasePairs.add(combinedSelf)) { featurePairActivations.adjustOrPutValue(combinedSelf, 1, 1); errorSums.adjustOrPutValue(combinedSelf, error, error); // if (relevantConstituent) // System.out.println("incremented for constituent " + i); } // else if (relevantConstituent) // { // System.out.println("Already observed for this action, so no increment for constituent " + i); // } for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance instanceJ = instancesToKeep.get(j); // increment off-diagonal entries final CombinableFeatureInstancePair combined = new CombinableFeatureInstancePair(game, instanceI, instanceJ); // boolean relevantCombined = false; // if (!combined.combinedFeature.isReactive() && combined.combinedFeature.pattern().featureElements().length == 2) // { // boolean onlyFriendElements = true; // for (final FeatureElement element : combined.combinedFeature.pattern().featureElements()) // { // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // onlyFriendElements = false; // break; // } // } // // if (onlyFriendElements) // relevantCombined = true; // } // if (relevantCombined) // { // System.out.println("relevant combined feature: " + combined.combinedFeature); // System.out.println("from constituent " + i + " = " + instanceI); // System.out.println("from constituent " + j + " = " + instanceJ); // } if (!existingFeatures.contains(combined.combinedFeature)) { if (observedCasePairs.add(combined)) { featurePairActivations.adjustOrPutValue(combined, 1, 1); errorSums.adjustOrPutValue(combined, error, error); // // if (relevantCombined) // System.out.println("incremented for combined"); } // else if (relevantCombined) // { // System.out.println("didn't add combined because already observed for this action "); // } } // else if (relevantCombined) // { // System.out.println("didn't add combined because feature already exists"); // } } } // if (numRelevantConstituents == 1) // System.out.println("origActiveInstances = " + origActiveInstances); } } if (sumErrors == 0.0 || sumSquaredErrors == 0.0) { // incredibly rare case but appears to be possible sometimes // we have nothing to guide our feature growing, so let's // just refuse to add a feature return null; } // Construct all possible pairs and scores; one priority queue for proactive features, // and one for reactive features // // In priority queues, we want highest scores at the head, hence "reversed" implementation // of comparator final Comparator<ScoredFeatureInstancePair> comparator = new Comparator<ScoredFeatureInstancePair>() { @Override public int compare(final ScoredFeatureInstancePair o1, final ScoredFeatureInstancePair o2) { if (o1.score < o2.score) return 1; else if (o1.score > o2.score) return -1; else return 0; } }; final PriorityQueue<ScoredFeatureInstancePair> proactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); final PriorityQueue<ScoredFeatureInstancePair> reactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // Randomly pick a minimum required sample size in [3, 5] final int requiredSampleSize = 3 + ThreadLocalRandom.current().nextInt(3); for (final CombinableFeatureInstancePair pair : featurePairActivations.keySet()) { // int numFriendElements = 0; // for (final FeatureElement element : ((RelativeFeature) pair.combinedFeature).pattern().featureElements()) // { // if (element.type() == ElementType.Friend && !element.not()) // ++numFriendElements; // } // final boolean couldBeWinFeature = (numFriendElements >= 3); // final boolean couldBeLossFeature = (numFriendElements == 2); if (!pair.a.equals(pair.b)) // Only interested in combinations of different instances { // if (pair.combinedFeature.toString().equals("rel:to=<{}>:pat=<els=[f{-1/6,1/6}, f{0,-1/6}]>")) // { // final int pairActs = featurePairActivations.get(pair); // final int actsI = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); // final int actsJ = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); // // if (pairActs != actsI || pairActs != actsJ || actsI != actsJ) // { // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("already contains = " + existingFeatures.contains(pair.combinedFeature)); // System.out.println("pair = " + pair); // System.out.println("errorSumsI = " + errorSums.get(new CombinableFeatureInstancePair(game, pair.a, pair.a))); // System.out.println("errorSumsJ = " + errorSums.get(new CombinableFeatureInstancePair(game, pair.b, pair.b))); // for (final CombinableFeatureInstancePair key : featurePairActivations.keySet()) // { // if (featurePairActivations.get(key) <= actsI && !key.combinedFeature.isReactive()) // { // boolean onlyFriendElements = true; // for (final FeatureElement element : key.combinedFeature.pattern().featureElements()) // { // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // onlyFriendElements = false; // break; // } // } // // if (onlyFriendElements) // System.out.println("Num activations for " + key + " = " + featurePairActivations.get(key)); // } // } // System.exit(0); // } // } final int pairActs = featurePairActivations.get(pair); if (pairActs == numCases || numCases < 4) { // Perfect correlation, so we should just skip this one // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of correlation: " + pair); continue; } if (pairActs < requiredSampleSize) { // Need a bigger sample size // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of sample size (" + pairActs + " < " + requiredSampleSize + "): " + pair); continue; } final int actsI = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); final int actsJ = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); if (actsI == numCases || actsJ == numCases || pairActs == actsI || pairActs == actsJ) { // Perfect correlation, so we should just skip this one // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of perfect correlation: " + pair); continue; } final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - featureDiscoveryParams.criticalValueCorrConf * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + featureDiscoveryParams.criticalValueCorrConf * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (pairActs * (numCases - actsI)) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(actsI * (numCases - actsI)) ) ); final double featureCorrJ = ( (pairActs * (numCases - actsJ)) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(actsJ * (numCases - actsJ)) ) ); final double worstFeatureCorr = Math.max ( Math.abs(featureCorrI), Math.abs(featureCorrJ) ); final double score; if (errorCorr >= 0.0) score = Math.max(0.0, lbErrorCorr) * (1.0 - worstFeatureCorr*worstFeatureCorr); else score = -Math.min(0.0, ubErrorCorr) * (1.0 - worstFeatureCorr*worstFeatureCorr); if (Double.isNaN(score)) { // System.err.println("numCases = " + numCases); // System.err.println("pairActs = " + pairActs); // System.err.println("actsI = " + actsI); // System.err.println("actsJ = " + actsJ); // System.err.println("sumErrors = " + sumErrors); // System.err.println("sumSquaredErrors = " + sumSquaredErrors); // if (couldBeWinFeature) // System.out.println("Skipping because of NaN score: " + pair); continue; } // if (couldBeWinFeature) // { // System.out.println("Might be win feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } // else if (couldBeLossFeature) // { // System.out.println("Might be loss feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } if (pair.combinedFeature.isReactive()) reactivePairs.add(new ScoredFeatureInstancePair(pair, score)); else proactivePairs.add(new ScoredFeatureInstancePair(pair, score)); } } // System.out.println("--------------------------------------------------------"); // final PriorityQueue<ScoredFeatureInstancePair> allPairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // allPairs.addAll(proactivePairs); // allPairs.addAll(reactivePairs); // while (!allPairs.isEmpty()) // { // final ScoredFeatureInstancePair pair = allPairs.poll(); // // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.b, pair.pair.b) // ); // // final int pairActs = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double pairErrorSum = // errorSums.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // System.out.println("score = " + pair.score); // System.out.println("correlation with errors = " + errorCorr); // System.out.println("lower bound correlation with errors = " + lbErrorCorr); // System.out.println("upper bound correlation with errors = " + ubErrorCorr); // System.out.println("correlation with first constituent = " + featureCorrI); // System.out.println("correlation with second constituent = " + featureCorrJ); // System.out.println("active feature A = " + pair.pair.a.feature()); // System.out.println("rot A = " + pair.pair.a.rotation()); // System.out.println("ref A = " + pair.pair.a.reflection()); // System.out.println("anchor A = " + pair.pair.a.anchorSite()); // System.out.println("active feature B = " + pair.pair.b.feature()); // System.out.println("rot B = " + pair.pair.b.rotation()); // System.out.println("ref B = " + pair.pair.b.reflection()); // System.out.println("anchor B = " + pair.pair.b.anchorSite()); // System.out.println("observed pair of instances " + pairActs + " times"); // System.out.println("observed first constituent " + actsI + " times"); // System.out.println("observed second constituent " + actsJ + " times"); // System.out.println(); // } // System.out.println("--------------------------------------------------------"); // Keep trying to add a proactive feature, until we succeed (almost always // this should be on the very first iteration) BaseFeatureSet currFeatureSet = featureSet; // TODO pretty much duplicate code of block below, should refactor into method while (!proactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = proactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); final int pairActs = featurePairActivations.get(pair); final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (numCases * pairActs - pairActs * actsI) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsI - actsI * actsI) ) ); final double featureCorrJ = ( (numCases * pairActs - pairActs * actsJ) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsJ - actsJ * actsJ) ) ); experiment.logLine(logWriter, "New proactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); experiment.logLine(logWriter, "score = " + bestPair.score); experiment.logLine(logWriter, "correlation with errors = " + errorCorr); experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); // System.out.println("BEST SCORE: " + bestPair.score); currFeatureSet = newFeatureSet; break; } } // Keep trying to add a reactive feature, until we succeed (almost always // this should be on the very first iteration) while (!reactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = reactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); final int pairActs = featurePairActivations.get(pair); final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (numCases * pairActs - pairActs * actsI) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsI - actsI * actsI) ) ); final double featureCorrJ = ( (numCases * pairActs - pairActs * actsJ) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsJ - actsJ * actsJ) ) ); experiment.logLine(logWriter, "New reactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); experiment.logLine(logWriter, "score = " + bestPair.score); experiment.logLine(logWriter, "correlation with errors = " + errorCorr); experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } return currFeatureSet; } }
50,895
38.515528
176
java
Ludii
Ludii-master/AI/src/training/feature_discovery/TargetCorrelationBasedExpander.java
package training.feature_discovery; import java.io.PrintWriter; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import features.FeatureVector; import features.feature_sets.BaseFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.impl.Constants; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TObjectDoubleHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import main.collections.FVector; import main.collections.FastArrayList; import main.collections.ListUtils; import other.move.Move; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import utils.experiments.InterruptableExperiment; /** * Feature Set Expander based on correlation with targets (i.e., expert policies), * irrespective of our current predictions / errors. * * @author Dennis Soemers */ public class TargetCorrelationBasedExpander implements FeatureSetExpander { @Override public BaseFeatureSet expandFeatureSet ( final List<? extends ExperienceSample> batch, final BaseFeatureSet featureSet, final SoftmaxPolicyLinear policy, final Game game, final int featureDiscoveryMaxNumFeatureInstances, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TDoubleArrayList featureActiveRatios, final PrintWriter logWriter, final InterruptableExperiment experiment ) { // we need a matrix C_f with, at every entry (i, j), // the sum of cases in which features i and j are both active // // we also need a similar matrix C_e with, at every entry (i, j), // the sum of errors in cases where features i and j are both active // // NOTE: both of the above are symmetric matrices // // we also need a vector X_f with, for every feature i, the sum of // cases where feature i is active. (we would need a similar vector // with sums of squares, but that can be omitted because our features // are binary) // // NOTE: in writing it is easier to mention X_f as described above as // a separate vector, but actually we don't need it; we can simply // use the main diagonal of C_f instead // // we need a scalar S which is the sum of all errors, // and a scalar SS which is the sum of all squared errors // // Given a candidate pair of features (i, j), we can compute the // correlation of that pair of features with the errors (an // indicator of the candidate pair's potential to be useful) as // (where n = the number of cases = number of state-action pairs): // // // n * C_e(i, j) - C_f(i, j) * S //------------------------------------------------------------ // SQRT( n * C_f(i, j) - C_f(i, j)^2 ) * SQRT( n * SS - S^2 ) // // // For numeric stability with extremely large batch sizes, // it is better to compute this as: // // n * C_e(i, j) - C_f(i, j) * S //------------------------------------------------------------ // SQRT( C_f(i, j) * (n - C_f(i, j)) ) * SQRT( n * SS - S^2 ) // // // We can similarly compare the correlation between any candidate pair // of features (i, j) and either of its constituents i (an indicator // of redundancy of the candidate pair) as: // // // n * C_f(i, j) - C_f(i, j) * X_f(i) //-------------------------------------------------------------------- // SQRT( n * C_f(i, j) - C_f(i, j)^2 ) * SQRT( n * X_f(i) - X_f(i)^2 ) // // // For numeric stability with extremely large batch sizes, // it is better to compute this as: // // C_f(i, j) * (n - X_f(i)) //-------------------------------------------------------------------- // SQRT( C_f(i, j) * (n - C_f(i, j)) ) * SQRT( X_f(i) * (n - X_f(i)) ) // // // (note; even better would be if we could compute correlation between // candidate pair and ANY other feature, rather than just its // constituents, but that would probably become too expensive) // // We want to maximise the absolute value of the first (correlation // between candidate feature pair and distribution error), but minimise // the worst-case absolute value of the second (correlation between // candidate feature pair and either of its constituents). // // // NOTE: in all of the above, when we say "feature", we actually // refer to a particular instantiation of a feature. This is important, // because otherwise we wouldn't be able to merge different // instantiations of the same feature into a more complex new feature // // Due to the large amount of possible pairings when considering // feature instances, we implement our "matrices" using hash tables, // and automatically ignore entries that would be 0 (they won't // be created if such pairs are never observed activating together) // System.out.println("-------------------------------------------------------------------"); int numCases = 0; // we'll increment this as we go // this is our C_f matrix final TObjectIntHashMap<CombinableFeatureInstancePair> featurePairActivations = new TObjectIntHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0); // this is our C_e matrix final TObjectDoubleHashMap<CombinableFeatureInstancePair> errorSums = new TObjectDoubleHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0.0); // these are our S and SS scalars double sumErrors = 0.0; double sumSquaredErrors = 0.0; // Create a Hash Set of features already in Feature Set; we won't // have to consider combinations that are already in final Set<SpatialFeature> existingFeatures = new HashSet<SpatialFeature> ( (int) Math.ceil(featureSet.getNumSpatialFeatures() / 0.75f), 0.75f ); for (final SpatialFeature feature : featureSet.spatialFeatures()) { existingFeatures.add(feature); } // For every sample in batch, first compute apprentice policies, errors, and sum of absolute errors final FVector[] apprenticePolicies = new FVector[batch.size()]; final FVector[] errorVectors = new FVector[batch.size()]; final float[] absErrorSums = new float[batch.size()]; final TDoubleArrayList[] errorsPerActiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; final TDoubleArrayList[] errorsPerInactiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; for (int i = 0; i < errorsPerActiveFeature.length; ++i) { errorsPerActiveFeature[i] = new TDoubleArrayList(); errorsPerInactiveFeature[i] = new TDoubleArrayList(); } double avgActionError = 0.0; for (int i = 0; i < batch.size(); ++i) { final ExperienceSample sample = batch.get(i); final FeatureVector[] featureVectors = sample.generateFeatureVectors(featureSet); final FVector apprenticePolicy = policy.computeDistribution(featureVectors, sample.gameState().mover()); final FVector errors = apprenticePolicy.copy(); for (int a = 0; a < featureVectors.length; ++a) { final float actionError = errors.get(a); final TIntArrayList sparseFeatureVector = featureVectors[a].activeSpatialFeatureIndices(); sparseFeatureVector.sort(); int sparseIdx = 0; for (int featureIdx = 0; featureIdx < featureSet.getNumSpatialFeatures(); ++featureIdx) { if (sparseIdx < sparseFeatureVector.size() && sparseFeatureVector.getQuick(sparseIdx) == featureIdx) { // This spatial feature is active errorsPerActiveFeature[featureIdx].add(actionError); // We've used the sparse index, so increment it ++sparseIdx; } else { // This spatial feature is not active errorsPerInactiveFeature[featureIdx].add(actionError); } } avgActionError += (actionError - avgActionError) / (numCases + 1); ++numCases; } final FVector absErrors = errors.copy(); absErrors.abs(); apprenticePolicies[i] = apprenticePolicy; errorVectors[i] = errors; absErrorSums[i] = absErrors.sum(); } // For every feature, compute sample correlation coefficient between its activity level (0 or 1) // and errors final double[] featureErrorCorrelations = new double[featureSet.getNumSpatialFeatures()]; // For every feature, compute expectation of absolute value of error given that feature is active final double[] expectedAbsErrorGivenFeature = new double[featureSet.getNumSpatialFeatures()]; // For every feature, computed expected value of feature activity times absolute error final double[] expectedFeatureTimesAbsError = new double[featureSet.getNumSpatialFeatures()]; for (int fIdx = 0; fIdx < featureSet.getNumSpatialFeatures(); ++fIdx) { final TDoubleArrayList errorsWhenActive = errorsPerActiveFeature[fIdx]; final TDoubleArrayList errorsWhenInactive = errorsPerInactiveFeature[fIdx]; final double avgFeatureVal = (double) errorsWhenActive.size() / (errorsWhenActive.size() + errorsPerInactiveFeature[fIdx].size()); double dErrorSquaresSum = 0.0; double numerator = 0.0; for (int i = 0; i < errorsWhenActive.size(); ++i) { final double error = errorsWhenActive.getQuick(i); final double dError = error - avgActionError; numerator += (1.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); expectedAbsErrorGivenFeature[fIdx] += (Math.abs(error) - expectedAbsErrorGivenFeature[fIdx]) / (i + 1); expectedFeatureTimesAbsError[fIdx] += (Math.abs(error) - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } for (int i = 0; i < errorsWhenInactive.size(); ++i) { final double error = errorsWhenInactive.getQuick(i); final double dError = error - avgActionError; numerator += (0.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); expectedFeatureTimesAbsError[fIdx] += (0.0 - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } final double dFeatureSquaresSum = errorsWhenActive.size() * ((1.0 - avgFeatureVal) * (1.0 - avgFeatureVal)) + errorsWhenInactive.size() * ((0.0 - avgFeatureVal) * (0.0 - avgFeatureVal)); final double denominator = Math.sqrt(dFeatureSquaresSum * dErrorSquaresSum); featureErrorCorrelations[fIdx] = numerator / denominator; if (Double.isNaN(featureErrorCorrelations[fIdx])) featureErrorCorrelations[fIdx] = 0.f; } // Create list of indices that we can use to index into batch, sorted in descending order // of sums of absolute errors. // This means that we prioritise looking at samples in the batch for which we have big policy // errors, and hence also focus on them when dealing with a cap in the number of active feature // instances we can look at final List<Integer> batchIndices = new ArrayList<Integer>(batch.size()); for (int i = 0; i < batch.size(); ++i) { batchIndices.add(Integer.valueOf(i)); } Collections.sort(batchIndices, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { final float deltaAbsErrorSums = absErrorSums[o1.intValue()] - absErrorSums[o2.intValue()]; if (deltaAbsErrorSums > 0.f) return -1; else if (deltaAbsErrorSums < 0.f) return 1; else return 0; } }); // Set of feature instances that we have already preserved (and hence must continue to preserve) final Set<CombinableFeatureInstancePair> preservedInstances = new HashSet<CombinableFeatureInstancePair>(); // Set of feature instances that we have already chosen to discard once (and hence must continue to discard) final Set<CombinableFeatureInstancePair> discardedInstances = new HashSet<CombinableFeatureInstancePair>(); // Loop through all samples in batch for (int bi = 0; bi < batchIndices.size(); ++bi) { final int batchIndex = batchIndices.get(bi).intValue(); final ExperienceSample sample = batch.get(batchIndex); final FVector errors = errorVectors[batchIndex]; final float minError = errors.min(); final float maxError = errors.max(); final FastArrayList<Move> moves = sample.moves(); final TIntArrayList sortedActionIndices = new TIntArrayList(); // Want to start looking at winning moves final BitSet winningMoves = sample.winningMoves(); for (int i = winningMoves.nextSetBit(0); i >= 0; i = winningMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // Look at losing moves next final BitSet losingMoves = sample.losingMoves(); for (int i = losingMoves.nextSetBit(0); i >= 0; i = losingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // And finally anti-defeating moves final BitSet antiDefeatingMoves = sample.antiDefeatingMoves(); for (int i = antiDefeatingMoves.nextSetBit(0); i >= 0; i = antiDefeatingMoves.nextSetBit(i + 1)) { sortedActionIndices.add(i); } // if (antiDefeatingMoves.cardinality() > 0) // System.out.println("Winning -- Losing -- AntiDefeating : " + winningMoves.cardinality() + " -- " + losingMoves.cardinality() + " -- " + antiDefeatingMoves.cardinality()); final TIntArrayList unsortedActionIndices = new TIntArrayList(); for (int a = 0; a < moves.size(); ++a) { if (!winningMoves.get(a) && !losingMoves.get(a) && !antiDefeatingMoves.get(a)) unsortedActionIndices.add(a); } // Finally, randomly fill up with the remaining actions while (!unsortedActionIndices.isEmpty()) { final int r = ThreadLocalRandom.current().nextInt(unsortedActionIndices.size()); final int a = unsortedActionIndices.getQuick(r); ListUtils.removeSwap(unsortedActionIndices, r); sortedActionIndices.add(a); } // Every action in the sample is a new "case" (state-action pair) for (int aIdx = 0; aIdx < sortedActionIndices.size(); ++aIdx) { final int a = sortedActionIndices.getQuick(aIdx); // keep track of pairs we've already seen in this "case" final Set<CombinableFeatureInstancePair> observedCasePairs = new HashSet<CombinableFeatureInstancePair>(256, .75f); // list --> set --> list to get rid of duplicates final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(new HashSet<FeatureInstance>( featureSet.getActiveSpatialFeatureInstances ( sample.gameState(), sample.lastFromPos(), sample.lastToPos(), FeatureUtils.fromPos(moves.get(a)), FeatureUtils.toPos(moves.get(a)), moves.get(a).mover() ))); // Save a copy of the above list, which we leave unmodified final List<FeatureInstance> origActiveInstances = new ArrayList<FeatureInstance>(activeInstances); // Start out by keeping all feature instances that have already been marked as having to be // preserved, and discarding those that have already been discarded before final List<FeatureInstance> instancesToKeep = new ArrayList<FeatureInstance>(); // For every instance in activeInstances, also keep track of a combined-self version final List<CombinableFeatureInstancePair> activeInstancesCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // And same for instancesToKeep final List<CombinableFeatureInstancePair> instancesToKeepCombinedSelfs = new ArrayList<CombinableFeatureInstancePair>(); // int numRelevantConstituents = 0; for (int i = 0; i < activeInstances.size(); /**/) { final FeatureInstance instance = activeInstances.get(i); final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instance, instance); if (preservedInstances.contains(combinedSelf)) { // if (instancesToKeepCombinedSelfs.contains(combinedSelf)) // { // System.out.println("already contains: " + combinedSelf); // System.out.println("instance: " + instance); // } instancesToKeepCombinedSelfs.add(combinedSelf); instancesToKeep.add(instance); ListUtils.removeSwap(activeInstances, i); } else if (discardedInstances.contains(combinedSelf)) { ListUtils.removeSwap(activeInstances, i); } else if (featureActiveRatios.getQuick(instance.feature().spatialFeatureSetIndex()) == 1.0) { ListUtils.removeSwap(activeInstances, i); } else { activeInstancesCombinedSelfs.add(combinedSelf); ++i; } } // if (activeInstances.size() > 0) // System.out.println(activeInstances.size() + "/" + origActiveInstances.size() + " left"); // This action is allowed to pick at most this many extra instances int numInstancesAllowedThisAction = Math.min ( Math.min ( 50, featureDiscoveryMaxNumFeatureInstances - preservedInstances.size() ), activeInstances.size() ); if (numInstancesAllowedThisAction > 0) { // System.out.println("allowed to add " + numInstancesAllowedThisAction + " instances"); // Create distribution over active instances proportional to scores that reward // features that correlate strongly with errors, as well as features that, when active, // imply expectations of high absolute errors, as well as features that are often active // when absolute errors are high, as well as features that have high absolute weights final FVector distr = new FVector(activeInstances.size()); for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); distr.set ( i, (float) ( // featureErrorCorrelations[fIdx] + expectedAbsErrorGivenFeature[fIdx] //+ // expectedFeatureTimesAbsError[fIdx] + // Math.abs // ( // policy.linearFunction // ( // sample.gameState().mover() // ).effectiveParams().allWeights().get(fIdx + featureSet.getNumAspatialFeatures()) // ) ) ); } distr.softmax(2.0); // For every instance, divide its probability by the number of active instances for the same // feature (because that feature is sort of "overrepresented") for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); int featureCount = 0; for (int j = 0; j < origActiveInstances.size(); ++j) { if (origActiveInstances.get(j).feature().spatialFeatureSetIndex() == fIdx) ++featureCount; } distr.set(i, distr.get(i) / featureCount); } distr.normalise(); // for (int i = 0; i < activeInstances.size(); ++i) // { // System.out.println("prob = " + distr.get(i) + " for " + activeInstances.get(i)); // } while (numInstancesAllowedThisAction > 0) { // Sample another instance final int sampledIdx = distr.sampleFromDistribution(); final CombinableFeatureInstancePair combinedSelf = activeInstancesCombinedSelfs.get(sampledIdx); final FeatureInstance keepInstance = activeInstances.get(sampledIdx); instancesToKeep.add(keepInstance); instancesToKeepCombinedSelfs.add(combinedSelf); preservedInstances.add(combinedSelf); // Remember to preserve this one forever now distr.updateSoftmaxInvalidate(sampledIdx); // Don't want to pick the same index again --numInstancesAllowedThisAction; // Maybe now have to auto-pick several other instances if they lead to equal combinedSelf for (int i = 0; i < distr.dim(); ++i) { if (distr.get(0) != 0.f) { if (combinedSelf.equals(activeInstancesCombinedSelfs.get(i))) { //System.out.println("auto-picking " + activeInstances.get(i) + " after " + keepInstance); instancesToKeep.add(activeInstances.get(i)); instancesToKeepCombinedSelfs.add(activeInstancesCombinedSelfs.get(i)); distr.updateSoftmaxInvalidate(i); // Don't want to pick the same index again --numInstancesAllowedThisAction; } } } } } // Mark all the instances that haven't been marked as preserved yet as discarded instead for (int i = 0; i < activeInstances.size(); ++i) { final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, activeInstances.get(i), activeInstances.get(i)); if (!preservedInstances.contains(combinedSelf)) discardedInstances.add(combinedSelf); } final int numActiveInstances = instancesToKeep.size(); //System.out.println("numActiveInstances = " + numActiveInstances); float error = errors.get(a); if (winningMoves.get(a)) { error = minError; // Reward correlation with winning moves } else if (losingMoves.get(a)) { error = maxError; // Reward correlation with losing moves } else if (antiDefeatingMoves.get(a)) { error = Math.min(error, minError + 0.1f); // Reward correlation with anti-defeating moves } sumErrors += error; sumSquaredErrors += error * error; for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance instanceI = instancesToKeep.get(i); // increment entries on ''main diagonals'' final CombinableFeatureInstancePair combinedSelf = instancesToKeepCombinedSelfs.get(i); // boolean relevantConstituent = false; // if (!combinedSelf.combinedFeature.isReactive()) // { // if (combinedSelf.combinedFeature.pattern().featureElements().length == 1) // { // relevantConstituent = true; // final FeatureElement element = combinedSelf.combinedFeature.pattern().featureElements()[0]; // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // relevantConstituent = false; // } // } // } // if (relevantConstituent) // { // System.out.println("relevant constituent " + i + ": " + instanceI); // ++numRelevantConstituents; // } if (observedCasePairs.add(combinedSelf)) { featurePairActivations.adjustOrPutValue(combinedSelf, 1, 1); errorSums.adjustOrPutValue(combinedSelf, error, error); // if (relevantConstituent) // System.out.println("incremented for constituent " + i); } // else if (relevantConstituent) // { // System.out.println("Already observed for this action, so no increment for constituent " + i); // } for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance instanceJ = instancesToKeep.get(j); // increment off-diagonal entries final CombinableFeatureInstancePair combined = new CombinableFeatureInstancePair(game, instanceI, instanceJ); // boolean relevantCombined = false; // if (!combined.combinedFeature.isReactive() && combined.combinedFeature.pattern().featureElements().length == 2) // { // boolean onlyFriendElements = true; // for (final FeatureElement element : combined.combinedFeature.pattern().featureElements()) // { // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // onlyFriendElements = false; // break; // } // } // // if (onlyFriendElements) // relevantCombined = true; // } // if (relevantCombined) // { // System.out.println("relevant combined feature: " + combined.combinedFeature); // System.out.println("from constituent " + i + " = " + instanceI); // System.out.println("from constituent " + j + " = " + instanceJ); // } if (!existingFeatures.contains(combined.combinedFeature)) { if (observedCasePairs.add(combined)) { featurePairActivations.adjustOrPutValue(combined, 1, 1); errorSums.adjustOrPutValue(combined, error, error); // // if (relevantCombined) // System.out.println("incremented for combined"); } // else if (relevantCombined) // { // System.out.println("didn't add combined because already observed for this action "); // } } // else if (relevantCombined) // { // System.out.println("didn't add combined because feature already exists"); // } } } // if (numRelevantConstituents == 1) // System.out.println("origActiveInstances = " + origActiveInstances); } } if (sumErrors == 0.0 || sumSquaredErrors == 0.0) { // incredibly rare case but appears to be possible sometimes // we have nothing to guide our feature growing, so let's // just refuse to add a feature return null; } // Construct all possible pairs and scores; one priority queue for proactive features, // and one for reactive features // // In priority queues, we want highest scores at the head, hence "reversed" implementation // of comparator final Comparator<ScoredFeatureInstancePair> comparator = new Comparator<ScoredFeatureInstancePair>() { @Override public int compare(final ScoredFeatureInstancePair o1, final ScoredFeatureInstancePair o2) { if (o1.score < o2.score) return 1; else if (o1.score > o2.score) return -1; else return 0; } }; final PriorityQueue<ScoredFeatureInstancePair> proactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); final PriorityQueue<ScoredFeatureInstancePair> reactivePairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // Randomly pick a minimum required sample size in [3, 5] final int requiredSampleSize = 3 + ThreadLocalRandom.current().nextInt(3); for (final CombinableFeatureInstancePair pair : featurePairActivations.keySet()) { // int numFriendElements = 0; // for (final FeatureElement element : ((RelativeFeature) pair.combinedFeature).pattern().featureElements()) // { // if (element.type() == ElementType.Friend && !element.not()) // ++numFriendElements; // } // final boolean couldBeWinFeature = (numFriendElements >= 3); // final boolean couldBeLossFeature = (numFriendElements == 2); if (!pair.a.equals(pair.b)) // Only interested in combinations of different instances { // if (pair.combinedFeature.toString().equals("rel:to=<{}>:pat=<els=[f{-1/6,1/6}, f{0,-1/6}]>")) // { // final int pairActs = featurePairActivations.get(pair); // final int actsI = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); // final int actsJ = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); // // if (pairActs != actsI || pairActs != actsJ || actsI != actsJ) // { // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("already contains = " + existingFeatures.contains(pair.combinedFeature)); // System.out.println("pair = " + pair); // System.out.println("errorSumsI = " + errorSums.get(new CombinableFeatureInstancePair(game, pair.a, pair.a))); // System.out.println("errorSumsJ = " + errorSums.get(new CombinableFeatureInstancePair(game, pair.b, pair.b))); // for (final CombinableFeatureInstancePair key : featurePairActivations.keySet()) // { // if (featurePairActivations.get(key) <= actsI && !key.combinedFeature.isReactive()) // { // boolean onlyFriendElements = true; // for (final FeatureElement element : key.combinedFeature.pattern().featureElements()) // { // if // ( // element.not() // || // element.type() != ElementType.Friend // || // ((RelativeFeatureElement)element).walk().steps().size() != 2 // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.5f, 0.f)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/3, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(0.f, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/3, -1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(-1.f/6, 1.f/3)) // || // ((RelativeFeatureElement)element).walk().equals(new Walk(1.f/6, -1.f/3)) // ) // { // onlyFriendElements = false; // break; // } // } // // if (onlyFriendElements) // System.out.println("Num activations for " + key + " = " + featurePairActivations.get(key)); // } // } // System.exit(0); // } // } final int pairActs = featurePairActivations.get(pair); if (pairActs == numCases || numCases < 4) { // Perfect correlation, so we should just skip this one // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of correlation: " + pair); continue; } if (pairActs < requiredSampleSize) { // Need a bigger sample size // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of sample size (" + pairActs + " < " + requiredSampleSize + "): " + pair); continue; } final int actsI = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); final int actsJ = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); if (actsI == numCases || actsJ == numCases || pairActs == actsI || pairActs == actsJ) { // Perfect correlation, so we should just skip this one // if (couldBeWinFeature || couldBeLossFeature) // System.out.println("Skipping because of perfect correlation: " + pair); continue; } final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - featureDiscoveryParams.criticalValueCorrConf * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + featureDiscoveryParams.criticalValueCorrConf * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (pairActs * (numCases - actsI)) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(actsI * (numCases - actsI)) ) ); final double featureCorrJ = ( (pairActs * (numCases - actsJ)) / ( Math.sqrt(pairActs * (numCases - pairActs)) * Math.sqrt(actsJ * (numCases - actsJ)) ) ); final double worstFeatureCorr = Math.max ( Math.abs(featureCorrI), Math.abs(featureCorrJ) ); final double score; if (errorCorr >= 0.0) score = Math.max(0.0, lbErrorCorr) * (1.0 - worstFeatureCorr*worstFeatureCorr); else score = -Math.min(0.0, ubErrorCorr) * (1.0 - worstFeatureCorr*worstFeatureCorr); if (Double.isNaN(score)) { // System.err.println("numCases = " + numCases); // System.err.println("pairActs = " + pairActs); // System.err.println("actsI = " + actsI); // System.err.println("actsJ = " + actsJ); // System.err.println("sumErrors = " + sumErrors); // System.err.println("sumSquaredErrors = " + sumSquaredErrors); // if (couldBeWinFeature) // System.out.println("Skipping because of NaN score: " + pair); continue; } // if (couldBeWinFeature) // { // System.out.println("Might be win feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } // else if (couldBeLossFeature) // { // System.out.println("Might be loss feature: " + pair); // System.out.println("errorCorr = " + errorCorr); // System.out.println("lbErrorCorr = " + lbErrorCorr); // System.out.println("ubErrorCorr = " + ubErrorCorr); // System.out.println("numCases = " + numCases); // System.out.println("pairActs = " + pairActs); // System.out.println("actsI = " + actsI); // System.out.println("actsJ = " + actsJ); // System.out.println("featureCorrI = " + featureCorrI); // System.out.println("featureCorrJ = " + featureCorrJ); // System.out.println("score = " + score); // } if (pair.combinedFeature.isReactive()) reactivePairs.add(new ScoredFeatureInstancePair(pair, score)); else proactivePairs.add(new ScoredFeatureInstancePair(pair, score)); } } // System.out.println("--------------------------------------------------------"); // final PriorityQueue<ScoredFeatureInstancePair> allPairs = new PriorityQueue<ScoredFeatureInstancePair>(comparator); // allPairs.addAll(proactivePairs); // allPairs.addAll(reactivePairs); // while (!allPairs.isEmpty()) // { // final ScoredFeatureInstancePair pair = allPairs.poll(); // // final int actsI = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.a) // ); // // final int actsJ = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.b, pair.pair.b) // ); // // final int pairActs = // featurePairActivations.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double pairErrorSum = // errorSums.get // ( // new CombinableFeatureInstancePair(game, pair.pair.a, pair.pair.b) // ); // // final double errorCorr = // ( // (numCases * pairErrorSum - pairActs * sumErrors) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) // ) // ); // // Fisher's r-to-z transformation // final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // // Standard deviation of the z // final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // // Lower bound of 90% confidence interval on z // final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // // Transform lower bound on z back to r // final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // // Upper bound of 90% confidence interval on z // final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // // Transform upper bound on z back to r // final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); // // final double featureCorrI = // ( // (numCases * pairActs - pairActs * actsI) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsI - actsI * actsI) // ) // ); // // final double featureCorrJ = // ( // (numCases * pairActs - pairActs * actsJ) // / // ( // Math.sqrt(numCases * pairActs - pairActs * pairActs) * // Math.sqrt(numCases * actsJ - actsJ * actsJ) // ) // ); // // System.out.println("score = " + pair.score); // System.out.println("correlation with errors = " + errorCorr); // System.out.println("lower bound correlation with errors = " + lbErrorCorr); // System.out.println("upper bound correlation with errors = " + ubErrorCorr); // System.out.println("correlation with first constituent = " + featureCorrI); // System.out.println("correlation with second constituent = " + featureCorrJ); // System.out.println("active feature A = " + pair.pair.a.feature()); // System.out.println("rot A = " + pair.pair.a.rotation()); // System.out.println("ref A = " + pair.pair.a.reflection()); // System.out.println("anchor A = " + pair.pair.a.anchorSite()); // System.out.println("active feature B = " + pair.pair.b.feature()); // System.out.println("rot B = " + pair.pair.b.rotation()); // System.out.println("ref B = " + pair.pair.b.reflection()); // System.out.println("anchor B = " + pair.pair.b.anchorSite()); // System.out.println("observed pair of instances " + pairActs + " times"); // System.out.println("observed first constituent " + actsI + " times"); // System.out.println("observed second constituent " + actsJ + " times"); // System.out.println(); // } // System.out.println("--------------------------------------------------------"); // Keep trying to add a proactive feature, until we succeed (almost always // this should be on the very first iteration) BaseFeatureSet currFeatureSet = featureSet; // TODO pretty much duplicate code of block below, should refactor into method while (!proactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = proactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); final int pairActs = featurePairActivations.get(pair); final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (numCases * pairActs - pairActs * actsI) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsI - actsI * actsI) ) ); final double featureCorrJ = ( (numCases * pairActs - pairActs * actsJ) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsJ - actsJ * actsJ) ) ); experiment.logLine(logWriter, "New proactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); experiment.logLine(logWriter, "score = " + bestPair.score); experiment.logLine(logWriter, "correlation with errors = " + errorCorr); experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); // System.out.println("BEST SCORE: " + bestPair.score); currFeatureSet = newFeatureSet; break; } } // Keep trying to add a reactive feature, until we succeed (almost always // this should be on the very first iteration) while (!reactivePairs.isEmpty()) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = reactivePairs.poll(); final BaseFeatureSet newFeatureSet = currFeatureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) ); final CombinableFeatureInstancePair pair = new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b); final int pairActs = featurePairActivations.get(pair); final double pairErrorSum = errorSums.get(pair); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); // Fisher's r-to-z transformation final double errorCorrZ = 0.5 * Math.log((1.0 + errorCorr) / (1.0 - errorCorr)); // Standard deviation of the z final double stdErrorCorrZ = Math.sqrt(1.0 / (numCases - 3)); // Lower bound of 90% confidence interval on z final double lbErrorCorrZ = errorCorrZ - 1.64 * stdErrorCorrZ; // Transform lower bound on z back to r final double lbErrorCorr = (Math.exp(2.0 * lbErrorCorrZ) - 1.0) / (Math.exp(2.0 * lbErrorCorrZ) + 1.0); // Upper bound of 90% confidence interval on z final double ubErrorCorrZ = errorCorrZ + 1.64 * stdErrorCorrZ; // Transform upper bound on z back to r final double ubErrorCorr = (Math.exp(2.0 * ubErrorCorrZ) - 1.0) / (Math.exp(2.0 * ubErrorCorrZ) + 1.0); final double featureCorrI = ( (numCases * pairActs - pairActs * actsI) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsI - actsI * actsI) ) ); final double featureCorrJ = ( (numCases * pairActs - pairActs * actsJ) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsJ - actsJ * actsJ) ) ); experiment.logLine(logWriter, "New reactive feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); experiment.logLine(logWriter, "avg error = " + sumErrors / numCases); experiment.logLine(logWriter, "avg error for pair = " + pairErrorSum / pairActs); experiment.logLine(logWriter, "score = " + bestPair.score); experiment.logLine(logWriter, "correlation with errors = " + errorCorr); experiment.logLine(logWriter, "lower bound correlation with errors = " + lbErrorCorr); experiment.logLine(logWriter, "upper bound correlation with errors = " + ubErrorCorr); experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); experiment.logLine(logWriter, "observed pair of instances " + pairActs + " times"); experiment.logLine(logWriter, "observed first constituent " + actsI + " times"); experiment.logLine(logWriter, "observed second constituent " + actsJ + " times"); currFeatureSet = newFeatureSet; break; } } return currFeatureSet; } }
51,160
38.690458
176
java
Ludii
Ludii-master/AI/src/training/feature_discovery/VarianceReductionExpander.java
package training.feature_discovery; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import features.FeatureVector; import features.feature_sets.BaseFeatureSet; import features.spatial.FeatureUtils; import features.spatial.SpatialFeature; import features.spatial.instances.FeatureInstance; import game.Game; import gnu.trove.impl.Constants; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TObjectDoubleHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import main.collections.FVector; import main.collections.FastArrayList; import other.move.Move; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.gradients.Gradients; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import utils.experiments.InterruptableExperiment; /** * Expands feature sets by adding features that maximally reduce variance in * at least one of the "splits", based on the upper bound of a confidence interval * on the split's variance. * * @author Dennis Soemers */ public class VarianceReductionExpander implements FeatureSetExpander { @Override public BaseFeatureSet expandFeatureSet ( final List<? extends ExperienceSample> batch, final BaseFeatureSet featureSet, final SoftmaxPolicyLinear policy, final Game game, final int featureDiscoveryMaxNumFeatureInstances, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TDoubleArrayList featureActiveRatios, final PrintWriter logWriter, final InterruptableExperiment experiment ) { // For every pair (i, j) of feature instances i and j, we need: // // n(i, j): the number of times that i and j are active at the same time // S(i, j): sum of errors in cases where i and j are both active // SS(i, j): sum of squares of errors in cases where i and j are both active // M(i, j): mean error in cases where i and j are both active // // Inverses of all four of the above (for cases where i and j are NOT both active), // but these do not need to be explicit. // // We similarly also need n, S, SS, and M values for all data (regardless of whether or // not i and j are active). // // For the set of cases where (i, j) are active, we can compute the sample variance in // errors using: // // SS(i, j) - 2*M(i, j)*S(i, j) + n(i, j)*M(i, j)*M(i, j) // ------------------------------------------------------ // n(i, j) - 1 // // Similar computations can be used for the cases where i and j are NOT both active, and // for the complete dataset. // This is our n(i, j) matrix final TObjectIntHashMap<CombinableFeatureInstancePair> featurePairActivations = new TObjectIntHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0); // This is our S(i, j) matrix final TObjectDoubleHashMap<CombinableFeatureInstancePair> errorSums = new TObjectDoubleHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0.0); // This is our SS(i, j) matrix final TObjectDoubleHashMap<CombinableFeatureInstancePair> squaredErrorSums = new TObjectDoubleHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0.0); // This is our M(i, j) matrix final TObjectDoubleHashMap<CombinableFeatureInstancePair> meanErrors = new TObjectDoubleHashMap<CombinableFeatureInstancePair>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0.0); // These are our n, S, SS, and M scalars for the complete dataset int numCases = 0; double sumErrors = 0.0; double sumSquaredErrors = 0.0; double meanError = 0.0; // Create a Hash Set of features already in Feature Set; we won't // have to consider combinations that are already in final Set<SpatialFeature> existingFeatures = new HashSet<SpatialFeature> ( (int) Math.ceil(featureSet.getNumSpatialFeatures() / 0.75f), 0.75f ); for (final SpatialFeature feature : featureSet.spatialFeatures()) { existingFeatures.add(feature); } // Set of feature instances that we have already preserved (and hence must continue to preserve) final Set<CombinableFeatureInstancePair> preservedInstances = new HashSet<CombinableFeatureInstancePair>(); // Set of feature instances that we have already chosen to discard once (and hence must continue to discard) final Set<CombinableFeatureInstancePair> discardedInstances = new HashSet<CombinableFeatureInstancePair>(); // For every sample in batch, first compute apprentice policies, errors, and sum of absolute errors final FVector[] apprenticePolicies = new FVector[batch.size()]; final FVector[] errorVectors = new FVector[batch.size()]; final float[] absErrorSums = new float[batch.size()]; final TDoubleArrayList[] errorsPerActiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; final TDoubleArrayList[] errorsPerInactiveFeature = new TDoubleArrayList[featureSet.getNumSpatialFeatures()]; for (int i = 0; i < errorsPerActiveFeature.length; ++i) { errorsPerActiveFeature[i] = new TDoubleArrayList(); errorsPerInactiveFeature[i] = new TDoubleArrayList(); } double avgActionError = 0.0; int totalNumActions = 0; for (int i = 0; i < batch.size(); ++i) { final ExperienceSample sample = batch.get(i); final FeatureVector[] featureVectors = sample.generateFeatureVectors(featureSet); final FVector apprenticePolicy = policy.computeDistribution(featureVectors, sample.gameState().mover()); final FVector errors = Gradients.computeDistributionErrors ( apprenticePolicy, sample.expertDistribution() ); for (int a = 0; a < featureVectors.length; ++a) { final float actionError = errors.get(a); final TIntArrayList sparseFeatureVector = featureVectors[a].activeSpatialFeatureIndices(); sparseFeatureVector.sort(); int sparseIdx = 0; for (int featureIdx = 0; featureIdx < featureSet.getNumSpatialFeatures(); ++featureIdx) { if (sparseIdx < sparseFeatureVector.size() && sparseFeatureVector.getQuick(sparseIdx) == featureIdx) { // This spatial feature is active errorsPerActiveFeature[featureIdx].add(actionError); // We've used the sparse index, so increment it ++sparseIdx; } else { // This spatial feature is not active errorsPerInactiveFeature[featureIdx].add(actionError); } } avgActionError += (actionError - avgActionError) / (totalNumActions + 1); ++totalNumActions; } final FVector absErrors = errors.copy(); absErrors.abs(); apprenticePolicies[i] = apprenticePolicy; errorVectors[i] = errors; absErrorSums[i] = absErrors.sum(); } // For every feature, compute sample correlation coefficient between its activity level (0 or 1) // and errors final double[] featureErrorCorrelations = new double[featureSet.getNumSpatialFeatures()]; // For every feature, compute expectation of its value multiplied by absolute value of error final double[] expectedFeatureTimesAbsError = new double[featureSet.getNumSpatialFeatures()]; for (int fIdx = 0; fIdx < featureSet.getNumSpatialFeatures(); ++fIdx) { final TDoubleArrayList errorsWhenActive = errorsPerActiveFeature[fIdx]; final TDoubleArrayList errorsWhenInactive = errorsPerInactiveFeature[fIdx]; final double avgFeatureVal = (double) errorsWhenActive.size() / (errorsWhenActive.size() + errorsPerInactiveFeature[fIdx].size()); double dErrorSquaresSum = 0.0; double numerator = 0.0; for (int i = 0; i < errorsWhenActive.size(); ++i) { final double error = errorsWhenActive.getQuick(i); final double dError = error - avgActionError; numerator += (1.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); expectedFeatureTimesAbsError[fIdx] += (Math.abs(error) - expectedFeatureTimesAbsError[fIdx]) / (i + 1); } for (int i = 0; i < errorsWhenInactive.size(); ++i) { final double error = errorsWhenInactive.getQuick(i); final double dError = error - avgActionError; numerator += (0.0 - avgFeatureVal) * dError; dErrorSquaresSum += (dError * dError); } final double dFeatureSquaresSum = errorsWhenActive.size() * ((1.0 - avgFeatureVal) * (1.0 - avgFeatureVal)) + errorsWhenInactive.size() * ((0.0 - avgFeatureVal) * (0.0 - avgFeatureVal)); final double denominator = Math.sqrt(dFeatureSquaresSum * dErrorSquaresSum); featureErrorCorrelations[fIdx] = numerator / denominator; } // Create list of indices that we can use to index into batch, sorted in descending order // of sums of absolute errors. // This means that we prioritise looking at samples in the batch for which we have big policy // errors, and hence also focus on them when dealing with a cap in the number of active feature // instances we can look at final List<Integer> batchIndices = new ArrayList<Integer>(batch.size()); for (int i = 0; i < batch.size(); ++i) { batchIndices.add(Integer.valueOf(i)); } Collections.sort(batchIndices, new Comparator<Integer>() { @Override public int compare(final Integer o1, final Integer o2) { final float deltaAbsErrorSums = absErrorSums[o1.intValue()] - absErrorSums[o2.intValue()]; if (deltaAbsErrorSums > 0.f) return -1; else if (deltaAbsErrorSums < 0.f) return 1; else return 0; } }); // Loop through all samples in batch for (int bi = 0; bi < batchIndices.size(); ++bi) { final int batchIndex = batchIndices.get(bi).intValue(); final ExperienceSample sample = batch.get(batchIndex); final FVector errors = errorVectors[batchIndex]; final FastArrayList<Move> moves = sample.moves(); // Every action in the sample is a new "case" (state-action pair) for (int a = 0; a < moves.size(); ++a) { ++numCases; // keep track of pairs we've already seen in this "case" final Set<CombinableFeatureInstancePair> observedCasePairs = new HashSet<CombinableFeatureInstancePair>(256, .75f); // list --> set --> list to get rid of duplicates final List<FeatureInstance> activeInstances = new ArrayList<FeatureInstance>(new HashSet<FeatureInstance>( featureSet.getActiveSpatialFeatureInstances ( sample.gameState(), sample.lastFromPos(), sample.lastToPos(), FeatureUtils.fromPos(moves.get(a)), FeatureUtils.toPos(moves.get(a)), moves.get(a).mover() ))); // Start out by keeping all feature instances that have already been marked as having to be // preserved, and discarding those that have already been discarded before final List<FeatureInstance> instancesToKeep = new ArrayList<FeatureInstance>(); for (int i = 0; i < activeInstances.size(); /**/) { final FeatureInstance instance = activeInstances.get(i); final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instance, instance); if (preservedInstances.contains(combinedSelf)) { instancesToKeep.add(instance); activeInstances.remove(i); } else if (discardedInstances.contains(combinedSelf)) { activeInstances.remove(i); } else { ++i; } } // This action is allowed to pick at most this many extra instances int numInstancesAllowedThisAction = Math.min(Math.min(Math.max( 5, // TODO make this a param featureDiscoveryMaxNumFeatureInstances - preservedInstances.size() / (moves.size() - a)), featureDiscoveryMaxNumFeatureInstances - preservedInstances.size()), activeInstances.size()); // Create distribution over active instances using softmax over logits that reward // features that correlate strongly with errors, as well as features that are often // active when absolute errors are high final FVector distr = new FVector(activeInstances.size()); for (int i = 0; i < activeInstances.size(); ++i) { final int fIdx = activeInstances.get(i).feature().spatialFeatureSetIndex(); distr.set(i, (float) (featureErrorCorrelations[fIdx] + expectedFeatureTimesAbsError[fIdx])); } distr.softmax(2.0); while (numInstancesAllowedThisAction > 0) { // Sample another instance final int sampledIdx = distr.sampleFromDistribution(); final FeatureInstance keepInstance = activeInstances.get(sampledIdx); instancesToKeep.add(keepInstance); final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, keepInstance, keepInstance); preservedInstances.add(combinedSelf); // Remember to preserve this one forever now distr.updateSoftmaxInvalidate(sampledIdx); // Don't want to pick the same index again --numInstancesAllowedThisAction; } // Mark all the instances that haven't been marked as preserved yet as discarded instead for (final FeatureInstance instance : activeInstances) { final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instance, instance); if (!preservedInstances.contains(combinedSelf)) discardedInstances.add(combinedSelf); } final int numActiveInstances = instancesToKeep.size(); final float error = errors.get(a); sumErrors += error; sumSquaredErrors += error * error; meanError += (error - meanError) / numCases; for (int i = 0; i < numActiveInstances; ++i) { final FeatureInstance instanceI = instancesToKeep.get(i); // increment entries on ''main diagonals'' final CombinableFeatureInstancePair combinedSelf = new CombinableFeatureInstancePair(game, instanceI, instanceI); if (observedCasePairs.add(combinedSelf)) { featurePairActivations.adjustOrPutValue(combinedSelf, 1, 1); errorSums.adjustOrPutValue(combinedSelf, error, error); squaredErrorSums.adjustOrPutValue(combinedSelf, error*error, error*error); final double deltaMean = (error - meanErrors.get(combinedSelf)) / featurePairActivations.get(combinedSelf); meanErrors.adjustOrPutValue(combinedSelf, deltaMean, deltaMean); } for (int j = i + 1; j < numActiveInstances; ++j) { final FeatureInstance instanceJ = instancesToKeep.get(j); // increment off-diagonal entries final CombinableFeatureInstancePair combined = new CombinableFeatureInstancePair(game, instanceI, instanceJ); if (!existingFeatures.contains(combined.combinedFeature)) { if (observedCasePairs.add(combined)) { featurePairActivations.adjustOrPutValue(combined, 1, 1); errorSums.adjustOrPutValue(combined, error, error); squaredErrorSums.adjustOrPutValue(combined, error*error, error*error); final double deltaMean = (error - meanErrors.get(combined)) / featurePairActivations.get(combined); meanErrors.adjustOrPutValue(combined, deltaMean, deltaMean); } } } } } } if (sumErrors == 0.0 || sumSquaredErrors == 0.0) { // incredibly rare case but appears to be possible sometimes // we have nothing to guide our feature growing, so let's // just refuse to add a feature return null; } // Construct all possible pairs and scores // as we go, keep track of best score and index at which we can find it final List<ScoredFeatureInstancePair> scoredPairs = new ArrayList<ScoredFeatureInstancePair>(featurePairActivations.size()); double bestScore = Double.NEGATIVE_INFINITY; int bestPairIdx = -1; for (final CombinableFeatureInstancePair pair : featurePairActivations.keySet()) { if (! pair.a.equals(pair.b)) // Only interested in combinations of different instances { final int nij = featurePairActivations.get(pair); if (nij == numCases) { // No variance reduction, so we should just skip this one continue; } if (nij < 2) { // Not enough cases to estimate sample variance in errors, so skip continue; } final int ni = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.a, pair.a)); final int nj = featurePairActivations.get(new CombinableFeatureInstancePair(game, pair.b, pair.b)); if (ni == numCases || nj == numCases) { // Perfect correlation with one of the constituents, we'll skip this continue; } // Compute sample variance for all cases final double varComplete = (sumSquaredErrors - 2*meanError*sumErrors + numCases*meanError*meanError) / (numCases - 1); // Compute sample variance for the "split" that includes the feature pair final double Sij = errorSums.get(pair); final double SSij = squaredErrorSums.get(pair); final double Mij = meanErrors.get(pair); final double varWithPair = (SSij - 2*Mij*Sij + nij*Mij*Mij) / (nij - 1); // Compute sample variance for the "split" that excludes the feature pair final int invNij = numCases - nij; final double invSij = sumErrors - Sij; final double invSSij = sumSquaredErrors - SSij; final double invMij = (meanError*numCases - Mij*nij) / invNij; final double varWithoutPair = (invSSij - 2*invMij*invSij + invNij*invMij*invMij) / (nij - 1); final double varReduction = varComplete - (varWithPair + varWithoutPair); final double featureCorrI = ( (nij * (numCases - ni)) / ( Math.sqrt(nij * (numCases - nij)) * Math.sqrt(ni * (numCases - ni)) ) ); final double featureCorrJ = ( (nij * (numCases - nj)) / ( Math.sqrt(nij * (numCases - nij)) * Math.sqrt(nj * (numCases - nj)) ) ); final double worstFeatureCorr = Math.max ( Math.abs(featureCorrI), Math.abs(featureCorrJ) ); if (worstFeatureCorr == 1.0) continue; if (Double.isNaN(varReduction)) continue; // continue if worst feature corr == 1.0 final double score = varReduction/* * (1.0 - worstFeatureCorr)*/; scoredPairs.add(new ScoredFeatureInstancePair(pair, score)); if (varReduction > bestScore) { bestScore = varReduction; bestPairIdx = scoredPairs.size() - 1; } } } // keep trying to generate an expanded (by one) feature set, until // we succeed (almost always this should be on the very first iteration) while (scoredPairs.size() > 0) { // extract pair of feature instances we want to try combining final ScoredFeatureInstancePair bestPair = scoredPairs.remove(bestPairIdx); final BaseFeatureSet newFeatureSet = featureSet.createExpandedFeatureSet(game, bestPair.pair.combinedFeature); if (newFeatureSet != null) { final int actsI = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.a) ); final int actsJ = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.b, bestPair.pair.b) ); final int pairActs = featurePairActivations.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b) ); final double pairErrorSum = errorSums.get ( new CombinableFeatureInstancePair(game, bestPair.pair.a, bestPair.pair.b) ); final double errorCorr = ( (numCases * pairErrorSum - pairActs * sumErrors) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * sumSquaredErrors - sumErrors * sumErrors) ) ); final double featureCorrI = ( (numCases * pairActs - pairActs * actsI) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsI - actsI * actsI) ) ); final double featureCorrJ = ( (numCases * pairActs - pairActs * actsJ) / ( Math.sqrt(numCases * pairActs - pairActs * pairActs) * Math.sqrt(numCases * actsJ - actsJ * actsJ) ) ); // Compute sample variance for all cases final double varComplete = (sumSquaredErrors - 2*meanError*sumErrors + numCases*meanError*meanError) / (numCases - 1); // Compute sample variance for the "split" that includes the feature pair final double Sij = errorSums.get(bestPair.pair); final double SSij = squaredErrorSums.get(bestPair.pair); final double Mij = meanErrors.get(bestPair.pair); final double varWithPair = (SSij - 2*Mij*Sij + pairActs*Mij*Mij) / (pairActs - 1); // Compute sample variance for the "split" that excludes the feature pair final int invNij = numCases - pairActs; final double invSij = sumErrors - Sij; final double invSSij = sumSquaredErrors - SSij; final double invMij = (meanError*numCases - Mij*pairActs) / invNij; final double varWithoutPair = (invSSij - 2*invMij*invSij + invNij*invMij*invMij) / (pairActs - 1); final double varReduction = varComplete - (varWithPair + varWithoutPair); experiment.logLine(logWriter, "New feature added!"); experiment.logLine(logWriter, "new feature = " + newFeatureSet.spatialFeatures()[newFeatureSet.getNumSpatialFeatures() - 1]); experiment.logLine(logWriter, "active feature A = " + bestPair.pair.a.feature()); experiment.logLine(logWriter, "rot A = " + bestPair.pair.a.rotation()); experiment.logLine(logWriter, "ref A = " + bestPair.pair.a.reflection()); experiment.logLine(logWriter, "anchor A = " + bestPair.pair.a.anchorSite()); experiment.logLine(logWriter, "active feature B = " + bestPair.pair.b.feature()); experiment.logLine(logWriter, "rot B = " + bestPair.pair.b.rotation()); experiment.logLine(logWriter, "ref B = " + bestPair.pair.b.reflection()); experiment.logLine(logWriter, "anchor B = " + bestPair.pair.b.anchorSite()); experiment.logLine(logWriter, "score = " + bestPair.score); experiment.logLine(logWriter, "correlation with errors = " + errorCorr); experiment.logLine(logWriter, "correlation with first constituent = " + featureCorrI); experiment.logLine(logWriter, "correlation with second constituent = " + featureCorrJ); experiment.logLine(logWriter, "varComplete = " + varComplete); experiment.logLine(logWriter, "varWithPair = " + varWithPair); experiment.logLine(logWriter, "varWithoutPair = " + varWithoutPair); experiment.logLine(logWriter, "varReduction = " + varReduction); return newFeatureSet; } // if we reach this point, it means we failed to create an // expanded feature set with our top-score pair. // so, we should search again for the next best pair bestScore = Double.NEGATIVE_INFINITY; bestPairIdx = -1; for (int i = 0; i < scoredPairs.size(); ++i) { if (scoredPairs.get(i).score > bestScore) { bestScore = scoredPairs.get(i).score; bestPairIdx = i; } } } return null; } }
23,410
36.042722
129
java
Ludii
Ludii-master/AI/src/training/policy_gradients/Reinforce.java
package training.policy_gradients; import java.io.PrintWriter; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import features.FeatureVector; import features.feature_sets.BaseFeatureSet; import features.feature_sets.network.JITSPatterNetFeatureSet; import features.spatial.FeatureUtils; import game.Game; import gnu.trove.list.array.TDoubleArrayList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.list.array.TLongArrayList; import main.DaemonThreadFactory; import main.collections.FVector; import main.collections.FastArrayList; import main.collections.ListUtils; import optimisers.Optimiser; import other.RankUtils; import other.context.Context; import other.move.Move; import other.state.State; import other.trial.Trial; import policies.softmax.SoftmaxPolicyLinear; import training.ExperienceSample; import training.expert_iteration.params.FeatureDiscoveryParams; import training.expert_iteration.params.ObjectiveParams; import training.expert_iteration.params.TrainingParams; import training.feature_discovery.FeatureSetExpander; import utils.ExponentialMovingAverage; import utils.experiments.InterruptableExperiment; /** * Self-play feature (pre-)training and discovery with REINFORCE * * @author Dennis Soemers */ public class Reinforce { //------------------------------------------------------------------------- /** We don't store experiences for which the discount factor drops below this threshold */ private static final double EXPERIENCE_DISCOUNT_THRESHOLD = 0.001; /** If we have a discount factor gamma = 1, we'll use this threshold to limit amount of data stored per trial */ private static final int DATA_PER_TRIAL_THRESHOLD = 50; //------------------------------------------------------------------------- /** * Runs self-play with Policy Gradient training of features * * @param game * @param selectionPolicy * @param inFeatureSets * @param featureSetExpander * @param optimisers * @param objectiveParams * @param featureDiscoveryParams * @param trainingParams * @param logWriter * @return New array of feature sets */ @SuppressWarnings("unchecked") public static BaseFeatureSet[] runSelfPlayPG ( final Game game, final SoftmaxPolicyLinear selectionPolicy, final SoftmaxPolicyLinear playoutPolicy, final SoftmaxPolicyLinear tspgPolicy, final BaseFeatureSet[] inFeatureSets, final FeatureSetExpander featureSetExpander, final Optimiser[] optimisers, final ObjectiveParams objectiveParams, final FeatureDiscoveryParams featureDiscoveryParams, final TrainingParams trainingParams, final PrintWriter logWriter, final InterruptableExperiment experiment ) { BaseFeatureSet[] featureSets = inFeatureSets; final int numPlayers = game.players().count(); // TODO actually use these? final ExponentialMovingAverage[] avgGameDurations = new ExponentialMovingAverage[numPlayers + 1]; final ExponentialMovingAverage[] avgPlayerOutcomeTrackers = new ExponentialMovingAverage[numPlayers + 1]; for (int p = 1; p <= numPlayers; ++p) { avgGameDurations[p] = new ExponentialMovingAverage(); avgPlayerOutcomeTrackers[p] = new ExponentialMovingAverage(); } final TLongArrayList[] featureLifetimes = new TLongArrayList[featureSets.length]; final TDoubleArrayList[] featureActiveRatios = new TDoubleArrayList[featureSets.length]; for (int i = 0; i < featureSets.length; ++i) { if (featureSets[i] != null) { final TLongArrayList featureLifetimesList = new TLongArrayList(); featureLifetimesList.fill(0, featureSets[i].getNumSpatialFeatures(), 0L); featureLifetimes[i] = featureLifetimesList; final TDoubleArrayList featureActiveRatiosList = new TDoubleArrayList(); featureActiveRatiosList.fill(0, featureSets[i].getNumSpatialFeatures(), 0.0); featureActiveRatios[i] = featureActiveRatiosList; } } // Thread pool for running trials in parallel final ExecutorService trialsThreadPool = Executors.newFixedThreadPool(trainingParams.numPolicyGradientThreads, DaemonThreadFactory.INSTANCE); for (int epoch = 0; epoch < trainingParams.numPolicyGradientEpochs; ++epoch) { if (experiment.wantsInterrupt()) break; //System.out.println("Starting Policy Gradient epoch: " + epoch); // Collect all experience (per player) for this epoch here final List<PGExperience>[] epochExperiences = new List[numPlayers + 1]; for (int p = 1; p <= numPlayers; ++p) { epochExperiences[p] = new ArrayList<PGExperience>(); } // Softmax should be thread-safe except for its initAI() and closeAI() methods // It's not perfect, but it works fine in the specific case of SoftmaxPolicy to only // init and close it before and after an entire batch of trials, rather than before // and after every trial. So, we'll just do that for the sake of thread-safety. // // Since our object will play as all players at once, we pass -1 for the player ID // This is fine since SoftmaxPolicy doesn't actually care about that argument playoutPolicy.initAI(game, -1); final CountDownLatch trialsLatch = new CountDownLatch(trainingParams.numPolicyGradientThreads); final AtomicInteger epochTrialsCount = new AtomicInteger(0); final BaseFeatureSet[] epochFeatureSets = featureSets; for (int th = 0; th < trainingParams.numPolicyGradientThreads; ++th) { trialsThreadPool.submit ( () -> { try { while (epochTrialsCount.getAndIncrement() < trainingParams.numTrialsPerPolicyGradientEpoch) { final List<State>[] encounteredGameStates = new List[numPlayers + 1]; final List<Move>[] lastDecisionMoves = new List[numPlayers + 1]; final List<FastArrayList<Move>>[] legalMovesLists = new List[numPlayers + 1]; final List<FeatureVector[]>[] featureVectorArrays = new List[numPlayers + 1]; final TIntArrayList[] playedMoveIndices = new TIntArrayList[numPlayers + 1]; for (int p = 1; p <= numPlayers; ++p) { encounteredGameStates[p] = new ArrayList<State>(); lastDecisionMoves[p] = new ArrayList<Move>(); legalMovesLists[p] = new ArrayList<FastArrayList<Move>>(); featureVectorArrays[p] = new ArrayList<FeatureVector[]>(); playedMoveIndices[p] = new TIntArrayList(); } final Trial trial = new Trial(game); final Context context = new Context(game, trial); game.start(context); // Play trial while (!trial.over()) { final int mover = context.state().mover(); final FastArrayList<Move> moves = game.moves(context).moves(); final BaseFeatureSet featureSet = epochFeatureSets[mover]; final FeatureVector[] featureVectors = featureSet.computeFeatureVectors(context, moves, false); for (final FeatureVector featureVector : featureVectors) { featureVector.activeSpatialFeatureIndices().trimToSize(); } final FVector distribution = playoutPolicy.computeDistribution(featureVectors, mover); final int moveIdx = playoutPolicy.selectActionFromDistribution(distribution); final Move move = moves.get(moveIdx); encounteredGameStates[mover].add(new Context(context).state()); lastDecisionMoves[mover].add(context.trial().lastMove()); legalMovesLists[mover].add(new FastArrayList<Move>(moves)); featureVectorArrays[mover].add(featureVectors); playedMoveIndices[mover].add(moveIdx); game.apply(context, move); updateFeatureActivityData(featureVectors, featureLifetimes, featureActiveRatios, mover); } final double[] utilities = RankUtils.agentUtilities(context); // Store all experiences addTrialData ( epochExperiences, numPlayers, encounteredGameStates, lastDecisionMoves, legalMovesLists, featureVectorArrays, playedMoveIndices, utilities, avgGameDurations, avgPlayerOutcomeTrackers, trainingParams ); } } catch (final Exception e) { e.printStackTrace(); // Need to do this here since we don't retrieve runnable's Future result } finally { trialsLatch.countDown(); } } ); } try { trialsLatch.await(); } catch (final InterruptedException e) { e.printStackTrace(); } playoutPolicy.closeAI(); for (int p = 1; p <= numPlayers; ++p) { final List<PGExperience> experiences = epochExperiences[p]; final int numExperiences = experiences.size(); final FVector grads = new FVector(playoutPolicy.linearFunction(p).trainableParams().allWeights().dim()); final double baseline = avgPlayerOutcomeTrackers[p].movingAvg(); for (int i = 0; i < numExperiences; ++i) { final PGExperience exp = experiences.get(i); final FVector distribution = playoutPolicy.computeDistribution(exp.featureVectors, p); final FVector policyGradients = computePolicyGradients ( exp, grads.dim(), baseline, trainingParams.entropyRegWeight, distribution.get(exp.movePlayedIdx()) ); // Now just need to divide gradients by the number of experiences we have and then we can // add them to the average gradients (averaged over all experiences) policyGradients.div(numExperiences); grads.add(policyGradients); } // Take gradient step optimisers[p].maximiseObjective(playoutPolicy.linearFunction(p).trainableParams().allWeights(), grads); } if (!featureDiscoveryParams.noGrowFeatureSet && (epoch + 1) % 5 == 0) { // Now we want to try growing our feature set final BaseFeatureSet[] expandedFeatureSets = new BaseFeatureSet[numPlayers + 1]; final ExecutorService threadPool = Executors.newFixedThreadPool(featureDiscoveryParams.numFeatureDiscoveryThreads); final CountDownLatch latch = new CountDownLatch(numPlayers); for (int pIdx = 1; pIdx <= numPlayers; ++pIdx) { final int p = pIdx; final BaseFeatureSet featureSetP = featureSets[p]; threadPool.submit ( () -> { try { // We'll sample a batch from our experiences, and grow feature set final int batchSize = trainingParams.batchSize; final List<PGExperience> batch = new ArrayList<PGExperience>(batchSize); while (batch.size() < batchSize && !epochExperiences[p].isEmpty()) { final int r = ThreadLocalRandom.current().nextInt(epochExperiences[p].size()); batch.add(epochExperiences[p].get(r)); ListUtils.removeSwap(epochExperiences[p], r); } if (batch.size() > 0) { final long startTime = System.currentTimeMillis(); final BaseFeatureSet expandedFeatureSet = featureSetExpander.expandFeatureSet ( batch, featureSetP, playoutPolicy, game, featureDiscoveryParams.combiningFeatureInstanceThreshold, objectiveParams, featureDiscoveryParams, featureActiveRatios[p], logWriter, experiment ); if (expandedFeatureSet != null) { expandedFeatureSets[p] = expandedFeatureSet; expandedFeatureSet.init(game, new int[]{p}, null); while (featureActiveRatios[p].size() < expandedFeatureSet.getNumSpatialFeatures()) { featureLifetimes[p].add(0L); featureActiveRatios[p].add(0.0); } } else { expandedFeatureSets[p] = featureSetP; } // Previously cached feature sets likely useless / less useful now, so clear cache JITSPatterNetFeatureSet.clearFeatureSetCache(); experiment.logLine ( logWriter, "Expanded feature set in " + (System.currentTimeMillis() - startTime) + " ms for P" + p + "." ); //System.out.println("Expanded feature set in " + (System.currentTimeMillis() - startTime) + " ms for P" + p + "."); } else { expandedFeatureSets[p] = featureSetP; } } catch (final Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } ); } try { latch.await(); } catch (final InterruptedException e) { e.printStackTrace(); } threadPool.shutdown(); selectionPolicy.updateFeatureSets(expandedFeatureSets); playoutPolicy.updateFeatureSets(expandedFeatureSets); tspgPolicy.updateFeatureSets(expandedFeatureSets); featureSets = expandedFeatureSets; } // TODO above will be lots of duplication with code in ExpertIteration, should refactor // TODO save checkpoints } trialsThreadPool.shutdownNow(); return featureSets; } //------------------------------------------------------------------------- /** * @param exp * @param dim Dimensionality we want for output vector * @param valueBaseline * @param entropyRegWeight Weight for entropy regularisation term * @param playedMoveProb Probably with which our policy picks the move that we ended up picking * @return Computes vector of policy gradients for given sample of experience */ private static FVector computePolicyGradients ( final PGExperience exp, final int dim, final double valueBaseline, final double entropyRegWeight, final float playedMoveProb ) { // Policy gradient giving the direction in which we should update parameters theta // can be estimated as: // // AVERAGE OVER ALL EXPERIENCE SAMPLES i with returns G_i: // \nabla_{\theta} \log ( \pi_{\theta} (a_i | s_i) ) * G_i // // Assuming that \pi_{\theta} (a_i | s_i) is given by a softmax over the logits of // all the actions legal in s_i, we have: // // \nabla_{\theta} \log ( \pi_{\theta} (a_i | s_i) ) = \phi(s_i, a_i) - E_{\pi_{\theta}} [\phi(s_i, \cdot)] final FeatureVector[] featureVectors = exp.featureVectors(); final FVector expectedPhi = new FVector(dim); final FVector gradLogPi = new FVector(dim); for (int moveIdx = 0; moveIdx < featureVectors.length; ++moveIdx) { final FeatureVector featureVector = featureVectors[moveIdx]; // Dense representation for aspatial features final FVector aspatialFeatureVals = featureVector.aspatialFeatureValues(); final int numAspatialFeatures = aspatialFeatureVals.dim(); for (int k = 0; k < numAspatialFeatures; ++k) { expectedPhi.addToEntry(k, aspatialFeatureVals.get(k)); } if (moveIdx == exp.movePlayedIdx()) { for (int k = 0; k < numAspatialFeatures; ++k) { gradLogPi.addToEntry(k, aspatialFeatureVals.get(k)); } } // Sparse representation for spatial features (num aspatial features as offset for indexing) final TIntArrayList sparseSpatialFeatures = featureVector.activeSpatialFeatureIndices(); for (int k = 0; k < sparseSpatialFeatures.size(); ++k) { final int feature = sparseSpatialFeatures.getQuick(k); expectedPhi.addToEntry(feature + numAspatialFeatures, 1.f); } if (moveIdx == exp.movePlayedIdx()) { for (int k = 0; k < sparseSpatialFeatures.size(); ++k) { final int feature = sparseSpatialFeatures.getQuick(k); gradLogPi.addToEntry(feature + numAspatialFeatures, 1.f); } } } expectedPhi.div(featureVectors.length); gradLogPi.subtract(expectedPhi); // Now we have the gradients of the log-probability of the action we played // We want to weight these by the returns of the episode gradLogPi.mult((float)(exp.discountMultiplier() * (exp.returns() - valueBaseline) - entropyRegWeight * Math.log(playedMoveProb))); return gradLogPi; } //------------------------------------------------------------------------- /** * Update feature activity data. Unfortunately this needs to be synchronized, * trial threads should only update this one-by-one * @param featureVectors * @param featureLifetimes * @param featureActiveRatios * @param mover */ private static synchronized void updateFeatureActivityData ( final FeatureVector[] featureVectors, final TLongArrayList[] featureLifetimes, final TDoubleArrayList[] featureActiveRatios, final int mover ) { // Update feature activity data for (final FeatureVector featureVector : featureVectors) { final TIntArrayList sparse = featureVector.activeSpatialFeatureIndices(); if (sparse.isEmpty()) continue; // Probably a pass/swap/other special move, don't want these affecting our active ratios // Following code expects the indices in the sparse feature vector to be sorted sparse.sort(); // Increase lifetime of all features by 1 featureLifetimes[mover].transformValues((final long l) -> {return l + 1L;}); // Incrementally update all average feature values final TDoubleArrayList list = featureActiveRatios[mover]; int vectorIdx = 0; for (int i = 0; i < list.size(); ++i) { final double oldMean = list.getQuick(i); if (vectorIdx < sparse.size() && sparse.getQuick(vectorIdx) == i) { // ith feature is active list.setQuick(i, oldMean + ((1.0 - oldMean) / featureLifetimes[mover].getQuick(i))); ++vectorIdx; } else { // ith feature is not active list.setQuick(i, oldMean + ((0.0 - oldMean) / featureLifetimes[mover].getQuick(i))); } } if (vectorIdx != sparse.size()) { System.err.println("ERROR: expected vectorIdx == sparse.size()!"); System.err.println("vectorIdx = " + vectorIdx); System.err.println("sparse.size() = " + sparse.size()); System.err.println("sparse = " + sparse); } } } /** * Record data collected from a trial. Needs to be synchronized, parallel trials * have to do this one-by-one. * * @param epochExperiences * @param numPlayers * @param encounteredGameStates * @param lastDecisionMoves * @param legalMovesLists * @param featureVectorArrays * @param playedMoveIndices * @param utilities * @param avgGameDurations * @param avgPlayerOutcomeTrackers * @param trainingParams */ private static synchronized void addTrialData ( final List<PGExperience>[] epochExperiences, final int numPlayers, final List<State>[] encounteredGameStates, final List<Move>[] lastDecisionMoves, final List<FastArrayList<Move>>[] legalMovesLists, final List<FeatureVector[]>[] featureVectorArrays, final TIntArrayList[] playedMoveIndices, final double[] utilities, final ExponentialMovingAverage[] avgGameDurations, final ExponentialMovingAverage[] avgPlayerOutcomeTrackers, final TrainingParams trainingParams ) { for (int p = 1; p <= numPlayers; ++p) { final List<State> gameStatesList = encounteredGameStates[p]; final List<Move> lastDecisionMovesList = lastDecisionMoves[p]; final List<FastArrayList<Move>> legalMovesList = legalMovesLists[p]; final List<FeatureVector[]> featureVectorsList = featureVectorArrays[p]; final TIntArrayList moveIndicesList = playedMoveIndices[p]; // Note: not really game duration! Just from perspective of one player! final int gameDuration = gameStatesList.size(); avgGameDurations[p].observe(gameDuration); avgPlayerOutcomeTrackers[p].observe(utilities[p]); double discountMultiplier = 1.0; final boolean[] skipData = new boolean[featureVectorsList.size()]; if (trainingParams.pgGamma == 1.0) { int numSkipped = 0; while (skipData.length - numSkipped > DATA_PER_TRIAL_THRESHOLD) { final int skipIdx = ThreadLocalRandom.current().nextInt(skipData.length); if (!skipData[skipIdx]) { skipData[skipIdx] = true; ++numSkipped; } } } for (int i = featureVectorsList.size() - 1; i >= 0; --i) { if (!skipData[i] && legalMovesList.get(i).size() > 1) { epochExperiences[p].add ( new PGExperience ( gameStatesList.get(i), lastDecisionMovesList.get(i), legalMovesList.get(i), featureVectorsList.get(i), moveIndicesList.getQuick(i), (float)utilities[p], discountMultiplier ) ); } discountMultiplier *= trainingParams.pgGamma; if (discountMultiplier < EXPERIENCE_DISCOUNT_THRESHOLD) break; } } } //------------------------------------------------------------------------- /** * Sample of experience for policy gradients * * NOTE: since our experiences just collect feature vectors rather than contexts, * we cannot reuse the same experiences after growing our feature sets * * @author Dennis Soemers */ private static class PGExperience extends ExperienceSample { /** Game state */ protected final State state; /** From-position of last decision move */ protected final int lastFromPos; /** To-position of last decision move */ protected final int lastToPos; /** List of legal moves */ protected final FastArrayList<Move> legalMoves; /** Array of feature vectors (one per legal move) */ protected final FeatureVector[] featureVectors; /** Index of move that we ended up playing */ protected final int movePlayedIdx; /** Returns we got at the end of the trial that this experience was a part of */ protected final float returns; /** Multiplier we should use due to discounting */ protected final double discountMultiplier; /** * Constructor * @param state * @param lastDecisionMove * @param legalMoves * @param featureVectors * @param movePlayedIdx * @param returns * @param discountMultiplier */ public PGExperience ( final State state, final Move lastDecisionMove, final FastArrayList<Move> legalMoves, final FeatureVector[] featureVectors, final int movePlayedIdx, final float returns, final double discountMultiplier ) { this.state = state; this.lastFromPos = FeatureUtils.fromPos(lastDecisionMove); this.lastToPos = FeatureUtils.toPos(lastDecisionMove); this.legalMoves = legalMoves; this.featureVectors = featureVectors; this.movePlayedIdx = movePlayedIdx; this.returns = returns; this.discountMultiplier = discountMultiplier; } /** * @return Array of feature vectors (one per legal move) */ public FeatureVector[] featureVectors() { return featureVectors; } /** * @return The index of the move we played */ public int movePlayedIdx() { return movePlayedIdx; } /** * @return The returns we got at end of trial that this experience was a part of */ public float returns() { return returns; } /** * @return Discount multiplier for this sample of experience */ public double discountMultiplier() { return discountMultiplier; } @Override public FeatureVector[] generateFeatureVectors(final BaseFeatureSet featureSet) { return featureVectors; } @Override public FVector expertDistribution() { // As an estimation of a good expert distribution, we'll use the // discounted returns as logit for the played action, with logits of 0 // everywhere else, and then use a softmax to turn it into // a distribution final FVector distribution = new FVector(featureVectors.length); distribution.set(movePlayedIdx, (float) (returns * discountMultiplier)); distribution.softmax(); return distribution; } @Override public State gameState() { return state; } @Override public int lastFromPos() { return lastFromPos; } @Override public int lastToPos() { return lastToPos; } @Override public FastArrayList<Move> moves() { return legalMoves; } @Override public BitSet winningMoves() { return new BitSet(); // TODO probably want to track these } @Override public BitSet losingMoves() { return new BitSet(); // TODO probably want to track these } @Override public BitSet antiDefeatingMoves() { return new BitSet(); // TODO probably want to track these } } //------------------------------------------------------------------------- }
24,693
30.457325
143
java
Ludii
Ludii-master/AI/src/utils/AIFactory.java
package utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import org.json.JSONObject; import org.json.JSONTokener; import game.Game; import main.FileHandling; import main.grammar.Report; import metadata.ai.Ai; import metadata.ai.agents.Agent; import metadata.ai.agents.BestAgent; import metadata.ai.agents.mcts.Mcts; import metadata.ai.agents.minimax.AlphaBeta; import other.AI; import policies.GreedyPolicy; import policies.ProportionalPolicyClassificationTree; import policies.softmax.SoftmaxPolicyLinear; import policies.softmax.SoftmaxPolicyLogitTree; import search.flat.FlatMonteCarlo; import search.flat.HeuristicSampling; import search.flat.OnePlyNoHeuristic; import search.mcts.MCTS; import search.mcts.MCTS.QInit; import search.mcts.backpropagation.AlphaGoBackprop; import search.mcts.backpropagation.MonteCarloBackprop; import search.mcts.backpropagation.QualitativeBonus; import search.mcts.finalmoveselection.RobustChild; import search.mcts.playout.MAST; import search.mcts.playout.NST; import search.mcts.playout.RandomPlayout; import search.mcts.selection.McBRAVE; import search.mcts.selection.McGRAVE; import search.mcts.selection.ProgressiveBias; import search.mcts.selection.ProgressiveHistory; import search.mcts.selection.UCB1; import search.mcts.selection.UCB1GRAVE; import search.mcts.selection.UCB1Tuned; import search.minimax.AlphaBetaSearch; import search.minimax.BRSPlus; import search.minimax.BiasedUBFM; import search.minimax.HybridUBFM; import search.minimax.LazyUBFM; import search.minimax.UBFM; /** * Can create AI agents based on strings / files * * @author Dennis Soemers */ public class AIFactory { //------------------------------------------------------------------------- /** * Map from absolute paths of JAR files to lists of loaded, third-party AI * classes */ private static Map<String, List<Class<?>>> thirdPartyAIClasses = new HashMap<>(); //------------------------------------------------------------------------- /** * Constructor should not be used. */ private AIFactory() { // not intended to be used } //------------------------------------------------------------------------- /** * @param string String representation of agent, or filename from which to load agent * @return Created AI */ public static AI createAI(final String string) { if (string.equalsIgnoreCase("Random")) return new RandomAI(); if (string.equalsIgnoreCase("Monte Carlo (flat)") || string.equalsIgnoreCase("Flat MC")) return new FlatMonteCarlo(); if (string.equalsIgnoreCase("Alpha-Beta") || string.equalsIgnoreCase("AlphaBeta")) return AlphaBetaSearch.createAlphaBeta(); if (string.equalsIgnoreCase("BRS+") || string.equalsIgnoreCase("Best-Reply Search+")) return new BRSPlus(); if (string.equalsIgnoreCase("UBFM")) return new UBFM(); if (string.equalsIgnoreCase("Hybrid UBFM")) return new HybridUBFM(); if (string.equalsIgnoreCase("Lazy UBFM")) return new LazyUBFM(); if (string.equalsIgnoreCase("Biased UBFM")) return new BiasedUBFM(); if (string.equalsIgnoreCase("UCT") || string.equalsIgnoreCase("MCTS")) return MCTS.createUCT(); if (string.equalsIgnoreCase("MC-GRAVE")) { final MCTS mcGRAVE = new MCTS ( new McGRAVE(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild() ); mcGRAVE.setQInit(QInit.INF); mcGRAVE.setFriendlyName("MC-GRAVE"); return mcGRAVE; } if (string.equalsIgnoreCase("MC-BRAVE")) { final MCTS mcBRAVE = new MCTS ( new McBRAVE(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild() ); mcBRAVE.setQInit(QInit.INF); mcBRAVE.setFriendlyName("MC-BRAVE"); return mcBRAVE; } if (string.equalsIgnoreCase("UCB1Tuned")) { final MCTS ucb1Tuned = new MCTS ( new UCB1Tuned(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild() ); ucb1Tuned.setQInit(QInit.PARENT); ucb1Tuned.setFriendlyName("UCB1Tuned"); return ucb1Tuned; } if (string.equalsIgnoreCase("Score Bounded MCTS") || string.equalsIgnoreCase("ScoreBoundedMCTS")) { final MCTS sbMCTS = new MCTS ( new UCB1(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild() ); sbMCTS.setQInit(QInit.PARENT); sbMCTS.setUseScoreBounds(true); sbMCTS.setFriendlyName("Score Bounded MCTS"); return sbMCTS; } if (string.equalsIgnoreCase("Progressive History") || string.equalsIgnoreCase("ProgressiveHistory")) { final MCTS progressiveHistory = new MCTS ( new ProgressiveHistory(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild() ); progressiveHistory.setQInit(QInit.PARENT); progressiveHistory.setFriendlyName("Progressive History"); return progressiveHistory; } if (string.equalsIgnoreCase("Progressive Bias") || string.equalsIgnoreCase("ProgressiveBias")) { final MCTS progressiveBias = new MCTS ( new ProgressiveBias(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild() ); progressiveBias.setQInit(QInit.INF); // This is probably important for sufficient exploration progressiveBias.setWantsMetadataHeuristics(true); progressiveBias.setFriendlyName("Progressive Bias"); return progressiveBias; } if (string.equalsIgnoreCase("MAST")) { final MCTS mast = new MCTS ( new UCB1(), new MAST(200, 0.1), new MonteCarloBackprop(), new RobustChild() ); mast.setQInit(QInit.PARENT); mast.setFriendlyName("MAST"); return mast; } if (string.equalsIgnoreCase("NST")) { final MCTS nst = new MCTS ( new UCB1(), new NST(200, 0.1), new MonteCarloBackprop(), new RobustChild() ); nst.setQInit(QInit.PARENT); nst.setFriendlyName("NST"); return nst; } if (string.equalsIgnoreCase("UCB1-GRAVE")) { final MCTS ucb1GRAVE = new MCTS ( new UCB1GRAVE(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild() ); ucb1GRAVE.setFriendlyName("UCB1-GRAVE"); return ucb1GRAVE; } if (string.equalsIgnoreCase("Ludii AI")) { return new LudiiAI(); } if (string.equalsIgnoreCase("Biased MCTS")) return MCTS.createBiasedMCTS(0.0); if (string.equalsIgnoreCase("Biased MCTS (Uniform Playouts)") || string.equalsIgnoreCase("MCTS (Biased Selection)")) return MCTS.createBiasedMCTS(1.0); if (string.equalsIgnoreCase("MCTS (Hybrid Selection)")) return MCTS.createHybridMCTS(); if (string.equalsIgnoreCase("Bandit Tree Search")) return MCTS.createBanditTreeSearch(); if (string.equalsIgnoreCase("EPT")) { final MCTS ept = new MCTS ( new UCB1(Math.sqrt(2.0)), new RandomPlayout(4), new AlphaGoBackprop(), new RobustChild() ); ept.setWantsMetadataHeuristics(true); ept.setPlayoutValueWeight(1.0); ept.setFriendlyName("EPT"); return ept; } if (string.equalsIgnoreCase("EPT-QB")) { final MCTS ept = new MCTS ( new UCB1(Math.sqrt(2.0)), new RandomPlayout(4), new QualitativeBonus(), new RobustChild() ); ept.setWantsMetadataHeuristics(true); ept.setFriendlyName("EPT-QB"); return ept; } if (string.equalsIgnoreCase("Heuristic Sampling")) { return new HeuristicSampling(); } else if (string.equalsIgnoreCase("Heuristic Sampling (1)")) { return new HeuristicSampling(1); } if (string.equalsIgnoreCase("One-Ply (No Heuristic)")) return new OnePlyNoHeuristic(); // try to interpret the given string as a resource or some other // kind of file final URL aiURL = AIFactory.class.getResource(string); File aiFile = null; if (aiURL != null) aiFile = new File(aiURL.getFile()); else aiFile = new File(string); String[] lines = new String[0]; if (aiFile.exists()) { try (final BufferedReader reader = new BufferedReader(new FileReader(aiFile))) { final List<String> linesList = new ArrayList<String>(); String line = reader.readLine(); while (line != null) { linesList.add(line); } lines = linesList.toArray(lines); } catch (final IOException e) { e.printStackTrace(); } } else { // assume semicolon-separated lines directly passed as // command line arg lines = string.split(";"); } final String firstLine = lines[0]; if (firstLine.startsWith("algorithm=")) { final String algName = firstLine.substring("algorithm=".length()); if ( algName.equalsIgnoreCase("MCTS") || algName.equalsIgnoreCase("UCT") ) { // UCT is the default implementation of MCTS, // so both cases are the same return MCTS.fromLines(lines); } else if ( algName.equalsIgnoreCase("AlphaBeta") || algName.equalsIgnoreCase("Alpha-Beta") ) { return AlphaBetaSearch.fromLines(lines); } else if (algName.equalsIgnoreCase("BRS+")) { return BRSPlus.fromLines(lines); } else if (algName.equalsIgnoreCase("HeuristicSampling")) { return HeuristicSampling.fromLines(lines); } else if ( algName.equalsIgnoreCase("Softmax") || algName.equalsIgnoreCase("SoftmaxPolicy") ) { return SoftmaxPolicyLinear.fromLines(lines); } else if ( algName.equalsIgnoreCase("Greedy") || algName.equalsIgnoreCase("GreedyPolicy") ) { return GreedyPolicy.fromLines(lines); } else if (algName.equalsIgnoreCase("ProportionalPolicyClassificationTree")) { return ProportionalPolicyClassificationTree.fromLines(lines); } else if (algName.equalsIgnoreCase("SoftmaxPolicyLogitTree")) { return SoftmaxPolicyLogitTree.fromLines(lines); } else if (algName.equalsIgnoreCase("Random")) { return new RandomAI(); } else { System.err.println("Unknown algorithm name: " + algName); } } else { System.err.println ( "Expecting AI file to start with \"algorithm=\", " + "but it starts with " + firstLine ); } System.err.println ( String.format ( "Warning: cannot convert string \"%s\" to AI; defaulting to random.", string ) ); return null; } //------------------------------------------------------------------------- /** * @param file * @return AI created based on configuration in given JSON file */ public static AI fromJsonFile(final File file) { try (final InputStream inputStream = new FileInputStream(file)) { final JSONObject json = new JSONObject(new JSONTokener(inputStream)); return fromJson(json); } catch (final IOException e) { e.printStackTrace(); } System.err.println("WARNING: Failed to construct AI from JSON file: " + file.getAbsolutePath()); return null; } /** * @param json * @return AI created based on configuration in given JSON object */ public static AI fromJson(final JSONObject json) { if (json.has("constructor")) { final AIConstructor constructor = (AIConstructor) json.get("constructor"); if (constructor != null) return constructor.constructAI(); } final JSONObject aiObj = json.getJSONObject("AI"); final String algName = aiObj.getString("algorithm"); if ( algName.equalsIgnoreCase("Ludii") || algName.equalsIgnoreCase("Ludii AI") || algName.equalsIgnoreCase("Default") ) { return new LudiiAI(); } else if (algName.equalsIgnoreCase("Random")) { return new RandomAI(); } else if (algName.equalsIgnoreCase("Lazy UBFM")) { return new LazyUBFM(); } else if (algName.equalsIgnoreCase("Hybrid UBFM")) { return new HybridUBFM(); } else if (algName.equalsIgnoreCase("Biased UBFM")) { return new BiasedUBFM(); } else if (algName.equalsIgnoreCase("UBFM")) { return UBFM.createUBFM(); } else if (algName.equalsIgnoreCase("Monte Carlo (flat)") || algName.equalsIgnoreCase("Flat MC")) { return new FlatMonteCarlo(); } else if (algName.equalsIgnoreCase("UCT")) { return MCTS.createUCT(); } else if (algName.equalsIgnoreCase("UCT (Uncapped)")) { final MCTS uct = new MCTS ( new UCB1(Math.sqrt(2.0)), new RandomPlayout(), new MonteCarloBackprop(), new RobustChild() ); uct.setFriendlyName("UCT (Uncapped)"); return uct; } else if (algName.equalsIgnoreCase("MCTS")) { return MCTS.fromJson(aiObj); } else if (algName.equalsIgnoreCase("MC-GRAVE")) { final MCTS mcGRAVE = new MCTS(new McGRAVE(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild()); mcGRAVE.setQInit(QInit.INF); mcGRAVE.setFriendlyName("MC-GRAVE"); return mcGRAVE; } else if (algName.equalsIgnoreCase("MC-BRAVE")) { final MCTS mcBRAVE = new MCTS(new McBRAVE(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild()); mcBRAVE.setQInit(QInit.INF); mcBRAVE.setFriendlyName("MC-BRAVE"); return mcBRAVE; } else if (algName.equalsIgnoreCase("UCB1Tuned")) { return createAI("UCB1Tuned"); } else if (algName.equalsIgnoreCase("Score Bounded MCTS") || algName.equalsIgnoreCase("ScoreBoundedMCTS")) { return createAI("Score Bounded MCTS"); } else if (algName.equalsIgnoreCase("Progressive History") || algName.equalsIgnoreCase("ProgressiveHistory")) { final MCTS progressiveHistory = new MCTS ( new ProgressiveHistory(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild() ); progressiveHistory.setQInit(QInit.PARENT); progressiveHistory.setFriendlyName("Progressive History"); return progressiveHistory; } else if (algName.equalsIgnoreCase("Progressive Bias") || algName.equalsIgnoreCase("ProgressiveBias")) { return AIFactory.createAI("Progressive Bias"); } else if (algName.equalsIgnoreCase("MAST")) { final MCTS mast = new MCTS ( new UCB1(), new MAST(200, 0.1), new MonteCarloBackprop(), new RobustChild() ); mast.setQInit(QInit.PARENT); mast.setFriendlyName("MAST"); return mast; } else if (algName.equalsIgnoreCase("NST")) { final MCTS nst = new MCTS ( new UCB1(), new NST(200, 0.1), new MonteCarloBackprop(), new RobustChild() ); nst.setQInit(QInit.PARENT); nst.setFriendlyName("NST"); return nst; } else if (algName.equalsIgnoreCase("UCB1-GRAVE")) { final MCTS ucb1GRAVE = new MCTS(new UCB1GRAVE(), new RandomPlayout(200), new MonteCarloBackprop(), new RobustChild()); ucb1GRAVE.setFriendlyName("UCB1-GRAVE"); return ucb1GRAVE; } else if (algName.equalsIgnoreCase("Biased MCTS")) { return MCTS.createBiasedMCTS(0.0); } else if (algName.equalsIgnoreCase("Biased MCTS (Uniform Playouts)") || algName.equalsIgnoreCase("MCTS (Biased Selection)")) { return MCTS.createBiasedMCTS(1.0); } else if (algName.equalsIgnoreCase("MCTS (Hybrid Selection)")) { return MCTS.createHybridMCTS(); } else if (algName.equalsIgnoreCase("Bandit Tree Search")) { return MCTS.createBanditTreeSearch(); } else if (algName.equalsIgnoreCase("EPT")) { return createAI("EPT"); } else if (algName.equalsIgnoreCase("EPT-QB")) { return createAI("EPT-QB"); } else if (algName.equalsIgnoreCase("Alpha-Beta") || algName.equalsIgnoreCase("AlphaBeta")) { return AlphaBetaSearch.createAlphaBeta(); } else if (algName.equalsIgnoreCase("BRS+") || algName.equalsIgnoreCase("Best-Reply Search+")) { return new BRSPlus(); } else if (algName.equalsIgnoreCase("Heuristic Sampling")) { return new HeuristicSampling(); } else if (algName.equalsIgnoreCase("Heuristic Sampling (1)")) { return new HeuristicSampling(1); } else if (algName.equalsIgnoreCase("One-Ply (No Heuristic)")) { return new OnePlyNoHeuristic(); } else if (algName.equalsIgnoreCase("From JAR")) { final File jarFile = new File(aiObj.getString("JAR File")); final String className = aiObj.getString("Class Name"); try { for (final Class<?> clazz : loadThirdPartyAIClasses(jarFile)) { if (clazz.getName().equals(className)) { return (AI) clazz.getConstructor().newInstance(); } } } catch (final Exception e) { e.printStackTrace(); } } else if (algName.equalsIgnoreCase("From AI.DEF")) { try { final String aiMetadataStr = FileHandling.loadTextContentsFromFile(aiObj.getString("AI.DEF File")); final Ai aiMetadata = (Ai)compiler.Compiler.compileObject ( aiMetadataStr, "metadata.ai.Ai", new Report() ); return fromDefAgent(aiMetadata.agent()); } catch (final IOException e) { e.printStackTrace(); } } System.err.println("WARNING: Failed to construct AI from JSON: " + json.toString(4)); return null; } //------------------------------------------------------------------------- /** * @param game * @return AI constructed from given game's metadata */ public static AI fromMetadata(final Game game) { // Try to find the best agent type String bestAgent; if (!game.isAlternatingMoveGame()) bestAgent = "Flat MC"; else bestAgent = "UCT"; if (game.metadata().ai().agent() != null) { return fromDefAgent(game.metadata().ai().agent()); } final AI ai = createAI(bestAgent); return ai; } //------------------------------------------------------------------------- /** * @param agent * @return AI constructed from agent metadata in some .def file */ public static AI fromDefAgent(final Agent agent) { if (agent instanceof BestAgent) return fromDefBestAgent((BestAgent) agent); else if (agent instanceof AlphaBeta) return fromDefAlphaBetaAgent((AlphaBeta) agent); else if (agent instanceof Mcts) return fromDefMctsAgent((Mcts) agent); System.err.println("AIFactory failed to load from def agent: " + agent); return null; } /** * @param agent * @return AI built from a best-agent string */ public static AI fromDefBestAgent(final BestAgent agent) { return createAI(agent.agent()); } /** * @param agent * @return AlphaBeta AI built from AlphaBeta metadata */ public static AlphaBetaSearch fromDefAlphaBetaAgent(final AlphaBeta agent) { if (agent.heuristics() == null) return new AlphaBetaSearch(); else return new AlphaBetaSearch(agent.heuristics()); } /** * @param agent * @return MCTS AI built from Mcts metadata */ public static MCTS fromDefMctsAgent(final Mcts agent) { System.err.println("Loading MCTS from def not yet implemented!"); return null; } //------------------------------------------------------------------------- /** * @param jarFile * @return List of all AI classes in the given JAR file */ public static List<Class<?>> loadThirdPartyAIClasses(final File jarFile) { List<Class<?>> classes = null; try { if (thirdPartyAIClasses.containsKey(jarFile.getAbsolutePath())) { classes = thirdPartyAIClasses.get(jarFile.getAbsolutePath()); } else { classes = new ArrayList<Class<?>>(); // search the full jar file for all classes that extend our AI abstract class final URL[] urls = { new URL("jar:file:" + jarFile.getAbsolutePath() + "!/") }; try (final URLClassLoader classLoader = URLClassLoader.newInstance(urls)) { try (final JarFile jar = new JarFile(jarFile)) { final Enumeration<? extends JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); try { if (entry.getName().endsWith(".class")) { final String className = entry.getName().replace(".class", "").replace("/", "."); final Class<?> clazz = classLoader.loadClass(className); if (AI.class.isAssignableFrom(clazz)) classes.add(clazz); } } catch (final NoClassDefFoundError exception) { continue; } } } } classes.sort(new Comparator<Class<?>>() { @Override public int compare(final Class<?> o1, final Class<?> o2) { return o1.getName().compareTo(o2.getName()); } }); thirdPartyAIClasses.put(jarFile.getAbsolutePath(), classes); } } catch (final Exception e) { e.printStackTrace(); } return classes; } //------------------------------------------------------------------------- /** * Interface for a functor that constructs AIs * * @author Dennis Soemers */ public static interface AIConstructor { /** * @return Constructed AI object */ public AI constructAI(); } //------------------------------------------------------------------------- }
21,436
23.668585
125
java
Ludii
Ludii-master/AI/src/utils/AIUtils.java
package utils; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import features.feature_sets.BaseFeatureSet; import function_approx.LinearFunction; import game.Game; import game.types.play.RoleType; import main.collections.FastArrayList; import main.collections.StringPair; import metadata.ai.features.Features; import metadata.ai.heuristics.Heuristics; import metadata.ai.heuristics.terms.CentreProximity; import metadata.ai.heuristics.terms.ComponentValues; import metadata.ai.heuristics.terms.CornerProximity; import metadata.ai.heuristics.terms.Influence; import metadata.ai.heuristics.terms.InfluenceAdvanced; import metadata.ai.heuristics.terms.LineCompletionHeuristic; import metadata.ai.heuristics.terms.Material; import metadata.ai.heuristics.terms.MobilityAdvanced; import metadata.ai.heuristics.terms.MobilitySimple; import metadata.ai.heuristics.terms.NullHeuristic; import metadata.ai.heuristics.terms.OwnRegionsCount; import metadata.ai.heuristics.terms.PlayerRegionsProximity; import metadata.ai.heuristics.terms.PlayerSiteMapCount; import metadata.ai.heuristics.terms.RegionProximity; import metadata.ai.heuristics.terms.Score; import metadata.ai.heuristics.terms.SidesProximity; import metadata.ai.heuristics.terms.UnthreatenedMaterial; import metadata.ai.misc.Pair; import other.AI; import other.RankUtils; import other.context.Context; import other.move.Move; import policies.softmax.SoftmaxPolicyLinear; import search.minimax.AlphaBetaSearch; /** * Some general utility methods for AI * * @author Dennis Soemers */ public class AIUtils { //------------------------------------------------------------------------- /** * We don't let value function estimates (e.g., from heuristics) exceed this absolute value. * This is to ensure that true wins/losses will still be valued more strongly. */ private static final double MAX_ABS_VALUE_FUNCTION_ESTIMATE = 0.95; //------------------------------------------------------------------------- /** * Constructor */ private AIUtils() { // do not instantiate } //------------------------------------------------------------------------- /** * @param game * @return Constructs and returns a default AI for the given game. */ public static AI defaultAiForGame(final Game game) { return new LudiiAI(); } /** * @param allMoves List of legal moves for all current players * @param mover Mover for which we want the list of legal moves * @return A list of legal moves for the given mover, extracted from a given * list of legal moves for any mover. */ public static FastArrayList<Move> extractMovesForMover(final FastArrayList<Move> allMoves, final int mover) { final FastArrayList<Move> moves = new FastArrayList<Move>(allMoves.size()); for (final Move move : allMoves) { if (move.mover() == mover) moves.add(move); } return moves; } //------------------------------------------------------------------------- /** * @param context * @param heuristics * @return An array of value estimates for all players (accounting for swaps), based on a heuristic * function (+ normalisation to map to value function) */ public static double[] heuristicValueEstimates(final Context context, final Heuristics heuristics) { final double[] valueEstimates = RankUtils.agentUtilities(context); if (context.active()) { final double[] heuristicScores = new double[valueEstimates.length]; final int numPlayers = valueEstimates.length - 1; for (int p = 1; p < heuristicScores.length; ++p) { final float score = heuristics.computeValue(context, p, AlphaBetaSearch.ABS_HEURISTIC_WEIGHT_THRESHOLD); heuristicScores[p] += score; for (int other = 1; other < heuristicScores.length; ++other) { if (other != p) heuristicScores[other] -= score; } } // Lower and upper bounds on util that may still be achieved final double utilLowerBound = RankUtils.rankToUtil(context.computeNextLossRank(), numPlayers); final double utilUpperBound = RankUtils.rankToUtil(context.computeNextWinRank(), numPlayers); final double deltaUtilBounds = utilUpperBound - utilLowerBound; for (int p = 1; p < valueEstimates.length; ++p) { if (context.active(context.state().currentPlayerOrder(p))) { // Need to set value estimate for this player, since rank not already determined double valueEstimate = (Math.tanh(heuristicScores[context.state().currentPlayerOrder(p)])); // Map to range given by lower and upper bounds valueEstimate = (((valueEstimate + 1.0) / 2.0) * deltaUtilBounds) + utilLowerBound; valueEstimates[p] = valueEstimate * MAX_ABS_VALUE_FUNCTION_ESTIMATE; } } } return valueEstimates; } /** * @param context * @param heuristics * @return An array of value bonus estimates for all players (accounting for swaps), based on a heuristic * function (+ normalisation to map to value function). This will compute and return heuristics\ * even for players that already have their final ranking determined. */ public static double[] heuristicValueBonusEstimates(final Context context, final Heuristics heuristics) { final double[] heuristicScores = new double[context.game().players().count() + 1]; for (int p = 1; p < heuristicScores.length; ++p) { final float score = heuristics.computeValue(context, p, AlphaBetaSearch.ABS_HEURISTIC_WEIGHT_THRESHOLD); heuristicScores[p] += score; for (int other = 1; other < heuristicScores.length; ++other) { if (other != p) heuristicScores[other] -= score; } } for (int p = 1; p < heuristicScores.length; ++p) { heuristicScores[p] = Math.tanh(heuristicScores[context.state().currentPlayerOrder(p)]); } return heuristicScores; } //------------------------------------------------------------------------- /** * @param pair * @return True if the given pair of Strings is recognised as AI-related metadata */ public static boolean isAIMetadata(final StringPair pair) { final String key = pair.key(); return ( // Some basic keywords key.startsWith("BestAgent") || key.startsWith("AIMetadataGameNameCheck") || // Features isFeaturesMetadata(pair) || // Heuristics isHeuristicsMetadata(pair) ); } /** * @param pair * @return True if the given pair of Strings is recognised as features-related metadata */ public static boolean isFeaturesMetadata(final StringPair pair) { final String key = pair.key(); return key.startsWith("Features"); } /** * @param pair * @return True if the given pair of Strings is recognised as heuristics-related metadata */ public static boolean isHeuristicsMetadata(final StringPair pair) { final String key = pair.key(); return ( // Heuristic transformations key.startsWith("DivNumBoardCells") || key.startsWith("DivNumInitPlacement") || key.startsWith("Logistic") || key.startsWith("Tanh") || // Heuristic terms key.startsWith("CentreProximity") || key.startsWith("ComponentValues") || key.startsWith("CornerProximity") || key.startsWith("CurrentMoverHeuristic") || key.startsWith("Influence") || key.startsWith("InfluenceAdvanced") || key.startsWith("Intercept") || key.startsWith("LineCompletionHeuristic") || key.startsWith("Material") || key.startsWith("MobilityAdvanced") || key.startsWith("MobilitySimple") || key.startsWith("NullHeuristic") || key.startsWith("OpponentPieceProximity") || key.startsWith("OwnRegionsCount") || key.startsWith("PlayerRegionsProximity") || key.startsWith("PlayerSiteMapCount") || key.startsWith("RegionProximity") || key.startsWith("Score") || key.startsWith("SidesProximity") || key.startsWith("UnthreatenedMaterial") ); } //------------------------------------------------------------------------- // /** // * @param game // * @param gameOptions // * @return All AI metadata relevant for given game with given options // */ // public static List<StringPair> extractAIMetadata(final Game game, final List<String> gameOptions) // { // final List<StringPair> metadata = game.metadata(); // final List<StringPair> relevantAIMetadata = new ArrayList<StringPair>(); // // for (final StringPair pair : metadata) // { // if (AIUtils.isAIMetadata(pair)) // { // final String key = pair.key(); // final String[] keySplit = key.split(Pattern.quote(":")); // // boolean allOptionsMatch = true; // if (keySplit.length > 1) // { // final String[] metadataOptions = keySplit[1].split(Pattern.quote(";")); // // for (int i = 0; i < metadataOptions.length; ++i) // { // if (!gameOptions.contains(metadataOptions[i])) // { // allOptionsMatch = false; // break; // } // } // } // // if (allOptionsMatch) // { // relevantAIMetadata.add(pair); // } // } // } // // return relevantAIMetadata; // } /** * @param game * @param gameOptions * @param metadata * @return All features metadata relevant for given game with given options */ public static List<StringPair> extractFeaturesMetadata ( final Game game, final List<String> gameOptions, final List<StringPair> metadata ) { final List<StringPair> relevantFeaturesMetadata = new ArrayList<StringPair>(); for (final StringPair pair : metadata) { if (AIUtils.isFeaturesMetadata(pair)) { final String key = pair.key(); final String[] keySplit = key.split(Pattern.quote(":")); boolean allOptionsMatch = true; if (keySplit.length > 1) { final String[] metadataOptions = keySplit[1].split(Pattern.quote(";")); for (int i = 0; i < metadataOptions.length; ++i) { if (!gameOptions.contains(metadataOptions[i])) { allOptionsMatch = false; break; } } } if (allOptionsMatch) { relevantFeaturesMetadata.add(pair); } } } return relevantFeaturesMetadata; } /** * @param game * @param gameOptions * @param metadata * @return All heuristics metadata relevant for given game with given options */ public static List<StringPair> extractHeuristicsMetadata ( final Game game, final List<String> gameOptions, final List<StringPair> metadata ) { final List<StringPair> relevantHeuristicsMetadata = new ArrayList<StringPair>(); for (final StringPair pair : metadata) { if (AIUtils.isHeuristicsMetadata(pair)) { final String key = pair.key(); final String[] keySplit = key.split(Pattern.quote(":")); boolean allOptionsMatch = true; if (keySplit.length > 1) { final String[] metadataOptions = keySplit[1].split(Pattern.quote(";")); for (int i = 0; i < metadataOptions.length; ++i) { if (!gameOptions.contains(metadataOptions[i])) { allOptionsMatch = false; break; } } } if (allOptionsMatch) { relevantHeuristicsMetadata.add(pair); } } } return relevantHeuristicsMetadata; } //------------------------------------------------------------------------- public static Heuristics convertStringtoHeuristic(String s) { switch(s) { case "MaterialPos" : return new Heuristics(new Material(null, Float.valueOf(1.f), null, null)); case "UnthreatenedMaterialPos" : return new Heuristics(new UnthreatenedMaterial(null, Float.valueOf(1.f), null)); case "InfluencePos" : return new Heuristics(new Influence(null, Float.valueOf(1.f))); case "InfluenceAdvancedPos" : return new Heuristics(new InfluenceAdvanced(null, Float.valueOf(1.f))); case "SidesProximityPos" : return new Heuristics(new SidesProximity(null, Float.valueOf(1.f), null)); case "LineCompletionHeuristicPos" : return new Heuristics(new LineCompletionHeuristic(null, Float.valueOf(1.f), null)); case "CornerProximityPos" : return new Heuristics(new CornerProximity(null, Float.valueOf(1.f), null)); case "MobilitySimplePos" : return new Heuristics(new MobilitySimple(null, Float.valueOf(1.f))); case "MobilityAdvancedPos" : return new Heuristics(new MobilityAdvanced(null, Float.valueOf(1.f))); case "CentreProximityPos" : return new Heuristics(new CentreProximity(null, Float.valueOf(1.f), null)); case "RegionProximityPos" : return new Heuristics(new RegionProximity(null, Float.valueOf(1.f), null, null)); case "ScorePos" : return new Heuristics(new Score(null, Float.valueOf(1.f))); case "PlayerRegionsProximityPos" : return new Heuristics(new PlayerRegionsProximity(null, Float.valueOf(1.f), null, null)); case "PlayerSiteMapCountPos" : return new Heuristics(new PlayerSiteMapCount(null, Float.valueOf(1.f))); case "OwnRegionsCountPos" : return new Heuristics(new OwnRegionsCount(null, Float.valueOf(1.f))); case "ComponentValuesPos" : return new Heuristics(new ComponentValues(null, Float.valueOf(1.f), null, null)); case "MaterialNeg" : return new Heuristics(new Material(null, Float.valueOf(-1.f), null, null)); case "UnthreatenedMaterialNeg" : return new Heuristics(new UnthreatenedMaterial(null, Float.valueOf(-1.f), null)); case "InfluenceNeg" : return new Heuristics(new Influence(null, Float.valueOf(-1.f))); case "InfluenceAdvancedNeg" : return new Heuristics(new InfluenceAdvanced(null, Float.valueOf(-1.f))); case "SidesProximityNeg" : return new Heuristics(new SidesProximity(null, Float.valueOf(-1.f), null)); case "LineCompletionHeuristicNeg" : return new Heuristics(new LineCompletionHeuristic(null, Float.valueOf(-1.f), null)); case "CornerProximityNeg" : return new Heuristics(new CornerProximity(null, Float.valueOf(-1.f), null)); case "MobilitySimpleNeg" : return new Heuristics(new MobilitySimple(null, Float.valueOf(-1.f))); case "MobilityAdvancedNeg" : return new Heuristics(new MobilityAdvanced(null, Float.valueOf(-1.f))); case "CentreProximityNeg" : return new Heuristics(new CentreProximity(null, Float.valueOf(-1.f), null)); case "RegionProximityNeg" : return new Heuristics(new RegionProximity(null, Float.valueOf(-1.f), null, null)); case "ScoreNeg" : return new Heuristics(new Score(null, Float.valueOf(-1.f))); case "PlayerRegionsProximityNeg" : return new Heuristics(new PlayerRegionsProximity(null, Float.valueOf(-1.f), null, null)); case "PlayerSiteMapCountNeg" : return new Heuristics(new PlayerSiteMapCount(null, Float.valueOf(-1.f))); case "OwnRegionsCountNeg" : return new Heuristics(new OwnRegionsCount(null, Float.valueOf(-1.f))); case "ComponentValuesNeg" : return new Heuristics(new ComponentValues(null, Float.valueOf(-1.f), null, null)); case "NullHeuristicPos" : return new Heuristics(new Material(null, Float.valueOf(1.f), null, null)); default : return new Heuristics(new NullHeuristic()); } } public static String[] allHeuristicNames() { return new String[] {"MaterialPos", "InfluencePos", "SidesProximityPos","LineCompletionHeuristicNeg", "NullHeuristicPos", "LineCompletionHeuristicPos", "CornerProximityNeg", "MobilitySimpleNeg", "CentreProximityNeg", "InfluenceNeg", "MaterialNeg", "CornerProximityPos", "MobilitySimplePos", "CentreProximityPos", "SidesProximityNeg", "RegionProximityNeg", "RegionProximityPos", "ScorePos", "ScoreNeg", "PlayerRegionsProximityNeg", "PlayerRegionsProximityPos", "PlayerSiteMapCountPos", "PlayerSiteMapCountNeg", "OwnRegionsCountPos", "OwnRegionsCountNeg", "ComponentValuesPos", "ComponentValuesNeg", "UnthreatenedMaterialPos", "UnthreatenedMaterialNeg", "MobilityAdvancedPos", "MobilityAdvancedNeg", "InfluenceAdvancedPos", "InfluenceAdvancedNeg"}; } //------------------------------------------------------------------------- /** * Generates features metadata from given Selection and Playout policies * @param selectionPolicy * @param playoutPolicy */ public static metadata.ai.features.Features generateFeaturesMetadata ( final SoftmaxPolicyLinear selectionPolicy, final SoftmaxPolicyLinear playoutPolicy ) { final Features features; Pair[][] selectionPairs = null; Pair[][] playoutPairs = null; Pair[][] tspgPairs = null; int numRoles = 0; if (selectionPolicy != null) { final BaseFeatureSet[] featureSets = selectionPolicy.featureSets(); final LinearFunction[] linearFunctions = selectionPolicy.linearFunctions(); selectionPairs = new Pair[featureSets.length][]; playoutPairs = new Pair[featureSets.length][]; tspgPairs = new Pair[featureSets.length][]; if (featureSets.length == 1) { // Just a single featureset for all players assert (numRoles == 1 || numRoles == 0); numRoles = 1; final BaseFeatureSet featureSet = featureSets[0]; final LinearFunction linFunc = linearFunctions[0]; final Pair[] pairs = new Pair[featureSet.spatialFeatures().length]; for (int i = 0; i < pairs.length; ++i) { final float weight = linFunc.effectiveParams().allWeights().get(i); pairs[i] = new Pair(featureSet.spatialFeatures()[i].toString(), Float.valueOf(weight)); if (Float.isNaN(weight)) System.err.println("WARNING: writing NaN weight"); else if (Float.isInfinite(weight)) System.err.println("WARNING: writing infinity weight"); } selectionPairs[0] = pairs; } else { // One featureset per player assert (numRoles == featureSets.length || numRoles == 0); numRoles = featureSets.length; for (int p = 0; p < featureSets.length; ++p) { final BaseFeatureSet featureSet = featureSets[p]; if (featureSet == null) continue; final LinearFunction linFunc = linearFunctions[p]; final Pair[] pairs = new Pair[featureSet.spatialFeatures().length]; for (int i = 0; i < pairs.length; ++i) { final float weight = linFunc.effectiveParams().allWeights().get(i); pairs[i] = new Pair(featureSet.spatialFeatures()[i].toString(), Float.valueOf(weight)); if (Float.isNaN(weight)) System.err.println("WARNING: writing NaN weight"); else if (Float.isInfinite(weight)) System.err.println("WARNING: writing infinity weight"); } selectionPairs[p] = pairs; } } } if (playoutPolicy != null) { final BaseFeatureSet[] featureSets = playoutPolicy.featureSets(); final LinearFunction[] linearFunctions = playoutPolicy.linearFunctions(); if (playoutPairs == null) { selectionPairs = new Pair[featureSets.length][]; playoutPairs = new Pair[featureSets.length][]; tspgPairs = new Pair[featureSets.length][]; } if (featureSets.length == 1) { // Just a single featureset for all players assert (numRoles == 1 || numRoles == 0); numRoles = 1; final BaseFeatureSet featureSet = featureSets[0]; final LinearFunction linFunc = linearFunctions[0]; final Pair[] pairs = new Pair[featureSet.spatialFeatures().length]; for (int i = 0; i < pairs.length; ++i) { final float weight = linFunc.effectiveParams().allWeights().get(i); pairs[i] = new Pair(featureSet.spatialFeatures()[i].toString(), Float.valueOf(weight)); if (Float.isNaN(weight)) System.err.println("WARNING: writing NaN weight"); else if (Float.isInfinite(weight)) System.err.println("WARNING: writing infinity weight"); } playoutPairs[0] = pairs; } else { // One featureset per player assert (numRoles == featureSets.length || numRoles == 0); numRoles = featureSets.length; for (int p = 0; p < featureSets.length; ++p) { final BaseFeatureSet featureSet = featureSets[p]; if (featureSet == null) continue; final LinearFunction linFunc = linearFunctions[p]; final Pair[] pairs = new Pair[featureSet.spatialFeatures().length]; for (int i = 0; i < pairs.length; ++i) { final float weight = linFunc.effectiveParams().allWeights().get(i); pairs[i] = new Pair(featureSet.spatialFeatures()[i].toString(), Float.valueOf(weight)); if (Float.isNaN(weight)) System.err.println("WARNING: writing NaN weight"); else if (Float.isInfinite(weight)) System.err.println("WARNING: writing infinity weight"); } playoutPairs[p] = pairs; } } } if (selectionPairs == null || playoutPairs == null || tspgPairs == null) return null; if (numRoles == 1) { features = new Features(new metadata.ai.features.FeatureSet(RoleType.Shared, selectionPairs[0], playoutPairs[0], tspgPairs[0])); } else { // One featureset per player final metadata.ai.features.FeatureSet[] metadataFeatureSets = new metadata.ai.features.FeatureSet[numRoles - 1]; for (int p = 1; p < numRoles; ++p) { if (selectionPairs[p] == null && playoutPairs[p] == null && tspgPairs[p] == null) continue; metadataFeatureSets[p - 1] = new metadata.ai.features.FeatureSet(RoleType.roleForPlayerId(p), selectionPairs[p], playoutPairs[p], tspgPairs[p]); } features = new Features(metadataFeatureSets); } return features; } //------------------------------------------------------------------------- /** * @param heuristicName * @return Shortened version of given heuristic name */ public static String shortenHeuristicName(final String heuristicName) { return heuristicName .replaceAll(Pattern.quote("CentreProximity"), "CeProx") .replaceAll(Pattern.quote("ComponentValues"), "CompVal") .replaceAll(Pattern.quote("CornerProximity"), "CoProx") .replaceAll(Pattern.quote("CurrentMoverHeuristic"), "CurrMov") .replaceAll(Pattern.quote("InfluenceAdvanced"), "InfAdv") .replaceAll(Pattern.quote("Influence"), "Inf") .replaceAll(Pattern.quote("Intercept"), "Inter") .replaceAll(Pattern.quote("LineCompletionHeuristic"), "LineComp") .replaceAll(Pattern.quote("MobilityAdvanced"), "MobAdv") .replaceAll(Pattern.quote("MobilitySimple"), "MobS") .replaceAll(Pattern.quote("NullHeuristic"), "Null") .replaceAll(Pattern.quote("OwnRegionsCount"), "OwnRegC") .replaceAll(Pattern.quote("PlayerRegionsProximity"), "PRegProx") .replaceAll(Pattern.quote("PlayerSiteMapCount"), "PSMapC") .replaceAll(Pattern.quote("RegionProximity"), "ReProx") .replaceAll(Pattern.quote("SidesProximity"), "SiProx") .replaceAll(Pattern.quote("UnthreatenedMaterial"), "UntMat") .replaceAll(Pattern.quote("Material"), "Mat"); } //------------------------------------------------------------------------- }
22,635
33.878274
133
java
Ludii
Ludii-master/AI/src/utils/DoNothingAI.java
package utils; import game.Game; import other.AI; import other.context.Context; import other.move.Move; /** * AI player doing nothing. * * @author Eric.Piette */ public class DoNothingAI extends AI { //------------------------------------------------------------------------- /** Our player index */ protected int player = -1; /** The last move we returned */ protected Move lastReturnedMove = null; //------------------------------------------------------------------------- /** * Constructor */ public DoNothingAI() { friendlyName = "Do Nothing"; } //------------------------------------------------------------------------- @Override public Move selectAction ( final Game game, final Context context, final double maxSeconds, final int maxIterations, final int maxDepth ) { return null; } /** * @return The last move we returned */ public Move lastReturnedMove() { return lastReturnedMove; } @Override public void initAI(final Game game, final int playerID) { this.player = playerID; lastReturnedMove = null; } //------------------------------------------------------------------------- }
1,172
16.507463
76
java
Ludii
Ludii-master/AI/src/utils/ExperimentFileUtils.java
package utils; import java.io.File; import java.util.regex.Pattern; /** * Some utilities related to files in experiments * * @author Dennis Soemers */ public class ExperimentFileUtils { //------------------------------------------------------------------------- /** Format used for filepaths in sequences of files (with increasing indices) */ private static final String fileSequenceFormat = "%s_%05d.%s"; //------------------------------------------------------------------------- private ExperimentFileUtils() { // should not instantiate } //------------------------------------------------------------------------- /** * Returns the filepath of the form {baseFilepath}_{index}.{extension} with * the minimum integer value >= 0 for {index} such that a File with that filepath * does not yet exist. * * For example, suppose baseFilepath = "/Directory/File", and extension = "csv". * Then, this method will return: * - "/Directory/File_0.csv" if that File does not yet exist, or * - "/Directory/File_1.csv" if that is the first File that does not yet exist, or * - "/Directory/File_2.csv" if that is the first File that does not yet exist, etc. * * It is assumed that leading zeros have been added to {index} to make sure that it has at least * 5 digits (not included in example above) * * This method can be used to easily figure out the filepath for the next File to write * to in a sequence of related files (for example, different checkpoints of a learned vector of weights). * * @param baseFilepath * @param extension * @return Next file path. */ public static String getNextFilepath(final String baseFilepath, final String extension) { int index = 0; String result = String.format(fileSequenceFormat, baseFilepath, Integer.valueOf(index), extension); while (new File(result).exists()) { ++index; result = String.format(fileSequenceFormat, baseFilepath, Integer.valueOf(index), extension); } return result; } /** * Returns the filepath of the form {baseFilepath}_{index}.{extension} with * the maximum integer value >= 0 for {index} such that a File with that filepath * exists, or null if no such File exists. Starts checking for index = 0, * then for index = 1 if 0 already exists, then index = 2, etc. This means * that the method may return incorrect results if files were created with an * index sequence different from 0, 1, 2, ... * * For example, suppose baseFilepath = "/Directory/File", and extension = "csv". * Then, this method will return: * - "/Directory/File_0.csv" if 0 is the greatest index such that such a File exists, or * - "/Directory/File_1.csv" if 1 is the greatest index such that such a File exists, or * - "/Directory/File_2.csv" if that file also exists, etc. * * Leading zeros will be added to {index} to make sure that it has at least * 5 digits (not included in example above) * * This method can be used to easily get the latest file in a sequence of related files * (for example, different checkpoints of a learned vector of weights), or null if * we do not yet have any such files. * * @param baseFilepath * @param extension * @return Last file path. */ public static String getLastFilepath(final String baseFilepath, final String extension) { int index = 0; String result = null; final File checkpoint0 = new File(String.format(fileSequenceFormat, baseFilepath, Integer.valueOf(index), extension)); if (checkpoint0.getParentFile().exists()) { final File dir = checkpoint0.getParentFile(); final File[] files = dir.listFiles(); for (final File file : files) { final String filepath = file.getAbsolutePath().replaceAll(Pattern.quote("\\"), "/"); if (filepath.endsWith("." + extension) && filepath.contains(baseFilepath.replaceAll(Pattern.quote("\\"), "/"))) { try { final int idx = Integer.parseInt ( filepath .substring(filepath.lastIndexOf("_") + 1) .replaceAll(Pattern.quote("." + extension), "") ); if (idx > index) { index = idx; result = String.format(fileSequenceFormat, baseFilepath, Integer.valueOf(index), extension); } } catch (final Exception e) { // Do nothing //e.printStackTrace(); } } } } return result; } //------------------------------------------------------------------------- }
4,498
32.325926
120
java
Ludii
Ludii-master/AI/src/utils/ExponentialMovingAverage.java
package utils; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; /** * Utility class to incrementally keep track of exponential * moving averages. * * @author Dennis Soemers */ public class ExponentialMovingAverage implements Serializable { //------------------------------------------------------------------------- /** */ private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Weight assigned to most recent point of data. 0 = all data points weighed equally */ protected final double alpha; /** Our running mean */ protected double runningMean = 0.0; /** Our denominator in running mean */ protected double denominator = 0.0; //------------------------------------------------------------------------- /** * Constructor (default alpha of 0.05) */ public ExponentialMovingAverage() { this(0.05); } /** * Constructor * @param alpha */ public ExponentialMovingAverage(final double alpha) { this.alpha = alpha; } //------------------------------------------------------------------------- /** * @return Our (exponential) moving average */ public double movingAvg() { return runningMean; } /** * Observe a new data point * @param data */ public void observe(final double data) { denominator = (1 - alpha) * denominator + 1; runningMean += (1.0 / denominator) * (data - runningMean); } //------------------------------------------------------------------------- /** * Writes this tracker to a binary file * @param filepath */ public void writeToFile(final String filepath) { try ( final ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filepath))) ) { out.writeObject(this); out.flush(); out.close(); } catch (final IOException e) { e.printStackTrace(); } } //------------------------------------------------------------------------- }
2,111
20.12
89
java
Ludii
Ludii-master/AI/src/utils/LudiiAI.java
package utils; import game.Game; import other.AI; import other.context.Context; import other.move.Move; /** * Default Ludii AI. This is an agent that attempts to automatically * switch to different algorithms based on the metadata in a game's * .lud file. * * If no best AI can be discovered from the metadata, this will default to: * - Flat Monte-Carlo for simultaneous-move games * - UCT for everything else * * @author Dennis Soemers */ public final class LudiiAI extends AI { //------------------------------------------------------------------------- /** The current agent we use for the current game */ private AI currentAgent = null; //------------------------------------------------------------------------- /** * Constructor */ public LudiiAI() { this.friendlyName = "Ludii"; } //------------------------------------------------------------------------- @Override public Move selectAction ( final Game game, final Context context, final double maxSeconds, final int maxIterations, final int maxDepth ) { return currentAgent.selectAction(game, context, maxSeconds, maxIterations, maxDepth); } //------------------------------------------------------------------------- @Override public void initAI(final Game game, final int playerID) { if (currentAgent != null) currentAgent.closeAI(); currentAgent = AIFactory.fromMetadata(game); if (currentAgent == null) { if (!game.isAlternatingMoveGame()) currentAgent = AIFactory.createAI("Flat MC"); else currentAgent = AIFactory.createAI("UCT"); } if (!currentAgent.supportsGame(game)) { System.err.println ( "Warning! Default AI (" + currentAgent + ")" + " does not support game (" + game.name() + ")" ); currentAgent = AIFactory.createAI("UCT"); } assert(currentAgent.supportsGame(game)); this.friendlyName = "Ludii (" + currentAgent.friendlyName() + ")"; currentAgent.initAI(game, playerID); } @Override public boolean supportsGame(final Game game) { return true; } @Override public double estimateValue() { if (currentAgent != null) return currentAgent.estimateValue(); else return 0.0; } @Override public String generateAnalysisReport() { if (currentAgent != null) return currentAgent.generateAnalysisReport(); else return null; } @Override public AIVisualisationData aiVisualisationData() { if (currentAgent != null) return currentAgent.aiVisualisationData(); else return null; } @Override public void setWantsInterrupt(final boolean val) { super.setWantsInterrupt(val); if (currentAgent != null) currentAgent.setWantsInterrupt(val); } @Override public boolean usesFeatures(final Game game) { return AIFactory.fromMetadata(game).usesFeatures(game); } //------------------------------------------------------------------------- }
2,920
20.321168
87
java
Ludii
Ludii-master/AI/src/utils/LudiiGameWrapper.java
package utils; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import game.Game; import game.equipment.component.Component; import game.equipment.container.Container; import game.types.state.GameType; import main.Constants; import main.FileHandling; import main.math.MathRoutines; import other.GameLoader; import other.action.Action; import other.action.others.ActionPropose; import other.action.others.ActionVote; import other.move.Move; import other.topology.TopologyElement; import utils.data_structures.ludeme_trees.LudemeTreeUtils; import utils.data_structures.support.zhang_shasha.Tree; /** * Wrapper around a Ludii game, with various extra methods required for * other frameworks that like to wrap around Ludii (e.g. OpenSpiel, Polygames) * * @author Dennis Soemers */ public final class LudiiGameWrapper { //------------------------------------------------------------------------- /** * Wrapper class for keys used to index into map of already-compiled * game wrappers. * * @author Dennis Soemers */ private static class GameWrapperCacheKey { private final String gameName; private final List<String> options; /** * Constructor * @param gameName * @param options */ public GameWrapperCacheKey(final String gameName, final List<String> options) { this.gameName = gameName; this.options = options; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((gameName == null) ? 0 : gameName.hashCode()); result = prime * result + ((options == null) ? 0 : options.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof GameWrapperCacheKey)) return false; final GameWrapperCacheKey other = (GameWrapperCacheKey) obj; return (gameName.equals(other.gameName) && options.equals(other.options)); } } /** Cache of already-instantiated LudiiGameWrapper objects */ private static Map<GameWrapperCacheKey, LudiiGameWrapper> gameWrappersCache = new HashMap<GameWrapperCacheKey, LudiiGameWrapper>(); //------------------------------------------------------------------------- /** x- and/or y-coordinates that differ by at most this amount are considered equal */ protected static final double EPSILON = 0.00001; /** Number of channels we use for stacks (just 1 for not-stacking-games) */ protected static final int NUM_STACK_CHANNELS = 10; /** Number of channels for local state per site (in games that have local state per site) */ protected static final int NUM_LOCAL_STATE_CHANNELS = 6; /** Maximum distance we consider between from and to x/y coords for move channels */ protected static final int DEFAULT_MOVE_TENSOR_DIST_CLIP = 3; /** Clipping variable for levelMin / levelMax terms in move channel index computation */ protected static final int MOVE_TENSOR_LEVEL_CLIP = 2; //------------------------------------------------------------------------- /** Our game object */ protected final Game game; /** X-coordinates in state tensors for all sites in game */ protected int[] xCoords; /** Y-coordinates in state tensors for all sites in game */ protected int[] yCoords; /** X-dimension for state tensors */ protected int tensorDimX; /** Y-dimension for state tensors */ protected int tensorDimY; /** Number of channels we need for state tensors */ protected int stateTensorNumChannels; /** Array of names for the channels in state tensors */ protected String[] stateTensorChannelNames; /** Maximum absolute distance we consider between from and to positions for move tensors */ protected final int moveTensorDistClip; /** Channel index for the first proposition channel in move-tensor-representation */ protected int FIRST_PROPOSITION_CHANNEL_IDX; /** Channel index for the first vote channel in move-tensor-representation */ protected int FIRST_VOTE_CHANNEL_IDX; /** Channel index for Pass move in move-tensor-representation */ protected int MOVE_PASS_CHANNEL_IDX; /** Channel index for Swap move in move-tensor-representation */ protected int MOVE_SWAP_CHANNEL_IDX; /** A flat version of a complete channel of only 1s */ protected float[] ALL_ONES_CHANNEL_FLAT; /** * A flat version of multiple concatenated channels (one per container), * indicating whether or not positions exist in containers */ protected float[] CONTAINER_POSITION_CHANNELS; //------------------------------------------------------------------------- /** * @param gameName * @return Returns LudiiGameWrapper for game name (default options) */ public synchronized static LudiiGameWrapper construct(final String gameName) { final GameWrapperCacheKey key = new GameWrapperCacheKey(gameName, new ArrayList<String>()); LudiiGameWrapper wrapper = gameWrappersCache.get(key); if (wrapper == null) { wrapper = new LudiiGameWrapper(GameLoader.loadGameFromName(gameName)); gameWrappersCache.put(key, wrapper); } return wrapper; } /** * @param gameName * @param gameOptions * @return Returns LudiiGameWrapper for give game name and options */ public static LudiiGameWrapper construct(final String gameName, final String... gameOptions) { final GameWrapperCacheKey key = new GameWrapperCacheKey(gameName, Arrays.asList(gameOptions)); LudiiGameWrapper wrapper = gameWrappersCache.get(key); if (wrapper == null) { wrapper = new LudiiGameWrapper(GameLoader.loadGameFromName(gameName, Arrays.asList(gameOptions))); gameWrappersCache.put(key, wrapper); } return wrapper; } /** * @param file * @return Returns LudiiGameWrapper for .lud file */ public static LudiiGameWrapper construct(final File file) { final Game game = GameLoader.loadGameFromFile(file); return new LudiiGameWrapper(game); } /** * @param file * @param gameOptions * @return Returns LudiiGameWrapper for .lud file with game options */ public static LudiiGameWrapper construct(final File file, final String... gameOptions) { final Game game = GameLoader.loadGameFromFile(file, Arrays.asList(gameOptions)); return new LudiiGameWrapper(game); } /** * Constructor for already-instantiated game. * @param game */ public LudiiGameWrapper(final Game game) { this.game = game; if ((game.gameFlags() & GameType.UsesFromPositions) == 0L) moveTensorDistClip = 0; // No from-positions in any moves in this game else moveTensorDistClip = DEFAULT_MOVE_TENSOR_DIST_CLIP; computeTensorCoords(); } //------------------------------------------------------------------------- /** * @return The version of Ludii that we're using (a String in * "x.y.z" format). */ public static String ludiiVersion() { return Constants.LUDEME_VERSION; } /** * @return True if and only if the game is a simultaneous-move game */ public boolean isSimultaneousMoveGame() { return !game.isAlternatingMoveGame(); } /** * @return True if and only if the game is a stochastic game */ public boolean isStochasticGame() { return game.isStochasticGame(); } /** * @return True if and only if the game is an imperfect-information game */ public boolean isImperfectInformationGame() { return game.hiddenInformation(); } /** * @return Game's name */ public String name() { return game.name(); } /** * @return Number of players */ public int numPlayers() { return game.players().count(); } /** * @return X coordinates in state tensors for all sites */ public int[] tensorCoordsX() { return xCoords; } /** * @return Y coordinates in state tensors for all sites */ public int[] tensorCoordsY() { return yCoords; } /** * @return Size of x-dimension for state tensors */ public int tensorDimX() { return tensorDimX; } /** * @return Size of y-dimension for state tensors */ public int tensorDimY() { return tensorDimY; } /** * @return Shape of tensors for moves: [numChannels, size(x dimension), size(y dimension)] */ public int[] moveTensorsShape() { return new int[] {MOVE_SWAP_CHANNEL_IDX + 1, tensorDimX(), tensorDimY()}; } /** * @return Shape of tensors for states: [numChannels, size(x dimension), size(y dimension)] */ public int[] stateTensorsShape() { return new int[] {stateTensorNumChannels, tensorDimX(), tensorDimY()}; } /** * @return Array of names for all the channels in our state tensors */ public String[] stateTensorChannelNames() { return stateTensorChannelNames; } /** * @param move * @return A tensor representation of given move (shape = [3]) */ public int[] moveToTensor(final Move move) { if (move.isPropose()) { int offset = 0; for (final Action a : move.actions()) { if (a instanceof ActionPropose && a.isDecision()) { final ActionPropose action = (ActionPropose) a; offset = action.propositionInt(); break; } } return new int[] {FIRST_PROPOSITION_CHANNEL_IDX + offset, 0, 0}; } else if (move.isVote()) { int offset = 0; for (final Action a : move.actions()) { if (a instanceof ActionVote && a.isDecision()) { final ActionVote action = (ActionVote) a; offset = action.voteInt(); break; } } return new int[] {FIRST_VOTE_CHANNEL_IDX + offset, 0, 0}; } else if (move.isPass()) { return new int[] {MOVE_PASS_CHANNEL_IDX, 0, 0}; } else if (move.isSwap()) { return new int[] {MOVE_SWAP_CHANNEL_IDX, 0, 0}; } else if (move.isOtherMove()) { // TODO stop treating these all as passes return new int[] {MOVE_PASS_CHANNEL_IDX, 0, 0}; } else { final int from = move.fromNonDecision(); final int to = move.toNonDecision(); final int levelMin = move.levelMinNonDecision(); final int levelMax = move.levelMaxNonDecision(); assert (to >= 0); final int fromX = from != Constants.OFF ? xCoords[from] : -1; final int fromY = from != Constants.OFF ? yCoords[from] : -1; final int toX = xCoords[to]; final int toY = yCoords[to]; final int diffX = from != Constants.OFF ? toX - fromX : 0; final int diffY = from != Constants.OFF ? toY - fromY : 0; int channelIdx = MathRoutines.clip( diffX, -moveTensorDistClip, moveTensorDistClip) + moveTensorDistClip; channelIdx *= (moveTensorDistClip * 2 + 1); channelIdx += MathRoutines.clip( diffY, -moveTensorDistClip, moveTensorDistClip) + moveTensorDistClip; if (game.isStacking()) { channelIdx *= (LudiiGameWrapper.MOVE_TENSOR_LEVEL_CLIP + 1); channelIdx += MathRoutines.clip(levelMin, 0, LudiiGameWrapper.MOVE_TENSOR_LEVEL_CLIP); channelIdx *= (LudiiGameWrapper.MOVE_TENSOR_LEVEL_CLIP + 1); channelIdx += MathRoutines.clip(levelMax - levelMin, 0, LudiiGameWrapper.MOVE_TENSOR_LEVEL_CLIP); } return new int[] {channelIdx, toX, toY}; } } /** * @param moveTensor * @return A single int representation of a move (converted from its tensor representation) */ public int moveTensorToInt(final int[] moveTensor) { final int[] moveTensorsShape = moveTensorsShape(); return moveTensorsShape[1] * moveTensorsShape[2] * moveTensor[0] + moveTensorsShape[2] * moveTensor[1] + moveTensor[2]; } /** * @param move * @return A single int representation of a move */ public int moveToInt(final Move move) { return moveTensorToInt(moveToTensor(move)); } /** * @return Number of distinct actions that we can represent in our tensor-based * representations for this game. */ public int numDistinctActions() { final int[] moveTensorsShape = moveTensorsShape(); return moveTensorsShape[0] * moveTensorsShape[1] * moveTensorsShape[2]; } /** * @return Max duration of game (measured in moves) */ public int maxGameLength() { return game.getMaxMoveLimit(); } /** * @return A flat representation of a channel fully filled with only 1s. */ public float[] allOnesChannelFlat() { return ALL_ONES_CHANNEL_FLAT; } /** * @return A flat version of multiple concatenated channels (one per container), * indicating whether or not positions exist in containers */ public float[] containerPositionChannels() { return CONTAINER_POSITION_CHANNELS; } //------------------------------------------------------------------------- /** * Computes x and y coordinates in state tensors for all sites in the game. */ private void computeTensorCoords() { if (game.hasSubgames()) { System.err.println("Computing tensors for Matches is not yet supported."); return; } final Container[] containers = game.equipment().containers(); final List<? extends TopologyElement> graphElements = game.graphPlayElements(); xCoords = new int[game.equipment().totalDefaultSites()]; yCoords = new int[game.equipment().totalDefaultSites()]; final int numBoardSites = graphElements.size(); // first sort by X, to find x indices for vertices final List<? extends TopologyElement> sortedGraphElements = new ArrayList<TopologyElement>(graphElements); sortedGraphElements.sort(new Comparator<TopologyElement>() { @Override public int compare(final TopologyElement o1, final TopologyElement o2) { if (o1.centroid().getX() < o2.centroid().getX()) return -1; else if (o1.centroid().getX() == o2.centroid().getX()) return 0; else return 1; } }); int currIdx = 0; double currXPos = sortedGraphElements.get(0).centroid().getX(); for (final TopologyElement e : sortedGraphElements) { final double xPos = e.centroid().getX(); if (xPos - EPSILON > currXPos) { ++currIdx; currXPos = xPos; } xCoords[e.index()] = currIdx; } final int maxBoardIndexX = currIdx; // now the same, but for y indices sortedGraphElements.sort(new Comparator<TopologyElement>() { @Override public int compare(final TopologyElement o1, final TopologyElement o2) { if (o1.centroid().getY() < o2.centroid().getY()) return -1; else if (o1.centroid().getY() == o2.centroid().getY()) return 0; else return 1; } }); currIdx = 0; double currYPos = sortedGraphElements.get(0).centroid().getY(); for (final TopologyElement e : sortedGraphElements) { final double yPos = e.centroid().getY(); if (yPos - EPSILON > currYPos) { ++currIdx; currYPos = yPos; } yCoords[e.index()] = currIdx; } final int maxBoardIndexY = currIdx; tensorDimX = maxBoardIndexX + 1; tensorDimY = maxBoardIndexY + 1; // Maybe need to extend the board a bit for hands / other containers final int numContainers = game.numContainers(); if (numContainers > 1) { int maxNonBoardContIdx = -1; for (int c = 1; c < numContainers; ++c) { maxNonBoardContIdx = Math.max(containers[c].numSites() - 1, maxNonBoardContIdx); } boolean handsAsRows = false; if (maxBoardIndexX < maxBoardIndexY && maxNonBoardContIdx <= maxBoardIndexX) handsAsRows = true; else if (maxNonBoardContIdx > maxBoardIndexX && maxBoardIndexX > maxBoardIndexY) handsAsRows = true; if (handsAsRows) { // We paste hands as extra rows for the board tensorDimY += 1; // a dummy row to split board from other containers tensorDimY += (numContainers - 1); // one extra row per container if (maxNonBoardContIdx > maxBoardIndexX) { // Hand rows are longer than the board's rows, so need extra cols too tensorDimX += (maxNonBoardContIdx - maxBoardIndexX); } // Compute coordinates for all vertices in extra containers int nextContStartIdx = numBoardSites; for (int c = 1; c < numContainers; ++c) { final Container cont = containers[c]; for (int site = 0; site < cont.numSites(); ++site) { xCoords[site + nextContStartIdx] = site; yCoords[site + nextContStartIdx] = maxBoardIndexY + 1 + c; } nextContStartIdx += cont.numSites(); } } else { // We paste hands as extra cols for the board tensorDimX += 1; // a dummy col to split board from other containers tensorDimX += (numContainers - 1); // one extra col per container if (maxNonBoardContIdx > maxBoardIndexY) { // Hand cols are longer than the board's cols, so need extra rows too tensorDimY += (maxNonBoardContIdx - maxBoardIndexY); } // Compute coordinates for all cells in extra containers for (int c = 1; c < numContainers; ++c) { final Container cont = containers[c]; int nextContStartIdx = numBoardSites; for (int site = 0; site < cont.numSites(); ++site) { xCoords[site + nextContStartIdx] = maxBoardIndexX + 1 + c; yCoords[site + nextContStartIdx] = site; } nextContStartIdx += cont.numSites(); } } } final Component[] components = game.equipment().components(); final int numPlayers = game.players().count(); final int numPieceTypes = components.length - 1; final boolean stacking = game.isStacking(); final boolean usesCount = game.requiresCount(); final boolean usesAmount = game.requiresBet(); final boolean usesState = game.requiresLocalState(); final boolean usesSwap = game.metaRules().usesSwapRule(); final List<String> channelNames = new ArrayList<String>(); // Number of channels required for piece types stateTensorNumChannels = stacking ? NUM_STACK_CHANNELS * numPieceTypes : numPieceTypes; if (!stacking) { for (int e = 1; e <= numPieceTypes; ++e) { channelNames.add("Piece Type " + e + " (" + components[e].name() + ")"); } } else { for (int e = 1; e <= numPieceTypes; ++e) { for (int i = 0; i < NUM_STACK_CHANNELS / 2; ++i) { channelNames.add("Piece Type " + e + " (" + components[e].name() + ") at level " + i + " from stack bottom."); } for (int i = 0; i < NUM_STACK_CHANNELS / 2; ++i) { channelNames.add("Piece Type " + e + " (" + components[e].name() + ") at level " + i + " from stack top."); } } } if (stacking) { stateTensorNumChannels += 1; // one more channel for size of stack channelNames.add("Stack sizes (non-binary channel!)"); } if (usesCount) { stateTensorNumChannels += 1; // channel for count channelNames.add("Counts (non-binary channel!)"); } if (usesAmount) { stateTensorNumChannels += numPlayers; // channel for amount for (int p = 1; p <= numPlayers; ++p) { channelNames.add("Amount for Player " + p); } } if (numPlayers > 1) { stateTensorNumChannels += numPlayers; // channels for current mover for (int p = 1; p <= numPlayers; ++p) { channelNames.add("Is Player " + p + " the current mover?"); } } if (usesState) { stateTensorNumChannels += NUM_LOCAL_STATE_CHANNELS; for (int i = 0; i < NUM_LOCAL_STATE_CHANNELS; ++i) { if (i + 1 == NUM_LOCAL_STATE_CHANNELS) channelNames.add("Local state >= " + i); else channelNames.add("Local state == " + i); } } if (usesSwap) { stateTensorNumChannels += 1; channelNames.add("Did Swap Occur?"); } stateTensorNumChannels += numContainers; // for maps of whether positions exist in containers for (int c = 0; c < numContainers; ++c) { channelNames.add("Does position exist in container " + c + " (" + containers[c].name() + ")?"); } stateTensorNumChannels += 4; // channels for last move and move before last move (from and to) channelNames.add("Last move's from-position"); channelNames.add("Last move's to-position"); channelNames.add("Second-to-last move's from-position"); channelNames.add("Second-to-last move's to-position"); assert (channelNames.size() == stateTensorNumChannels); stateTensorChannelNames = channelNames.toArray(new String[stateTensorNumChannels]); final int firstAuxilChannelIdx = computeFirstAuxilChannelIdx(); if (game.usesVote()) { FIRST_PROPOSITION_CHANNEL_IDX = firstAuxilChannelIdx; FIRST_VOTE_CHANNEL_IDX = FIRST_PROPOSITION_CHANNEL_IDX + game.numVoteStrings(); MOVE_PASS_CHANNEL_IDX = FIRST_VOTE_CHANNEL_IDX + game.numVoteStrings(); } else { MOVE_PASS_CHANNEL_IDX = firstAuxilChannelIdx; } MOVE_SWAP_CHANNEL_IDX = MOVE_PASS_CHANNEL_IDX + 1; ALL_ONES_CHANNEL_FLAT = new float[tensorDimX * tensorDimY]; Arrays.fill(ALL_ONES_CHANNEL_FLAT, 1.f); CONTAINER_POSITION_CHANNELS = new float[containers.length * tensorDimX * tensorDimY]; for (int c = 0; c < containers.length; ++c) { final Container cont = containers[c]; final int contStartSite = game.equipment().sitesFrom()[c]; for (int site = 0; site < cont.numSites(); ++site) { CONTAINER_POSITION_CHANNELS[yCoords[contStartSite + site] + tensorDimY * (xCoords[contStartSite + site] + (c * tensorDimX))] = 1.f; } } } //------------------------------------------------------------------------- /** * @return First channel index for auxiliary in move-tensor-representation */ private int computeFirstAuxilChannelIdx() { // legal values for diff x = {-clip, ..., -2, -1, 0, 1, 2, ..., +clip} final int numValsDiffX = 2 * moveTensorDistClip + 1; // legal values for diff y = {-clip, ..., -2, -1, 0, 1, 2, ..., +clip} (mult with diff x) final int numValsDiffY = numValsDiffX * (2 * moveTensorDistClip + 1); if (!game.isStacking()) { return numValsDiffY; } else { // legal values for clipped levelMin = {0, 1, 2, ..., clip} (mult with all the above) final int numValsLevelMin = numValsDiffY * (MOVE_TENSOR_LEVEL_CLIP + 1); // legal values for clipped levelMax - levelMin = {0, 1, 2, ..., clip} (mult with all the above) final int numValsLevelMax = numValsLevelMin * (MOVE_TENSOR_LEVEL_CLIP + 1); // The max index using variables mentioned above is 1 less than the number of values // we computed, since we start at 0. // So, the number we just computed can be used as the next index (for Pass moves) return numValsLevelMax; } } //------------------------------------------------------------------------- /** * Computes and returns array of indices of source channels that we should * transfer from, for move tensors. At index i of the returned array, we * have the index of the move tensor channel that we should transfer from * in the source domain. * * This array should be of length equal to the * number of channels in this game. * * If the source game does not contain any matching channels for our * i'th channel, we have a value of -1 in the returned array. * * @param sourceGame * @return Indices of source channels we should transfer from */ public int[] moveTensorSourceChannels(final LudiiGameWrapper sourceGame) { final int[] sourceChannelIndices = new int[moveTensorsShape()[0]]; for (int targetChannel = 0; targetChannel < sourceChannelIndices.length; ++targetChannel) { if (targetChannel == MOVE_PASS_CHANNEL_IDX) { sourceChannelIndices[targetChannel] = sourceGame.MOVE_PASS_CHANNEL_IDX; } else if (targetChannel == MOVE_SWAP_CHANNEL_IDX) { sourceChannelIndices[targetChannel] = sourceGame.MOVE_SWAP_CHANNEL_IDX; } else { // TODO not handling stacking games yet in these cases if ((game.gameFlags() & GameType.UsesFromPositions) == 0L) { // Target domain is placement game if ((sourceGame.game.gameFlags() & GameType.UsesFromPositions) == 0L) { // Source domain is placement game sourceChannelIndices[targetChannel] = targetChannel; } else { // Source domain is movement game // // We can't properly make every different movement channel from source // domain map to the single placement channel // So, we'll be more strict and instead only map the dx = dy = 0 movement // channel to the target placement channel, leaving all other source movement // channels unused. if (targetChannel != 0) throw new UnsupportedOperationException("LudiiGameWrapper::moveTensorSourceChannels() expected targetChannel == 0!"); int channelIdx = MathRoutines.clip( 0, -sourceGame.moveTensorDistClip, sourceGame.moveTensorDistClip) + sourceGame.moveTensorDistClip; channelIdx *= (sourceGame.moveTensorDistClip * 2 + 1); channelIdx += MathRoutines.clip( 0, -sourceGame.moveTensorDistClip, sourceGame.moveTensorDistClip) + sourceGame.moveTensorDistClip; sourceChannelIndices[targetChannel] = channelIdx; } } else { // Target domain is movement game if ((sourceGame.game.gameFlags() & GameType.UsesFromPositions) == 0L) { // Source domain is placement game // // We'll transfer the 0 channel (= placement channel) to all the different // movement channels sourceChannelIndices[targetChannel] = 0; } else { // Source domain is movement game sourceChannelIndices[targetChannel] = targetChannel; } } } } return sourceChannelIndices; } /** * Computes and returns array of indices of source channels that we should * transfer from, for state tensors. At index i of the returned array, we * have the index of the state tensor channel that we should transfer from * in the source domain. * * This array should be of length equal to the * number of channels in this game. * * If the source game does not contain any matching channels for our * i'th channel, we have a value of -1 in the returned array. * * @param sourceGame * @return Indices of source channels we should transfer from */ public int[] stateTensorSourceChannels(final LudiiGameWrapper sourceGame) { final String[] sourceChannelNames = sourceGame.stateTensorChannelNames(); final int[] sourceChannelIndices = new int[stateTensorsShape()[0]]; final Component[] targetComps = game.equipment().components(); final Component[] sourceComps = sourceGame.game.equipment().components(); for (int targetChannel = 0; targetChannel < sourceChannelIndices.length; ++targetChannel) { final String targetChannelName = stateTensorChannelNames[targetChannel]; if (targetChannelName.startsWith("Piece Type ")) { if (targetChannelName.endsWith(" from stack bottom.") || targetChannelName.endsWith(" from stack top.")) { // TODO handle stacking games throw new UnsupportedOperationException("Stacking games not yet handled by stateTensorSourceChannels()!"); } else { final int pieceType = Integer.parseInt( targetChannelName.substring("Piece Type ".length()).split(Pattern.quote(" "))[0]); final Component targetPiece = targetComps[pieceType]; final String targetPieceName = targetPiece.name(); final int owner = targetPiece.owner(); int bestMatch = -1; // First try to find a source piece with same name and same owner for (int i = 1; i < sourceComps.length; ++i) { final Component sourcePiece = sourceComps[i]; if (sourcePiece.owner() == owner && sourcePiece.name().equals(targetPieceName)) { bestMatch = i; break; } } if (bestMatch == -1) { // Try to find a source piece with similar ludeme tree final Tree ludemeTree = LudemeTreeUtils.buildLudemeZhangShashaTree(targetPiece.generator()); int lowestDist = Integer.MAX_VALUE; for (int i = 1; i < sourceComps.length; ++i) { final Component sourcePiece = sourceComps[i]; if (sourcePiece.owner() == owner) { final Tree otherTree = LudemeTreeUtils.buildLudemeZhangShashaTree(sourcePiece.generator()); final int treeEditDist = Tree.ZhangShasha(ludemeTree, otherTree); if (treeEditDist < lowestDist) { lowestDist = treeEditDist; bestMatch = i; } } } } if (bestMatch >= 0) { int sourceChannelIdx = -1; for (int i = 0; i < sourceChannelNames.length; ++i) { if (sourceChannelNames[i].equals("Piece Type " + bestMatch + " (" + sourceComps[bestMatch].name() + ")")) { sourceChannelIdx = i; break; } } sourceChannelIndices[targetChannel] = sourceChannelIdx; } else { sourceChannelIndices[targetChannel] = -1; } } } else if (targetChannelName.startsWith("Does position exist in container ")) { final int containerIdx = Integer.parseInt( targetChannelName.substring("Does position exist in container ".length()).split(Pattern.quote(" "))[0]); // For now we just search for container with same index, since usually we're consistent in how we // order the containers in different games // TODO can probably do something smarter later. Like maybe looking at the ratio of sites that // a container has relative to the number of sites across entire game? int idx = -1; for (int i = 0; i < sourceChannelNames.length; ++i) { final String sourceChannelName = sourceChannelNames[i]; if (sourceChannelName.startsWith("Does position exist in container ")) { final int sourceContainerIdx = Integer.parseInt( sourceChannelName.substring("Does position exist in container ".length()).split(Pattern.quote(" "))[0]); if (containerIdx == sourceContainerIdx) { idx = i; break; } } } if (idx >= 0) { sourceChannelIndices[targetChannel] = idx; } else { sourceChannelIndices[targetChannel] = -1; } } else if ( targetChannelName.equals("Stack sizes (non-binary channel!)") || targetChannelName.equals("Counts (non-binary channel!)") || targetChannelName.startsWith("Amount for Player ") || (targetChannelName.startsWith("Is Player ") && targetChannelName.endsWith(" the current mover?")) || targetChannelName.startsWith("Local state >= ") || targetChannelName.startsWith("Local state == ") || targetChannelName.startsWith("Did Swap Occur?") || targetChannelName.startsWith("Last move's from-position") || targetChannelName.startsWith("Last move's to-position") || targetChannelName.startsWith("Second-to-last move's from-position") || targetChannelName.startsWith("Second-to-last move's to-position") ) { sourceChannelIndices[targetChannel] = identicalChannelIdx(targetChannelName, sourceChannelNames); } else { throw new UnsupportedOperationException("stateTensorSourceChannels() does not recognise channel name: " + targetChannelName); } } return sourceChannelIndices; } /** * @param targetChannel * @param sourceChannels * @return Index of source channel that is identical to given target channel. * Returns -1 if no identical source channel exists. */ private static int identicalChannelIdx(final String targetChannel, final String[] sourceChannels) { int idx = -1; for (int i = 0; i < sourceChannels.length; ++i) { if (sourceChannels[i].equals(targetChannel)) { idx = i; break; } } return idx; } //------------------------------------------------------------------------- /** * Main method prints some relevant information for these wrappers * @param args */ public static void main(final String[] args) { final String[] gameNames = FileHandling.listGames(); for (final String name : gameNames) { if (name.replaceAll(Pattern.quote("\\"), "/").contains("/wip/")) continue; if (name.replaceAll(Pattern.quote("\\"), "/").contains("/wishlist/")) continue; if (name.replaceAll(Pattern.quote("\\"), "/").contains("/test/")) continue; if (name.replaceAll(Pattern.quote("\\"), "/").contains("/bad_playout/")) continue; if (name.replaceAll(Pattern.quote("\\"), "/").contains("/bad/")) continue; if (name.replaceAll(Pattern.quote("\\"), "/").contains("/plex/")) continue; if (name.replaceAll(Pattern.quote("\\"), "/").contains("/math/graph/")) continue; System.out.println("name = " + name); final LudiiGameWrapper game = LudiiGameWrapper.construct(name); if (!game.game.hasSubgames()) { System.out.println("State tensor shape = " + Arrays.toString(game.stateTensorsShape())); System.out.println("Moves tensor shape = " + Arrays.toString(game.moveTensorsShape())); } } } }
32,977
28.004398
135
java
Ludii
Ludii-master/AI/src/utils/LudiiStateWrapper.java
package utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import game.equipment.container.Container; import gnu.trove.list.array.TIntArrayList; import main.Constants; import main.collections.FastArrayList; import other.RankUtils; import other.context.Context; import other.context.TempContext; import other.move.Move; import other.state.State; import other.state.container.ContainerState; import other.state.owned.Owned; import other.state.stacking.BaseContainerStateStacking; import other.trial.Trial; /** * Wrapper around a Ludii context (trial + state), with various extra methods required for * other frameworks that like to wrap around Ludii (e.g. OpenSpiel, Polygames) * * @author Dennis Soemers */ public final class LudiiStateWrapper { //------------------------------------------------------------------------- /** Reference back to our wrapped Ludii game */ protected LudiiGameWrapper game; /** Our wrapped context */ protected Context context; /** Our wrapped trial */ protected Trial trial; //------------------------------------------------------------------------- /** * Constructor * @param game */ public LudiiStateWrapper(final LudiiGameWrapper game) { this.game = game; trial = new Trial(game.game); context = new Context(game.game, trial); game.game.start(context); } /** * Constructor * @param gameWrapper * @param context */ public LudiiStateWrapper(final LudiiGameWrapper gameWrapper, final Context context) { this.game = gameWrapper; trial = context.trial(); this.context = context; } /** * Copy constructor * @param other */ public LudiiStateWrapper(final LudiiStateWrapper other) { this.game = other.game; this.context = new Context(other.context); this.trial = this.context.trial(); } //------------------------------------------------------------------------- /** * Copies data from given other LudiiStateWrapper. * TODO can optimise this if we provide optimised copyFrom implementations * for context and trial! * * @param other */ public void copyFrom(final LudiiStateWrapper other) { this.game = other.game; this.context = new Context(other.context); this.trial = this.context.trial(); } //------------------------------------------------------------------------- /** * @param actionID * @param player * @return A string (with fairly detailed information) on the move(s) represented * by the given actionID in the current game state. */ public String actionToString(final int actionID, final int player) { final FastArrayList<Move> legalMoves; if (game.isSimultaneousMoveGame()) legalMoves = AIUtils.extractMovesForMover(game.game.moves(context).moves(), player + 1); else legalMoves = game.game.moves(context).moves(); final List<Move> moves = new ArrayList<Move>(); for (final Move move : legalMoves) { if (game.moveToInt(move) == actionID) moves.add(move); } if (moves.isEmpty()) { return "[Ludii found no move for ID: " + actionID + "!]"; } else if (moves.size() == 1) { return moves.get(0).toTrialFormat(context); } else { final StringBuilder sb = new StringBuilder(); sb.append("[Multiple Ludii moves for ID=" + actionID + ": "); sb.append(moves); sb.append("]"); return sb.toString(); } } /** * Applies the given move * @param move */ public void applyMove(final Move move) { game.game.apply(context, move); } /** * Applies the nth legal move in current game state * * @param n Legal move index. NOTE: index in Ludii's list of legal move, * not a move converted into an int for e.g. OpenSpiel representation */ public void applyNthMove(final int n) { final FastArrayList<Move> legalMoves = game.game.moves(context).moves(); final Move moveToApply = legalMoves.get(n); game.game.apply(context, moveToApply); } /** * Applies a move represented by given int in the single-int-action-representation. * Note that this method may have to randomly select a move among multiple legal * moves if multiple different legal moves are represented by the same int. * * @param action * @param player */ public void applyIntAction(final int action, final int player) { final FastArrayList<Move> legalMoves; if (game.isSimultaneousMoveGame()) legalMoves = AIUtils.extractMovesForMover(game.game.moves(context).moves(), player + 1); else legalMoves = game.game.moves(context).moves(); final List<Move> moves = new ArrayList<Move>(); for (final Move move : legalMoves) { if (game.moveToInt(move) == action) moves.add(move); } game.game.apply(context, moves.get(ThreadLocalRandom.current().nextInt(moves.size()))); } @Override public LudiiStateWrapper clone() { return new LudiiStateWrapper(this); } /** * @return Current player to move (not accurate in simultaneous-move games). * Returns a 0-based index. Returns the player/agent to move, not necessarily * the "colour" to move (may be different in games with Swap rule). */ public int currentPlayer() { return context.state().playerToAgent(context.state().mover()) - 1; } /** * @return True if and only if current trial is over (terminal game state reached) */ public boolean isTerminal() { return trial.over(); } /** * @return The full Zobrist hash of the current state */ public long fullZobristHash() { return context.state().fullHash(); } /** * Resets this game state back to an initial game state */ public void reset() { game.game.start(context); } /** * @return Array of legal Move objects */ public Move[] legalMovesArray() { return game.game.moves(context).moves().toArray(new Move[0]); } /** * @return Array of indices for legal moves. For a game state with N legal moves, * this will always simply be [0, 1, 2, ..., N-1] */ public int[] legalMoveIndices() { final FastArrayList<Move> moves = game.game.moves(context).moves(); final int[] indices = new int[moves.size()]; for (int i = 0; i < indices.length; ++i) { indices[i] = i; } return indices; } /** * @return Number of legal moves in current state */ public int numLegalMoves() { return Math.max(1, game.game.moves(context).moves().size()); } /** * @return Array of integers corresponding to moves that are legal in current * game state. */ public int[] legalMoveInts() { final FastArrayList<Move> moves = game.game.moves(context).moves(); final TIntArrayList moveInts = new TIntArrayList(moves.size()); // TODO could speed up this method by implementing an auto-sorting // class that extends TIntArrayList for (final Move move : moves) { final int toAdd = game.moveToInt(move); if (!moveInts.contains(toAdd)) moveInts.add(toAdd); } moveInts.sort(); return moveInts.toArray(); } /** * @param player * @return Array of integers corresponding to moves that are legal in current * game state for the given player. */ public int[] legalMoveIntsPlayer(final int player) { final FastArrayList<Move> legalMoves; if (game.isSimultaneousMoveGame()) legalMoves = AIUtils.extractMovesForMover(game.game.moves(context).moves(), player + 1); else legalMoves = game.game.moves(context).moves(); final TIntArrayList moveInts = new TIntArrayList(legalMoves.size()); // TODO could speed up this method by implementing an auto-sorting // class that extends TIntArrayList for (final Move move : legalMoves) { final int toAdd = game.moveToInt(move); if (!moveInts.contains(toAdd)) moveInts.add(toAdd); } moveInts.sort(); return moveInts.toArray(); } /** * @return Array with a length equal to the number of legal moves in current state. * Every element is an int array of size 3, containing [channel_idx, x, y] for * that move. This is used for action representation in Polygames. */ public int[][] legalMovesTensors() { final FastArrayList<Move> moves = game.game.moves(context).moves(); final int[][] movesTensors; if (moves.isEmpty()) { movesTensors = new int[1][]; movesTensors[0] = new int[] {game.MOVE_PASS_CHANNEL_IDX, 0, 0}; } else { movesTensors = new int[moves.size()][]; for (int i = 0; i < moves.size(); ++i) { movesTensors[i] = game.moveToTensor(moves.get(i)); } } return movesTensors; } /** * Runs a random playout. */ public void runRandomPlayout() { game.game.playout(context, null, 0.0, null, 0, -1, ThreadLocalRandom.current()); } /** * Estimates a reward for a given player (assumed 0-index player) based on one * or more random rollouts from the current state. * * @param player * @param numRollouts * @param playoutCap Max number of random actions we'll select in playout * @return Estimated reward */ public double getRandomRolloutsReward(final int player, final int numRollouts, final int playoutCap) { double sumRewards = 0.0; for (int i = 0; i < numRollouts; ++i) { final TempContext copyContext = new TempContext(context); game.game.playout(copyContext, null, 0.1f, null, 0, playoutCap, ThreadLocalRandom.current()); final double[] returns = RankUtils.agentUtilities(copyContext); sumRewards += returns[player + 1]; } return sumRewards / numRollouts; } /** * NOTE: the returns are for the original player indices at the start of the episode; * this can be different from player-to-colour assignments in the current game state * if the Swap rule was used. * * @return Array of utilities in [-1, 1] for all players. Player * index assumed to be 0-based! */ public double[] returns() { if (!isTerminal()) return new double[game.numPlayers()]; final double[] returns = RankUtils.agentUtilities(context); return Arrays.copyOfRange(returns, 1, returns.length); } /** * NOTE: the returns are for the original player indices at the start of the episode; * this can be different from player-to-colour assignments in the current game state * if the Swap rule was used. * * @param player * @return The returns for given player (index assumed to be 0-based!). Returns * are always in [-1, 1] */ public double returns(final int player) { if (!isTerminal()) return 0.0; final double[] returns = RankUtils.agentUtilities(context); return returns[player + 1]; } /** * Undo the last move. * * NOTE: implementation is NOT efficient. It restarts to the initial game * state, and re-applies all moves except for the last one */ public void undoLastMove() { final List<Move> moves = context.trial().generateCompleteMovesList(); reset(); for (int i = context.trial().numInitialPlacementMoves(); i < moves.size() - 1; ++i) { game.game.apply(context, moves.get(i)); } } /** * @return A flat, 1D array tensor representation of the current game state */ public float[] toTensorFlat() { // TODO we also want to support edges and faces for some games final Container[] containers = game.game.equipment().containers(); final int numPlayers = game.game.players().count(); final int numPieceTypes = game.game.equipment().components().length - 1; final boolean stacking = game.game.isStacking(); final boolean usesCount = game.game.requiresCount(); final boolean usesAmount = game.game.requiresBet(); final boolean usesState = game.game.requiresLocalState(); final boolean usesSwap = game.game.metaRules().usesSwapRule(); final int[] xCoords = game.tensorCoordsX(); final int[] yCoords = game.tensorCoordsY(); final int tensorDimX = game.tensorDimX(); final int tensorDimY = game.tensorDimY(); final int numChannels = game.stateTensorNumChannels; final float[] flatTensor = new float[numChannels * tensorDimX * tensorDimY]; int currentChannel = 0; if (!stacking) { // Just one channel per piece type final Owned owned = context.state().owned(); for (int e = 1; e <= numPieceTypes; ++e) { for (int p = 1; p <= numPlayers + 1; ++p) { final TIntArrayList sites = owned.sites(p, e); for (int i = 0; i < sites.size(); ++i) { final int site = sites.getQuick(i); flatTensor[yCoords[site] + tensorDimY * (xCoords[site] + (currentChannel * tensorDimX))] = 1.f; } } ++currentChannel; } } else { // We have to deal with stacking for (int c = 0; c < containers.length; ++c) { final Container cont = containers[c]; final BaseContainerStateStacking cs = (BaseContainerStateStacking) context.state().containerStates()[c]; final int contStartSite = game.game.equipment().sitesFrom()[c]; for (int site = 0; site < cont.numSites(); ++site) { final int stackSize = cs.sizeStackCell(contStartSite + site); if (stackSize > 0) { // Store in channels for bottom 5 elements of stack for (int i = 0; i < LudiiGameWrapper.NUM_STACK_CHANNELS / 2; ++i) { if (i >= stackSize) break; final int what = cs.whatCell(contStartSite + site, i); final int channel = currentChannel + ((what - 1) * LudiiGameWrapper.NUM_STACK_CHANNELS + i); flatTensor[yCoords[contStartSite + site] + tensorDimY * (xCoords[contStartSite + site] + (channel * tensorDimX))] = 1.f; } // And same for top 5 elements of stack for (int i = 0; i < LudiiGameWrapper.NUM_STACK_CHANNELS / 2; ++i) { if (i >= stackSize) break; final int what = cs.whatCell(contStartSite + site, stackSize - 1 - i); final int channel = currentChannel + ((what - 1) * LudiiGameWrapper.NUM_STACK_CHANNELS + (LudiiGameWrapper.NUM_STACK_CHANNELS / 2) + i); flatTensor[yCoords[contStartSite + site] + tensorDimY * (xCoords[contStartSite + site] + (channel * tensorDimX))] = 1.f; } // Finally a non-binary channel storing the height of stack final int channel = currentChannel + LudiiGameWrapper.NUM_STACK_CHANNELS * numPieceTypes; flatTensor[yCoords[contStartSite + site] + tensorDimY * (xCoords[contStartSite + site] + (channel * tensorDimX))] = stackSize; } } } // + 1 for stack size channel currentChannel += LudiiGameWrapper.NUM_STACK_CHANNELS * numPieceTypes + 1; } if (usesCount) { // non-binary channel for counts for (int c = 0; c < containers.length; ++c) { final Container cont = containers[c]; final ContainerState cs = context.state().containerStates()[c]; final int contStartSite = game.game.equipment().sitesFrom()[c]; for (int site = 0; site < cont.numSites(); ++site) { flatTensor[yCoords[contStartSite + site] + tensorDimY * (xCoords[contStartSite + site] + (currentChannel * tensorDimX))] = cs.countCell(contStartSite + site); } } ++currentChannel; } if (usesAmount) { // One channel per player for their amount for (int p = 1; p <= numPlayers; ++p) { final int amount = context.state().amount(p); final int startFill = tensorDimY * currentChannel * tensorDimX; final int endFill = startFill + (tensorDimY * tensorDimX); Arrays.fill(flatTensor, startFill, endFill, amount); ++currentChannel; } } if (numPlayers > 1) { // One binary channel per player for whether or not they're current mover // (one will be all-1s, all the others will be all-0) // Takes into account swap rule! final int mover = context.state().playerToAgent(context.state().mover()); final int startFill = tensorDimY * (currentChannel + mover - 1) * tensorDimX; System.arraycopy(game.allOnesChannelFlat(), 0, flatTensor, startFill, (tensorDimY * tensorDimX)); currentChannel += numPlayers; } if (usesState) { // Channels for local state: 0, 1, 2, 3, 4, or >= 5 for (int c = 0; c < containers.length; ++c) { final Container cont = containers[c]; final int contStartSite = game.game.equipment().sitesFrom()[c]; final ContainerState cs = context.state().containerStates()[c]; for (int site = 0; site < cont.numSites(); ++site) { final int state = Math.min(cs.stateCell(contStartSite + site), LudiiGameWrapper.NUM_LOCAL_STATE_CHANNELS - 1); flatTensor[yCoords[contStartSite + site] + tensorDimY * (xCoords[contStartSite + site] + ((currentChannel + state) * tensorDimX))] = 1.f; } } currentChannel += LudiiGameWrapper.NUM_LOCAL_STATE_CHANNELS; } if (usesSwap) { // Channel for whether or not swap occurred if (context.state().orderHasChanged()) { final int startFill = tensorDimY * currentChannel * tensorDimX; System.arraycopy(game.allOnesChannelFlat(), 0, flatTensor, startFill, (tensorDimY * tensorDimX)); } currentChannel += 1; } // Channels for whether or not positions exist in containers final int startFill = tensorDimY * currentChannel * tensorDimX; System.arraycopy(game.containerPositionChannels(), 0, flatTensor, startFill, (containers.length * tensorDimY * tensorDimX)); currentChannel += containers.length; // Channels marking from and to of last Move final List<Move> trialMoves = trial.generateCompleteMovesList(); if (trialMoves.size() - trial.numInitialPlacementMoves() > 0) { final Move lastMove = trialMoves.get(trialMoves.size() - 1); final int from = lastMove.fromNonDecision(); if (from != Constants.OFF) flatTensor[yCoords[from] + tensorDimY * (xCoords[from] + (currentChannel * tensorDimX))] = 1.f; ++currentChannel; final int to = lastMove.toNonDecision(); if (to != Constants.OFF) flatTensor[yCoords[to] + tensorDimY * (xCoords[to] + (currentChannel * tensorDimX))] = 1.f; ++currentChannel; } else { currentChannel += 2; } // And the same for move before last move if (trialMoves.size() - trial.numInitialPlacementMoves() > 1) { final Move lastLastMove = trialMoves.get(trialMoves.size() - 2); final int from = lastLastMove.fromNonDecision(); if (from != Constants.OFF) flatTensor[yCoords[from] + tensorDimY * (xCoords[from] + (currentChannel * tensorDimX))] = 1.f; ++currentChannel; final int to = lastLastMove.toNonDecision(); if (to != Constants.OFF) flatTensor[yCoords[to] + tensorDimY * (xCoords[to] + (currentChannel * tensorDimX))] = 1.f; ++currentChannel; } else { currentChannel += 2; } // Assert that we correctly ran through all channels assert (currentChannel == numChannels); return flatTensor; } /** * @return A single (3D) tensor representation of the current game state */ public float[][][] toTensor() { final int tensorDimX = game.tensorDimX(); final int tensorDimY = game.tensorDimY(); final int numChannels = game.stateTensorNumChannels; final float[] flatTensor = toTensorFlat(); final float[][][] tensor = new float[numChannels][tensorDimX][tensorDimY]; for (int c = 0; c < numChannels; ++c) { for (int x = 0; x < tensorDimX; ++x) { System.arraycopy(flatTensor, tensorDimY * (x + (c * tensorDimX)), tensor[c][x], 0, tensorDimY); } } return tensor; } /** * @return The wrapped trial object */ public Trial trial() { return trial; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); final State state = context.state(); sb.append("BEGIN LUDII STATE\n"); sb.append("Mover colour = " + state.mover() + "\n"); sb.append("Mover player/agent = " + state.playerToAgent(state.mover()) + "\n"); sb.append("Next = " + state.next() + "\n"); sb.append("Previous = " + state.prev() + "\n"); for (int p = 1; p <= state.numPlayers(); ++p) { sb.append("Player " + p + " active = " + context.active(p) + "\n"); } sb.append("State hash = " + state.stateHash() + "\n"); if (game.game.requiresScore()) { for (int p = 1; p <= state.numPlayers(); ++p) { sb.append("Player " + p + " score = " + context.score(p) + "\n"); } } for (int p = 1; p <= state.numPlayers(); ++p) { sb.append("Player " + p + " ranking = " + context.trial().ranking()[p] + "\n"); } for (int i = 0; i < state.containerStates().length; ++i) { final ContainerState cs = state.containerStates()[i]; sb.append("BEGIN CONTAINER STATE " + i + "\n"); sb.append(cs.toString() + "\n"); sb.append("END CONTAINER STATE " + i + "\n"); } sb.append("END LUDII GAME STATE\n"); return sb.toString(); } }
20,747
27.151967
142
java
Ludii
Ludii-master/AI/src/utils/RandomAI.java
package utils; import java.util.concurrent.ThreadLocalRandom; import game.Game; import main.collections.FastArrayList; import other.AI; import other.context.Context; import other.move.Move; /** * AI player which selects actions uniformly at random. * * @author Dennis Soemers */ public class RandomAI extends AI { //------------------------------------------------------------------------- /** Our player index */ protected int player = -1; /** The last move we returned */ protected Move lastReturnedMove = null; //------------------------------------------------------------------------- /** * Constructor */ public RandomAI() { friendlyName = "Random"; } //------------------------------------------------------------------------- @Override public Move selectAction ( final Game game, final Context context, final double maxSeconds, final int maxIterations, final int maxDepth ) { FastArrayList<Move> legalMoves = game.moves(context).moves(); if (!game.isAlternatingMoveGame()) legalMoves = AIUtils.extractMovesForMover(legalMoves, player); final int r = ThreadLocalRandom.current().nextInt(legalMoves.size()); final Move move = legalMoves.get(r); lastReturnedMove = move; return move; } /** * @return The last move we returned */ public Move lastReturnedMove() { return lastReturnedMove; } @Override public void initAI(final Game game, final int playerID) { this.player = playerID; lastReturnedMove = null; } //------------------------------------------------------------------------- }
1,587
19.358974
76
java
Ludii
Ludii-master/AI/src/utils/analysis/BestBaseAgents.java
package utils.analysis; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Wrapper around collected data on the best base agents in all games * * TODO could probably make sure we only ever load the data once... * * @author Dennis Soemers */ public class BestBaseAgents { //------------------------------------------------------------------------- /** Map of entries (mapping from cleaned game names to entries of data) */ private final Map<String, Entry> entries; //------------------------------------------------------------------------- /** * @return Loads and returns the analysed data as stored so far. */ public static BestBaseAgents loadData() { final Map<String, Entry> entries = new HashMap<String, Entry>(); final File file = new File("../AI/resources/Analysis/BestBaseAgents.csv"); try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { reader.readLine(); // headers line, which we don't use for (String line; (line = reader.readLine()) != null; /**/) { final String[] lineSplit = line.split(Pattern.quote(",")); entries.put(lineSplit[2], new Entry ( lineSplit[0], lineSplit[1], lineSplit[2], lineSplit[3], Float.parseFloat(lineSplit[4]) )); } } catch (final IOException e) { e.printStackTrace(); } return new BestBaseAgents(entries); } /** * Constructor * @param entries */ private BestBaseAgents(final Map<String, Entry> entries) { this.entries = entries; } //------------------------------------------------------------------------- /** * @param cleanGameName * @return Stored entry for given game name */ public Entry getEntry(final String cleanGameName) { return entries.get(cleanGameName); } /** * @return Set of all game keys in our file */ public Set<String> keySet() { return entries.keySet(); } //------------------------------------------------------------------------- /** * An entry with data for one game in our collected data. * * @author Dennis Soemers */ public static class Entry { /** Name of game for which we stored data */ private final String gameName; /** Name of ruleset for which we stored data */ private final String rulesetName; /** Name of game+ruleset for which we stored data */ private final String gameRulesetName; /** String description of top agent */ private final String topAgent; /** Win percentage of the top agent */ private final float topScore; /** * Constructor * @param cleanGameName * @param rulesetName * @param gameRulesetName * @param topAgent * @param topScore */ protected Entry ( final String gameName, final String rulesetName, final String gameRulesetName, final String topAgent, final float topScore ) { this.gameName = gameName; this.rulesetName = rulesetName; this.gameRulesetName = gameRulesetName; this.topAgent = topAgent; this.topScore = topScore; } /** * @return Name of game for which we stored data */ public String gameName() { return gameName; } /** * @return Name of ruleset for which we stored data */ public String rulesetName() { return rulesetName; } /** * @return Name of game+ruleset for which we stored data */ public String gameRulesetName() { return gameRulesetName; } /** * @return String description of top agent */ public String topAgent() { return topAgent; } /** * @return Win percentage of the top agent */ public float topScore() { return topScore; } } //------------------------------------------------------------------------- }
3,911
20.26087
78
java
Ludii
Ludii-master/AI/src/utils/analysis/BestStartingHeuristics.java
package utils.analysis; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Wrapper around collected data on the best starting heuristics * to start training Alpha-Beta agents with. * * TODO could probably make sure we only ever load the data once... * * @author Dennis Soemers */ public class BestStartingHeuristics { //------------------------------------------------------------------------- /** Map of entries (mapping from cleaned game names to entries of data) */ private final Map<String, Entry> entries; //------------------------------------------------------------------------- /** * @return Loads and returns the analysed data as stored so far. */ public static BestStartingHeuristics loadData() { final Map<String, Entry> entries = new HashMap<String, Entry>(); final File file = new File("../AI/resources/Analysis/BestStartingHeuristics.csv"); try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { reader.readLine(); // headers line, which we don't use for (String line; (line = reader.readLine()) != null; /**/) { final String[] lineSplit = line.split(Pattern.quote(",")); entries.put(lineSplit[2], new Entry ( lineSplit[0], lineSplit[1], lineSplit[2], lineSplit[3], Float.parseFloat(lineSplit[4]) )); } } catch (final IOException e) { e.printStackTrace(); } return new BestStartingHeuristics(entries); } /** * Constructor * @param entries */ private BestStartingHeuristics(final Map<String, Entry> entries) { this.entries = entries; } //------------------------------------------------------------------------- /** * @param cleanGameName * @return Stored entry for given game name */ public Entry getEntry(final String cleanGameName) { return entries.get(cleanGameName); } /** * @return Set of all game keys in our file */ public Set<String> keySet() { return entries.keySet(); } //------------------------------------------------------------------------- /** * An entry with data for one game in our collected data. * * @author Dennis Soemers */ public static class Entry { /** Name of game for which we stored data */ private final String gameName; /** Name of ruleset for which we stored data */ private final String rulesetName; /** Name of game+ruleset for which we stored data */ private final String gameRulesetName; /** String description of top starting heuristic */ private final String topHeuristic; /** Win percentage of the Alpha-Beta agent with the top starting heuristic */ private final float topScore; /** * Constructor * @param cleanGameName * @param rulesetName * @param gameRulesetName * @param topHeuristic * @param topScore */ protected Entry ( final String gameName, final String rulesetName, final String gameRulesetName, final String topHeuristic, final float topScore ) { this.gameName = gameName; this.rulesetName = rulesetName; this.gameRulesetName = gameRulesetName; this.topHeuristic = topHeuristic; this.topScore = topScore; } /** * @return Name of game for which we stored data */ public String gameName() { return gameName; } /** * @return Name of ruleset for which we stored data */ public String rulesetName() { return rulesetName; } /** * @return Name of game+ruleset for which we stored data */ public String gameRulesetName() { return gameRulesetName; } /** * @return String description of top starting heuristic */ public String topHeuristic() { return topHeuristic; } /** * @return Win percentage of the Alpha-Beta agent with the top starting heuristic */ public float topScore() { return topScore; } } //------------------------------------------------------------------------- }
4,123
21.291892
84
java
Ludii
Ludii-master/AI/src/utils/data_structures/ScoredIndex.java
package utils.data_structures; /** * * Simple wrapper for score + index, used for sorting indices (usually move indices) based on scores. * Almost identical to ScoredMove. * * @author cyprien * */ public class ScoredIndex implements Comparable<ScoredIndex> { /** The move */ public final int index; /** The move's score */ public final float score; /** * Constructor * @param score */ public ScoredIndex(final int index, final float score) { this.index = index; this.score = score; } @Override public int compareTo(final ScoredIndex other) { final float delta = other.score - score; if (delta < 0.f) return -1; else if (delta > 0.f) return 1; else return 0; } }
719
16.142857
101
java
Ludii
Ludii-master/AI/src/utils/data_structures/ScoredMove.java
package utils.data_structures; import other.move.Move; /** * Simple wrapper for score + move, used for sorting moves based on scores. * Copied from the AB-Code, but put in an external class so that it can be used by Transposition Tables. * * @author cyprien */ public class ScoredMove implements Comparable<ScoredMove> { /** The move */ public final Move move; /** The move's score */ public final float score; /** The number of times this move was explored */ public int nbVisits; /** * Constructor * @param move * @param score */ public ScoredMove(final Move move, final float score, final int nbVisits) { this.move = move; this.score = score; this.nbVisits = nbVisits; } @Override public int compareTo(final ScoredMove other) { //nbVisits is not taken into account for the moment final float delta = other.score - score; if (delta < 0.f) return -1; else if (delta > 0.f) return 1; else return 0; } }
964
19.978261
104
java
Ludii
Ludii-master/AI/src/utils/data_structures/experience_buffers/ExperienceBuffer.java
package utils.data_structures.experience_buffers; import java.util.List; import training.expert_iteration.ExItExperience; /** * Interface for experience buffers. Declares common methods * that we expect in uniform as well as Prioritized Experience Replay * buffers. * * @author Dennis Soemers */ public interface ExperienceBuffer { /** * Adds a new sample of experience. * Defaulting to the max observed priority level in the case of PER. * * @param experience */ public void add(final ExItExperience experience); /** * @param batchSize * @return A batch of the given batch size, sampled uniformly with * replacement. */ public List<ExItExperience> sampleExperienceBatch(final int batchSize); /** * @param batchSize * @return Sample of batchSize tuples of experience, sampled uniformly */ public List<ExItExperience> sampleExperienceBatchUniformly(final int batchSize); /** * @return Return the backing array containing ALL experience (including likely * null entries if the buffer was not completely filled). */ public ExItExperience[] allExperience(); /** * Writes this complete buffer to a binary file * @param filepath */ public void writeToFile(final String filepath); }
1,245
23.431373
81
java
Ludii
Ludii-master/AI/src/utils/data_structures/experience_buffers/PrioritizedReplayBuffer.java
package utils.data_structures.experience_buffers; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import game.Game; import game.equipment.container.Container; import other.state.container.ContainerState; import training.expert_iteration.ExItExperience; import training.expert_iteration.ExItExperience.ExItExperienceState; /** * Replay Buffer for Prioritized Experience Replay, as described * by Schaul et a.l (2015). * * Implementation based on that from Dopamine (but translated to Java): * https://github.com/google/dopamine/blob/master/dopamine/replay_memory/prioritized_replay_buffer.py * * Implementation afterwards also adjusted to bring back in some of the * hyperparameters from the original publication. Changes also inspired by stable-baselines implementation: * https://github.com/hill-a/stable-baselines/blob/master/stable_baselines/deepq/replay_buffer.py * * * @author Dennis Soemers */ public class PrioritizedReplayBuffer implements Serializable, ExperienceBuffer { //------------------------------------------------------------------------- /** */ private static final long serialVersionUID = 1L; /** Our maximum capacity */ protected final int replayCapacity; /** Our sum tree data structure */ protected final SumTree sumTree; /** This contains our data */ protected final ExItExperience[] buffer; /** How many elements did we add? */ protected long addCount; /** Hyperparameter for sampling. 0 --> uniform, 1 --> proportional to priorities */ protected final double alpha; /** Hyperparameter for importance sampling. 0 --> no correction, 1 --> full correction for bias */ protected final double beta; //------------------------------------------------------------------------- /** * Constructor. * Default hyperparam values of 0.5 for alpha as well as beta, * based on the defaults in Dopamine. * * @param replayCapacity Maximum capacity of our buffer */ public PrioritizedReplayBuffer(final int replayCapacity) { this(replayCapacity, 0.5, 0.5); } /** * Constructor * @param replayCapacity Maximum capacity of our buffer * @param alpha * @param beta */ public PrioritizedReplayBuffer(final int replayCapacity, final double alpha, final double beta) { this.replayCapacity = replayCapacity; this.sumTree = new SumTree(replayCapacity); buffer = new ExItExperience[replayCapacity]; addCount = 0L; this.alpha = alpha; this.beta = beta; } //------------------------------------------------------------------------- @Override public void add(final ExItExperience experience) { sumTree.set(cursor(), sumTree.maxRecordedPriority()); buffer[cursor()] = experience; ++addCount; } /** * Adds a new sample of experience, with given priority level. * @param experience * @param priority */ public void add(final ExItExperience experience, final float priority) { sumTree.set(cursor(), (float) Math.pow(priority, alpha)); buffer[cursor()] = experience; ++addCount; } /** * @param indices * @return Array of priorities for the given indices */ public float[] getPriorities(final int[] indices) { final float[] priorities = new float[indices.length]; for (int i = 0; i < indices.length; ++i) { priorities[i] = sumTree.get(indices[i]); } return priorities; } /** * @return True if we're empty */ public boolean isEmpty() { return addCount == 0L; } /** * @return True if we're full */ public boolean isFull() { return addCount >= replayCapacity; } /** * @return Number of samples we currently contain */ public int size() { if (isFull()) return replayCapacity; else return (int) addCount; } /** * @param batchSize * @return Sample of batchSize indices (stratified). */ public int[] sampleIndexBatch(final int batchSize) { return sumTree.stratifiedSample(batchSize); } @Override public List<ExItExperience> sampleExperienceBatch(final int batchSize) { final int numSamples = (int) Math.min(batchSize, addCount); final List<ExItExperience> batch = new ArrayList<ExItExperience>(numSamples); final int[] indices = sampleIndexBatch(numSamples); final double[] weights = new double[batchSize]; double maxWeight = Double.NEGATIVE_INFINITY; final int maxIdx = Math.min(replayCapacity, (int) addCount) - 1; for (int i = 0; i < numSamples; ++i) { // in very rare cases (when query val approximates 1.0 very very closely) // we'll sample an invalid index; we'll just round down to the last valid // index if (indices[i] > maxIdx) indices[i] = maxIdx; } final float[] priorities = getPriorities(indices); for (int i = 0; i < numSamples; ++i) { batch.add(buffer[indices[i]]); double prob = priorities[i] / sumTree.totalPriority(); weights[i] = Math.pow((1.0 / size()) * (1.0 / prob), beta); maxWeight = Math.max(maxWeight, weights[i]); } for (int i = 0; i < numSamples; ++i) { batch.get(i).setWeightPER((float) (weights[i] / maxWeight)); batch.get(i).setBufferIdx(indices[i]); } return batch; } @Override public List<ExItExperience> sampleExperienceBatchUniformly(final int batchSize) { final int numSamples = (int) Math.min(batchSize, addCount); final List<ExItExperience> batch = new ArrayList<ExItExperience>(numSamples); final int bufferSize = size(); for (int i = 0; i < numSamples; ++i) { batch.add(buffer[ThreadLocalRandom.current().nextInt(bufferSize)]); } return batch; } @Override public ExItExperience[] allExperience() { return buffer; } /** * Sets priority levels * @param indices * @param priorities */ public void setPriorities(final int[] indices, final float[] priorities) { assert (indices.length == priorities.length); for (int i = 0; i < indices.length; ++i) { if (indices[i] >= 0) sumTree.set(indices[i], (float) Math.pow(priorities[i], alpha)); } } /** * @return Our sum tree data structure. */ public SumTree sumTree() { return sumTree; } /** * @return Alpha hyperparam */ public double alpha() { return alpha; } /** * @return Beta hyperparam */ public double beta() { return beta; } //------------------------------------------------------------------------- /** * @return Number of samples we have added */ public long addCount() { return addCount; } /** * @return Index of next location that we'll write to */ public int cursor() { return (int) (addCount % replayCapacity); } //------------------------------------------------------------------------- /** * @param game * @param filepath * @return Experience buffer restored from binary file */ public static PrioritizedReplayBuffer fromFile ( final Game game, final String filepath ) { try ( final ObjectInputStream reader = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filepath))) ) { final PrioritizedReplayBuffer buffer = (PrioritizedReplayBuffer) reader.readObject(); // special handling of objects that contain game states; // we need to fix their references to containers for all ItemStates for (final ExItExperience exp : buffer.buffer) { if (exp == null) continue; final ExItExperienceState state = exp.state(); final ContainerState[] containerStates = state.state().containerStates(); for (final ContainerState containerState : containerStates) { if (containerState != null) { final String containerName = containerState.nameFromFile(); for (final Container container : game.equipment().containers()) { if (container != null && container.name().equals(containerName)) { containerState.setContainer(container); break; } } } } } return buffer; } catch (final IOException | ClassNotFoundException e) { e.printStackTrace(); } return null; } @Override public void writeToFile(final String filepath) { try ( final ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filepath))) ) { out.writeObject(this); out.flush(); out.close(); } catch (final IOException e) { e.printStackTrace(); } } //------------------------------------------------------------------------- }
8,713
23.071823
107
java
Ludii
Ludii-master/AI/src/utils/data_structures/experience_buffers/SumTree.java
package utils.data_structures.experience_buffers; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import main.collections.FVector; import main.math.BitTwiddling; //----------------------------------------------------------------------------- /** * Sum tree data structure for Prioritized Experience Replay. * * Implementation based on that from Dopamine (but translated to Java): * https://github.com/google/dopamine/blob/master/dopamine/replay_memory/sum_tree.py * * * * * A sum tree is a complete binary tree whose leaves contain values called * priorities. Internal nodes maintain the sum of the priorities of all leaf * nodes in their subtree. * For capacity = 4, the tree may look like this: * * +---+ * |2.5| * +-+-+ * | * +-------+--------+ * | | * +-+-+ +-+-+ * |1.5| |1.0| * +-+-+ +-+-+ * | | * +----+----+ +----+----+ * | | | | * +-+-+ +-+-+ +-+-+ +-+-+ * |0.5| |1.0| |0.5| |0.5| * +---+ +---+ +---+ +---+ * * This is stored in a list of FVectors: * self.nodes = [ [2.5], [1.5, 1], [0.5, 1, 0.5, 0.5] ] * For conciseness, we allocate arrays as powers of two, and pad the excess * elements with zero values. * This is similar to the usual array-based representation of a complete binary * tree, but is a little more user-friendly. * * * @author Dennis Soemers */ public class SumTree implements Serializable { //------------------------------------------------------------------------- /** */ private static final long serialVersionUID = 1L; /** Our list of nodes (stored in FVectors) */ protected final List<FVector> nodes; /** Max recorded priority throughout the tree */ protected float maxRecordedPriority; //------------------------------------------------------------------------- /** * Constructor * @param capacity */ public SumTree(final int capacity) { assert (capacity > 0); nodes = new ArrayList<FVector>(); final int treeDepth = BitTwiddling.log2RoundUp(capacity); int levelSize = 1; for (int i = 0; i < (treeDepth + 1); ++i) { final FVector nodesAtThisDepth = new FVector(levelSize); nodes.add(nodesAtThisDepth); levelSize *= 2; } assert (nodes.get(nodes.size() - 1).dim() == BitTwiddling.nextPowerOf2(capacity)); maxRecordedPriority = 1.f; } //------------------------------------------------------------------------- /** * Sample from the sum tree. * * Each element has a probability p_i / sum_j p_j of being picked, where p_i * is the (positive) value associated with node i (possibly unnormalised). * * @return Sampled index */ public int sample() { return sample(ThreadLocalRandom.current().nextDouble()); } /** * Sample from the sum tree * * Each element has a probability p_i / sum_j p_j of being picked, where p_i * is the (positive) value associated with node i (possibly unnormalised). * * @param inQueryValue A value in [0, 1], used for sampling * @return Sampled index */ public int sample(final double inQueryValue) { assert (totalPriority() != 0.f); assert (inQueryValue >= 0.0); assert (inQueryValue <= 1.0); double queryValue = inQueryValue * totalPriority(); // Traverse the sum tree int nodeIdx = 0; for (int i = 1; i < nodes.size(); ++i) { final FVector nodesAtThisDepth = nodes.get(i); // Compute children of previous depth's node. final int leftChild = nodeIdx * 2; final float leftSum = nodesAtThisDepth.get(leftChild); // Each subtree describes a range [0, a), where a is its value. if (queryValue < leftSum) // Recurse into left subtree. { nodeIdx = leftChild; } else // Recurse into right subtree. { nodeIdx = leftChild + 1; // Adjust query to be relative to right subtree. queryValue -= leftSum; } } return nodeIdx; } /** * Sample a stratified batch of given size. * * Let R be the value at the root (total value of sum tree). This method * will divide [0, R) into batchSize segments, pick a random number from * each of those segments, and use that random number to sample from the * SumTree. This is as specified in Schaul et al. (2015). * * @param batchSize * @return Array of size batchSize, sampled from the sum tree. */ public int[] stratifiedSample(final int batchSize) { assert (totalPriority() != 0.0); final FVector bounds = FVector.linspace(0.f, 1.f, batchSize + 1, true); assert (bounds.dim() == batchSize + 1); final int[] result = new int[batchSize]; for (int i = 0; i < batchSize; ++i) { final float segmentStart = bounds.get(i); final float segmentEnd = bounds.get(i + 1); final double queryVal = ThreadLocalRandom.current().nextDouble(segmentStart, segmentEnd); result[i] = sample(queryVal); } return result; } //------------------------------------------------------------------------- /** * @param nodeIdx * @return Value of the leaf node corresponding to given node index */ public float get(final int nodeIdx) { return nodes.get(nodes.size() - 1).get(nodeIdx); } /** * Sets the value of a given leaf node, and updates internal nodes accordingly. * * This operation takes O(log(capacity)). * * @param inNodeIdx Index of leaf node to be updated * @param value Nonnegative value to be assigned to node. A value * of 0 causes a node to never be sampled. */ public void set(final int inNodeIdx, final float value) { assert (value >= 0.f); int nodeIdx = inNodeIdx; maxRecordedPriority = Math.max(maxRecordedPriority, value); final float deltaValue = value - get(nodeIdx); // Now traverse back the tree, adjusting all sums along the way. for (int i = nodes.size() - 1; i >= 0; --i) { final FVector nodesAtThisDepth = nodes.get(i); nodesAtThisDepth.addToEntry(nodeIdx, deltaValue); nodeIdx /= 2; } assert (nodeIdx == 0); } /** * @return Our max recorded priority */ public float maxRecordedPriority() { return maxRecordedPriority; } //------------------------------------------------------------------------- /** * @return Total priority summed up over the entire tree */ public float totalPriority() { return nodes.get(0).get(0); } //------------------------------------------------------------------------- }
6,624
26.489627
92
java
Ludii
Ludii-master/AI/src/utils/data_structures/experience_buffers/UniformExperienceBuffer.java
package utils.data_structures.experience_buffers; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import game.Game; import game.equipment.container.Container; import other.state.container.ContainerState; import training.expert_iteration.ExItExperience; import training.expert_iteration.ExItExperience.ExItExperienceState; /** * A size-restricted, FIFO buffer to contain samples of experience. * * @author Dennis Soemers */ public class UniformExperienceBuffer implements Serializable, ExperienceBuffer { //------------------------------------------------------------------------- /** */ private static final long serialVersionUID = 1L; /** * Maximum number of elements the buffer can contain before removing * elements from the front. */ protected final int replayCapacity; /** This contains our data */ protected final ExItExperience[] buffer; /** How many elements did we add? */ protected long addCount; //------------------------------------------------------------------------- /** * Constructor * @param replayCapacity */ public UniformExperienceBuffer(final int replayCapacity) { this.replayCapacity = replayCapacity; buffer = new ExItExperience[replayCapacity]; } //------------------------------------------------------------------------- @Override public void add(final ExItExperience experience) { buffer[cursor()] = experience; ++addCount; } /** * @return True if we're empty */ public boolean isEmpty() { return addCount == 0L; } /** * @return True if we're full */ public boolean isFull() { return addCount >= replayCapacity; } /** * @return Number of samples we currently contain */ public int size() { if (isFull()) return replayCapacity; else return (int) addCount; } //------------------------------------------------------------------------- @Override public List<ExItExperience> sampleExperienceBatch(final int batchSize) { return sampleExperienceBatchUniformly(batchSize); } @Override public List<ExItExperience> sampleExperienceBatchUniformly(final int batchSize) { final int numSamples = (int) Math.min(batchSize, addCount); final List<ExItExperience> batch = new ArrayList<ExItExperience>(numSamples); final int bufferSize = size(); for (int i = 0; i < numSamples; ++i) { batch.add(buffer[ThreadLocalRandom.current().nextInt(bufferSize)]); } return batch; } @Override public ExItExperience[] allExperience() { return buffer; } //------------------------------------------------------------------------- /** * @return Index of next location that we'll write to */ private int cursor() { return (int) (addCount % replayCapacity); } //------------------------------------------------------------------------- /** * @param game * @param filepath * @return Experience buffer restored from binary file */ public static UniformExperienceBuffer fromFile ( final Game game, final String filepath ) { try ( final ObjectInputStream reader = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filepath))) ) { final UniformExperienceBuffer buffer = (UniformExperienceBuffer) reader.readObject(); // special handling of objects that contain game states; // we need to fix their references to containers for all ItemStates for (final ExItExperience exp : buffer.buffer) { if (exp == null) continue; final ExItExperienceState state = exp.state(); final ContainerState[] containerStates = state.state().containerStates(); for (final ContainerState containerState : containerStates) { if (containerState != null) { final String containerName = containerState.nameFromFile(); for (final Container container : game.equipment().containers()) { if (container != null && container.name().equals(containerName)) { containerState.setContainer(container); break; } } } } } return buffer; } catch (final IOException | ClassNotFoundException e) { e.printStackTrace(); } return null; } @Override public void writeToFile(final String filepath) { try ( final ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filepath))) ) { out.writeObject(this); out.flush(); out.close(); } catch (final IOException e) { e.printStackTrace(); } } //------------------------------------------------------------------------- }
4,915
21.865116
88
java
Ludii
Ludii-master/AI/src/utils/data_structures/ludeme_trees/LudemeTreeUtils.java
package utils.data_structures.ludeme_trees; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import main.ReflectionUtils; import other.Ludeme; import utils.data_structures.support.zhang_shasha.Node; import utils.data_structures.support.zhang_shasha.Tree; /** * Utils for building trees of Ludemes for AI purposes. * * @author Dennis Soemers */ public class LudemeTreeUtils { /** * Builds a Zhang-Shasha tree (for tree edit distance computations) for the given * root ludeme. * * @param rootLudeme * @return Tree that can be used for Zhang-Shasha tree edit distance computations */ public static Tree buildLudemeZhangShashaTree(final Ludeme rootLudeme) { if (rootLudeme == null) { return new Tree(new Node("")); } else { final Node root = buildTree(rootLudeme, new HashMap<Object, Set<String>>()); return new Tree(root); } } /** * Recursively builds tree for given ludeme * @param ludeme Root of ludemes-subtree to traverse * @param visited Map of fields we've already visited, to avoid cycles * @return Root node for the subtree rooted in given ludeme */ private static Node buildTree ( final Ludeme ludeme, final Map<Object, Set<String>> visited ) { final Class<? extends Ludeme> clazz = ludeme.getClass(); final List<Field> fields = ReflectionUtils.getAllFields(clazz); final Node node = new Node(clazz.getName()); try { for (final Field field : fields) { if (field.getName().contains("$")) continue; field.setAccessible(true); if ((field.getModifiers() & Modifier.STATIC) != 0) continue; if (visited.containsKey(ludeme) && visited.get(ludeme).contains(field.getName())) continue; // avoid stack overflow final Object value = field.get(ludeme); if (!visited.containsKey(ludeme)) visited.put(ludeme, new HashSet<String>()); visited.get(ludeme).add(field.getName()); if (value != null) { final Class<?> valueClass = value.getClass(); if (Enum.class.isAssignableFrom(valueClass)) continue; if (Ludeme.class.isAssignableFrom(valueClass)) { final Ludeme innerLudeme = (Ludeme) value; final Node child = buildTree(innerLudeme, visited); node.children.add(child); } else if (valueClass.isArray()) { final Object[] array = ReflectionUtils.castArray(value); for (final Object element : array) { if (element != null) { final Class<?> elementClass = element.getClass(); if (Ludeme.class.isAssignableFrom(elementClass)) { final Ludeme innerLudeme = (Ludeme) element; final Node child = buildTree(innerLudeme, visited); node.children.add(child); } } } } else if (Iterable.class.isAssignableFrom(valueClass)) { final Iterable<?> iterable = (Iterable<?>) value; for (final Object element : iterable) { if (element != null) { final Class<?> elementClass = element.getClass(); if (Ludeme.class.isAssignableFrom(elementClass)) { final Ludeme innerLudeme = (Ludeme) element; final Node child = buildTree(innerLudeme, visited); node.children.add(child); } } } } else if (field.getType().isPrimitive() || String.class.isAssignableFrom(valueClass)) { node.children.add(new Node(value.toString())); } } else { node.children.add(new Node("null")); } // Remove again, to avoid excessively shortening the subtree if we encounter // this object again later visited.get(ludeme).remove(field.getName()); } } catch (final IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } return node; } }
4,017
24.592357
89
java
Ludii
Ludii-master/AI/src/utils/data_structures/support/zhang_shasha/Main.java
package utils.data_structures.support.zhang_shasha; /** * Code originally from: https://github.com/ijkilchenko/ZhangShasha * * Afterwards modified for style / various improvements * * @author Dennis Soemers */ public class Main { public static void main(String[] args) { // Sample trees (in preorder). String tree1Str1 = "f(d(a c(b)) e)"; String tree1Str2 = "f(c(d(a b)) e)"; // Distance: 2 (main example used in the Zhang-Shasha paper) String tree1Str3 = "a(b(c d) e(f g(i)))"; String tree1Str4 = "a(b(c d) e(f g(h)))"; // Distance: 1 String tree1Str5 = "d"; String tree1Str6 = "g(h)"; // Distance: 2 Tree tree1 = new Tree(tree1Str1); Tree tree2 = new Tree(tree1Str2); Tree tree3 = new Tree(tree1Str3); Tree tree4 = new Tree(tree1Str4); Tree tree5 = new Tree(tree1Str5); Tree tree6 = new Tree(tree1Str6); int distance1 = Tree.ZhangShasha(tree1, tree2); System.out.println("Expected 2; got " + distance1); int distance2 = Tree.ZhangShasha(tree3, tree4); System.out.println("Expected 1; got " + distance2); int distance3 = Tree.ZhangShasha(tree5, tree6); System.out.println("Expected 2; got " + distance3); //---------------------------------------- final String a = "game(TicTacToe players(a))"; final String b = "game(TicTacToe players(b))"; final Tree ta = new Tree(a); final Tree tb = new Tree(b); int dist = Tree.ZhangShasha(ta, tb); System.out.println("dist=" + dist + "."); final String ttt1 = "game(\"Tic-Tac-Toe\" "+ " players(\"2\") " + " equipment( " + " board(square(\"3\")) " + " piece(\"Disc\" P1) " + " piece(\"Cross\" P2) " + " ) " + " rules( " + " play(add(empty)) " + " end(if(isLine(\"3\") result(Mover Win))) " + " )" + ")"; final Tree treeA = new Tree(ttt1); System.out.println("treeA: " + treeA); final String ttt1a = "game(\"Tic-Tac-Toe\" "+ " players(\"2\") " + " equipment( " + " board(hexagon(\"3\")) " + " piece(\"Disc\" P1) " + " piece(\"Cross\" P2) " + " ) " + " rules( " + " play(add(empty)) " + " end(if(isLine(\"4\") result(Mover Win))) " + " )" + ")"; final Tree treeAa = new Tree(ttt1a); System.out.println("treeAa: " + treeAa); int distX = Tree.ZhangShasha(treeA, treeA); int distY = Tree.ZhangShasha(treeA, treeAa); System.out.println("distX=" + distX + ", distY=" + distY + "."); final String ttt2 = "(game \"Tic-Tac-Toe\" " + " (players 2) " + " (equipment { " + " (board (hexagon 3)) " + " (piece \"Disc\" P1) " + " (piece \"Cross\" P2) " + " }) " + " (rules " + " (play (add (empty))) " + " (end (if (isLine 3) (result Mover Win))) " + " )" + ")"; final Tree treeB = new Tree(ttt2); System.out.println("treeB: " + treeB); final String hex = "(game \"Hex\" " + " (players 2) " + " (equipment { " + " (board (rhombus 11)) " + " (piece \"Ball\" Each) " + " (regions P1 { (sites Side NE) (sites Side SW) } ) " + " (regions P2 { (sites Side NW) (sites Side SE) } ) " + " }) " + " (rules " + " (meta (swap)) " + " (play (add (empty))) " + " (end (if (isConnected Mover) (result Mover Win))) " + " ) " + ")"; final Tree treeC = new Tree(hex); System.out.println("treeC: " + treeC); int distAA = Tree.ZhangShasha(treeA, treeA); int distAB = Tree.ZhangShasha(treeA, treeB); int distAC = Tree.ZhangShasha(treeA, treeC); int distBC = Tree.ZhangShasha(treeB, treeC); int distBA = Tree.ZhangShasha(treeB, treeA); int distCA = Tree.ZhangShasha(treeC, treeA); int distCB = Tree.ZhangShasha(treeC, treeB); System.out.println("distAA=" + distAA + "."); System.out.println("distAB=" + distAB + ", distAC=" + distAC + ", distBC=" + distBC + "."); System.out.println("distBA=" + distBA + ", distCA=" + distCA + ", distCB=" + distCB + "."); } }
4,312
29.160839
93
java
Ludii
Ludii-master/AI/src/utils/data_structures/support/zhang_shasha/Node.java
package utils.data_structures.support.zhang_shasha; import java.util.ArrayList; /** * Code originally from: https://github.com/ijkilchenko/ZhangShasha * * Afterwards modified for style / various improvements * * @author Dennis Soemers */ public class Node { /** Label of this node */ public String label; /** Index of this node for pre-order traversal of tree */ public int index; // note: trees need not be binary /** List of children */ public ArrayList<Node> children = new ArrayList<Node>(); /** Leftmost node in subtree rooted in this node (or this node if it's a leaf) */ public Node leftmost; // Used by the recursive O(n) leftmost() function /** * Constructor */ public Node() { // Do nothing } /** * Constructor * @param label */ public Node(final String label) { this.label = label; } }
854
17.586957
82
java
Ludii
Ludii-master/AI/src/utils/data_structures/support/zhang_shasha/Tree.java
package utils.data_structures.support.zhang_shasha; import java.io.IOException; import java.io.StreamTokenizer; import java.io.StringReader; import java.util.ArrayList; import gnu.trove.list.array.TIntArrayList; /** * Code originally from: https://github.com/ijkilchenko/ZhangShasha * * Afterwards modified for style / various improvements * * @author Dennis Soemers */ public class Tree { //--------------------------------------------------------------------- Node root = new Node(); // function l() which gives the leftmost child TIntArrayList l = new TIntArrayList(); /** List of keyroots, i.e., nodes with a left child and the tree root */ TIntArrayList keyroots = new TIntArrayList(); /** List of the labels of the nodes used for node comparison */ ArrayList<String> labels = new ArrayList<String>(); //--------------------------------------------------------------------- /** * Constructor for tree described in preorder notation, e.g. f(a b(c)) * @param s */ public Tree(final String s) { try { final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(s)); tokenizer.nextToken(); root = parseString(root, tokenizer); if (tokenizer.ttype != StreamTokenizer.TT_EOF) { throw new RuntimeException("Leftover token: " + tokenizer.ttype); } } catch (final Exception e) { e.printStackTrace(); } } /** * Constructor with root already given * @param root */ public Tree(final Node root) { this.root = root; } //--------------------------------------------------------------------- private static Node parseString(final Node node, final StreamTokenizer tokenizer) throws IOException { node.label = tokenizer.sval; tokenizer.nextToken(); if (tokenizer.ttype == '(') { tokenizer.nextToken(); do { node.children.add(parseString(new Node(), tokenizer)); } while (tokenizer.ttype != ')'); tokenizer.nextToken(); } return node; } public void traverse() { // put together an ordered list of node labels of the tree traverse(root, labels); } private static void traverse(final Node node, final ArrayList<String> labels) { for (int i = 0; i < node.children.size(); i++) { traverse(node.children.get(i), labels); } labels.add(node.label); } public void index() { // index each node in the tree according to traversal method index(root, 0); } private static int index(final Node node, final int indexIn) { int index = indexIn; for (int i = 0; i < node.children.size(); i++) { index = index(node.children.get(i), index); } index++; node.index = index; return index; } public void l() { // put together a function which gives l() leftmost(); l = new TIntArrayList(); l(root, l); } private void l(final Node node, final TIntArrayList ll) { for (int i = 0; i < node.children.size(); i++) { l(node.children.get(i), ll); } ll.add(node.leftmost.index); } private void leftmost() { leftmost(root); } private static void leftmost(final Node node) { if (node == null) return; for (int i = 0; i < node.children.size(); i++) { leftmost(node.children.get(i)); } if (node.children.size() == 0) { node.leftmost = node; } else { node.leftmost = node.children.get(0).leftmost; } } public void keyroots() { // calculate the keyroots for (int i = 0; i < l.size(); i++) { int flag = 0; for (int j = i + 1; j < l.size(); j++) { if (l.getQuick(j) == l.getQuick(i)) { flag = 1; } } if (flag == 0) { keyroots.add(i + 1); } } } public int size() { int treeSize = 1; for (final Node n : root.children) { treeSize += 1; treeSize += size(n); } return treeSize; } private int size(final Node parent) { int treeSize = 1; for (final Node child : parent.children) { treeSize += 1; treeSize += size(child); } return treeSize; } //--------------------------------------------------------------------- public static int ZhangShasha(final Tree tree1, final Tree tree2) { tree1.index(); tree1.l(); tree1.keyroots(); tree1.traverse(); tree2.index(); tree2.l(); tree2.keyroots(); tree2.traverse(); final TIntArrayList l1 = tree1.l; final TIntArrayList keyroots1 = tree1.keyroots; final TIntArrayList l2 = tree2.l; final TIntArrayList keyroots2 = tree2.keyroots; // space complexity of the algorithm final int[][] TD = new int[l1.size() + 1][l2.size() + 1]; // solve subproblems for (int i1 = 1; i1 < keyroots1.size() + 1; i1++) { for (int j1 = 1; j1 < keyroots2.size() + 1; j1++) { final int i = keyroots1.getQuick(i1 - 1); final int j = keyroots2.getQuick(j1 - 1); TD[i][j] = treedist(l1, l2, i, j, tree1, tree2, TD); } } return TD[l1.size()][l2.size()]; } private static int treedist ( final TIntArrayList l1, final TIntArrayList l2, final int i, final int j, final Tree tree1, final Tree tree2, final int[][] TD ) { final int[][] forestdist = new int[i + 1][j + 1]; // costs of the three atomic operations final int Delete = 1; final int Insert = 1; final int Relabel = 1; forestdist[0][0] = 0; for (int i1 = l1.getQuick(i - 1); i1 <= i; i1++) { forestdist[i1][0] = forestdist[i1 - 1][0] + Delete; } for (int j1 = l2.getQuick(j - 1); j1 <= j; j1++) { forestdist[0][j1] = forestdist[0][j1 - 1] + Insert; } for (int i1 = l1.getQuick(i - 1); i1 <= i; i1++) { for (int j1 = l2.getQuick(j - 1); j1 <= j; j1++) { final int i_temp = (l1.getQuick(i - 1) > i1 - 1) ? 0 : i1 - 1; final int j_temp = (l2.getQuick(j - 1) > j1 - 1) ? 0 : j1 - 1; if ((l1.getQuick(i1 - 1) == l1.getQuick(i - 1)) && (l2.getQuick(j1 - 1) == l2.get(j - 1))) { final int Cost = (tree1.labels.get(i1 - 1).equals(tree2.labels.get(j1 - 1))) ? 0 : Relabel; forestdist[i1][j1] = Math.min( Math.min(forestdist[i_temp][j1] + Delete, forestdist[i1][j_temp] + Insert), forestdist[i_temp][j_temp] + Cost); TD[i1][j1] = forestdist[i1][j1]; } else { final int i1_temp = l1.getQuick(i1 - 1) - 1; final int j1_temp = l2.getQuick(j1 - 1) - 1; final int i_temp2 = (l1.getQuick(i - 1) > i1_temp) ? 0 : i1_temp; final int j_temp2 = (l2.getQuick(j - 1) > j1_temp) ? 0 : j1_temp; forestdist[i1][j1] = Math.min( Math.min(forestdist[i_temp][j1] + Delete, forestdist[i1][j_temp] + Insert), forestdist[i_temp2][j_temp2] + TD[i1][j1]); } } } return forestdist[i][j]; } //--------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); toString(root, sb, 0); return sb.toString(); } private static void toString(final Node node, final StringBuilder sb, final int indent) { for (int i = 0; i < indent; ++i) { sb.append(" "); } sb.append(node.label + "\n"); for (final Node child : node.children) { toString(child, sb, indent + 2); } } //--------------------------------------------------------------------- public String bracketNotation() { final StringBuilder sb = new StringBuilder(); bracketNotation(root, sb); return sb.toString(); } private static void bracketNotation(final Node node, final StringBuilder sb) { sb.append("{" + node.label); for (final Node child : node.children) { bracketNotation(child, sb); } sb.append("}"); } //--------------------------------------------------------------------- }
7,616
21.402941
102
java
Ludii
Ludii-master/AI/src/utils/data_structures/transposition_table/TranspositionTable.java
package utils.data_structures.transposition_table; import other.move.Move; /** * Transposition table for Alpha-Beta search. * * @author Dennis Soemers */ public class TranspositionTable { //------------------------------------------------------------------------- /** An invalid value stored in Transposition Table */ public final static byte INVALID_VALUE = (byte) 0x0; /** An exact (maybe heuristic) value stored in Transposition Table */ public final static byte EXACT_VALUE = (byte) 0x1; /** A lower bound stored in Transposition Table */ public final static byte LOWER_BOUND = (byte) (0x1 << 1); /** A upper bound stored in Transposition Table */ public final static byte UPPER_BOUND = (byte) (0x1 << 2); //------------------------------------------------------------------------- /** Number of bits from hashes to use as primary code */ private final int numBitsPrimaryCode; /** Max number of entries for which we've allocated space */ private final int maxNumEntries; /** Our table of entries */ private ABTTEntry[] table; //------------------------------------------------------------------------- /** * Constructor. * * NOTE: does not yet allocate memory! * * @param numBitsPrimaryCode Number of bits from hashes to use as primary code. */ public TranspositionTable(final int numBitsPrimaryCode) { this.numBitsPrimaryCode = numBitsPrimaryCode; maxNumEntries = 1 << numBitsPrimaryCode; table = null; } //------------------------------------------------------------------------- /** * Allocates a brand new table with space for 2^(numBitsPrimaryCode) entries. */ public void allocate() { table = new ABTTEntry[maxNumEntries]; } /** * Clears up all memory of our table */ public void deallocate() { table = null; } /** * @param fullHash * @return Stored data for given full hash (full 64bits code), or null if not found */ public ABTTData retrieve(final long fullHash) { final ABTTEntry entry = table[(int) (fullHash >>> (Long.SIZE - numBitsPrimaryCode))]; if (entry == null) return null; if (entry.data1 != null && entry.data1.fullHash == fullHash) return entry.data1; if (entry.data2 != null && entry.data2.fullHash == fullHash) return entry.data2; return null; } /** * Stores new data for given full hash (full 64bits code) * @param bestMove * @param fullHash * @param value * @param depth * @param valueType */ public void store ( final Move bestMove, final long fullHash, final float value, final int depth, final byte valueType ) { final int idx = (int) (fullHash >>> (Long.SIZE - numBitsPrimaryCode)); ABTTEntry entry = table[idx]; if (entry == null) { entry = new ABTTEntry(); entry.data1 = new ABTTData(bestMove, fullHash, value, depth, valueType); table[idx] = entry; } else { // See if we have empty slots in data if (entry.data1 == null) { entry.data1 = new ABTTData(bestMove, fullHash, value, depth, valueType); return; } else if (entry.data2 == null) { entry.data2 = new ABTTData(bestMove, fullHash, value, depth, valueType); return; } // Check if one of them has an identical full hash value, and if so, // prefer data with largest search depth if (entry.data1.fullHash == fullHash) { if (depth > entry.data1.depth) // Only change data if we've searched to a deeper depth now { entry.data1.bestMove = bestMove; entry.data1.depth = depth; entry.data1.fullHash = fullHash; entry.data1.value = value; entry.data1.valueType = valueType; } return; } else if (entry.data2.fullHash == fullHash) { if (depth > entry.data2.depth) // Only change data if we've searched to a deeper depth now { entry.data2.bestMove = bestMove; entry.data2.depth = depth; entry.data2.fullHash = fullHash; entry.data2.value = value; entry.data2.valueType = valueType; } return; } // Both slots already filled, so replace whichever has the lowest depth if (entry.data1.depth < entry.data2.depth) // Slot 1 searched less deep than slot 2, so replace that { entry.data1.bestMove = bestMove; entry.data1.depth = depth; entry.data1.fullHash = fullHash; entry.data1.value = value; entry.data1.valueType = valueType; } else if (entry.data2.depth < entry.data1.depth) // Slot 2 searched less deep than slot 1, so replace that { entry.data2.bestMove = bestMove; entry.data2.depth = depth; entry.data2.fullHash = fullHash; entry.data2.value = value; entry.data2.valueType = valueType; } else // Both existing slots have equal search depth, move data from 1 to 2 and then replace 1 { entry.data2.bestMove = entry.data1.bestMove; entry.data2.depth = entry.data1.depth; entry.data2.fullHash = entry.data1.fullHash; entry.data2.value = entry.data1.value; entry.data2.valueType = entry.data1.valueType; entry.data1.bestMove = bestMove; entry.data1.depth = depth; entry.data1.fullHash = fullHash; entry.data1.value = value; entry.data1.valueType = valueType; } } } //------------------------------------------------------------------------- /** * Data we wish to store in TT entries for Alpha-Beta Search * * @author Dennis Soemers */ public static final class ABTTData { /** The best move according to previous AB search */ public Move bestMove = null; /** Full 64bits hash code for which this data was stored */ public long fullHash = -1L; /** The (maybe heuristic) value stored in Table */ public float value = Float.NaN; /** The depth to which the search tree was explored below the node corresponding to this data */ public int depth = -1; /** The type of value stored */ public byte valueType = INVALID_VALUE; /** * Constructor * @param bestMove * @param fullHash * @param value * @param depth * @param valueType */ public ABTTData ( final Move bestMove, final long fullHash, final float value, final int depth, final byte valueType ) { this.bestMove = bestMove; this.fullHash = fullHash; this.value = value; this.depth = depth; this.valueType = valueType; } } //------------------------------------------------------------------------- public int nbEntries() // (counts entries with double data as 1 entry) { int res = 0; for (int i=0; i<maxNumEntries; i++) { if (table[i]!=null) res += 1; } return res; } public void dispValueStats() // (counts entries with double data as 1 entry) { int maxDepth = 0; for (int i=0; i<maxNumEntries; i++) { if (table[i]!=null) { if (table[i].data1!=null) { if (table[i].data1.depth>maxDepth) maxDepth = table[i].data1.depth; } if (table[i].data2!=null) { if (table[i].data2.depth>maxDepth) maxDepth = table[i].data2.depth; } } } int[][] counters = new int[maxDepth+1][6]; for (int i=0; i<maxNumEntries; i++) { if (table[i]!=null) { if (table[i].data1!=null) { int index = table[i].data1.valueType; switch (index) { case 0: break; case 1: break; case 2: break; case 4: break; default: index = 5; } counters[table[i].data1.depth][index] += 1; } if (table[i].data2!=null) { int index = table[i].data2.valueType; switch (index) { case 0: break; case 1: break; case 2: break; case 4: break; default: index = 5; } counters[table[i].data2.depth][index] += 1; } } } System.out.println("Search tree analysis:"); for (int i=1; i<maxDepth; i++) { System.out.print("At depth "+i+": "); for (int k : new int[]{0,1,2,4}) { System.out.print("value "+k+": "+counters[i][k]+", "); } System.out.println(); } } //------------------------------------------------------------------------- /** * An entry in a Transposition Table for Alpha-Beta. Every entry contains * two slots. * * @author Dennis Soemers */ public static final class ABTTEntry { /** Data in our entry's first slot */ public ABTTData data1 = null; /** Data in our entry's second slot */ public ABTTData data2 = null; } //------------------------------------------------------------------------- }
8,460
23.812317
110
java
Ludii
Ludii-master/AI/src/utils/data_structures/transposition_table/TranspositionTableUBFM.java
package utils.data_structures.transposition_table; import java.util.ArrayList; import java.util.List; import utils.data_structures.ScoredMove; /** * Transposition table for Unbounded Best-First Minimax. Works as a hash tables, where the beginning of the hash code * points to an entry which contains a list of data. * * @author cyprien */ public class TranspositionTableUBFM { //------------------------------------------------------------------------- /** An invalid value stored in Transposition Table */ public final static byte INVALID_VALUE = (byte) 0x0; /** An exact (maybe heuristic) value stored in Transposition Table */ public final static byte EXACT_VALUE = (byte) 0x1; /** An exact value marked (only used by the heuristic learning code) */ public final static byte MARKED = (byte) (0x1 << 1); /** An exact value validated (only used by the heuristic learning code) */ public final static byte VALIDATED = (byte) (0x1 << 2); //------------------------------------------------------------------------- /** Number of bits from hashes to use as primary code */ private final int numBitsPrimaryCode; /** Max number of entries for which we've allocated space */ private final int maxNumEntries; /** Our table of entries */ private UBFMTTEntry[] table; //------------------------------------------------------------------------- /** * Constructor. * * NOTE: does not yet allocate memory! * * @param numBitsPrimaryCode Number of bits from hashes to use as primary code. */ public TranspositionTableUBFM(final int numBitsPrimaryCode) { this.numBitsPrimaryCode = numBitsPrimaryCode; maxNumEntries = 1 << numBitsPrimaryCode; table = null; } //------------------------------------------------------------------------- /** * Allocates a brand new table with space for 2^(numBitsPrimaryCode) entries. */ public void allocate() { table = new UBFMTTEntry[maxNumEntries]; } /** * Clears up all memory of our table */ public void deallocate() { table = null; } /** * Return true if and only if the table is allocated */ public boolean isAllocated() { return (table != null); } /** * @param fullHash * @return Stored data for given full hash (full 64bits code), or null if not found */ public UBFMTTData retrieve(final long fullHash) { final UBFMTTEntry entry = table[(int) (fullHash >>> (Long.SIZE - numBitsPrimaryCode))]; if (entry != null) { for (UBFMTTData data : entry.data) { if (data.fullHash == fullHash) return data; } } return null; } /** * Stores new data for given full hash (full 64bits code) * @param fullHash * @param value * @param depth * @param valueType */ public void store ( final long fullHash, final float value, final int depth, final byte valueType, final List<ScoredMove> sortedScoredMoves ) { final int idx = (int) (fullHash >>> (Long.SIZE - numBitsPrimaryCode)); UBFMTTEntry entry = table[idx]; if (entry == null) { entry = new UBFMTTEntry(); entry.data.add(new UBFMTTData(fullHash, value, depth, valueType, sortedScoredMoves)); table[idx] = entry; } else { UBFMTTData dataToSave = new UBFMTTData(fullHash, value, depth, valueType, sortedScoredMoves); // We erase a previous entry if it has the same fullHash for (int i =0; i<entry.data.size(); i++) { UBFMTTData data = entry.data.get(i); if (data.fullHash == fullHash) { // is the previous entry properly erased from memory? entry.data.set(i, dataToSave); return; } } // If we arrive to this point it means that we had no previous data about this fullHash entry.data.add(dataToSave); } } //------------------------------------------------------------------------- /** * Data we wish to store in TT entries for Alpha-Beta Search * * @author cyprien */ public static final class UBFMTTData { /** Full 64bits hash code for which this data was stored */ public long fullHash = -1L; /** The (maybe heuristic) value stored in Table */ public float value = Float.NaN; /** The depth to which the search tree was explored below the node corresponding to this data */ public int depth = -1; /** The type of value stored */ public byte valueType = INVALID_VALUE; /** The list of possible moves at this position, with their scores, sorted (can be null if we don't know) */ public List<ScoredMove> sortedScoredMoves = null; /** * Constructor * @param fullHash * @param value * @param depth * @param valueType */ public UBFMTTData ( final long fullHash, final float value, final int depth, final byte valueType, final List<ScoredMove> sortedScoredMoves ) { this.fullHash = fullHash; this.value = value; this.depth = depth; this.valueType = valueType; this.sortedScoredMoves = sortedScoredMoves; } } //------------------------------------------------------------------------- public int nbEntries() { int res = 0; for (int i=0; i<maxNumEntries; i++) { if (table[i] != null) res += table[i].data.size(); } return res; } public int nbMarkedEntries() { int res = 0; for (int i=0; i<maxNumEntries; i++) if (table[i] != null) for (UBFMTTData entry : table[i].data) if (entry.valueType == MARKED) res += 1; return res; } public void dispValueStats() // (counts entries with double data as 1 entry) { System.out.println("Number of entries:"+Integer.toString(nbEntries())); int maxDepth = 0; for (int i=0; i<maxNumEntries; i++) { if (table[i]!=null) { for (UBFMTTData data : table[i].data) { if (data.depth>maxDepth) maxDepth = data.depth; } } } int[][] counters = new int[maxDepth+1][7]; for (int i=0; i<maxNumEntries; i++) { if (table[i]!=null) { for (UBFMTTData data : table[i].data) { int index = data.valueType; switch (index) { case 0: break; case 1: break; case 2: break; case 4: index = 3; break; case 8: index = 4; break; case 16: index = 5; break; default: index = 6; } counters[data.depth][index] += 1; } } } System.out.println("Search tree analysis:"); for (int i=0; i<maxDepth; i++) { System.out.print("At depth "+i+": "); for (int k : new int[]{0,1,2,4,5,6}) { System.out.print("value "+k+": "+counters[i][k]+", "); } System.out.println(); } } //------------------------------------------------------------------------- /** * An entry in a Transposition Table for Alpha-Beta. Every entry can contain any number * of slots (BFSTTData). * * @author cyprien */ public static final class UBFMTTEntry { /** Data in our entry's first slot */ public List<UBFMTTData> data = new ArrayList<UBFMTTData>(3); } }
6,919
22.862069
117
java
Ludii
Ludii-master/AI/src/utils/experiments/InterruptableExperiment.java
package utils.experiments; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.time.LocalDateTime; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants; /** * A wrapper around a (long) interruptible experiment. This class * provides a small, simple frame with a button that can be used to set a boolean * "interrupted" flag to true. An abstract method can be overridden by subclasses * to run an experiment. Inside that method, subclasses can periodically check the * flag, and cleanly interrupt the experiment (after performing any required * file saving etc.) if the button has been pressed. * * The complete GUI functionality can also be disabled (which allows the same experiment * code to run in headless mode on cluster for example). * * @author Dennis Soemers */ public abstract class InterruptableExperiment { //------------------------------------------------------------------------- /** Flag which will be set to true if the interrupt button is pressed */ protected boolean interrupted = false; /** Start time of experiment (in milliseconds) */ protected final long experimentStartTime; /** Maximum wall time we're allowed to run for (in milliseconds) */ protected final long maxWallTimeMs; //------------------------------------------------------------------------- /** * Creates an "interruptible" experiment (with button to interrupt * experiment if useGUI = True), which will then also immediately * start running. * * @param useGUI */ public InterruptableExperiment(final boolean useGUI) { this(useGUI, -1); } /** * Creates an "interruptible" experiment (with button to interrupt * experiment if useGUI = True), which will then also immediately * start running. * * Using the checkWallTime() method, the experiment can also automatically * interrupt itself and exit cleanly before getting interrupted in a * not-clean manner due to exceeding wall time (e.g. on cluster) * * @param useGUI * @param maxWallTime Maximum wall time (in minutes) */ public InterruptableExperiment(final boolean useGUI, final int maxWallTime) { JFrame frame = null; experimentStartTime = System.currentTimeMillis(); maxWallTimeMs = 60L * 1000L * maxWallTime; if (useGUI) { frame = new JFrame("Ludii Interruptible Experiment"); frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { interrupted = true; } }); // Logo try { final URL resource = this.getClass().getResource("/ludii-logo-100x100.png"); final BufferedImage image = ImageIO.read(resource); frame.setIconImage(image); } catch (final IOException e) { e.printStackTrace(); } final JPanel panel = new JPanel(new GridLayout()); final JButton interruptButton = new JButton("Interrupt Experiment"); interruptButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { interrupted = true; } }); panel.add(interruptButton); frame.setContentPane(panel); frame.setSize(600, 250); frame.setLocationRelativeTo(null); frame.setVisible(true); } try { runExperiment(); } finally { if (frame != null) { frame.dispose(); } } } //------------------------------------------------------------------------- /** Implement experiment code here */ public abstract void runExperiment(); //------------------------------------------------------------------------- /** * Checks if we're about to exceed maximum wall time, and automatically * sets the interrupted flag if we are. * * @param safetyBuffer Ratio of maximum wall time that we're willing to * throw away just to be safe (0.01 or 0.05 should be good values) */ public void checkWallTime(final double safetyBuffer) { if (maxWallTimeMs > 0) { final long terminateAt = (long) (experimentStartTime + (1.0 - safetyBuffer) * maxWallTimeMs); if (System.currentTimeMillis() >= terminateAt) { interrupted = true; } } } /** * Utility method that uses a given PrintWriter to print a single given * line to a log, but with the current time prepended. * @param logWriter * @param line */ @SuppressWarnings("static-method") public void logLine(final PrintWriter logWriter, final String line) { if (logWriter != null) { logWriter.println ( String.format ( "[%s]: %s", LocalDateTime.now(), line ) ); } } /** * @return Do we want to be interrupted? */ public boolean wantsInterrupt() { return interrupted; } //------------------------------------------------------------------------- }
5,139
24.445545
88
java
Ludii
Ludii-master/AI/src/utils/experiments/ResultsSummary.java
package utils.experiments; import java.io.File; import java.io.FileNotFoundException; 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 game.Game; import gnu.trove.map.TObjectIntMap; import gnu.trove.map.hash.TObjectIntHashMap; import main.math.statistics.Stats; /** * A summary of results for multiple played games. Thread-safe. * * @author Dennis Soemers */ public class ResultsSummary { //------------------------------------------------------------------------- /** List of names / descriptions / string-representations of agents */ protected final List<String> agents; /** Points per agent (regardless of player number). Wins = 1, draws = 0.5, losses = 0. */ protected Stats[] agentPoints; /** Points per agent per player number. Wins = 1, draws = 0.5, losses = 0. */ protected Stats[][] agentPointsPerPlayer; /** For every game in which the agent played, the duration (in number of decisions) */ protected Stats[] agentGameDurations; /** For every game in which the agent played per player number, the duration (in number of decisions) */ protected Stats[][] agentGameDurationsPerPlayer; /** Map from matchup lists to arrays of sums of payoffs */ protected Map<List<String>, double[]> matchupPayoffsMap; /** Map from matchup arrays to counts of how frequently we observed that matchup */ protected TObjectIntMap<List<String>> matchupCountsMap; //------------------------------------------------------------------------- /** * Construct a new object to collect a summary of results for a * larger number of games being played * @param game * @param agents */ public ResultsSummary(final Game game, final List<String> agents) { this.agents = agents; final int numPlayers = game.players().count(); agentPoints = new Stats[agents.size()]; agentPointsPerPlayer = new Stats[agents.size()][numPlayers + 1]; agentGameDurations = new Stats[agents.size()]; agentGameDurationsPerPlayer = new Stats[agents.size()][numPlayers + 1]; for (int i = 0; i < agents.size(); ++i) { agentPoints()[i] = new Stats(agents.get(i) + " points"); agentGameDurations[i] = new Stats(agents.get(i) + " game durations"); for (int p = 1; p <= numPlayers; ++p) { agentPointsPerPlayer[i][p] = new Stats(agents.get(i) + " points as P" + p); agentGameDurationsPerPlayer[i][p] = new Stats(agents.get(i) + " game durations as P" + p); } } matchupPayoffsMap = new HashMap<List<String>, double[]>(); matchupCountsMap = new TObjectIntHashMap<List<String>>(); } //------------------------------------------------------------------------- /** * Records the results from a played game * @param agentPermutation * Array giving us the original agent index for every player index 1 <= p <= numPlayers * @param utilities * Array of utilities for the players * @param gameDuration * Number of moves made in the game */ public synchronized void recordResults ( final int[] agentPermutation, final double[] utilities, final int gameDuration ) { for (int p = 1; p < agentPermutation.length; ++p) { // Convert utility from [-1.0, 1.0] to [0.0, 1.0] final double points = (utilities[p] + 1.0) / 2.0; final int agentNumber = agentPermutation[p]; agentPoints()[agentNumber].addSample(points); agentPointsPerPlayer[agentNumber][p].addSample(points); agentGameDurations[agentNumber].addSample(gameDuration); agentGameDurationsPerPlayer[agentNumber][p].addSample(gameDuration); } final List<String> agentsList = new ArrayList<String>(agentPermutation.length - 1); for (int p = 1; p < agentPermutation.length; ++p) { agentsList.add(agents.get(agentPermutation[p])); } if (!matchupPayoffsMap.containsKey(agentsList)) { matchupPayoffsMap.put(agentsList, new double[utilities.length - 1]); } matchupCountsMap.adjustOrPutValue(agentsList, +1, 1); final double[] sumUtils = matchupPayoffsMap.get(agentsList); for (int p = 1; p < utilities.length; ++p) { sumUtils[p - 1] += utilities[p]; } } //------------------------------------------------------------------------- /** * @param agentName * @return Score averaged over all games, all agents with name equal to * given name. */ public synchronized double avgScoreForAgentName(final String agentName) { double sumScores = 0.0; int sumNumGames = 0; for (int i = 0; i < agents.size(); ++i) { if (agents.get(i).equals(agentName)) { agentPoints()[i].measure(); sumScores += agentPoints()[i].sum(); sumNumGames += agentPoints()[i].n(); } } return sumScores / sumNumGames; } //------------------------------------------------------------------------- /** * Generates an intermediate summary of results. * @return The generated summary */ public synchronized String generateIntermediateSummary() { final StringBuilder sb = new StringBuilder(); sb.append("=====================================================\n"); int totGamesPlayed = 0; for (int i = 0; i < agentPointsPerPlayer.length; ++i) { totGamesPlayed += agentPointsPerPlayer[i][1].n(); } sb.append("Completed " + totGamesPlayed + " games.\n"); sb.append("\n"); for (int i = 0; i < agents.size(); ++i) { sb.append("Agent " + (i+1) + " (" + agents.get(i) + ")\n"); agentPoints()[i].measure(); sb.append("Winning score (between 0 and 1) " + agentPoints()[i] + "\n"); for (int p = 1; p < agentPointsPerPlayer[i].length; ++p) { agentPointsPerPlayer[i][p].measure(); sb.append("P" + p + agentPointsPerPlayer[i][p] + "\n"); } agentGameDurations[i].measure(); sb.append("Game Durations" + agentGameDurations[i] + "\n"); for (int p = 1; p < agentGameDurationsPerPlayer[i].length; ++p) { agentGameDurationsPerPlayer[i][p].measure(); sb.append("P" + p + agentGameDurationsPerPlayer[i][p] + "\n"); } if (i < agents.size() - 1) { sb.append("\n"); } } sb.append("=====================================================\n"); return sb.toString(); } //------------------------------------------------------------------------- /** * Writes results data for processing by the OpenSpiel implementation of alpha-rank, * to a .csv file. * * @param outFile */ public synchronized void writeAlphaRankData(final File outFile) { try (final PrintWriter writer = new PrintWriter(outFile, "UTF-8")) { writer.write("agents,scores\n"); for (final List<String> matchup : matchupPayoffsMap.keySet()) { final StringBuilder agentTuple = new StringBuilder(); agentTuple.append("\"("); for (int i = 0; i < matchup.size(); ++i) { if (i > 0) agentTuple.append(", "); agentTuple.append("'"); agentTuple.append(matchup.get(i)); agentTuple.append("'"); } agentTuple.append(")\""); final double[] scoreSums = matchupPayoffsMap.get(matchup); final int count = matchupCountsMap.get(matchup); final double[] avgScores = Arrays.copyOf(scoreSums, scoreSums.length); for (int i = 0; i < avgScores.length; ++i) { avgScores[i] /= count; } final StringBuilder scoreTuple = new StringBuilder(); scoreTuple.append("\"("); for (int i = 0; i < avgScores.length; ++i) { if (i > 0) scoreTuple.append(", "); scoreTuple.append(avgScores[i]); } scoreTuple.append(")\""); writer.write(agentTuple + "," + scoreTuple + "\n"); } } catch (final FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } //------------------------------------------------------------------------- public synchronized Stats[] agentPoints() { return agentPoints; } //------------------------------------------------------------------------- }
8,035
27.39576
105
java
Ludii
Ludii-master/Common/src/annotations/Alias.java
package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Alias to use for keyword in grammar instead of class. * @author cambolbro */ @Retention(RetentionPolicy.RUNTIME) public @interface Alias { public String alias() default ""; }
292
18.533333
56
java
Ludii
Ludii-master/Common/src/annotations/And.java
package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Named parameter in the grammar. * * @author cambolbro */ @Retention(RetentionPolicy.RUNTIME) public @interface And { // ... }
246
14.4375
44
java
Ludii
Ludii-master/Common/src/annotations/And2.java
package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Named parameter in the grammar. * * @author cambolbro */ @Retention(RetentionPolicy.RUNTIME) public @interface And2 { // ... }
247
14.5
44
java
Ludii
Ludii-master/Common/src/annotations/Anon.java
package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Anonymous parameter in the grammar, i.e. parameter name is not shown or * bracketed. * @author cambolbro */ @Retention(RetentionPolicy.RUNTIME) public @interface Anon { // ... }
297
17.625
74
java
Ludii
Ludii-master/Common/src/annotations/Hide.java
package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Hides this class or constructor. * * 1. If applied to the class, then the class is not shown in the grammar. * This is used for support classes for internal working, e.g. BaseMoves. * * 2. If applied to constructors, then the class shows in the grammar as a * rule but the hidden constructors do not, e.g. * <component> ::= <card> | <dice> | ... * * @author cambolbro */ @Retention(RetentionPolicy.RUNTIME) public @interface Hide { // ... }
581
24.304348
76
java
Ludii
Ludii-master/Common/src/annotations/Name.java
package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Named parameter in the grammar. * * @author cambolbro */ @Retention(RetentionPolicy.RUNTIME) public @interface Name { // ... }
247
14.5
44
java
Ludii
Ludii-master/Common/src/annotations/Opt.java
package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Named parameter in the grammar. * * @author cambolbro */ @Retention(RetentionPolicy.RUNTIME) public @interface Opt { // ... }
246
14.4375
44
java
Ludii
Ludii-master/Common/src/annotations/Or.java
package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Named parameter in the grammar. * * @author cambolbro */ @Retention(RetentionPolicy.RUNTIME) public @interface Or { // ... }
245
14.375
44
java
Ludii
Ludii-master/Common/src/annotations/Or2.java
package annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Named parameter in the grammar. * * @author cambolbro */ @Retention(RetentionPolicy.RUNTIME) public @interface Or2 { // ... }
246
14.4375
44
java
Ludii
Ludii-master/Common/src/exception/DuplicateOptionUseException.java
package exception; /** * Exception indicating that a String description of an option was * used more than once (matched multiple distinct options). * * @author Dennis Soemers */ public class DuplicateOptionUseException extends RuntimeException { /** */ private static final long serialVersionUID = 1L; /** * Constructor * @param optionString */ public DuplicateOptionUseException(final String optionString) { super("Option with duplicate matches: " + optionString); } }
494
18.8
66
java
Ludii
Ludii-master/Common/src/exception/IndexPlayerException.java
package exception; /** * Changed to RuntimeException because no way to recover, I think. * An exception to prevent to create an instance of a player with an index <= 0 or > maxPlayer * * @author Eric.Piette and cambolbro * */ public class IndexPlayerException extends RuntimeException { private static final long serialVersionUID = 1L; public IndexPlayerException(int index) { System.err.println("Instantiation of a player with the index " + index); } }
471
22.6
94
java
Ludii
Ludii-master/Common/src/exception/LimitPlayerException.java
package exception; /** * No way to recover. Runtime exception. An exception to prevent to create an * instance with more players than the max number of players or with less than 0 * player. * * @author Eric.Piette and cambolbro * */ public class LimitPlayerException extends RuntimeException { private static final long serialVersionUID = 1L; public LimitPlayerException(int numPlayers) { System.err.println("Instantiation of a play with " + numPlayers); } }
479
20.818182
80
java
Ludii
Ludii-master/Common/src/exception/UnusedOptionException.java
package exception; /** * Exception indicating that a String description of an option was * not used at all in a game. * * @author Dennis Soemers */ public class UnusedOptionException extends RuntimeException { /** */ private static final long serialVersionUID = 1L; /** * Constructor * @param optionString */ public UnusedOptionException(final String optionString) { super("Unused option: " + optionString); } }
436
16.48
66
java
Ludii
Ludii-master/Common/src/graphics/Filters.java
package graphics; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; //------------------------------------ /** * Image processing filters. */ public class Filters { /** * Prepares a convolve operator for a Gaussian blur filter. * @param radius radius of blur in pixels. * @param horizontal whether the blur is horizontal or vertical. * @return corresponding convolve operator. */ public static ConvolveOp gaussianBlurFilter(int radius, boolean horizontal) { if (radius < 1) { System.out.printf("radius=%d.\n", Integer.valueOf(radius)); //throw new IllegalArgumentException("Radius must be >= 1"); return null; } int size = radius * 2 + 1; float[] data = new float[size]; float sigma = radius / 3.0f; float twoSigmaSquare = 2.0f * sigma * sigma; float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI); float total = 0.0f; for (int i = -radius; i <= radius; i++) { float distance = i * i; int index = i + radius; data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot; total += data[index]; } for (int i = 0; i < data.length; i++) data[i] /= total; Kernel kernel = horizontal ? new Kernel(size, 1, data) : new Kernel(1, size, data); return new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); } }
1,474
27.921569
91
java
Ludii
Ludii-master/Common/src/graphics/ImageConstants.java
package graphics; /** * Useful constants for UI graphics. * * @author cambolbro */ public class ImageConstants { public final static String[] customImageKeywords = { "marker", "ball", "seed", "ring", "chocolate", "null" }; public final static String[] defaultFamilyKeywords = { "Defined", "Themed", "Basic" }; public final static String abstractFamilyKeyword = "Abstract"; }
393
20.888889
87
java
Ludii
Ludii-master/Common/src/graphics/ImageProcessing.java
package graphics; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RadialGradientPaint; import java.awt.Shape; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; /** * Image processing routines. * @author cambolbro */ public class ImageProcessing { //------------------------------------------------------------------------- // /** // * Flood fills image, replacing all pixels with the replacement colour, unless target colour or already visited. // * Uses a depth first search approach. (can lead to stack memory overflow for large images) // */ // public static void floodFillDepth // ( // final BufferedImage img, final int x, final int y, final int minWidth, final int minHeight, final int maxWidth, final int maxHeight, // final int[] rgbaTarget, final int[] rgbaReplacement // ) // { // if (x < minWidth || y < minHeight || x >= maxWidth || y >= maxHeight) // return; // // final WritableRaster raster = img.getRaster(); // final int[] rgba = { 0, 0, 0, 255 }; // // raster.getPixel(x, y, rgba); // // if (rgba[0] == rgbaReplacement[0] && rgba[1] == rgbaReplacement[1] && rgba[2] == rgbaReplacement[2] && rgba[3] == rgbaReplacement[3]) // return; // already visited // // if (rgba[0] == rgbaTarget[0] && rgba[1] == rgbaTarget[1] && rgba[2] == rgbaTarget[2] && rgba[3] == rgbaTarget[3]) // return; // is target colour // // raster.setPixel(x, y, rgbaReplacement); // // final int[][] off = { {-1,0}, {0,1}, {1,0}, {0,-1} }; // for (int a = 0; a < 4; a++) // { // floodFillDepth(img, x+off[a][0], y+off[a][1], minWidth, minHeight, maxWidth, maxHeight, rgbaTarget, rgbaReplacement); // } // } // /** // * Flood fills image, replacing all pixels with the replacement colour, unless target colour or already visited. // * Uses a breadth first search approach. // */ // public static ArrayList<Point> floodFillBreadth // ( // final BufferedImage img, final ArrayList<Point> pointsToCheck, final int x, final int y, final int width, final int height, // final int[] rgbaTarget, final int[] rgbaReplacement // ) // { // final WritableRaster raster = img.getRaster(); // final int[] rgba = { 0, 0, 0, 255 }; // raster.getPixel(x, y, rgba); // raster.setPixel(x, y, rgbaReplacement); // // pointsToCheck.remove(0); // // final int[][] off = { {-1,0}, {0,1}, {1,0}, {0,-1} }; // for (int a = 0; a < 4; a++) // { // if (x+off[a][0] < 0 || y+off[a][1] < 0 || x+off[a][0] >= width || y+off[a][1] >= height) // continue; // raster.getPixel(x+off[a][0], y+off[a][1], rgba); // if (rgba[0] == rgbaReplacement[0] && rgba[1] == rgbaReplacement[1] && rgba[2] == rgbaReplacement[2] && rgba[3] == rgbaReplacement[3]) // continue; // already visited // if (rgba[0] == rgbaTarget[0] && rgba[1] == rgbaTarget[1] && rgba[2] == rgbaTarget[2] && rgba[3] == rgbaTarget[3]) // continue; // is target colour // boolean inPointsToCheck = false; // final Point pointToAdd = new Point(x+off[a][0],y+off[a][1]); // // for (int i =0; i < pointsToCheck.size(); i++) // { // if ((pointToAdd.x == pointsToCheck.get(i).x) && (pointToAdd.y == pointsToCheck.get(i).y)) // inPointsToCheck = true; // } // if (!inPointsToCheck) // pointsToCheck.add(new Point(x+off[a][0],y+off[a][1])); // } // return pointsToCheck; // } //------------------------------------------------------------------------- // /** // * Contracts an image by one pixel, i.e. shaves off out pixel layer. // * @param img // * @param width // * @param height // */ // public static void contractImage(final BufferedImage img, final int width, final int height) // { // int x, y; // final int[][] off = { {-1,0}, {0,1}, {1,0}, {0,-1} }; // // final WritableRaster raster = img.getRaster(); // final int[] rgba = { 0, 0, 0, 255 }; // final int[] rgbaOff = { 0, 0, 0, 0 }; // // // Pass 1: Find border // final boolean[][] border = new boolean[width][height]; // // for (y = 0; y < height; y++) // for (x = 0; x < width; x++) // { // raster.getPixel(x, y, rgba); // if (rgba[0] != 0 || rgba[1] != 0 || rgba[2] != 0 || rgba[3] != 0) // { // for (int a = 0; a < 4; a++) // { // final int xx = x + off[a][0]; // final int yy = y + off[a][1]; // if (xx >= 0 && yy >= 0 && xx < width && yy < height) // { // raster.getPixel(xx, yy, rgba); // if (rgba[0] == 0 && rgba[1] == 0 && rgba[2] == 0 && rgba[3] == 0) // border[x][y] = true; // } // } // } // } // // // Pass 2: Remove border pixels // for (y = 0; y < height; y++) // for (x = 0; x < width; x++) // if (border[x][y]) // raster.setPixel(x, y, rgbaOff); // } //------------------------------------------------------------------------- // /** // * Converts all non-transparent pixels to the specified mask colour. // * @param img // * @param width // * @param height // * @param rgbaMask Mask colour. // */ // public static void makeMask(final BufferedImage img, final int width, final int height, final int[] rgbaMask) // { // final WritableRaster raster = img.getRaster(); // final int[] rgba = { 0, 0, 0, 255 }; // // for (int y = 0; y < height; y++) // for (int x = 0; x < width; x++) // { // raster.getPixel(x, y, rgba); // if (rgba[0] != 0 || rgba[1] != 0 || rgba[2] != 0 || rgba[3] != 0) // raster.setPixel(x, y, rgbaMask); // } // } //------------------------------------------------------------------------ // public static BufferedImage resize(final BufferedImage img, final int newW, final int newH) // { // final Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH); // final BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB); // // final Graphics2D g2d = dimg.createGraphics(); // g2d.drawImage(tmp, 0, 0, null); // g2d.dispose(); // // return dimg; // } //------------------------------------------------------------------------ public static void ballImage ( final Graphics2D g2d, final int x0, final int y0, final int r, final Color baseColour ) { // Create general ball final float[] dist = { 0f, 0.25f, 0.4f, 1f}; final Color[] colors = {Color.WHITE, baseColour, baseColour, Color.BLACK}; RadialGradientPaint rgp = new RadialGradientPaint(new Point(x0 + r*2/3, y0 + r*2/3), r*2, dist, colors); g2d.setPaint(rgp); g2d.fill(new Ellipse2D.Double(x0, y0, r * 2, r * 2)); // add inner shadow final float[] dist2 = { 0f, 0.35f, 1f}; final Color[] colors2 = {new Color(0,0,0,0), new Color(0,0,0,0), Color.BLACK}; rgp = new RadialGradientPaint(new Point(x0 + r, y0 + r), r*2, dist2, colors2); g2d.setPaint(rgp); g2d.fill(new Ellipse2D.Double(x0, y0, r * 2, r * 2)); } //------------------------------------------------------------------------ public static void markerImage ( final Graphics2D g2d, final int x0, final int y0, final int r, final Color baseColour ) { RadialGradientPaint rgp; // Fill flat disc g2d.setPaint(baseColour); g2d.fill(new Ellipse2D.Double(x0, y0, r * 2, r * 2)); // Darken exterior final float[] dists = { 0f, 0.9f, 1f}; final int rr = baseColour.getRed() / 2; final int gg = baseColour.getGreen() / 2; final int bb = baseColour.getBlue() / 2; final Color[] colors = {new Color(0,0,0,0), new Color(0,0,0,0), new Color(rr, gg, bb, 127)}; //final Color[] colors = {new Color(0,0,0,0), new Color(0,0,0,0), new Color(0, 0, 0, 80)}; rgp = new RadialGradientPaint(new Point(x0 + r, y0 + r), r, dists, colors); g2d.setPaint(rgp); g2d.fill(new Ellipse2D.Double(x0, y0, r * 2, r * 2)); // Darken bottom right even more //final float[] dist3 = { 0f, 0.9f, 1f}; //final Color[] colors3 = {new Color(0,0,0,0), new Color(0,0,0,0), new Color(0, 0, 0, 63)}; rgp = new RadialGradientPaint(new Point(x0 + r-r/16, y0 + r-r/16), r, dists, colors); g2d.setPaint(rgp); g2d.fill(new Ellipse2D.Double(x0, y0, r * 2, r * 2)); // Add highlight //final float[] distsH = { 0.8f, 0.85f, 0.9f}; final float[] distsH = { 0.85f, 0.9f, 0.95f}; final Color[] colorsH = { new Color(255,255,255,0), new Color(255,255,255,150), new Color(255,255,255,0) }; rgp = new RadialGradientPaint(new Point(x0 + r, y0 + r), r, distsH, colorsH); g2d.setPaint(rgp); g2d.fill(new Ellipse2D.Double(x0, y0, r * 1.666, r * 1.666)); } //------------------------------------------------------------------------ /** * Create ring image with empty centre. */ public static void ringImage ( final Graphics2D g2d, final int x0, final int y0, final int imageSize, final Color baseColour ) { final int r = (int)(0.425 * imageSize); // - 1; final int off = (imageSize - 2 * r) / 2; final float swO = 0.15f * imageSize; final float swI = 0.075f * imageSize; final Shape circle = new Ellipse2D.Double(x0 + off, y0 + off, r * 2 - 1, r * 2 - 1); g2d.setStroke(new BasicStroke(swO, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g2d.setColor(Color.black); g2d.draw(circle); g2d.setStroke(new BasicStroke(swI, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g2d.setColor(baseColour); g2d.draw(circle); } //------------------------------------------------------------------------ /** * Create chocolate piece image. */ public static void chocolateImage ( final Graphics2D g2d, final int imageSize, final int numSides, final Color baseColour ) { if (numSides != 4) System.out.println("** Only four sided chocolate pieces supported."); final int offO = (int)(0.125 * imageSize); final int offI = (int)(0.2 * imageSize); final Point[][] pts = new Point[4][2]; g2d.setColor(baseColour); g2d.fillRect(0, 0, imageSize, imageSize); pts[0][0] = new Point(offO, imageSize - 1 - offO); pts[0][1] = new Point(offI, imageSize - 1 - offI); pts[1][0] = new Point(offO, offO); pts[1][1] = new Point(offI, offI); pts[2][0] = new Point(imageSize - 1 - offO, offO); pts[2][1] = new Point(imageSize - 1 - offI, offI); pts[3][0] = new Point(imageSize - 1 - offO, imageSize - 1 - offO); pts[3][1] = new Point(imageSize - 1 - offI, imageSize - 1 - offI); g2d.setColor(baseColour); g2d.fillRect(0, 0, imageSize, imageSize); GeneralPath path = new GeneralPath(); path.moveTo(pts[0][0].x, pts[0][0].y); path.lineTo(pts[1][0].x, pts[1][0].y); path.lineTo(pts[2][0].x, pts[2][0].y); path.lineTo(pts[2][1].x, pts[2][1].y); path.lineTo(pts[1][1].x, pts[1][1].y); path.lineTo(pts[0][1].x, pts[0][1].y); path.closePath(); g2d.setColor(new Color(255, 230, 200, 100)); g2d.fill(path); path = new GeneralPath(); path.moveTo(pts[0][0].x, pts[0][0].y); path.lineTo(pts[3][0].x, pts[3][0].y); path.lineTo(pts[2][0].x, pts[2][0].y); path.lineTo(pts[2][1].x, pts[2][1].y); path.lineTo(pts[3][1].x, pts[3][1].y); path.lineTo(pts[0][1].x, pts[0][1].y); path.closePath(); g2d.setColor(new Color(50, 40, 20, 100)); g2d.fill(path); } //------------------------------------------------------------------------ // public static BufferedImage pillImage // ( // final double pieceScale, // final int dim, // final int r, // final Color baseColour // ) // { // final int diameter = r; // eh? // final int sz_master = 2*diameter; // allow margin so shading can be blurred in from outside // final int off = diameter/2; // final Color clr_off = new Color(0f, 0f, 0f, 0f); // final Color clr_off_w = new Color(255, 255, 255, 1); //1f, 1f, 1f, 0f); // final Color clr_on = new Color(1f, 1f, 1f, 1f); // // // Create super-sized image // final BufferedImage img_master = new BufferedImage(sz_master, sz_master, BufferedImage.TYPE_INT_ARGB); // final Graphics2D g2d_master = (Graphics2D)img_master.getGraphics(); // g2d_master.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // g2d_master.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // // // Fill dark shadow circle // int r0=0, g0=0, b0=0, r1=0, g1=0, b1=0; // int r_hi=0, g_hi=0, b_hi=0; // final int blur_amount_hi = 2; // // r0 = Math.max(0, baseColour.getRed() - 75); // g0 = Math.max(0, baseColour.getGreen() - 75); // b0 = Math.max(0, baseColour.getBlue() - 75); // r1 = baseColour.getRed(); // g1 = baseColour.getGreen(); // b1 = baseColour.getBlue(); // // r_hi = Math.min(255, baseColour.getRed() + 255); // g_hi = Math.min(255, baseColour.getGreen() + 250); // b_hi = Math.min(255, baseColour.getBlue() + 240); // //// r_ref = Math.min(255, baseColour.getRed() + 100); //// g_ref = Math.min(255, baseColour.getGreen() + 100); //// b_ref = Math.min(255, baseColour.getBlue() + 100); // // final Color clr_hi = new Color(r_hi, g_hi, b_hi); // // // Draw shaded disc // final WritableRaster raster = img_master.getRaster(); // final int[] rgba = { 0, 0, 0, 255 }; // final int dr = r1 - r0; // final int dg = g1 - g0; // final int db = b1 - b0; // final double radius = diameter / 2.0; // final int cx = sz_master / 2 - 1; // final int cy = sz_master / 2 - 1; // for (int x = 0; x < sz_master; x++) // for (int y = 0; y < sz_master; y++) // { // final double dx = x - cx; // final double dy = y - cy; // final double dist = Math.sqrt(dx * dx + dy * dy) / radius; // double t = 1 - dist; // // if (dist < .8) // t = 1; // else // t = 1 - (dist - .8) * 5; // // t = Math.pow(t, .5); //33); // rgba[0] = r0 + (int)(dr * t + 0.5); // rgba[1] = g0 + (int)(dg * t + 0.5); // rgba[2] = b0 + (int)(db * t + 0.5); // raster.setPixel(x, y, rgba); // } // // // Add highlight // BufferedImage img_hi = new BufferedImage(sz_master, sz_master, BufferedImage.TYPE_INT_ARGB); // final Graphics2D g2d_hi = (Graphics2D)img_hi.getGraphics(); // g2d_hi.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // g2d_hi.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // g2d_hi.setPaint(clr_off_w); // g2d_hi.fillRect(0, 0, sz_master, sz_master); // g2d_hi.setPaint(clr_hi); // final float rHi = 0.41f * diameter; // radius of top left highlight // final float rHole = 0.575f * diameter; // radius of hole that clips top left highlight // final float offHole = 0.14f * diameter; // final int x = cx; // final int y = cy; //- 3 * spacing; // final Shape hi = new Ellipse2D.Float(x-rHi, y-rHi, 2*rHi, 2*rHi); // final Area areaHi = new Area(hi); // final Shape hole = new Ellipse2D.Float(x-rHole+offHole, y-rHole+offHole, 2*rHole, 2*rHole); // final Area areaHole = new Area(hole); // areaHi.subtract(areaHole); // g2d_hi.fill(areaHi); // img_hi = Filters.gaussianBlurFilter(blur_amount_hi, true).filter(img_hi, null); // img_hi = Filters.gaussianBlurFilter(blur_amount_hi, false).filter(img_hi, null); // g2d_master.drawImage(img_hi, 0, 0, null); // // // Clip the master // final BufferedImage img_mask = new BufferedImage(sz_master, sz_master, BufferedImage.TYPE_INT_ARGB); // final Graphics2D g2d_mask = (Graphics2D)img_mask.getGraphics(); // g2d_mask.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // g2d_mask.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // g2d_mask.setPaint(clr_off); // g2d_mask.fillRect(0, 0, sz_master, sz_master); // g2d_mask.setPaint(clr_on); // g2d_mask.fillOval(off, off, diameter, diameter); // g2d_master.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN, 1.0f)); // g2d_master.drawImage(img_mask, 0, 0, null); // //// // Copy the master to the final result. //// // Shrink by one pixel in each direction to stop antialiased pixels on outer edges being clipped. //// Graphics2D g2d_final = (Graphics2D)this.getGraphics(); //// g2d_final.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //// g2d_final.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); //// //g2d_final.drawImage(img_master, 0,0, diameter,diameter, off,off, off+diameter,off+diameter, null); //// g2d_final.drawImage(img_master, 0,0, diameter,diameter, off-1,off-1, off+diameter+1,off+diameter+1, null); // // // Copy the master to the final result. // // Shrink by one pixel in each direction to stop antialiased pixels on outer edges being clipped. // final BufferedImage imgFinal = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB); // final Graphics2D g2dFinal = (Graphics2D)imgFinal.getGraphics(); // g2dFinal.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // g2dFinal.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // // //g2d_final.drawImage(img_master, 0,0, diameter,diameter, off,off, off+diameter,off+diameter, null); // g2dFinal.drawImage // ( // img_master, // (int) (0 + dim * (1-pieceScale)/2), // (int) (0 + dim * (1-pieceScale)/2), // (int) (diameter + dim * (1-pieceScale)/2), // (int) (diameter + dim * (1-pieceScale)/2), // off-1, // off-1, // off+diameter+1, // off+diameter+1, // null // ); // // return imgFinal; // } //------------------------------------------------------------------------ }
18,228
35.90081
140
java
Ludii
Ludii-master/Common/src/graphics/ImageUtil.java
package graphics; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.regex.Pattern; import graphics.svg.SVGLoader; /** * Functions for assisting with images. * * @author Matthew.Stephenson */ public class ImageUtil { //------------------------------------------------------------------------- /** * Determines the full file path of a specified image name. */ public static String getImageFullPath(final String imageName) { final String imageNameLower = imageName.toLowerCase(); final String[] svgNames = SVGLoader.listSVGs(); // Pass 1: Look for exact match for (final String svgName : svgNames) { final String sReplaced = svgName.replaceAll(Pattern.quote("\\"), "/"); final String[] subs = sReplaced.split("/"); if (subs[subs.length-1].toLowerCase().equals(imageNameLower + ".svg")) { String fullPath = svgName.replaceAll(Pattern.quote("\\"), "/"); fullPath = fullPath.substring(fullPath.indexOf("/svg/")); return fullPath; } } // Pass 2: Look for exact match outside of the Jar, at root location. final File svgImage = new File("."); final String fileName = imageName.toLowerCase(); for(final File file : svgImage.listFiles()) { if(file.getName().toLowerCase().equals(fileName) || file.getName().toLowerCase().equals(fileName + ".svg")) { try { return file.getCanonicalPath(); } catch (final IOException e) { e.printStackTrace(); } } } // Handle predefined image types that do not have an SVG if (Arrays.asList(ImageConstants.customImageKeywords).contains(imageNameLower)) return imageNameLower; // ball is not an SVG, it's a predefined image type // Pass 3: Look for best substring match String longestName = null; String longestNamePath = null; for (final String svgName : svgNames) { final String sReplaced = svgName.replaceAll(Pattern.quote("\\"), "/"); final String[] subs = sReplaced.split("/"); final String shortName = subs[subs.length-1].split("\\.")[0].toLowerCase(); if (imageNameLower.contains(shortName)) { String fullPath = svgName.replaceAll(Pattern.quote("\\"), "/"); fullPath = fullPath.substring(fullPath.indexOf("/svg/")); if (longestName == null || shortName.length() > longestName.length()) { longestName = new String(shortName); // store this closest match so far longestNamePath = fullPath; } } } return longestNamePath; } //------------------------------------------------------------------------- // /** // * Draws and image at a specified position, size, colour and rotation. // */ // public static void drawImageAtPosn(final Graphics2D g2d, final String img, final Rectangle2D rect, final Color edgeColour, final Color fillColour, final boolean centerImage, final int rotation) // { // // Need to shift x or y position if the bounds are different. //// int yPush = 0; //// int xPush = 0; //// final Rectangle2D bounds = SVGtoImage.getBounds(img, (int) Math.max(rect.getWidth(), rect.getHeight())); //// if (bounds.getWidth() > bounds.getHeight()) //// yPush = (int) ((bounds.getWidth() - bounds.getHeight())); //// if (bounds.getHeight() > bounds.getWidth()) //// xPush = (int) ((bounds.getHeight() - bounds.getWidth())); //// //// final int x = (int) (rect.getX() - rect.getWidth() / 2) + xPush/2; //// final int y = (int) (rect.getY() - rect.getHeight() / 2) + yPush/2; // //// final Rectangle2D adjustedRectangle = rect; //// if (centerImage) //// { //// adjustedRectangle.setRect(rect.getX() + rect.getWidth()/4, rect.getY() + rect.getHeight()/4, rect.getWidth(), rect.getHeight()); //// } // // SVGtoImage.loadFromString(g2d, img, (int)rect.getWidth(), (int)rect.getHeight(), (int)rect.getX(), (int)rect.getY(), edgeColour, fillColour, false, rotation); // } //------------------------------------------------------------------------- }
3,997
32.596639
197
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/BitBuffer.java
package graphics.qr_codes; /* * Fast QR Code generator library * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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 java.util.Arrays; import java.util.Objects; // An appendable sequence of bits (0s and 1s), mainly used by QrSegment. final class BitBuffer { /*---- Fields ----*/ int[] data; // In each 32-bit word, bits are filled from top down. int bitLength; // Always non-negative. /*---- Constructor ----*/ // Creates an empty bit buffer. public BitBuffer() { data = new int[64]; bitLength = 0; } /*---- Methods ----*/ // Returns the bit at the given index, yielding 0 or 1. public int getBit(int index) { if (index < 0 || index >= bitLength) throw new IndexOutOfBoundsException(); return (data[index >>> 5] >>> ~index) & 1; } // Returns a new array representing this buffer's bits packed into // bytes in big endian. The current bit length must be a multiple of 8. public byte[] getBytes() { if (bitLength % 8 != 0) throw new IllegalStateException("Data is not a whole number of bytes"); byte[] result = new byte[bitLength / 8]; for (int i = 0; i < result.length; i++) result[i] = (byte)(data[i >>> 2] >>> (~i << 3)); return result; } // Appends the given number of low-order bits of the given value // to this buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len. public void appendBits(final int value, final int length) { int val = value; int len = length; if (len < 0 || len > 31 || val >>> len != 0) throw new IllegalArgumentException("Value out of range"); if (len > Integer.MAX_VALUE - bitLength) throw new IllegalStateException("Maximum length reached"); if (bitLength + len + 1 > data.length << 5) data = Arrays.copyOf(data, data.length * 2); assert bitLength + len <= data.length << 5; int remain = 32 - (bitLength & 0x1F); assert 1 <= remain && remain <= 32; if (remain < len) { data[bitLength >>> 5] |= val >>> (len - remain); bitLength += remain; assert (bitLength & 0x1F) == 0; len -= remain; val &= (1 << len) - 1; remain = 32; } data[bitLength >>> 5] |= val << (remain - len); bitLength += len; } // Appends to this buffer the sequence of bits represented by the given // word array and given bit length. Requires 0 <= len <= 32 * vals.length. public void appendBits(int[] vals, int len) { Objects.requireNonNull(vals); if (len == 0) return; if (len < 0 || len > vals.length * 32L) throw new IllegalArgumentException("Value out of range"); int wholeWords = len / 32; int tailBits = len % 32; if (tailBits > 0 && vals[wholeWords] << tailBits != 0) throw new IllegalArgumentException("Last word must have low bits clear"); if (len > Integer.MAX_VALUE - bitLength) throw new IllegalStateException("Maximum length reached"); while (bitLength + len > data.length * 32) data = Arrays.copyOf(data, data.length * 2); int shift = bitLength % 32; if (shift == 0) { System.arraycopy(vals, 0, data, bitLength / 32, (len + 31) / 32); bitLength += len; } else { for (int i = 0; i < wholeWords; i++) { int word = vals[i]; data[bitLength >>> 5] |= word >>> shift; bitLength += 32; data[bitLength >>> 5] = word << (32 - shift); } if (tailBits > 0) appendBits(vals[wholeWords] >>> (32 - tailBits), tailBits); } } }
4,509
31.446043
83
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/DataTooLongException.java
package graphics.qr_codes; /* * Fast QR Code generator library * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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. */ /** * Thrown when the supplied data does not fit any QR Code version. Ways to handle this exception include: * <ul> * <li><p>Decrease the error correction level if it was greater than {@code Ecc.LOW}.</p></li> * <li><p>If the advanced {@code encodeSegments()} function with 6 arguments or the * {@code makeSegmentsOptimally()} function was called, then increase the maxVersion argument * if it was less than {@link QrCode#MAX_VERSION}. (This advice does not apply to the other * factory functions because they search all versions up to {@code QrCode.MAX_VERSION}.)</p></li> * <li><p>Split the text data into better or optimal segments in order to reduce the number of * bits required. (See {@link QrSegmentAdvanced#makeSegmentsOptimally(String,QrCode.Ecc,int,int) * QrSegmentAdvanced.makeSegmentsOptimally()}.)</p></li> * <li><p>Change the text or binary data to be shorter.</p></li> * <li><p>Change the text to fit the character set of a particular segment mode (e.g. alphanumeric).</p></li> * <li><p>Propagate the error upward to the caller/user.</p></li> * </ul> * @see QrCode#encodeText(String, QrCode.Ecc) * @see QrCode#encodeBinary(byte[], QrCode.Ecc) * @see QrCode#encodeSegments(java.util.List, QrCode.Ecc) * @see QrCode#encodeSegments(java.util.List, QrCode.Ecc, int, int, int, boolean) * @see QrSegmentAdvanced#makeSegmentsOptimally(String, QrCode.Ecc, int, int) */ public class DataTooLongException extends IllegalArgumentException { private static final long serialVersionUID = 1L; public DataTooLongException() {} public DataTooLongException(String msg) { super(msg); } }
2,921
49.37931
111
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/Memoizer.java
package graphics.qr_codes; /* * Fast QR Code generator library * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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 java.lang.ref.SoftReference; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; // A thread-safe cache based on soft references. final class Memoizer<T,R> { private final Function<T,R> function; Map<T,SoftReference<R>> cache = new ConcurrentHashMap<>(); private Set<T> pending = new HashSet<>(); // Creates a memoizer based on the given function that takes one input to compute an output. public Memoizer(Function<T,R> func) { function = func; } // Computes function.apply(arg) or returns a cached copy of a previous call. public R get(T arg) { // Non-blocking fast path { SoftReference<R> ref = cache.get(arg); if (ref != null) { R result = ref.get(); if (result != null) return result; } } // Sequential slow path while (true) { synchronized(this) { SoftReference<R> ref = cache.get(arg); if (ref != null) { R result = ref.get(); if (result != null) return result; cache.remove(arg); } assert !cache.containsKey(arg); if (pending.add(arg)) break; try { this.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } try { R result = function.apply(arg); cache.put(arg, new SoftReference<>(result)); return result; } finally { synchronized(this) { pending.remove(arg); this.notifyAll(); } } } }
2,776
27.927083
93
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/Mode.java
package graphics.qr_codes; /* * Fast QR Code generator library * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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. */ /*---- Public helper enumeration ----*/ /** * Describes how a segment's data bits are interpreted. */ public enum Mode { /*-- Constants --*/ NUMERIC (0x1, 10, 12, 14), ALPHANUMERIC(0x2, 9, 11, 13), BYTE (0x4, 8, 16, 16), KANJI (0x8, 8, 10, 12), ECI (0x7, 0, 0, 0); /*-- Fields --*/ // The mode indicator bits, which is a uint4 value (range 0 to 15). final int modeBits; // Number of character count bits for three different version ranges. private final int[] numBitsCharCount; /*-- Constructor --*/ private Mode(int mode, int... ccbits) { modeBits = mode; numBitsCharCount = ccbits; } /*-- Method --*/ // Returns the bit width of the character count field for a segment in this mode // in a QR Code at the given version number. The result is in the range [0, 16]. int numCharCountBits(int ver) { assert QrCode.MIN_VERSION <= ver && ver <= QrCode.MAX_VERSION; return numBitsCharCount[(ver + 7) / 17]; } }
2,263
31.811594
83
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/QrCode.java
package graphics.qr_codes; /* * Fast QR Code generator library * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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 java.util.Arrays; import java.util.List; import java.util.Objects; /** * A QR Code symbol, which is a type of two-dimension barcode. * Invented by Denso Wave and described in the ISO/IEC 18004 standard. * <p>Instances of this class represent an immutable square grid of dark and light cells. * The class provides static factory functions to create a QR Code from text or binary data. * The class covers the QR Code Model 2 specification, supporting all versions (sizes) * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.</p> * <p>Ways to create a QR Code object:</p> * <ul> * <li><p>High level: Take the payload data and call {@link QrCode#encodeText(String,Ecc)} * or {@link QrCode#encodeBinary(byte[],Ecc)}.</p></li> * <li><p>Mid level: Custom-make the list of {@link QrSegment segments} * and call {@link QrCode#encodeSegments(List,Ecc)} or * {@link QrCode#encodeSegments(List,Ecc,int,int,int,boolean)}</p></li> * <li><p>Low level: Custom-make the array of data codeword bytes (including segment headers and * final padding, excluding error correction codewords), supply the appropriate version number, * and call the {@link QrCode#QrCode(int,Ecc,byte[],int) constructor}.</p></li> * </ul> * <p>(Note that all ways require supplying the desired error correction level.)</p> * @see QrSegment */ public final class QrCode { // Public immutable scalar parameters: /** The version number of this QR Code, which is between 1 and 40 (inclusive). * This determines the size of this barcode. */ public final int version; /** The width and height of this QR Code, measured in modules, between * 21 and 177 (inclusive). This is equal to version &#xD7; 4 + 17. */ public final int size; /** The error correction level used in this QR Code, which is not {@code null}. */ public final Ecc errorCorrectionLevel; /** The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). * <p>Even if a QR Code is created with automatic masking requested (mask = * &#x2212;1), the resulting object still has a mask value between 0 and 7. */ public final int mask; // Private grid of modules of this QR Code, packed tightly into bits. // Immutable after constructor finishes. Accessed through getModule(). private final int[] modules; /*---- Constructor (low level) ----*/ /** * Constructs a QR Code with the specified version number, * error correction level, data codeword bytes, and mask number. * <p>This is a low-level API that most users should not use directly. A mid-level * API is the {@link #encodeSegments(List,Ecc,int,int,int,boolean)} function.</p> * @param ver the version number to use, which must be in the range 1 to 40 (inclusive) * @param ecl the error correction level to use * @param dataCodewords the bytes representing segments to encode (without ECC) * @param msk the mask pattern to use, which is either &#x2212;1 for automatic choice or from 0 to 7 for fixed choice * @throws NullPointerException if the byte array or error correction level is {@code null} * @throws IllegalArgumentException if the version or mask value is out of range, * or if the data is the wrong length for the specified version and error correction level */ public QrCode(int ver, Ecc ecl, byte[] dataCodewords, int msk) { // Check arguments and initialize fields if (ver < MIN_VERSION || ver > MAX_VERSION) throw new IllegalArgumentException("Version value out of range"); if (msk < -1 || msk > 7) throw new IllegalArgumentException("Mask value out of range"); version = ver; size = ver * 4 + 17; errorCorrectionLevel = Objects.requireNonNull(ecl); Objects.requireNonNull(dataCodewords); QrTemplate tpl = QrTemplate.MEMOIZER.get(ver); modules = tpl.template.clone(); // Compute ECC, draw modules, do masking byte[] allCodewords = addEccAndInterleave(dataCodewords); drawCodewords(tpl.dataOutputBitIndexes, allCodewords); mask = handleConstructorMasking(tpl.masks, msk); } /*---- Static factory functions (high level) ----*/ /** * Returns a QR Code representing the specified Unicode text string at the specified error correction level. * As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer * Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible * QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the * ecl argument if it can be done without increasing the version. * @param text the text to be encoded (not {@code null}), which can be any Unicode string * @param ecl the error correction level to use (not {@code null}) (boostable) * @return a QR Code (not {@code null}) representing the text * @throws NullPointerException if the text or error correction level is {@code null} * @throws DataTooLongException if the text fails to fit in the * largest version QR Code at the ECL, which means it is too long */ public static QrCode encodeText(String text, Ecc ecl) { Objects.requireNonNull(text); Objects.requireNonNull(ecl); List<QrSegment> segs = QrSegment.makeSegments(text); return encodeSegments(segs, ecl); } /** * Returns a QR Code representing the specified binary data at the specified error correction level. * This function always encodes using the binary segment mode, not any text mode. The maximum number of * bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. * The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. * @param data the binary data to encode (not {@code null}) * @param ecl the error correction level to use (not {@code null}) (boostable) * @return a QR Code (not {@code null}) representing the data * @throws NullPointerException if the data or error correction level is {@code null} * @throws DataTooLongException if the data fails to fit in the * largest version QR Code at the ECL, which means it is too long */ public static QrCode encodeBinary(byte[] data, Ecc ecl) { Objects.requireNonNull(data); Objects.requireNonNull(ecl); QrSegment seg = QrSegment.makeBytes(data); return encodeSegments(Arrays.asList(seg), ecl); } /*---- Static factory functions (mid level) ----*/ /** * Returns a QR Code representing the specified segments at the specified error correction * level. The smallest possible QR Code version is automatically chosen for the output. The ECC level * of the result may be higher than the ecl argument if it can be done without increasing the version. * <p>This function allows the user to create a custom sequence of segments that switches * between modes (such as alphanumeric and byte) to encode text in less space. * This is a mid-level API; the high-level API is {@link #encodeText(String,Ecc)} * and {@link #encodeBinary(byte[],Ecc)}.</p> * @param segs the segments to encode * @param ecl the error correction level to use (not {@code null}) (boostable) * @return a QR Code (not {@code null}) representing the segments * @throws NullPointerException if the list of segments, any segment, or the error correction level is {@code null} * @throws DataTooLongException if the segments fail to fit in the * largest version QR Code at the ECL, which means they are too long */ public static QrCode encodeSegments(List<QrSegment> segs, Ecc ecl) { return encodeSegments(segs, ecl, MIN_VERSION, MAX_VERSION, -1, true); } /** * Returns a QR Code representing the specified segments with the specified encoding parameters. * The smallest possible QR Code version within the specified range is automatically * chosen for the output. Iff boostEcl is {@code true}, then the ECC level of the * result may be higher than the ecl argument if it can be done without increasing * the version. The mask number is either between 0 to 7 (inclusive) to force that * mask, or &#x2212;1 to automatically choose an appropriate mask (which may be slow). * <p>This function allows the user to create a custom sequence of segments that switches * between modes (such as alphanumeric and byte) to encode text in less space. * This is a mid-level API; the high-level API is {@link #encodeText(String,Ecc)} * and {@link #encodeBinary(byte[],Ecc)}.</p> * @param segs the segments to encode * @param minVersion the minimum allowed version of the QR Code (at least 1) * @param maxVersion the maximum allowed version of the QR Code (at most 40) * @param mask the mask number to use (between 0 and 7 (inclusive)), or &#x2212;1 for automatic mask * @param boostEcl increases the ECC level as long as it doesn't increase the version number * @return a QR Code (not {@code null}) representing the segments * @throws NullPointerException if the list of segments, any segment, or the error correction level is {@code null} * @throws IllegalArgumentException if 1 &#x2264; minVersion &#x2264; maxVersion &#x2264; 40 * or &#x2212;1 &#x2264; mask &#x2264; 7 is violated * @throws DataTooLongException if the segments fail to fit in * the maxVersion QR Code at the ECL, which means they are too long */ public static QrCode encodeSegments ( List<QrSegment> segs, Ecc eclIn, int minVersion, int maxVersion, int mask, boolean boostEcl ) { Ecc ecl = eclIn; Objects.requireNonNull(segs); Objects.requireNonNull(ecl); if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) throw new IllegalArgumentException("Invalid value"); // Find the minimal version number to use int version, dataUsedBits; for (version = minVersion; ; version++) { int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; // Number of data bits available dataUsedBits = QrSegment.getTotalBits(segs, version); if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) break; // This version number is found to be suitable if (version >= maxVersion) { // All versions in the range could not fit the given data String msg = "Segment too long"; if (dataUsedBits != -1) msg = String.format("Data length = %d bits, Max capacity = %d bits", dataUsedBits, dataCapacityBits); throw new DataTooLongException(msg); } } assert dataUsedBits != -1; // Increase the error correction level while the data still fits in the current version number for (Ecc newEcl : Ecc.values()) { // From low to high if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) ecl = newEcl; } // Concatenate all segments to create the data bit string BitBuffer bb = new BitBuffer(); for (QrSegment seg : segs) { bb.appendBits(seg.mode.modeBits, 4); bb.appendBits(seg.numChars, seg.mode.numCharCountBits(version)); bb.appendBits(seg.data, seg.bitLength); } assert bb.bitLength == dataUsedBits; // Add terminator and pad up to a byte if applicable int dataCapacityBits = getNumDataCodewords(version, ecl) * 8; assert bb.bitLength <= dataCapacityBits; bb.appendBits(0, Math.min(4, dataCapacityBits - bb.bitLength)); bb.appendBits(0, (8 - bb.bitLength % 8) % 8); assert bb.bitLength % 8 == 0; // Pad with alternating bytes until data capacity is reached for (int padByte = 0xEC; bb.bitLength < dataCapacityBits; padByte ^= 0xEC ^ 0x11) bb.appendBits(padByte, 8); // Create the QR Code object return new QrCode(version, ecl, bb.getBytes(), mask); } /*---- Public instance methods ----*/ /** * Returns the color of the module (pixel) at the specified coordinates, which is {@code false} * for light or {@code true} for dark. The top left corner has the coordinates (x=0, y=0). * If the specified coordinates are out of bounds, then {@code false} (light) is returned. * @param x the x coordinate, where 0 is the left edge and size&#x2212;1 is the right edge * @param y the y coordinate, where 0 is the top edge and size&#x2212;1 is the bottom edge * @return {@code true} if the coordinates are in bounds and the module * at that location is dark, or {@code false} (light) otherwise */ public boolean getModule(int x, int y) { if (0 <= x && x < size && 0 <= y && y < size) { int i = y * size + x; return getBit(modules[i >>> 5], i) != 0; } return false; } /*---- Private helper methods for constructor: Drawing function modules ----*/ // Draws two copies of the format bits (with its own error correction code) // based on the given mask and this object's error correction level field. private void drawFormatBits(int msk) { // Calculate error correction code and pack bits int data = errorCorrectionLevel.formatBits << 3 | msk; // errCorrLvl is uint2, mask is uint3 int rem = data; for (int i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537); int bits = (data << 10 | rem) ^ 0x5412; // uint15 assert bits >>> 15 == 0; // Draw first copy for (int i = 0; i <= 5; i++) setModule(8, i, getBit(bits, i)); setModule(8, 7, getBit(bits, 6)); setModule(8, 8, getBit(bits, 7)); setModule(7, 8, getBit(bits, 8)); for (int i = 9; i < 15; i++) setModule(14 - i, 8, getBit(bits, i)); // Draw second copy for (int i = 0; i < 8; i++) setModule(size - 1 - i, 8, getBit(bits, i)); for (int i = 8; i < 15; i++) setModule(8, size - 15 + i, getBit(bits, i)); setModule(8, size - 8, 1); // Always dark } // Sets the module at the given coordinates to the given color. // Only used by the constructor. Coordinates must be in bounds. private void setModule(int x, int y, int dark) { assert 0 <= x && x < size; assert 0 <= y && y < size; assert dark == 0 || dark == 1; int i = y * size + x; modules[i >>> 5] &= ~(1 << i); modules[i >>> 5] |= dark << i; } /*---- Private helper methods for constructor: Codewords and masking ----*/ // Returns a new byte string representing the given data with the appropriate error correction // codewords appended to it, based on this object's version and error correction level. private byte[] addEccAndInterleave(byte[] data) { Objects.requireNonNull(data); if (data.length != getNumDataCodewords(version, errorCorrectionLevel)) throw new IllegalArgumentException(); // Calculate parameter numbers int numBlocks = NUM_ERROR_CORRECTION_BLOCKS[errorCorrectionLevel.ordinal()][version]; int blockEccLen = ECC_CODEWORDS_PER_BLOCK [errorCorrectionLevel.ordinal()][version]; int rawCodewords = QrTemplate.getNumRawDataModules(version) / 8; int numShortBlocks = numBlocks - rawCodewords % numBlocks; int shortBlockDataLen = rawCodewords / numBlocks - blockEccLen; // Split data into blocks, calculate ECC, and interleave // (not concatenate) the bytes into a single sequence byte[] result = new byte[rawCodewords]; ReedSolomonGenerator rs = ReedSolomonGenerator.MEMOIZER.get(blockEccLen); byte[] ecc = new byte[blockEccLen]; // Temporary storage per iteration for (int i = 0, k = 0; i < numBlocks; i++) { int datLen = shortBlockDataLen + (i < numShortBlocks ? 0 : 1); rs.getRemainder(data, k, datLen, ecc); for (int j = 0, l = i; j < datLen; j++, k++, l += numBlocks) { // Copy data if (j == shortBlockDataLen) l -= numShortBlocks; result[l] = data[k]; } for (int j = 0, l = data.length + i; j < blockEccLen; j++, l += numBlocks) // Copy ECC result[l] = ecc[j]; } return result; } // Draws the given sequence of 8-bit codewords (data and error correction) // onto the entire data area of this QR Code, based on the given bit indexes. private void drawCodewords(int[] dataOutputBitIndexes, byte[] allCodewords) { Objects.requireNonNull(dataOutputBitIndexes); Objects.requireNonNull(allCodewords); if (allCodewords.length * 8 != dataOutputBitIndexes.length) throw new IllegalArgumentException(); for (int i = 0; i < dataOutputBitIndexes.length; i++) { int j = dataOutputBitIndexes[i]; int bit = getBit(allCodewords[i >>> 3], ~i & 7); modules[j >>> 5] |= bit << j; } } // XORs the codeword modules in this QR Code with the given mask pattern. // The function modules must be marked and the codeword bits must be drawn // before masking. Due to the arithmetic of XOR, calling applyMask() with // the same mask value a second time will undo the mask. A final well-formed // QR Code needs exactly one (not zero, two, etc.) mask applied. private void applyMask(int[] msk) { if (msk.length != modules.length) throw new IllegalArgumentException(); for (int i = 0; i < msk.length; i++) modules[i] ^= msk[i]; } // A messy helper function for the constructor. This QR Code must be in an unmasked state when this // method is called. The 'mask' argument is the requested mask, which is -1 for auto or 0 to 7 for fixed. // This method applies and returns the actual mask chosen, from 0 to 7. private int handleConstructorMasking(final int[][] masks, final int mskIn) { int msk = mskIn; if (msk == -1) { // Automatically choose best mask int minPenalty = Integer.MAX_VALUE; for (int i = 0; i < 8; i++) { applyMask(masks[i]); drawFormatBits(i); int penalty = getPenaltyScore(); if (penalty < minPenalty) { msk = i; minPenalty = penalty; } applyMask(masks[i]); // Undoes the mask due to XOR } } assert 0 <= msk && msk <= 7; applyMask(masks[msk]); // Apply the final choice of mask drawFormatBits(msk); // Overwrite old format bits return msk; // The caller shall assign this value to the final-declared field } // Calculates and returns the penalty score based on state of this QR Code's current modules. // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. private int getPenaltyScore() { int result = 0; int dark = 0; int[] runHistory = new int[7]; // Iterate over adjacent pairs of rows for (int index = 0, downIndex = size, end = size * size; index < end; ) { int runColor = 0; int runX = 0; Arrays.fill(runHistory, 0); int curRow = 0; int nextRow = 0; for (int x = 0; x < size; x++, index++, downIndex++) { int c = getBit(modules[index >>> 5], index); if (c == runColor) { runX++; if (runX == 5) result += PENALTY_N1; else if (runX > 5) result++; } else { finderPenaltyAddHistory(runX, runHistory); if (runColor == 0) result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; runColor = c; runX = 1; } dark += c; if (downIndex < end) { curRow = ((curRow << 1) | c) & 3; nextRow = ((nextRow << 1) | getBit(modules[downIndex >>> 5], downIndex)) & 3; // 2*2 blocks of modules having same color if (x >= 1 && (curRow == 0 || curRow == 3) && curRow == nextRow) result += PENALTY_N2; } } result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; } // Iterate over single columns for (int x = 0; x < size; x++) { int runColor = 0; int runY = 0; Arrays.fill(runHistory, 0); for (int y = 0, index = x; y < size; y++, index += size) { int c = getBit(modules[index >>> 5], index); if (c == runColor) { runY++; if (runY == 5) result += PENALTY_N1; else if (runY > 5) result++; } else { finderPenaltyAddHistory(runY, runHistory); if (runColor == 0) result += finderPenaltyCountPatterns(runHistory) * PENALTY_N3; runColor = c; runY = 1; } } result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; } // Balance of dark and light modules int total = size * size; // Note that size is odd, so dark/total != 1/2 // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% int k = (Math.abs(dark * 20 - total * 10) + total - 1) / total - 1; result += k * PENALTY_N4; return result; } /*---- Private helper functions ----*/ // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any // QR Code of the given version number and error correction level, with remainder bits discarded. // This stateless pure function could be implemented as a (40*4)-cell lookup table. static int getNumDataCodewords(int ver, Ecc ecl) { return QrTemplate.getNumRawDataModules(ver) / 8 - ECC_CODEWORDS_PER_BLOCK [ecl.ordinal()][ver] * NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal()][ver]; } // Can only be called immediately after a light run is added, and // returns either 0, 1, or 2. A helper function for getPenaltyScore(). private int finderPenaltyCountPatterns(int[] runHistory) { int n = runHistory[1]; assert n <= size * 3; boolean core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n; return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); } // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). private int finderPenaltyTerminateAndCount(int currentRunColor, int currRunLength, int[] runHistory) { int currentRunLength = currRunLength; if (currentRunColor == 1) { // Terminate dark run finderPenaltyAddHistory(currentRunLength, runHistory); currentRunLength = 0; } currentRunLength += size; // Add light border to final run finderPenaltyAddHistory(currentRunLength, runHistory); return finderPenaltyCountPatterns(runHistory); } // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). private void finderPenaltyAddHistory(final int currRunLength, final int[] runHistory) { int currentRunLength = currRunLength; if (runHistory[0] == 0) currentRunLength += size; // Add light border to initial run System.arraycopy(runHistory, 0, runHistory, 1, runHistory.length - 1); runHistory[0] = currentRunLength; } // Returns 0 or 1 based on the (i mod 32)'th bit of x. static int getBit(int x, int i) { return (x >>> i) & 1; } /*---- Constants and tables ----*/ /** The minimum version number (1) supported in the QR Code Model 2 standard. */ public static final int MIN_VERSION = 1; /** The maximum version number (40) supported in the QR Code Model 2 standard. */ public static final int MAX_VERSION = 40; // For use in getPenaltyScore(), when evaluating which mask is best. private static final int PENALTY_N1 = 3; private static final int PENALTY_N2 = 3; private static final int PENALTY_N3 = 40; private static final int PENALTY_N4 = 10; private static final byte[][] ECC_CODEWORDS_PER_BLOCK = { // Version: (note that index 0 is for padding, and is set to an illegal value) //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level {-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Low {-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28}, // Medium {-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // Quartile {-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, // High }; private static final byte[][] NUM_ERROR_CORRECTION_BLOCKS = { // Version: (note that index 0 is for padding, and is set to an illegal value) //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level {-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25}, // Low {-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49}, // Medium {-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68}, // Quartile {-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81}, // High }; /*---- Public helper enumeration ----*/ /** * The error correction level in a QR Code symbol. */ public enum Ecc { // Must be declared in ascending order of error protection // so that the implicit ordinal() and values() work properly /** The QR Code can tolerate about 7% erroneous codewords. */ LOW(1), /** The QR Code can tolerate about 15% erroneous codewords. */ MEDIUM(0), /** The QR Code can tolerate about 25% erroneous codewords. */ QUARTILE(3), /** The QR Code can tolerate about 30% erroneous codewords. */ HIGH(2); // In the range 0 to 3 (unsigned 2-bit integer). final int formatBits; // Constructor. private Ecc(int fb) { formatBits = fb; } } }
26,862
44.147899
191
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/QrCodeGeneratorDemo.java
package graphics.qr_codes; /* * Fast QR Code generator demo * * Run this command-line program with no arguments. The program creates/overwrites a bunch of * PNG and SVG files in the current working directory to demonstrate the creation of QR Codes. * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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 java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; //----------------------------------------------------------------------------- public final class QrCodeGeneratorDemo { // The main application program. public static void main(String[] args) throws IOException { doLudiiDemo(); } private static void doLudiiDemo() throws IOException { // Make the QR code object final String text = "https://ludii.games/variantDetails.php?keyword=Achi&variant=563"; final QrCode qr = QrCode.encodeText(text, QrCode.Ecc.MEDIUM); // Make the image final int scale = 10; final int border = 4; //final BufferedImage img = ToImage.toImage(qr, scale, border); //ToImage.addLudiiLogo(img, scale, false); final BufferedImage img = ToImage.toLudiiCodeImage(qr, scale, border); ImageIO.write(img, "png", new File("qr-game-1.png")); //String svg = ToImage.toSvgString(qr, 4, "#FFFFFF", "#000000"); //File svgFile = new File("game-1.svg"); //Files.write(svgFile.toPath(), svg.getBytes(StandardCharsets.UTF_8)); } }
2,572
39.203125
94
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/QrSegment.java
package graphics.qr_codes; /* * Fast QR Code generator library * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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 java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * A segment of character/binary/control data in a QR Code symbol. * Instances of this class are immutable. * <p>The mid-level way to create a segment is to take the payload data and call a * static factory function such as {@link QrSegment#makeNumeric(String)}. The low-level * way to create a segment is to custom-make the bit buffer and call the {@link * QrSegment#QrSegment(Mode,int,int[],int) constructor} with appropriate values.</p> * <p>This segment class imposes no length restrictions, but QR Codes have restrictions. * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. * Any segment longer than this is meaningless for the purpose of generating QR Codes. * This class can represent kanji mode segments, but provides no help in encoding them * - see {@link QrSegmentAdvanced} for full kanji support.</p> */ public final class QrSegment { /*---- Static factory functions (mid level) ----*/ /** * Returns a segment representing the specified binary data * encoded in byte mode. All input byte arrays are acceptable. * <p>Any text string can be converted to UTF-8 bytes ({@code * s.getBytes(StandardCharsets.UTF_8)}) and encoded as a byte mode segment.</p> * @param data the binary data (not {@code null}) * @return a segment (not {@code null}) containing the data * @throws NullPointerException if the array is {@code null} */ public static QrSegment makeBytes(byte[] data) { Objects.requireNonNull(data); if (data.length * 8L > Integer.MAX_VALUE) throw new IllegalArgumentException("Data too long"); int[] bits = new int[(data.length + 3) / 4]; for (int i = 0; i < data.length; i++) bits[i >>> 2] |= (data[i] & 0xFF) << (~i << 3); return new QrSegment(Mode.BYTE, data.length, bits, data.length * 8); } /** * Returns a segment representing the specified string of decimal digits encoded in numeric mode. * @param digits the text (not {@code null}), with only digits from 0 to 9 allowed * @return a segment (not {@code null}) containing the text * @throws NullPointerException if the string is {@code null} * @throws IllegalArgumentException if the string contains non-digit characters */ public static QrSegment makeNumeric(String digits) { Objects.requireNonNull(digits); BitBuffer bb = new BitBuffer(); int accumData = 0; int accumCount = 0; for (int i = 0; i < digits.length(); i++) { char c = digits.charAt(i); if (c < '0' || c > '9') throw new IllegalArgumentException("String contains non-numeric characters"); accumData = accumData * 10 + (c - '0'); accumCount++; if (accumCount == 3) { bb.appendBits(accumData, 10); accumData = 0; accumCount = 0; } } if (accumCount > 0) // 1 or 2 digits remaining bb.appendBits(accumData, accumCount * 3 + 1); return new QrSegment(Mode.NUMERIC, digits.length(), bb.data, bb.bitLength); } /** * Returns a segment representing the specified text string encoded in alphanumeric mode. * The characters allowed are: 0 to 9, A to Z (uppercase only), space, * dollar, percent, asterisk, plus, hyphen, period, slash, colon. * @param text the text (not {@code null}), with only certain characters allowed * @return a segment (not {@code null}) containing the text * @throws NullPointerException if the string is {@code null} * @throws IllegalArgumentException if the string contains non-encodable characters */ public static QrSegment makeAlphanumeric(String text) { Objects.requireNonNull(text); BitBuffer bb = new BitBuffer(); int accumData = 0; int accumCount = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c >= ALPHANUMERIC_MAP.length || ALPHANUMERIC_MAP[c] == -1) throw new IllegalArgumentException("String contains unencodable characters in alphanumeric mode"); accumData = accumData * 45 + ALPHANUMERIC_MAP[c]; accumCount++; if (accumCount == 2) { bb.appendBits(accumData, 11); accumData = 0; accumCount = 0; } } if (accumCount > 0) // 1 character remaining bb.appendBits(accumData, 6); return new QrSegment(Mode.ALPHANUMERIC, text.length(), bb.data, bb.bitLength); } /** * Returns a list of zero or more segments to represent the specified Unicode text string. * The result may use various segment modes and switch modes to optimize the length of the bit stream. * @param text the text to be encoded, which can be any Unicode string * @return a new mutable list (not {@code null}) of segments (not {@code null}) containing the text * @throws NullPointerException if the text is {@code null} */ public static List<QrSegment> makeSegments(String text) { Objects.requireNonNull(text); // Select the most efficient segment encoding automatically List<QrSegment> result = new ArrayList<>(); if (text.equals("")) return result; // Leave result empty else if (isNumeric(text)) result.add(makeNumeric(text)); else if (isAlphanumeric(text)) result.add(makeAlphanumeric(text)); else result.add(makeBytes(text.getBytes(StandardCharsets.UTF_8))); return result; } /** * Returns a segment representing an Extended Channel Interpretation * (ECI) designator with the specified assignment value. * @param assignVal the ECI assignment number (see the AIM ECI specification) * @return a segment (not {@code null}) containing the data * @throws IllegalArgumentException if the value is outside the range [0, 10<sup>6</sup>) */ public static QrSegment makeEci(int assignVal) { BitBuffer bb = new BitBuffer(); if (assignVal < 0) throw new IllegalArgumentException("ECI assignment value out of range"); else if (assignVal < (1 << 7)) bb.appendBits(assignVal, 8); else if (assignVal < (1 << 14)) { bb.appendBits(2, 2); bb.appendBits(assignVal, 14); } else if (assignVal < 1_000_000) { bb.appendBits(6, 3); bb.appendBits(assignVal, 21); } else throw new IllegalArgumentException("ECI assignment value out of range"); return new QrSegment(Mode.ECI, 0, bb.data, bb.bitLength); } /** * Tests whether the specified string can be encoded as a segment in numeric mode. * A string is encodable iff each character is in the range 0 to 9. * @param text the string to test for encodability (not {@code null}) * @return {@code true} iff each character is in the range 0 to 9. * @throws NullPointerException if the string is {@code null} * @see #makeNumeric(String) */ public static boolean isNumeric(String text) { for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c < '0' || c > '9') return false; } return true; } /** * Tests whether the specified string can be encoded as a segment in alphanumeric mode. * A string is encodable iff each character is in the following set: 0 to 9, A to Z * (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. * @param text the string to test for encodability (not {@code null}) * @return {@code true} iff each character is in the alphanumeric mode character set * @throws NullPointerException if the string is {@code null} * @see #makeAlphanumeric(String) */ public static boolean isAlphanumeric(String text) { for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c >= ALPHANUMERIC_MAP.length || ALPHANUMERIC_MAP[c] == -1) return false; } return true; } /*---- Instance fields ----*/ /** The mode indicator of this segment. Not {@code null}. */ public final Mode mode; /** The length of this segment's unencoded data. Measured in characters for * numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. * Always zero or positive. Not the same as the data's bit length. */ public final int numChars; // The data bits of this segment. Not null. final int[] data; // Requires 0 <= bitLength <= data.length * 32. final int bitLength; /*---- Constructor (low level) ----*/ /** * Constructs a QR Code segment with the specified attributes and data. * The character count (numCh) must agree with the mode and the bit buffer length, * but the constraint isn't checked. The specified bit buffer is cloned and stored. * @param md the mode (not {@code null}) * @param numCh the data length in characters or bytes, which is non-negative * @param data the data bits (not {@code null}) * @param bitLen the number of valid prefix bits in the data array * @throws NullPointerException if the mode or data is {@code null} * @throws IllegalArgumentException if the character count is negative */ public QrSegment(Mode md, int numCh, int[] data, int bitLen) { mode = Objects.requireNonNull(md); this.data = Objects.requireNonNull(data); if (numCh < 0 || bitLen < 0 || bitLen > data.length * 32L) throw new IllegalArgumentException("Invalid value"); numChars = numCh; bitLength = bitLen; } // Calculates the number of bits needed to encode the given segments at the given version. // Returns a non-negative number if successful. Otherwise returns -1 if a segment has too // many characters to fit its length field, or the total bits exceeds Integer.MAX_VALUE. static int getTotalBits(List<QrSegment> segs, int version) { Objects.requireNonNull(segs); long result = 0; for (QrSegment seg : segs) { Objects.requireNonNull(seg); int ccbits = seg.mode.numCharCountBits(version); if (seg.numChars >= (1 << ccbits)) return -1; // The segment's length doesn't fit the field's bit width result += 4L + ccbits + seg.bitLength; if (result > Integer.MAX_VALUE) return -1; // The sum will overflow an int type } return (int)result; } /*---- Constants ----*/ static final int[] ALPHANUMERIC_MAP; static { final String ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; int maxCh = -1; for (int i = 0; i < ALPHANUMERIC_CHARSET.length(); i++) maxCh = Math.max(ALPHANUMERIC_CHARSET.charAt(i), maxCh); ALPHANUMERIC_MAP = new int[maxCh + 1]; Arrays.fill(ALPHANUMERIC_MAP, -1); for (int i = 0; i < ALPHANUMERIC_CHARSET.length(); i++) ALPHANUMERIC_MAP[ALPHANUMERIC_CHARSET.charAt(i)] = i; } // /*---- Public helper enumeration ----*/ // // /** // * Describes how a segment's data bits are interpreted. // */ // public enum Mode { // // /*-- Constants --*/ // // NUMERIC (0x1, 10, 12, 14), // ALPHANUMERIC(0x2, 9, 11, 13), // BYTE (0x4, 8, 16, 16), // KANJI (0x8, 8, 10, 12), // ECI (0x7, 0, 0, 0); // // // /*-- Fields --*/ // // // The mode indicator bits, which is a uint4 value (range 0 to 15). // final int modeBits; // // // Number of character count bits for three different version ranges. // private final int[] numBitsCharCount; // // // /*-- Constructor --*/ // // private Mode(int mode, int... ccbits) { // modeBits = mode; // numBitsCharCount = ccbits; // } // // // /*-- Method --*/ // // // Returns the bit width of the character count field for a segment in this mode // // in a QR Code at the given version number. The result is in the range [0, 16]. // int numCharCountBits(int ver) { // assert QrCode.MIN_VERSION <= ver && ver <= QrCode.MAX_VERSION; // return numBitsCharCount[(ver + 7) / 17]; // } // // } }
12,759
36.529412
103
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/QrSegmentAdvanced.java
package graphics.qr_codes; /* * Fast QR Code generator library * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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 java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.List; import java.util.Objects; /** * Splits text into optimal segments and encodes kanji segments. * Provides static functions only; not instantiable. * @see QrSegment * @see QrCode */ public final class QrSegmentAdvanced { /*---- Optimal list of segments encoder ----*/ /** * Returns a list of zero or more segments to represent the specified Unicode text string. * The resulting list optimally minimizes the total encoded bit length, subjected to the constraints * in the specified {error correction level, minimum version number, maximum version number}. * <p>This function can utilize all four text encoding modes: numeric, alphanumeric, byte (UTF-8), * and kanji. This can be considered as a sophisticated but slower replacement for {@link * QrSegment#makeSegments(String)}. This requires more input parameters because it searches a * range of versions, like {@link QrCode#encodeSegments(List,QrCode.Ecc,int,int,int,boolean)}.</p> * @param text the text to be encoded (not {@code null}), which can be any Unicode string * @param ecl the error correction level to use (not {@code null}) * @param minVersion the minimum allowed version of the QR Code (at least 1) * @param maxVersion the maximum allowed version of the QR Code (at most 40) * @return a new mutable list (not {@code null}) of segments (not {@code null}) * containing the text, minimizing the bit length with respect to the constraints * @throws NullPointerException if the text or error correction level is {@code null} * @throws IllegalArgumentException if 1 &#x2264; minVersion &#x2264; maxVersion &#x2264; 40 is violated * @throws DataTooLongException if the text fails to fit in the maxVersion QR Code at the ECL */ public static List<QrSegment> makeSegmentsOptimally(String text, QrCode.Ecc ecl, int minVersion, int maxVersion) { // Check arguments Objects.requireNonNull(text); Objects.requireNonNull(ecl); if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)) throw new IllegalArgumentException("Invalid value"); // Iterate through version numbers, and make tentative segments List<QrSegment> segs = null; int[] codePoints = toCodePoints(text); for (int version = minVersion; ; version++) { if (version == minVersion || version == 10 || version == 27) segs = makeSegmentsOptimally(codePoints, version); assert segs != null; // Check if the segments fit int dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8; int dataUsedBits = QrSegment.getTotalBits(segs, version); if (dataUsedBits != -1 && dataUsedBits <= dataCapacityBits) return segs; // This version number is found to be suitable if (version >= maxVersion) { // All versions in the range could not fit the given text String msg = "Segment too long"; if (dataUsedBits != -1) msg = String.format("Data length = %d bits, Max capacity = %d bits", dataUsedBits, dataCapacityBits); throw new DataTooLongException(msg); } } } // Returns a new list of segments that is optimal for the given text at the given version number. private static List<QrSegment> makeSegmentsOptimally(int[] codePoints, int version) { if (codePoints.length == 0) return new ArrayList<>(); Mode[] charModes = computeCharacterModes(codePoints, version); return splitIntoSegments(codePoints, charModes); } // Returns a new array representing the optimal mode per code point based on the given text and version. private static Mode[] computeCharacterModes(int[] codePoints, int version) { if (codePoints.length == 0) throw new IllegalArgumentException(); final Mode[] modeTypes = {Mode.BYTE, Mode.ALPHANUMERIC, Mode.NUMERIC, Mode.KANJI}; // Do not modify final int numModes = modeTypes.length; // Segment header sizes, measured in 1/6 bits final int[] headCosts = new int[numModes]; for (int i = 0; i < numModes; i++) headCosts[i] = (4 + modeTypes[i].numCharCountBits(version)) * 6; // charModes[i][j] represents the mode to encode the code point at // index i such that the final segment ends in modeTypes[j] and the // total number of bits is minimized over all possible choices Mode[][] charModes = new Mode[codePoints.length][numModes]; // At the beginning of each iteration of the loop below, // prevCosts[j] is the exact minimum number of 1/6 bits needed to // encode the entire string prefix of length i, and end in modeTypes[j] int[] prevCosts = headCosts.clone(); // Calculate costs using dynamic programming for (int i = 0; i < codePoints.length; i++) { int c = codePoints[i]; int[] curCosts = new int[numModes]; { // Always extend a byte mode segment curCosts[0] = prevCosts[0] + countUtf8Bytes(c) * 8 * 6; charModes[i][0] = modeTypes[0]; } // Extend a segment if possible if (QrSegment.ALPHANUMERIC_MAP[c] != -1) { // Is alphanumeric curCosts[1] = prevCosts[1] + 33; // 5.5 bits per alphanumeric char charModes[i][1] = modeTypes[1]; } if ('0' <= c && c <= '9') { // Is numeric curCosts[2] = prevCosts[2] + 20; // 3.33 bits per digit charModes[i][2] = modeTypes[2]; } if (isKanji(c)) { curCosts[3] = prevCosts[3] + 78; // 13 bits per Shift JIS char charModes[i][3] = modeTypes[3]; } // Start new segment at the end to switch modes for (int j = 0; j < numModes; j++) { // To mode for (int k = 0; k < numModes; k++) { // From mode int newCost = (curCosts[k] + 5) / 6 * 6 + headCosts[j]; if (charModes[i][k] != null && (charModes[i][j] == null || newCost < curCosts[j])) { curCosts[j] = newCost; charModes[i][j] = modeTypes[k]; } } } prevCosts = curCosts; } // Find optimal ending mode Mode curMode = null; for (int i = 0, minCost = 0; i < numModes; i++) { if (curMode == null || prevCosts[i] < minCost) { minCost = prevCosts[i]; curMode = modeTypes[i]; } } // Get optimal mode for each code point by tracing backwards Mode[] result = new Mode[charModes.length]; for (int i = result.length - 1; i >= 0; i--) { for (int j = 0; j < numModes; j++) { if (modeTypes[j] == curMode) { curMode = charModes[i][j]; result[i] = curMode; break; } } } return result; } // Returns a new list of segments based on the given text and modes, such that // consecutive code points in the same mode are put into the same segment. private static List<QrSegment> splitIntoSegments(int[] codePoints, Mode[] charModes) { if (codePoints.length == 0) throw new IllegalArgumentException(); List<QrSegment> result = new ArrayList<>(); // Accumulate run of modes Mode curMode = charModes[0]; int start = 0; for (int i = 1; ; i++) { if (i < codePoints.length && charModes[i] == curMode) continue; String s = new String(codePoints, start, i - start); if (curMode == Mode.BYTE) result.add(QrSegment.makeBytes(s.getBytes(StandardCharsets.UTF_8))); else if (curMode == Mode.NUMERIC) result.add(QrSegment.makeNumeric(s)); else if (curMode == Mode.ALPHANUMERIC) result.add(QrSegment.makeAlphanumeric(s)); else if (curMode == Mode.KANJI) result.add(makeKanji(s)); else throw new AssertionError(); if (i >= codePoints.length) return result; curMode = charModes[i]; start = i; } } // Returns a new array of Unicode code points (effectively // UTF-32 / UCS-4) representing the given UTF-16 string. private static int[] toCodePoints(String s) { int[] result = s.codePoints().toArray(); for (int c : result) { if (Character.isSurrogate((char)c)) throw new IllegalArgumentException("Invalid UTF-16 string"); } return result; } // Returns the number of UTF-8 bytes needed to encode the given Unicode code point. private static int countUtf8Bytes(int cp) { if (cp < 0) throw new IllegalArgumentException("Invalid code point"); else if (cp < 0x80) return 1; else if (cp < 0x800) return 2; else if (cp < 0x10000) return 3; else if (cp < 0x110000) return 4; else throw new IllegalArgumentException("Invalid code point"); } /*---- Kanji mode segment encoder ----*/ /** * Returns a segment representing the specified text string encoded in kanji mode. * Broadly speaking, the set of encodable characters are {kanji used in Japan, * hiragana, katakana, East Asian punctuation, full-width ASCII, Greek, Cyrillic}. * Examples of non-encodable characters include {ordinary ASCII, half-width katakana, * more extensive Chinese hanzi}. * @param text the text (not {@code null}), with only certain characters allowed * @return a segment (not {@code null}) containing the text * @throws NullPointerException if the string is {@code null} * @throws IllegalArgumentException if the string contains non-encodable characters * @see #isEncodableAsKanji(String) */ public static QrSegment makeKanji(String text) { Objects.requireNonNull(text); BitBuffer bb = new BitBuffer(); text.chars().forEachOrdered(c -> { int val = UNICODE_TO_QR_KANJI[c]; if (val == -1) throw new IllegalArgumentException("String contains non-kanji-mode characters"); bb.appendBits(val, 13); }); return new QrSegment(Mode.KANJI, text.length(), bb.data, bb.bitLength); } /** * Tests whether the specified string can be encoded as a segment in kanji mode. * Broadly speaking, the set of encodable characters are {kanji used in Japan, * hiragana, katakana, East Asian punctuation, full-width ASCII, Greek, Cyrillic}. * Examples of non-encodable characters include {ordinary ASCII, half-width katakana, * more extensive Chinese hanzi}. * @param text the string to test for encodability (not {@code null}) * @return {@code true} iff each character is in the kanji mode character set * @throws NullPointerException if the string is {@code null} * @see #makeKanji(String) */ public static boolean isEncodableAsKanji(String text) { Objects.requireNonNull(text); return text.chars().allMatch( c -> isKanji((char)c)); } private static boolean isKanji(int c) { return c < UNICODE_TO_QR_KANJI.length && UNICODE_TO_QR_KANJI[c] != -1; } // Data derived from ftp://ftp.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/JIS/SHIFTJIS.TXT private static final String PACKED_QR_KANJI_TO_UNICODE = "MAAwATAC/wz/DjD7/xr/G/8f/wEwmzCcALT/QACo/z7/4/8/MP0w/jCdMJ4wA07dMAUwBjAHMPwgFSAQ/w8AXDAcIBb/XCAmICUgGCAZIBwgHf8I/wkwFDAV/zv/Pf9b/10wCDAJMAowCzAMMA0wDjAPMBAwEf8LIhIAsQDX//8A9/8dImD/HP8eImYiZyIeIjQmQiZA" + "ALAgMiAzIQP/5f8EAKIAo/8F/wP/Bv8K/yAApyYGJgUlyyXPJc4lxyXGJaEloCWzJbIlvSW8IDswEiGSIZAhkSGTMBP/////////////////////////////IggiCyKGIocigiKDIioiKf////////////////////8iJyIoAKwh0iHUIgAiA///////////////////" + "//////////8iICKlIxIiAiIHImEiUiJqImsiGiI9Ih0iNSIrIiz//////////////////yErIDAmbyZtJmogICAhALb//////////yXv/////////////////////////////////////////////////xD/Ef8S/xP/FP8V/xb/F/8Y/xn///////////////////8h" + "/yL/I/8k/yX/Jv8n/yj/Kf8q/yv/LP8t/y7/L/8w/zH/Mv8z/zT/Nf82/zf/OP85/zr///////////////////9B/0L/Q/9E/0X/Rv9H/0j/Sf9K/0v/TP9N/07/T/9Q/1H/Uv9T/1T/Vf9W/1f/WP9Z/1r//////////zBBMEIwQzBEMEUwRjBHMEgwSTBKMEswTDBN" + "ME4wTzBQMFEwUjBTMFQwVTBWMFcwWDBZMFowWzBcMF0wXjBfMGAwYTBiMGMwZDBlMGYwZzBoMGkwajBrMGwwbTBuMG8wcDBxMHIwczB0MHUwdjB3MHgweTB6MHswfDB9MH4wfzCAMIEwgjCDMIQwhTCGMIcwiDCJMIowizCMMI0wjjCPMJAwkTCSMJP/////////////" + "////////////////////////MKEwojCjMKQwpTCmMKcwqDCpMKowqzCsMK0wrjCvMLAwsTCyMLMwtDC1MLYwtzC4MLkwujC7MLwwvTC+ML8wwDDBMMIwwzDEMMUwxjDHMMgwyTDKMMswzDDNMM4wzzDQMNEw0jDTMNQw1TDWMNcw2DDZMNow2zDcMN0w3jDf//8w4DDh" + "MOIw4zDkMOUw5jDnMOgw6TDqMOsw7DDtMO4w7zDwMPEw8jDzMPQw9TD2/////////////////////wORA5IDkwOUA5UDlgOXA5gDmQOaA5sDnAOdA54DnwOgA6EDowOkA6UDpgOnA6gDqf////////////////////8DsQOyA7MDtAO1A7YDtwO4A7kDugO7A7wDvQO+" + "A78DwAPBA8MDxAPFA8YDxwPIA8n/////////////////////////////////////////////////////////////////////////////////////////////////////////////BBAEEQQSBBMEFAQVBAEEFgQXBBgEGQQaBBsEHAQdBB4EHwQgBCEEIgQjBCQEJQQm" + "BCcEKAQpBCoEKwQsBC0ELgQv////////////////////////////////////////BDAEMQQyBDMENAQ1BFEENgQ3BDgEOQQ6BDsEPAQ9//8EPgQ/BEAEQQRCBEMERARFBEYERwRIBEkESgRLBEwETQROBE///////////////////////////////////yUAJQIlDCUQ" + "JRglFCUcJSwlJCU0JTwlASUDJQ8lEyUbJRclIyUzJSslOyVLJSAlLyUoJTclPyUdJTAlJSU4JUL/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "/////////////////////////////////////06cVRZaA5Y/VMBhG2MoWfaQIoR1gxx6UGCqY+FuJWXthGaCppv1aJNXJ2WhYnFbm1nQhnuY9H1ifb6bjmIWfJ+It1uJXrVjCWaXaEiVx5eNZ09O5U8KT01PnVBJVvJZN1nUWgFcCWDfYQ9hcGYTaQVwunVPdXB5+32t" + "fe+Aw4QOiGOLApBVkHpTO06VTqVX34CykMF4704AWPFuopA4ejKDKIKLnC9RQVNwVL1U4VbgWftfFZjybeuA5IUt////////lmKWcJagl/tUC1PzW4dwz3+9j8KW6FNvnVx6uk4ReJOB/G4mVhhVBGsdhRqcO1nlU6ltZnTclY9WQk6RkEuW8oNPmQxT4VW2WzBfcWYg" + "ZvNoBGw4bPNtKXRbdsh6Tpg0gvGIW4pgku1tsnWrdsqZxWCmiwGNipWyaY5TrVGG//9XElgwWURbtF72YChjqWP0bL9vFHCOcRRxWXHVcz9+AYJ2gtGFl5BgkludG1hpZbxsWnUlUflZLlllX4Bf3GK8ZfpqKmsna7Rzi3/BiVadLJ0OnsRcoWyWg3tRBFxLYbaBxmh2" + "cmFOWU/6U3hgaW4pek+X804LUxZO7k9VTz1PoU9zUqBT71YJWQ9awVu2W+F50WaHZ5xntmtMbLNwa3PCeY15vno8e4eCsYLbgwSDd4Pvg9OHZoqyVimMqI/mkE6XHoaKT8Rc6GIRcll1O4Hlgr2G/ozAlsWZE5nVTstPGonjVt5YSljKXvtf62AqYJRgYmHQYhJi0GU5" + "////////m0FmZmiwbXdwcHVMdoZ9dYKlh/mVi5aOjJ1R8VK+WRZUs1uzXRZhaGmCba94jYTLiFeKcpOnmrhtbJmohtlXo2f/hs6SDlKDVodUBF7TYuFkuWg8aDhru3NyeLp6a4maidKNa48DkO2Vo5aUl2lbZlyzaX2YTZhOY5t7IGor//9qf2i2nA1vX1JyVZ1gcGLs" + "bTtuB27RhFuJEI9EThScOVP2aRtqOpeEaCpRXHrDhLKR3JOMVludKGgigwWEMXylUgiCxXTmTn5Pg1GgW9JSClLYUudd+1WaWCpZ5luMW5hb215yXnlgo2EfYWNhvmPbZWJn0WhTaPprPmtTbFdvIm+Xb0V0sHUYduN3C3r/e6F8IX3pfzZ/8ICdgmaDnomzisyMq5CE" + "lFGVk5WRlaKWZZfTmSiCGE44VCtcuF3Mc6l2THc8XKl/640LlsGYEZhUmFhPAU8OU3FVnFZoV/pZR1sJW8RckF4MXn5fzGPuZzpl12XiZx9oy2jE////////al9eMGvFbBdsfXV/eUhbY3oAfQBfvYmPihiMtI13jsyPHZjimg6bPE6AUH1RAFmTW5xiL2KAZOxrOnKg" + "dZF5R3+ph/uKvItwY6yDypegVAlUA1WraFRqWIpweCdndZ7NU3RbooEahlCQBk4YTkVOx08RU8pUOFuuXxNgJWVR//9nPWxCbHJs43B4dAN6dnquewh9Gnz+fWZl53JbU7tcRV3oYtJi4GMZbiCGWooxjd2S+G8BeaabWk6oTqtOrE+bT6BQ0VFHevZRcVH2U1RTIVN/" + "U+tVrFiDXOFfN19KYC9gUGBtYx9lWWpLbMFywnLtd++A+IEFggiFTpD3k+GX/5lXmlpO8FHdXC1mgWltXEBm8ml1c4loUHyBUMVS5FdHXf6TJmWkayNrPXQ0eYF5vXtLfcqCuYPMiH+JX4s5j9GR0VQfkoBOXVA2U+VTOnLXc5Z36YLmjq+ZxpnImdJRd2Eahl5VsHp6" + "UHZb05BHloVOMmrbkedcUVxI////////Y5h6n2yTl3SPYXqqcYqWiHyCaBd+cGhRk2xS8lQbhauKE3+kjs2Q4VNmiIh5QU/CUL5SEVFEVVNXLXPqV4tZUV9iX4RgdWF2YWdhqWOyZDplbGZvaEJuE3Vmej18+31MfZl+S39rgw6DSobNigiKY4tmjv2YGp2PgriPzpvo" + "//9Sh2IfZINvwJaZaEFQkWsgbHpvVHp0fVCIQIojZwhO9lA5UCZQZVF8UjhSY1WnVw9YBVrMXvphsmH4YvNjcmkcailyfXKscy54FHhvfXl3DICpiYuLGYzijtKQY5N1lnqYVZoTnnhRQ1OfU7Nee18mbhtukHOEc/59Q4I3igCK+pZQTk5QC1PkVHxW+lnRW2Rd8V6r" + "XydiOGVFZ69uVnLQfMqItIChgOGD8IZOioeN6JI3lseYZ58TTpROkk8NU0hUSVQ+Wi9fjF+hYJ9op2qOdFp4gYqeiqSLd5GQTl6byU6kT3xPr1AZUBZRSVFsUp9SuVL+U5pT41QR////////VA5ViVdRV6JZfVtUW11bj13lXedd9154XoNeml63XxhgUmFMYpdi2GOn" + "ZTtmAmZDZvRnbWghaJdpy2xfbSptaW4vbp11MnaHeGx6P3zgfQV9GH1efbGAFYADgK+AsYFUgY+CKoNSiEyIYYsbjKKM/JDKkXWScXg/kvyVpJZN//+YBZmZmtidO1JbUqtT91QIWNVi92/gjGqPX565UUtSO1RKVv16QJF3nWCe0nNEbwmBcHURX/1g2pqoctuPvGtk" + "mANOylbwV2RYvlpaYGhhx2YPZgZoOWixbfd11X06gm6bQk6bT1BTyVUGXW9d5l3uZ/tsmXRzeAKKUJOWiN9XUF6nYytQtVCsUY1nAFTJWF5Zu1uwX2liTWOhaD1rc24IcH2Rx3KAeBV4JnltZY59MIPciMGPCZabUmRXKGdQf2qMoVG0V0KWKlg6aYqAtFSyXQ5X/HiV" + "nfpPXFJKVItkPmYoZxRn9XqEe1Z9IpMvaFybrXs5UxlRilI3////////W99i9mSuZOZnLWu6hamW0XaQm9ZjTJMGm6t2v2ZSTglQmFPCXHFg6GSSZWNoX3Hmc8p1I3uXfoKGlYuDjNuReJkQZaxmq2uLTtVO1E86T39SOlP4U/JV41bbWOtZy1nJWf9bUFxNXgJeK1/X" + "YB1jB2UvW1xlr2W9ZehnnWti//9re2wPc0V5SXnBfPh9GX0rgKKBAoHziZaKXoppimaKjIrujMeM3JbMmPxrb06LTzxPjVFQW1db+mFIYwFmQmshbstsu3I+dL111HjBeTqADIAzgeqElI+ebFCef18Pi1idK3r6jvhbjZbrTgNT8Vf3WTFayVukYIluf28Gdb6M6luf" + "hQB74FByZ/SCnVxhhUp+HoIOUZlcBGNojWZlnHFueT59F4AFix2OypBuhseQqlAfUvpcOmdTcHxyNZFMkciTK4LlW8JfMWD5TjtT1luIYktnMWuKculz4HougWuNo5FSmZZRElPXVGpb/2OIajl9rJcAVtpTzlRo////////W5dcMV3eT+5hAWL+bTJ5wHnLfUJ+TX/S" + "ge2CH4SQiEaJcouQjnSPL5AxkUuRbJbGkZxOwE9PUUVTQV+TYg5n1GxBbgtzY34mkc2Sg1PUWRlbv23ReV1+LnybWH5xn1H6iFOP8E/KXPtmJXeseuOCHJn/UcZfqmXsaW9riW3z//9ulm9kdv59FF3hkHWRh5gGUeZSHWJAZpFm2W4aXrZ90n9yZviFr4X3ivhSqVPZ" + "WXNej1+QYFWS5JZkULdRH1LdUyBTR1PsVOhVRlUxVhdZaFm+WjxbtVwGXA9cEVwaXoReil7gX3Bif2KEYttjjGN3ZgdmDGYtZnZnfmiiah9qNWy8bYhuCW5YcTxxJnFndcd3AXhdeQF5ZXnweuB7EXynfTmAloPWhIuFSYhdiPOKH4o8ilSKc4xhjN6RpJJmk36UGJac" + "l5hOCk4ITh5OV1GXUnBXzlg0WMxbIl44YMVk/mdhZ1ZtRHK2dXN6Y4S4i3KRuJMgVjFX9Jj+////////Yu1pDWuWce1+VIB3gnKJ5pjfh1WPsVw7TzhP4U+1VQdaIFvdW+lfw2FOYy9lsGZLaO5pm214bfF1M3W5dx95XnnmfTOB44KvhaqJqoo6jquPm5Aykd2XB066" + "TsFSA1h1WOxcC3UaXD2BTooKj8WWY5dteyWKz5gIkWJW81Oo//+QF1Q5V4JeJWOobDRwindhfIt/4IhwkEKRVJMQkxiWj3RemsRdB11pZXBnoo2olttjbmdJaRmDxZgXlsCI/m+EZHpb+E4WcCx1XWYvUcRSNlLiWdNfgWAnYhBlP2V0Zh9mdGjyaBZrY24FcnJ1H3bb" + "fL6AVljwiP2Jf4qgipOKy5AdkZKXUpdZZYl6DoEGlrteLWDcYhplpWYUZ5B383pNfE1+PoEKjKyNZI3hjl94qVIHYtljpWRCYpiKLXqDe8CKrJbqfXaCDIdJTtlRSFNDU2Bbo1wCXBZd3WImYkdksGgTaDRsyW1FbRdn029ccU5xfWXLen97rX3a////////fkp/qIF6" + "ghuCOYWmim6Mzo31kHiQd5KtkpGVg5uuUk1VhG84cTZRaHmFflWBs3zOVkxYUVyoY6pm/mb9aVpy2XWPdY55DnlWed98l30gfUSGB4o0ljuQYZ8gUOdSdVPMU+JQCVWqWO5ZT3I9W4tcZFMdYONg82NcY4NjP2O7//9kzWXpZvld42nNaf1vFXHlTol16Xb4epN8333P" + "fZyAYYNJg1iEbIS8hfuIxY1wkAGQbZOXlxyaElDPWJdhjoHThTWNCJAgT8NQdFJHU3Ngb2NJZ19uLI2zkB9P11xejMplz32aU1KIllF2Y8NbWFtrXApkDWdRkFxO1lkaWSpscIpRVT5YFVmlYPBiU2fBgjVpVZZAmcSaKE9TWAZb/oAQXLFeL1+FYCBhS2I0Zv9s8G7e" + "gM6Bf4LUiIuMuJAAkC6Wip7bm9tO41PwWSd7LJGNmEyd+W7dcCdTU1VEW4ViWGKeYtNsom/vdCKKF5Q4b8GK/oM4UeeG+FPq////////U+lPRpBUj7BZaoExXf166o+/aNqMN3L4nEhqPYqwTjlTWFYGV2ZixWOiZeZrTm3hbltwrXfteu97qn27gD2AxobLipWTW1bj" + "WMdfPmWtZpZqgGu1dTeKx1Akd+VXMF8bYGVmemxgdfR6Gn9ugfSHGJBFmbN7yXVcevl7UYTE//+QEHnpepKDNlrhd0BOLU7yW5lf4GK9Zjxn8WzohmuId4o7kU6S85nQahdwJnMqgueEV4yvTgFRRlHLVYtb9V4WXjNegV8UXzVfa1+0YfJjEWaiZx1vbnJSdTp3OoB0" + "gTmBeId2ir+K3I2FjfOSmpV3mAKc5VLFY1d29GcVbIhzzYzDk66Wc20lWJxpDmnMj/2TmnXbkBpYWmgCY7Rp+09Dbyxn2I+7hSZ9tJNUaT9vcFdqWPdbLH0scipUCpHjnbROrU9OUFxQdVJDjJ5USFgkW5peHV6VXq1e918fYIxitWM6Y9Bor2xAeId5jnoLfeCCR4oC" + "iuaORJAT////////kLiRLZHYnw5s5WRYZOJldW70doR7G5Bpk9FuulTyX7lkpI9Nj+2SRFF4WGtZKVxVXpdt+36PdRyMvI7imFtwuU8da79vsXUwlvtRTlQQWDVYV1msXGBfkmWXZ1xuIXZ7g9+M7ZAUkP2TTXgleDpSql6mVx9ZdGASUBJRWlGs//9RzVIAVRBYVFhY" + "WVdblVz2XYtgvGKVZC1ncWhDaLxo33bXbdhub22bcG9xyF9Tddh5d3tJe1R7UnzWfXFSMIRjhWmF5IoOiwSMRo4PkAOQD5QZlnaYLZowldhQzVLVVAxYAlwOYadknm0ed7N65YD0hASQU5KFXOCdB1M/X5dfs22ccnl3Y3m/e+Rr0nLsiq1oA2phUfh6gWk0XEqc9oLr" + "W8WRSXAeVnhcb2DHZWZsjIxakEGYE1RRZseSDVlIkKNRhU5NUeqFmYsOcFhjepNLaWKZtH4EdXdTV2lgjt+W42xdToxcPF8Qj+lTAozRgImGeV7/ZeVOc1Fl////////WYJcP5fuTvtZil/Nio1v4XmweWJb54RxcytxsV50X/Vje2SaccN8mE5DXvxOS1fcVqJgqW/D" + "fQ2A/YEzgb+PsomXhqRd9GKKZK2Jh2d3bOJtPnQ2eDRaRn91gq2ZrE/zXsNi3WOSZVdnb3bDckyAzIC6jymRTVANV/lakmiF//9pc3Fkcv2Mt1jyjOCWapAZh3955HfnhClPL1JlU1pizWfPbMp2fXuUfJWCNoWEj+tm3W8gcgZ+G4OrmcGeplH9e7F4cnu4gId7SGro" + "XmGAjHVRdWBRa5Jibox2epGXmupPEH9wYpx7T5WlnOlWelhZhuSWvE80UiRTSlPNU9teBmQsZZFnf2w+bE5ySHKvc+11VH5BgiyF6Yype8SRxnFpmBKY72M9Zml1anbkeNCFQ4buUypTUVQmWYNeh198YLJiSWJ5YqtlkGvUbMx1snaueJF52H3Lf3eApYirirmMu5B/" + "l16Y22oLfDhQmVw+X65nh2vYdDV3CX+O////////nztnynoXUzl1i5rtX2aBnYPxgJhfPF/FdWJ7RpA8aGdZ61qbfRB2fossT/VfamoZbDdvAnTieWiIaIpVjHle32PPdcV50oLXkyiS8oSchu2cLVTBX2xljG1ccBWMp4zTmDtlT3T2Tg1O2FfgWStaZlvMUaheA16c" + "YBZidmV3//9lp2ZubW5yNnsmgVCBmoKZi1yMoIzmjXSWHJZET65kq2tmgh6EYYVqkOhcAWlTmKiEeoVXTw9Sb1+pXkVnDXmPgXmJB4mGbfVfF2JVbLhOz3Jpm5JSBlQ7VnRYs2GkYm5xGllufIl83n0blvBlh4BeThlPdVF1WEBeY15zXwpnxE4mhT2ViZZbfHOYAVD7" + "WMF2VninUiV3pYURe4ZQT1kJckd7x33oj7qP1JBNT79SyVopXwGXrU/dgheS6lcDY1VraXUriNyPFHpCUt9Yk2FVYgpmrmvNfD+D6VAjT/hTBVRGWDFZSVudXPBc710pXpZisWNnZT5luWcL////////bNVs4XD5eDJ+K4DegrOEDITshwKJEooqjEqQppLSmP2c851s" + "Tk9OoVCNUlZXSlmoXj1f2F/ZYj9mtGcbZ9Bo0lGSfSGAqoGoiwCMjIy/kn6WMlQgmCxTF1DVU1xYqGSyZzRyZ3dmekaR5lLDbKFrhlgAXkxZVGcsf/tR4XbG//9kaXjom1Seu1fLWblmJ2eaa85U6WnZXlWBnGeVm6pn/pxSaF1Opk/jU8hiuWcrbKuPxE+tfm2ev04H" + "YWJugG8rhRNUc2cqm0Vd83uVXKxbxoccbkqE0XoUgQhZmXyNbBF3IFLZWSJxIXJfd9uXJ51haQtaf1oYUaVUDVR9Zg5234/3kpic9Fnqcl1uxVFNaMl9v33sl2KeumR4aiGDAlmEW19r23MbdvJ9soAXhJlRMmcontl27mdiUv+ZBVwkYjt8foywVU9gtn0LlYBTAU5f" + "UbZZHHI6gDaRzl8ld+JThF95fQSFrIozjo2XVmfzha6UU2EJYQhsuXZS////////iu2POFUvT1FRKlLHU8tbpV59YKBhgmPWZwln2m5nbYxzNnM3dTF5UIjVipiQSpCRkPWWxIeNWRVOiE9ZTg6KiY8/mBBQrV58WZZbuV64Y9pj+mTBZtxpSmnYbQtutnGUdSh6r3+K" + "gACESYTJiYGLIY4KkGWWfZkKYX5ikWsy//9sg210f8x//G3Af4WHuoj4Z2WDsZg8lvdtG31hhD2Rak5xU3VdUGsEb+uFzYYtiadSKVQPXGVnTmiodAZ0g3XiiM+I4ZHMluKWeF+Lc4d6y4ROY6B1ZVKJbUFunHQJdVl4a3ySloZ63J+NT7ZhbmXFhlxOhk6uUNpOIVHM" + "W+5lmWiBbbxzH3ZCd616HHzngm+K0pB8kc+WdZgYUpt90VArU5hnl23LcdB0M4HojyqWo5xXnp90YFhBbZl9L5heTuRPNk+LUbdSsV26YBxzsnk8gtOSNJa3lvaXCp6Xn2Jmpmt0UhdSo3DIiMJeyWBLYZBvI3FJfD599IBv////////hO6QI5MsVEKbb2rTcImMwo3v" + "lzJStFpBXspfBGcXaXxplG1qbw9yYnL8e+2AAYB+h0uQzlFtnpN5hICLkzKK1lAtVIyKcWtqjMSBB2DRZ6Cd8k6ZTpicEIprhcGFaGkAbn54l4FV////////////////////////////////////////////////////////////////////////////////////////" + "/////////////////////////////18MThBOFU4qTjFONk48Tj9OQk5WTlhOgk6FjGtOioISXw1Ojk6eTp9OoE6iTrBOs062Ts5OzU7ETsZOwk7XTt5O7U7fTvdPCU9aTzBPW09dT1dPR092T4hPj0+YT3tPaU9wT5FPb0+GT5ZRGE/UT99Pzk/YT9tP0U/aT9BP5E/l" + "UBpQKFAUUCpQJVAFTxxP9lAhUClQLE/+T+9QEVAGUENQR2cDUFVQUFBIUFpQVlBsUHhQgFCaUIVQtFCy////////UMlQylCzUMJQ1lDeUOVQ7VDjUO5Q+VD1UQlRAVECURZRFVEUURpRIVE6UTdRPFE7UT9RQFFSUUxRVFFievhRaVFqUW5RgFGCVthRjFGJUY9RkVGT" + "UZVRllGkUaZRolGpUapRq1GzUbFRslGwUbVRvVHFUclR21HghlVR6VHt//9R8FH1Uf5SBFILUhRSDlInUipSLlIzUjlST1JEUktSTFJeUlRSalJ0UmlSc1J/Un1SjVKUUpJScVKIUpGPqI+nUqxSrVK8UrVSwVLNUtdS3lLjUuaY7VLgUvNS9VL4UvlTBlMIdThTDVMQ" + "Uw9TFVMaUyNTL1MxUzNTOFNAU0ZTRU4XU0lTTVHWU15TaVNuWRhTe1N3U4JTllOgU6ZTpVOuU7BTtlPDfBKW2VPfZvxx7lPuU+hT7VP6VAFUPVRAVCxULVQ8VC5UNlQpVB1UTlSPVHVUjlRfVHFUd1RwVJJUe1SAVHZUhFSQVIZUx1SiVLhUpVSsVMRUyFSo////////" + "VKtUwlSkVL5UvFTYVOVU5lUPVRRU/VTuVO1U+lTiVTlVQFVjVUxVLlVcVUVVVlVXVThVM1VdVZlVgFSvVYpVn1V7VX5VmFWeVa5VfFWDValVh1WoVdpVxVXfVcRV3FXkVdRWFFX3VhZV/lX9VhtV+VZOVlBx31Y0VjZWMlY4//9Wa1ZkVi9WbFZqVoZWgFaKVqBWlFaP" + "VqVWrla2VrRWwla8VsFWw1bAVshWzlbRVtNW11buVvlXAFb/VwRXCVcIVwtXDVcTVxhXFlXHVxxXJlc3VzhXTlc7V0BXT1dpV8BXiFdhV39XiVeTV6BXs1ekV6pXsFfDV8ZX1FfSV9NYClfWV+NYC1gZWB1YclghWGJYS1hwa8BYUlg9WHlYhVi5WJ9Yq1i6WN5Yu1i4" + "WK5YxVjTWNFY11jZWNhY5VjcWORY31jvWPpY+Vj7WPxY/VkCWQpZEFkbaKZZJVksWS1ZMlk4WT560llVWVBZTllaWVhZYllgWWdZbFlp////////WXhZgVmdT15Pq1mjWbJZxlnoWdxZjVnZWdpaJVofWhFaHFoJWhpaQFpsWklaNVo2WmJaalqaWrxavlrLWsJavVrj" + "Wtda5lrpWtZa+lr7WwxbC1sWWzJa0FsqWzZbPltDW0VbQFtRW1VbWltbW2VbaVtwW3NbdVt4ZYhbeluA//9bg1umW7hbw1vHW8lb1FvQW+Rb5lviW95b5VvrW/Bb9lvzXAVcB1wIXA1cE1wgXCJcKFw4XDlcQVxGXE5cU1xQXE9bcVxsXG5OYlx2XHlcjFyRXJRZm1yr" + "XLtctly8XLdcxVy+XMdc2VzpXP1c+lztXYxc6l0LXRVdF11cXR9dG10RXRRdIl0aXRldGF1MXVJdTl1LXWxdc112XYddhF2CXaJdnV2sXa5dvV2QXbddvF3JXc1d013SXdZd213rXfJd9V4LXhpeGV4RXhteNl43XkReQ15AXk5eV15UXl9eYl5kXkdedV52XnqevF5/" + "XqBewV7CXshe0F7P////////XtZe417dXtpe217iXuFe6F7pXuxe8V7zXvBe9F74Xv5fA18JX11fXF8LXxFfFl8pXy1fOF9BX0hfTF9OXy9fUV9WX1dfWV9hX21fc193X4Nfgl9/X4pfiF+RX4dfnl+ZX5hfoF+oX61fvF/WX/tf5F/4X/Ff3WCzX/9gIWBg//9gGWAQ" + "YClgDmAxYBtgFWArYCZgD2A6YFpgQWBqYHdgX2BKYEZgTWBjYENgZGBCYGxga2BZYIFgjWDnYINgmmCEYJtglmCXYJJgp2CLYOFguGDgYNNgtF/wYL1gxmC1YNhhTWEVYQZg9mD3YQBg9GD6YQNhIWD7YPFhDWEOYUdhPmEoYSdhSmE/YTxhLGE0YT1hQmFEYXNhd2FY" + "YVlhWmFrYXRhb2FlYXFhX2FdYVNhdWGZYZZhh2GsYZRhmmGKYZFhq2GuYcxhymHJYfdhyGHDYcZhumHLf3lhzWHmYeNh9mH6YfRh/2H9Yfxh/mIAYghiCWINYgxiFGIb////////Yh5iIWIqYi5iMGIyYjNiQWJOYl5iY2JbYmBiaGJ8YoJiiWJ+YpJik2KWYtRig2KU" + "Ytdi0WK7Ys9i/2LGZNRiyGLcYsxiymLCYsdim2LJYwxi7mLxYydjAmMIYu9i9WNQYz5jTWQcY09jlmOOY4Bjq2N2Y6Njj2OJY59jtWNr//9jaWO+Y+ljwGPGY+NjyWPSY/ZjxGQWZDRkBmQTZCZkNmUdZBdkKGQPZGdkb2R2ZE5lKmSVZJNkpWSpZIhkvGTaZNJkxWTH" + "ZLtk2GTCZPFk54IJZOBk4WKsZONk72UsZPZk9GTyZPplAGT9ZRhlHGUFZSRlI2UrZTRlNWU3ZTZlOHVLZUhlVmVVZU1lWGVeZV1lcmV4ZYJlg4uKZZtln2WrZbdlw2XGZcFlxGXMZdJl22XZZeBl4WXxZ3JmCmYDZftnc2Y1ZjZmNGYcZk9mRGZJZkFmXmZdZmRmZ2Zo" + "Zl9mYmZwZoNmiGaOZolmhGaYZp1mwWa5Zslmvma8////////ZsRmuGbWZtpm4GY/ZuZm6WbwZvVm92cPZxZnHmcmZyeXOGcuZz9nNmdBZzhnN2dGZ15nYGdZZ2NnZGeJZ3BnqWd8Z2pnjGeLZ6ZnoWeFZ7dn72e0Z+xns2fpZ7hn5GfeZ91n4mfuZ7lnzmfGZ+dqnGge" + "aEZoKWhAaE1oMmhO//9os2graFloY2h3aH9on2iPaK1olGidaJtog2quaLlodGi1aKBoumkPaI1ofmkBaMppCGjYaSJpJmjhaQxozWjUaOdo1Wk2aRJpBGjXaONpJWj5aOBo72koaSppGmkjaSFoxml5aXdpXGl4aWtpVGl+aW5pOWl0aT1pWWkwaWFpXmldaYFpammy" + "aa5p0Gm/acFp02m+ac5b6GnKad1pu2nDaadqLmmRaaBpnGmVabRp3mnoagJqG2n/awpp+WnyaedqBWmxah5p7WoUaetqCmoSasFqI2oTakRqDGpyajZqeGpHamJqWWpmakhqOGoiapBqjWqgaoRqomqj////////apeGF2q7asNqwmq4arNqrGreatFq32qqatpq6mr7" + "awWGFmr6axJrFpsxax9rOGs3dtxrOZjua0drQ2tJa1BrWWtUa1trX2tha3hreWt/a4BrhGuDa41rmGuVa55rpGuqa6trr2uya7Frs2u3a7xrxmvLa9Nr32vsa+tr82vv//+evmwIbBNsFGwbbCRsI2xebFVsYmxqbIJsjWyabIFsm2x+bGhsc2ySbJBsxGzxbNNsvWzX" + "bMVs3WyubLFsvmy6bNts72zZbOptH4hNbTZtK209bThtGW01bTNtEm0MbWNtk21kbVpteW1ZbY5tlW/kbYVt+W4VbgpttW3HbeZtuG3Gbext3m3Mbeht0m3Fbfpt2W3kbdVt6m3ubi1ubm4ubhlucm5fbj5uI25rbitudm5Nbh9uQ246bk5uJG7/bh1uOG6CbqpumG7J" + "brdu0269bq9uxG6ybtRu1W6PbqVuwm6fb0FvEXBMbuxu+G7+bz9u8m8xbu9vMm7M////////bz5vE273b4Zvem94b4FvgG9vb1tv829tb4JvfG9Yb45vkW/Cb2Zvs2+jb6FvpG+5b8Zvqm/fb9Vv7G/Ub9hv8W/ub9twCXALb/pwEXABcA9v/nAbcBpvdHAdcBhwH3Aw" + "cD5wMnBRcGNwmXCScK9w8XCscLhws3CucN9wy3Dd//9w2XEJcP1xHHEZcWVxVXGIcWZxYnFMcVZxbHGPcftxhHGVcahxrHHXcblxvnHScclx1HHOceBx7HHncfVx/HH5cf9yDXIQchtyKHItcixyMHIycjtyPHI/ckByRnJLclhydHJ+coJygXKHcpJylnKicqdyuXKy" + "csNyxnLEcs5y0nLicuBy4XL5cvdQD3MXcwpzHHMWcx1zNHMvcylzJXM+c05zT57Yc1dzanNoc3BzeHN1c3tzenPIc7NzznO7c8Bz5XPuc950onQFdG90JXP4dDJ0OnRVdD90X3RZdEF0XHRpdHB0Y3RqdHZ0fnSLdJ50p3TKdM901HPx////////dOB043TndOl07nTy" + "dPB08XT4dPd1BHUDdQV1DHUOdQ11FXUTdR51JnUsdTx1RHVNdUp1SXVbdUZ1WnVpdWR1Z3VrdW11eHV2dYZ1h3V0dYp1iXWCdZR1mnWddaV1o3XCdbN1w3W1db11uHW8dbF1zXXKddJ12XXjdd51/nX///91/HYBdfB1+nXydfN2C3YNdgl2H3YndiB2IXYidiR2NHYw" + "djt2R3ZIdkZ2XHZYdmF2YnZodml2anZndmx2cHZydnZ2eHZ8doB2g3aIdot2jnaWdpN2mXaadrB2tHa4drl2unbCds121nbSdt524Xbldud26oYvdvt3CHcHdwR3KXckdx53JXcmdxt3N3c4d0d3Wndod2t3W3dld393fnd5d453i3eRd6B3nnewd7Z3uXe/d7x3vXe7" + "d8d3zXfXd9p33Hfjd+53/HgMeBJ5JnggeSp4RXiOeHR4hnh8eJp4jHijeLV4qniveNF4xnjLeNR4vni8eMV4ynjs////////eOd42nj9ePR5B3kSeRF5GXkseSt5QHlgeVd5X3laeVV5U3l6eX95inmdeaefS3mqea55s3m5ebp5yXnVeed57HnheeN6CHoNehh6GXog" + "eh95gHoxejt6Pno3ekN6V3pJemF6Ynppn516cHp5en16iHqXepV6mHqWeql6yHqw//96tnrFesR6v5CDesd6ynrNes961XrTetl62nrdeuF64nrmeu168HsCew97CnsGezN7GHsZex57NXsoezZ7UHt6ewR7TXsLe0x7RXt1e2V7dHtne3B7cXtse257nXuYe597jXuc" + "e5p7i3uSe497XXuZe8t7wXvMe897tHvGe9176XwRfBR75nvlfGB8AHwHfBN783v3fBd8DXv2fCN8J3wqfB98N3wrfD18THxDfFR8T3xAfFB8WHxffGR8VnxlfGx8dXyDfJB8pHytfKJ8q3yhfKh8s3yyfLF8rny5fL18wHzFfMJ82HzSfNx84ps7fO988nz0fPZ8+n0G" + "////////fQJ9HH0VfQp9RX1LfS59Mn0/fTV9Rn1zfVZ9Tn1yfWh9bn1PfWN9k32JfVt9j319fZt9un2ufaN9tX3Hfb19q349faJ9r33cfbh9n32wfdh93X3kfd59+33yfeF+BX4KfiN+IX4SfjF+H34Jfgt+In5GfmZ+O341fjl+Q343//9+Mn46fmd+XX5Wfl5+WX5a" + "fnl+an5pfnx+e36DfdV+fY+ufn9+iH6Jfox+kn6QfpN+lH6Wfo5+m36cfzh/On9Ff0x/TX9Of1B/UX9Vf1R/WH9ff2B/aH9pf2d/eH+Cf4Z/g3+If4d/jH+Uf55/nX+af6N/r3+yf7l/rn+2f7iLcX/Ff8Z/yn/Vf9R/4X/mf+l/83/5mNyABoAEgAuAEoAYgBmAHIAh" + "gCiAP4A7gEqARoBSgFiAWoBfgGKAaIBzgHKAcIB2gHmAfYB/gISAhoCFgJuAk4CagK1RkICsgNuA5YDZgN2AxIDagNaBCYDvgPGBG4EpgSOBL4FL////////louBRoE+gVOBUYD8gXGBboFlgWaBdIGDgYiBioGAgYKBoIGVgaSBo4FfgZOBqYGwgbWBvoG4gb2BwIHC" + "gbqByYHNgdGB2YHYgciB2oHfgeCB54H6gfuB/oIBggKCBYIHggqCDYIQghaCKYIrgjiCM4JAglmCWIJdglqCX4Jk//+CYoJogmqCa4IugnGCd4J4gn6CjYKSgquCn4K7gqyC4YLjgt+C0oL0gvOC+oOTgwOC+4L5gt6DBoLcgwmC2YM1gzSDFoMygzGDQIM5g1CDRYMv" + "gyuDF4MYg4WDmoOqg5+DooOWgyODjoOHg4qDfIO1g3ODdYOgg4mDqIP0hBOD64POg/2EA4PYhAuDwYP3hAeD4IPyhA2EIoQgg72EOIUGg/uEbYQqhDyFWoSEhHeEa4SthG6EgoRphEaELIRvhHmENYTKhGKEuYS/hJ+E2YTNhLuE2oTQhMGExoTWhKGFIYT/hPSFF4UY" + "hSyFH4UVhRSE/IVAhWOFWIVI////////hUGGAoVLhVWFgIWkhYiFkYWKhaiFbYWUhZuF6oWHhZyFd4V+hZCFyYW6hc+FuYXQhdWF3YXlhdyF+YYKhhOGC4X+hfqGBoYihhqGMIY/hk1OVYZUhl+GZ4ZxhpOGo4aphqqGi4aMhraGr4bEhsaGsIbJiCOGq4bUht6G6Ybs" + "//+G34bbhu+HEocGhwiHAIcDhvuHEYcJhw2G+YcKhzSHP4c3hzuHJYcphxqHYIdfh3iHTIdOh3SHV4doh26HWYdTh2OHaogFh6KHn4eCh6+Hy4e9h8CH0JbWh6uHxIezh8eHxoe7h++H8ofgiA+IDYf+h/aH94gOh9KIEYgWiBWIIoghiDGINog5iCeIO4hEiEKIUohZ" + "iF6IYohriIGIfoieiHWIfYi1iHKIgoiXiJKIroiZiKKIjYikiLCIv4ixiMOIxIjUiNiI2YjdiPmJAoj8iPSI6IjyiQSJDIkKiROJQ4keiSWJKokriUGJRIk7iTaJOIlMiR2JYIle////////iWaJZIltiWqJb4l0iXeJfomDiYiJiomTiZiJoYmpiaaJrImvibKJuom9" + "ib+JwInaidyJ3YnnifSJ+IoDihaKEIoMihuKHYolijaKQYpbilKKRopIinyKbYpsimKKhYqCioSKqIqhipGKpYqmipqKo4rEis2KworaiuuK84rn//+K5IrxixSK4IriiveK3orbiwyLB4saiuGLFosQixeLIIszl6uLJosriz6LKItBi0yLT4tOi0mLVotbi1qLa4tf" + "i2yLb4t0i32LgIuMi46LkouTi5aLmYuajDqMQYw/jEiMTIxOjFCMVYxijGyMeIx6jIKMiYyFjIqMjYyOjJSMfIyYYh2MrYyqjL2MsoyzjK6MtozIjMGM5IzjjNqM/Yz6jPuNBI0FjQqNB40PjQ2NEJ9OjROMzY0UjRaNZ41tjXGNc42BjZmNwo2+jbqNz43ajdaNzI3b" + "jcuN6o3rjd+N4438jgiOCY3/jh2OHo4Qjh+OQo41jjCONI5K////////jkeOSY5MjlCOSI5ZjmSOYI4qjmOOVY52jnKOfI6BjoeOhY6EjouOio6TjpGOlI6ZjqqOoY6sjrCOxo6xjr6OxY7IjsuO247jjvyO+47rjv6PCo8FjxWPEo8ZjxOPHI8fjxuPDI8mjzOPO485" + "j0WPQo8+j0yPSY9Gj06PV49c//+PYo9jj2SPnI+fj6OPrY+vj7eP2o/lj+KP6o/vkIeP9JAFj/mP+pARkBWQIZANkB6QFpALkCeQNpA1kDmP+JBPkFCQUZBSkA6QSZA+kFaQWJBekGiQb5B2lqiQcpCCkH2QgZCAkIqQiZCPkKiQr5CxkLWQ4pDkYkiQ25ECkRKRGZEy" + "kTCRSpFWkViRY5FlkWmRc5FykYuRiZGCkaKRq5GvkaqRtZG0kbqRwJHBkcmRy5HQkdaR35HhkduR/JH1kfaSHpH/khSSLJIVkhGSXpJXkkWSSZJkkkiSlZI/kkuSUJKckpaSk5KbklqSz5K5kreS6ZMPkvqTRJMu////////kxmTIpMakyOTOpM1kzuTXJNgk3yTbpNW" + "k7CTrJOtk5STuZPWk9eT6JPlk9iTw5Pdk9CTyJPklBqUFJQTlAOUB5QQlDaUK5Q1lCGUOpRBlFKURJRblGCUYpRelGqSKZRwlHWUd5R9lFqUfJR+lIGUf5WClYeVipWUlZaVmJWZ//+VoJWolaeVrZW8lbuVuZW+lcpv9pXDlc2VzJXVldSV1pXcleGV5ZXiliGWKJYu" + "li+WQpZMlk+WS5Z3llyWXpZdll+WZpZylmyWjZaYlpWWl5aqlqeWsZaylrCWtJa2lriWuZbOlsuWyZbNiU2W3JcNltWW+ZcElwaXCJcTlw6XEZcPlxaXGZcklyqXMJc5lz2XPpdEl0aXSJdCl0mXXJdgl2SXZpdoUtKXa5dxl3mXhZd8l4GXepeGl4uXj5eQl5yXqJem" + "l6OXs5e0l8OXxpfIl8uX3Jftn0+X8nrfl/aX9ZgPmAyYOJgkmCGYN5g9mEaYT5hLmGuYb5hw////////mHGYdJhzmKqYr5ixmLaYxJjDmMaY6ZjrmQOZCZkSmRSZGJkhmR2ZHpkkmSCZLJkumT2ZPplCmUmZRZlQmUuZUZlSmUyZVZmXmZiZpZmtma6ZvJnfmduZ3ZnY" + "mdGZ7ZnumfGZ8pn7mfiaAZoPmgWZ4poZmiuaN5pFmkKaQJpD//+aPppVmk2aW5pXml+aYpplmmSaaZprmmqarZqwmryawJrPmtGa05rUmt6a35rimuOa5prvmuua7pr0mvGa95r7mwabGJsamx+bIpsjmyWbJ5somymbKpsumy+bMptEm0ObT5tNm06bUZtYm3Sbk5uD" + "m5GblpuXm5+boJuom7SbwJvKm7mbxpvPm9Gb0pvjm+Kb5JvUm+GcOpvym/Gb8JwVnBScCZwTnAycBpwInBKcCpwEnC6cG5wlnCScIZwwnEecMpxGnD6cWpxgnGecdpx4nOec7JzwnQmdCJzrnQOdBp0qnSadr50jnR+dRJ0VnRKdQZ0/nT6dRp1I////////nV2dXp1k" + "nVGdUJ1ZnXKdiZ2Hnaudb516nZqdpJ2pnbKdxJ3BnbuduJ26ncadz53Cndmd0534nead7Z3vnf2eGp4bnh6edZ55nn2egZ6InouejJ6SnpWekZ6dnqWeqZ64nqqerZdhnsyezp7PntCe1J7cnt6e3Z7gnuWe6J7v//+e9J72nvee+Z77nvye/Z8Hnwh2t58VnyGfLJ8+" + "n0qfUp9Un2OfX59gn2GfZp9nn2yfap93n3Kfdp+Vn5yfoFgvaceQWXRkUdxxmf//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" + "/////////////////////////////////////////////w=="; private static short[] UNICODE_TO_QR_KANJI = new short[1 << 16]; static { // Unpack the Shift JIS table into a more computation-friendly form Arrays.fill(UNICODE_TO_QR_KANJI, (short)-1); byte[] bytes = Base64.getDecoder().decode(PACKED_QR_KANJI_TO_UNICODE); for (int i = 0; i < bytes.length; i += 2) { char c = (char)(((bytes[i] & 0xFF) << 8) | (bytes[i + 1] & 0xFF)); if (c == 0xFFFF) continue; assert UNICODE_TO_QR_KANJI[c] == -1; UNICODE_TO_QR_KANJI[c] = (short)(i / 2); } } /*---- Miscellaneous ----*/ private QrSegmentAdvanced() {} // Not instantiable }
35,053
81.869976
206
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/QrTemplate.java
package graphics.qr_codes; /* * Fast QR Code generator library * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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. */ // Stores the parts of a QR Code that depend only on the version number, // and does not depend on the data or error correction level or mask. final class QrTemplate { // Use this memoizer to get instances of this class. public static final Memoizer<Integer,QrTemplate> MEMOIZER = new Memoizer<>(QrTemplate::new); private final int version; // In the range [1, 40]. private final int size; // Derived from version. final int[] template; // Length and values depend on version. final int[][] masks; // masks.length == 8, and masks[i].length == template.length. final int[] dataOutputBitIndexes; // Length and values depend on version. // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. // Otherwise when the constructor is running, isFunction.length == template.length. private int[] isFunction; // Creates a QR Code template for the given version number. private QrTemplate(int ver) { if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) throw new IllegalArgumentException("Version out of range"); version = ver; size = version * 4 + 17; template = new int[(size * size + 31) / 32]; isFunction = new int[template.length]; drawFunctionPatterns(); // Reads and writes fields masks = generateMasks(); // Reads fields, returns array dataOutputBitIndexes = generateZigzagScan(); // Reads fields, returns array isFunction = null; } // Reads this object's version field, and draws and marks all function modules. private void drawFunctionPatterns() { // Draw horizontal and vertical timing patterns for (int i = 0; i < size; i++) { darkenFunctionModule(6, i, ~i & 1); darkenFunctionModule(i, 6, ~i & 1); } // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) drawFinderPattern(3, 3); drawFinderPattern(size - 4, 3); drawFinderPattern(3, size - 4); // Draw numerous alignment patterns int[] alignPatPos = getAlignmentPatternPositions(); int numAlign = alignPatPos.length; for (int i = 0; i < numAlign; i++) { for (int j = 0; j < numAlign; j++) { // Don't draw on the three finder corners if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0)) drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); } } // Draw configuration data drawDummyFormatBits(); drawVersion(); } // Draws two blank copies of the format bits. private void drawDummyFormatBits() { // Draw first copy for (int i = 0; i <= 5; i++) darkenFunctionModule(8, i, 0); darkenFunctionModule(8, 7, 0); darkenFunctionModule(8, 8, 0); darkenFunctionModule(7, 8, 0); for (int i = 9; i < 15; i++) darkenFunctionModule(14 - i, 8, 0); // Draw second copy for (int i = 0; i < 8; i++) darkenFunctionModule(size - 1 - i, 8, 0); for (int i = 8; i < 15; i++) darkenFunctionModule(8, size - 15 + i, 0); darkenFunctionModule(8, size - 8, 1); // Always dark } // Draws two copies of the version bits (with its own error correction code), // based on this object's version field, iff 7 <= version <= 40. private void drawVersion() { if (version < 7) return; // Calculate error correction code and pack bits int rem = version; // version is uint6, in the range [7, 40] for (int i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25); int bits = version << 12 | rem; // uint18 assert bits >>> 18 == 0; // Draw two copies for (int i = 0; i < 18; i++) { int bit = QrCode.getBit(bits, i); int a = size - 11 + i % 3; int b = i / 3; darkenFunctionModule(a, b, bit); darkenFunctionModule(b, a, bit); } } // Draws a 9*9 finder pattern including the border separator, // with the center module at (x, y). Modules can be out of bounds. private void drawFinderPattern(int x, int y) { for (int dy = -4; dy <= 4; dy++) { for (int dx = -4; dx <= 4; dx++) { int dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm int xx = x + dx, yy = y + dy; if (0 <= xx && xx < size && 0 <= yy && yy < size) darkenFunctionModule(xx, yy, (dist != 2 && dist != 4) ? 1 : 0); } } } // Draws a 5*5 alignment pattern, with the center module // at (x, y). All modules must be in bounds. private void drawAlignmentPattern(int x, int y) { for (int dy = -2; dy <= 2; dy++) { for (int dx = -2; dx <= 2; dx++) darkenFunctionModule(x + dx, y + dy, Math.abs(Math.max(Math.abs(dx), Math.abs(dy)) - 1)); } } // Computes and returns a new array of masks, based on this object's various fields. private int[][] generateMasks() { int[][] result = new int[8][template.length]; for (int mask = 0; mask < result.length; mask++) { int[] maskModules = result[mask]; for (int y = 0, i = 0; y < size; y++) { for (int x = 0; x < size; x++, i++) { boolean invert; switch (mask) { case 0: invert = (x + y) % 2 == 0; break; case 1: invert = y % 2 == 0; break; case 2: invert = x % 3 == 0; break; case 3: invert = (x + y) % 3 == 0; break; case 4: invert = (x / 3 + y / 2) % 2 == 0; break; case 5: invert = x * y % 2 + x * y % 3 == 0; break; case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break; case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break; default: throw new AssertionError(); } int bit = (invert ? 1 : 0) & ~getModule(isFunction, x, y); maskModules[i >>> 5] |= bit << i; } } } return result; } // Computes and returns an array of bit indexes, based on this object's various fields. private int[] generateZigzagScan() { int[] result = new int[getNumRawDataModules(version) / 8 * 8]; int i = 0; // Bit index into the data for (int right = size - 1; right >= 1; right -= 2) { // Index of right column in each column pair if (right == 6) right = 5; for (int vert = 0; vert < size; vert++) { // Vertical counter for (int j = 0; j < 2; j++) { int x = right - j; // Actual x coordinate boolean upward = ((right + 1) & 2) == 0; int y = upward ? size - 1 - vert : vert; // Actual y coordinate if (getModule(isFunction, x, y) == 0 && i < result.length) { result[i] = y * size + x; i++; } } } } assert i == result.length; return result; } // Returns the value of the bit at the given coordinates in the given grid. private int getModule(int[] grid, int x, int y) { assert 0 <= x && x < size; assert 0 <= y && y < size; int i = y * size + x; return QrCode.getBit(grid[i >>> 5], i); } // Marks the module at the given coordinates as a function module. // Also either sets that module dark or keeps its color unchanged. private void darkenFunctionModule(int x, int y, int enable) { assert 0 <= x && x < size; assert 0 <= y && y < size; assert enable == 0 || enable == 1; int i = y * size + x; template[i >>> 5] |= enable << i; isFunction[i >>> 5] |= 1 << i; } // Returns an ascending list of positions of alignment patterns for this version number. // Each position is in the range [0,177), and are used on both the x and y axes. // This could be implemented as lookup table of 40 variable-length lists of unsigned bytes. private int[] getAlignmentPatternPositions() { if (version == 1) return new int[]{}; int numAlign = version / 7 + 2; int step = (version == 32) ? 26 : (version * 4 + numAlign * 2 + 1) / (numAlign * 2 - 2) * 2; int[] result = new int[numAlign]; result[0] = 6; for (int i = result.length - 1, pos = size - 7; i >= 1; i--, pos -= step) result[i] = pos; return result; } // Returns the number of data bits that can be stored in a QR Code of the given version number, after // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. static int getNumRawDataModules(int ver) { if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) throw new IllegalArgumentException("Version number out of range"); int result = (16 * ver + 128) * ver + 64; if (ver >= 2) { int numAlign = ver / 7 + 2; result -= (25 * numAlign - 10) * numAlign - 55; if (ver >= 7) result -= 36; } return result; } }
9,759
35.148148
104
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/ReedSolomonGenerator.java
package graphics.qr_codes; /* * Fast QR Code generator library * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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 java.util.Arrays; import java.util.Objects; // Computes Reed-Solomon error correction codewords for given data codewords. final class ReedSolomonGenerator { // Use this memoizer to get instances of this class. public static final Memoizer<Integer,ReedSolomonGenerator> MEMOIZER = new Memoizer<>(ReedSolomonGenerator::new); // A table of size 256 * degree, where polynomialMultiply[i][j] = multiply(i, coefficients[j]). // 'coefficients' is the temporary array computed in the constructor. private byte[][] polynomialMultiply; // Creates a Reed-Solomon ECC generator polynomial for the given degree. private ReedSolomonGenerator(int degree) { if (degree < 1 || degree > 255) throw new IllegalArgumentException("Degree out of range"); // The divisor polynomial, whose coefficients are stored from highest to lowest power. // For example, x^3 + 255x^2 + 8x + 93 is stored as the uint8 array {255, 8, 93}. byte[] coefficients = new byte[degree]; coefficients[degree - 1] = 1; // Start off with the monomial x^0 // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), // and drop the highest monomial term which is always 1x^degree. // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). int root = 1; for (int i = 0; i < degree; i++) { // Multiply the current product by (x - r^i) for (int j = 0; j < coefficients.length; j++) { coefficients[j] = (byte)multiply(coefficients[j] & 0xFF, root); if (j + 1 < coefficients.length) coefficients[j] ^= coefficients[j + 1]; } root = multiply(root, 0x02); } polynomialMultiply = new byte[256][degree]; for (int i = 0; i < polynomialMultiply.length; i++) { for (int j = 0; j < degree; j++) polynomialMultiply[i][j] = (byte)multiply(i, coefficients[j] & 0xFF); } } // Returns the error correction codeword for the given data polynomial and this divisor polynomial. public void getRemainder(byte[] data, int dataOff, int dataLen, byte[] result) { Objects.requireNonNull(data); Objects.requireNonNull(result); int degree = polynomialMultiply[0].length; assert result.length == degree; Arrays.fill(result, (byte)0); for (int i = dataOff, dataEnd = dataOff + dataLen; i < dataEnd; i++) { // Polynomial division byte[] table = polynomialMultiply[(data[i] ^ result[0]) & 0xFF]; for (int j = 0; j < degree - 1; j++) result[j] = (byte)(result[j + 1] ^ table[j]); result[degree - 1] = table[degree - 1]; } } // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. private static int multiply(int x, int y) { assert x >> 8 == 0 && y >> 8 == 0; // Russian peasant multiplication int z = 0; for (int i = 7; i >= 0; i--) { z = (z << 1) ^ ((z >>> 7) * 0x11D); z ^= ((y >>> i) & 1) * x; } assert z >>> 8 == 0; return z; } }
4,302
39.214953
105
java
Ludii
Ludii-master/Common/src/graphics/qr_codes/ToImage.java
package graphics.qr_codes; /* * Fast QR Code generator demo * * Run this command-line program with no arguments. The program creates/overwrites a bunch of * PNG and SVG files in the current working directory to demonstrate the creation of QR Codes. * * Copyright (c) Project Nayuki. (MIT License) * https://www.nayuki.io/page/fast-qr-code-generator-library * * 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. */ /** * cambolbro: Added Ludii logo insertion into final image. */ import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.Arc2D; import java.awt.geom.GeneralPath; import java.awt.image.BufferedImage; import java.util.Objects; //----------------------------------------------------------------------------- public final class ToImage { public static BufferedImage toLudiiCodeImage ( final QrCode qr, final int scale, final int border ) { final BufferedImage img = toImage(qr, scale, border, 0xFFFFFF, 0x000000); insertLudiiLogo(img, scale, false); insertTeardropMarkers(img, qr, scale, border); return img; } public static BufferedImage toImage(QrCode qr, int scale, int border) { return toImage(qr, scale, border, 0xFFFFFF, 0x000000); } /** * Returns a raster image depicting the specified QR Code, with * the specified module scale, border modules, and module colors. * <p>For example, scale=10 and border=4 means to pad the QR Code with 4 light border * modules on all four sides, and use 10&#xD7;10 pixels to represent each module. * @param qr the QR Code to render (not {@code null}) * @param scale the side length (measured in pixels, must be positive) of each module * @param border the number of border modules to add, which must be non-negative * @param lightColor the color to use for light modules, in 0xRRGGBB format * @param darkColor the color to use for dark modules, in 0xRRGGBB format * @return a new image representing the QR Code, with padding and scaling * @throws NullPointerException if the QR Code is {@code null} * @throws IllegalArgumentException if the scale or border is out of range, or if * {scale, border, size} cause the image dimensions to exceed Integer.MAX_VALUE */ public static BufferedImage toImage ( QrCode qr, int scale, int border, int lightColor, int darkColor ) { Objects.requireNonNull(qr); if (scale <= 0 || border < 0) throw new IllegalArgumentException("Value out of range"); if (border > Integer.MAX_VALUE / 2 || qr.size + border * 2L > Integer.MAX_VALUE / scale) throw new IllegalArgumentException("Scale or border too large"); //System.out.println("border=" + border + ", qr.size=" + qr.size + ", scale=" + scale); final int width = (qr.size + border * 2) * scale; final int height = (qr.size + border * 2) * scale; final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int y = 0; y < img.getHeight(); y++) for (int x = 0; x < img.getWidth(); x++) { boolean color = qr.getModule(x / scale - border, y / scale - border); img.setRGB(x, y, color ? darkColor : lightColor); } return img; } /** * Insert the Ludii logo in the centre of the image. * Destructively modifies the code, so use MEDIUM error correction level or better! * @param img * @param scale * @param invert */ public static void insertLudiiLogo ( final BufferedImage img, final int scale, final boolean invert ) { // . . . . . . . . . // . o o o . o o o . // . o . o . o . o . // . o o o o o o o . // . . . o . o . . . // . o o o o o o o . // . o . o . o . o . // . o o o . o o o . // . . . . . . . . . final int cx = img.getWidth() / 2; final int cy = img.getHeight() / 2; final int r = scale; final int d2 = 2 * scale; final int d92 = 9 * scale / 2; Graphics2D g2d = (Graphics2D)img.getGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // Fill square background area if (invert) g2d.setColor(Color.black); else g2d.setColor(Color.white); g2d.fillRect(cx-d92, cy-d92, 2*d92, 2*d92); // Draw logo in opposite colour if (invert) g2d.setColor(Color.white); else g2d.setColor(Color.black); final GeneralPath path = new GeneralPath(); path.append(new Arc2D.Double(cx-d2-r, cy+d2-r, 2*r, 2*r, 90, 270, Arc2D.OPEN), true); path.append(new Arc2D.Double(cx-d2-r, cy-d2-r, 2*r, 2*r, 0, 270, Arc2D.OPEN), true); path.append(new Arc2D.Double(cx+d2-r, cy-d2-r, 2*r, 2*r, 270, 270, Arc2D.OPEN), true); path.append(new Arc2D.Double(cx+d2-r, cy+d2-r, 2*r, 2*r, 180, 270, Arc2D.OPEN), true); path.closePath(); final float sw = (float)(1.25 * scale); g2d.setStroke(new BasicStroke(sw, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g2d.draw(path); } /** * Make the three corner markers rounded teardop shapes. * @param img * @param scale */ public static void insertTeardropMarkers ( final BufferedImage img, final QrCode qr, final int scale, final int border ) { // . . . . . . . // . . o o o . . // . o . . . o . // . o . . . o . // . o . . . o . // . . o o o o . // . . . . . . . // Determine marker size final int sx = img.getWidth(); final int sy = img.getHeight(); // final int cx = sx / 2; // final int cy = sy / 2; // Determine marker size int sz = -1; int numOff = 0; for (int i = 0; i < sx / scale; i++) { final boolean on = qr.getModule(i, 2); //System.out.println(i + ": on=" + on); if (!on) { numOff++; if (numOff == 3) { sz = i; break; } } } //System.out.println("sz=" + sz); final int rndO = 4 * scale; final int rndI = 2 * scale; Graphics2D g2d = (Graphics2D)img.getGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); final float sw = scale; g2d.setStroke(new BasicStroke(sw, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)); int a = border * scale; int b = a + scale; int c = b + scale; int f = (border + sz) * scale; int e = f - scale; int d = e - scale; int m = (a + f) / 2; final int ab = (a + b) / 2; final int ef = (e + f) / 2; // Top left marker g2d.setColor(Color.white); g2d.fillRect(a, a, sz * scale, sz * scale); g2d.setColor(Color.black); g2d.drawRoundRect((a + b) / 2, (a + b) / 2, (sz - 1) * scale, (sz - 1) * scale, rndO, rndO); g2d.fillRoundRect(c, c, (sz - 4) * scale, (sz - 4) * scale, rndI, rndI); g2d.setColor(Color.white); g2d.fillRect(m+1, m+1, sz*scale/2+1, sz*scale/2+1); g2d.setColor(Color.black); g2d.fillRect(m, m, d-m, d-m); final GeneralPath path = new GeneralPath(); path.moveTo( m, ef); path.lineTo(ef, ef); path.lineTo(ef, m); g2d.draw(path); // Bottom left marker int dx = 0; int dy = sy - (2 * border + sz) * scale; g2d.setColor(Color.white); g2d.fillRect(dx+a, dy+a, sz * scale, sz * scale); g2d.setColor(Color.black); g2d.drawRoundRect(dx+(a + b) / 2, dy+(a + b) / 2, (sz - 1) * scale, (sz - 1) * scale, rndO, rndO); g2d.fillRoundRect(dx+c, dy+c, (sz - 4) * scale, (sz - 4) * scale, rndI, rndI); g2d.setColor(Color.white); g2d.fillRect(dx+m+1, dy+a-1, sz*scale/2+1, sz*scale/2+1); g2d.setColor(Color.black); g2d.fillRect(dx+m, dy+c, d-m, d-m); path.reset(); path.moveTo(dx+ m, dy+ab); path.lineTo(dx+ef, dy+ab); path.lineTo(dx+ef, dy+m); g2d.draw(path); // Top right marker dx = sx - (2 * border + sz) * scale; dy = 0; g2d.setColor(Color.white); g2d.fillRect(dx+a, dy+a, sz * scale, sz * scale); g2d.setColor(Color.black); g2d.drawRoundRect(dx+(a + b) / 2, dy+(a + b) / 2, (sz - 1) * scale, (sz - 1) * scale, rndO, rndO); g2d.fillRoundRect(dx+c, dy+c, (sz - 4) * scale, (sz - 4) * scale, rndI, rndI); g2d.setColor(Color.white); g2d.fillRect(dx+a-1, dy+m+1, sz*scale/2+1, sz*scale/2+1); g2d.setColor(Color.black); g2d.fillRect(dx+c, dy+m, d-m, d-m); path.reset(); path.moveTo(dx+ab, dy+m); path.lineTo(dx+ab, dy+ef); path.lineTo(dx+ m, dy+ef); g2d.draw(path); } // // Helper function to reduce code duplication. // private static void writePng(BufferedImage img, String filepath) throws IOException // { // ImageIO.write(img, "png", new File(filepath)); // } /** * Returns a string of SVG code for an image depicting the specified QR Code, with the specified * number of border modules. The string always uses Unix newlines (\n), regardless of the platform. * @param qr the QR Code to render (not {@code null}) * @param border the number of border modules to add, which must be non-negative * @param lightColor the color to use for light modules, in any format supported by CSS, not {@code null} * @param darkColor the color to use for dark modules, in any format supported by CSS, not {@code null} * @return a string representing the QR Code as an SVG XML document * @throws NullPointerException if any object is {@code null} * @throws IllegalArgumentException if the border is negative */ public static String toSvgString ( QrCode qr, int border, String lightColor, String darkColor ) { Objects.requireNonNull(qr); Objects.requireNonNull(lightColor); Objects.requireNonNull(darkColor); if (border < 0) throw new IllegalArgumentException("Border must be non-negative"); long brd = border; StringBuilder sb = new StringBuilder() .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n") .append(String.format("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 %1$d %1$d\" stroke=\"none\">\n", qr.size + brd * 2)) .append("\t<rect width=\"100%\" height=\"100%\" fill=\"" + lightColor + "\"/>\n") .append("\t<path d=\""); for (int y = 0; y < qr.size; y++) for (int x = 0; x < qr.size; x++) if (qr.getModule(x, y)) { if (x != 0 || y != 0) sb.append(" "); sb.append(String.format("M%d,%dh1v1h-1z", x + brd, y + brd)); } return sb .append("\" fill=\"" + darkColor + "\"/>\n") .append("</svg>\n") .toString(); } }
11,611
32.755814
130
java
Ludii
Ludii-master/Common/src/graphics/svg/BallSVG.java
package graphics.svg; import java.awt.Color; //----------------------------------------------------------------------------- /** * Generates a ball SVG for a given colour. * @author cambolbro */ public class BallSVG { private static final String[] template = { "<?xml version=\"1.0\" standalone=\"no\"?>", "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"", "\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">", "<svg", " width=\"10cm\" height=\"10cm\" viewBox=\"0 0 1000 1000\" version=\"1.1\"", " xmlns=\"http://www.w3.org/2000/svg\">", " <desc>Rendered 3Dish reflective ball.</desc>", " <g>", " <defs>", " <radialGradient id=\"Shading\" gradientUnits=\"userSpaceOnUse\"", " cx=\"500\" cy=\"500\" r=\"490\" fx=\"500\" fy=\"500\">", " <stop offset= \"0%\" stop-color=\"rgb(<RGB_0>)\" />", " <stop offset= \"10%\" stop-color=\"rgb(<RGB_10>)\" />", " <stop offset= \"20%\" stop-color=\"rgb(<RGB_20>)\" />", " <stop offset= \"30%\" stop-color=\"rgb(<RGB_30>)\" />", " <stop offset= \"40%\" stop-color=\"rgb(<RGB_40>)\" />", " <stop offset= \"50%\" stop-color=\"rgb(<RGB_50>)\" />", " <stop offset= \"60%\" stop-color=\"rgb(<RGB_60>)\" />", " <stop offset= \"70%\" stop-color=\"rgb(<RGB_70>)\" />", " <stop offset= \"80%\" stop-color=\"rgb(<RGB_80>)\" />", " <stop offset= \"90%\" stop-color=\"rgb(<RGB_90>)\" />", " <stop offset= \"100%\" stop-color=\"rgb(<RGB_100>)\" />", " </radialGradient>", " <radialGradient id=\"Highlight\" gradientUnits=\"userSpaceOnUse\"", " cx=\"500\" cy=\"500\" r=\"490\" fx=\"500\" fy=\"500\">", " <stop offset= \"0%\" stop-color=\"rgb(255,255,255,0.0)\" />", " <stop offset= \"25%\" stop-color=\"rgb(255,255,255,0.05)\" />", " <stop offset= \"50%\" stop-color=\"rgb(255,255,255,0.15)\" />", " <stop offset= \"75%\" stop-color=\"rgb(255,255,255,0.5)\" />", " <stop offset= \"100%\" stop-color=\"rgb(255,255,255,1.0)\" />", " </radialGradient>", " </defs>", " <circle cx=\"500\" cy=\"500\" r=\"490\" fill=\"url(#Shading)\" />", " <path", " d=\"M500,500", " C250,500,100,475,100,340", " C100,130,360,25,500,25", " C640,25,900,130,900,340", " C900,475,750,500,500,500", " z\"", " fill=\"url(#Highlight)\"", " />", " </g>", "</svg>" }; //------------------------------------------------------------------------- public static String generate(final Color shade) { final StringBuilder svg = new StringBuilder(); final int r1 = shade.getRed(); final int g1 = shade.getGreen(); final int b1 = shade.getBlue(); final int darken = 4; final int r0 = r1 / darken; final int g0 = g1 / darken; final int b0 = b1 / darken; for (int l = 0; l < template.length; l++) { String line = template[l]; if (line.contains("<RGB_")) { // Replace with appropriate colour for (int perc = 0; perc <= 100; perc++) { final String pattern = "<RGB_" + perc + ">"; final int c = line.indexOf(pattern); if (c != -1) { final double t = Math.pow(perc / 100.0, 4); final int r = r1 - (int)(t * (r1 - r0)); final int g = g1 - (int)(t * (g1 - g0)); final int b = b1 - (int)(t * (b1 - b0)); line = line.substring(0, c) + r + "," + g + "," + b + line.substring(c+pattern.length()); break; } } } svg.append(line + "\n"); } return svg.toString(); } }
3,865
35.471698
87
java
Ludii
Ludii-master/Common/src/graphics/svg/SVG.java
package graphics.svg; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.List; import graphics.svg.element.BaseElement; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * Contents of an SVG file. * @author cambolbro */ public class SVG { //private final XMLHeader = null; //private final SVGHeader = null; //private double width = 0; //private double height = 0; private final List<Element> elements = new ArrayList<Element>(); private Rectangle2D.Double bounds = new Rectangle2D.Double(); //------------------------------------------------------------------------- public List<Element> elements() { return Collections.unmodifiableList(elements); } //------------------------------------------------------------------------- // public double width() // { // return width; // } // // public double height() // { // return height; // } // // public void setWidth(final double set) // { // width = set; // } // // public void setHeight(final double set) // { // height = set; // } public Rectangle2D.Double bounds() { return bounds; } //------------------------------------------------------------------------- public void clear() { elements.clear(); } //------------------------------------------------------------------------- public void setBounds() { bounds = null; for (Element element : elements) { ((BaseElement)element).setBounds(); if (bounds == null) { bounds = new Rectangle2D.Double(); bounds.setRect(((BaseElement)element).bounds()); } else { bounds.add(((BaseElement)element).bounds()); } } // System.out.println("Bounds are: " + bounds); } //------------------------------------------------------------------------- /** * @return Maximum stroke width specified for any element. */ public double maxStrokeWidth() { double maxWidth = 0; for (Element element : elements) { final double sw = ((BaseElement)element).strokeWidth(); if (sw > maxWidth) maxWidth = sw; } return maxWidth; } //------------------------------------------------------------------------- /** * Render an image from the SVG code just parsed. */ public BufferedImage render ( final Color fillColour, final Color borderColour, final int desiredSize ) { final int x0 = (int)(bounds.getX()) - 1; final int x1 = (int)(bounds.getX() + bounds.getWidth()) + 1; final int sx = x1 - x0; final int y0 = (int)(bounds.getY()) - 1; final int y1 = (int)(bounds.getY() + bounds.getHeight()) + 1; final int sy = y1 - y0; //final double scale = maxDim / (double)Math.max(sx, sy); //final int imgSx = (int)(scale * sx + 0.5); //final int imgSy = (int)(scale * sy + 0.5); // final BufferedImage image = new BufferedImage(imgSx, imgSy, BufferedImage.TYPE_INT_ARGB); BufferedImage image = new BufferedImage(sx, sy, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = image.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); //g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // Pass 1: Fill footprint with player colour for (Element element : elements) element.render(g2d, -bounds.getX(), -bounds.getY(), fillColour, null, null); // Pass 2: Fill paths with border colour for (Element element : elements) element.render(g2d, -bounds.getX(), -bounds.getY(), null, borderColour, null); // Pass 3: Stroke edges in border colour (if element's stroke width > 0) for (Element element : elements) if (element.style().strokeWidth() > 0) { System.out.println("Stroking element " + element.label()); element.render(g2d, -bounds.getX(), -bounds.getY(), null, null, borderColour); } // Resize image to requested size // int sxDesired = sx; // int syDesired = sy; // // if (sx >= sy) // { // // Image is wider than tall (or square) // syDesired = (int)(desiredSize * sx / (double)sy + 0.5); // // } // else // { // // Image is taller than wide // sxDesired = (int)(desiredSize * sy / (double)sx + 0.5); // } image = resize(image, desiredSize, desiredSize); //sxDesired, syDesired); return image; } //------------------------------------------------------------------------- /** * Resizes a buffered image to the specified width and height values * * @param img buffered image to be resized * @param newW width in pixels * @param newH height in pixels * @return Resized image. */ public static BufferedImage resize(final BufferedImage img, final int newW, final int newH) { final Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH); final BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = dimg.createGraphics(); g2d.drawImage(tmp, 0, 0, null); g2d.dispose(); return dimg; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(elements.size() + " elements:\n"); for (Element element : elements) sb.append(element + "\n"); return sb.toString(); } //------------------------------------------------------------------------- }
6,225
26.671111
113
java
Ludii
Ludii-master/Common/src/graphics/svg/SVGLoader.java
package graphics.svg; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import main.FileHandling; /** * Utility class for svg-loading. * @author Matthew.Stephenson */ public final class SVGLoader { private static String[] choices = null; //------------------------------------------------------------------------- /** * Constructor */ private SVGLoader() { // should not instantiate } //------------------------------------------------------------------------- /** * @param filePath * @return Whether this file contains a game description (not tested). */ public static boolean containsSVG(final String filePath) { final File file = new File(filePath); if (file != null) { InputStream in = null; String path = file.getPath().replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/svg/")); final URL url = SVGLoader.class.getResource ( path ); try { in = new FileInputStream(new File(url.toURI())); } catch (final FileNotFoundException | URISyntaxException e) { e.printStackTrace(); } try (BufferedReader rdr = new BufferedReader(new InputStreamReader(in))) { String line; while ((line = rdr.readLine()) != null) if (line.contains("svg")) return true; } catch (final Exception e) { System.out.println("GameLoader.containsGame(): Failed to load " + filePath + "."); System.out.println(e); } } return false; } //------------------------------------------------------------------------- public static String[] listSVGs() { // Try loading from JAR file if (choices == null) { choices = FileHandling.getResourceListing(SVGLoader.class, "svg/", ".svg"); if (choices == null) { try { // Try loading from memory in IDE // Start with known .svg file final URL url = SVGLoader.class.getResource("/svg/misc/dot.svg"); String path = new File(url.toURI()).getPath(); path = path.substring(0, path.length() - "misc/dot.svg".length()); // Get the list of .svg files in this directory and subdirectories final List<String> names = new ArrayList<>(); visit(path, names); Collections.sort(names); choices = names.toArray(new String[names.size()]); } catch (final URISyntaxException exception) { exception.printStackTrace(); } } } return choices; } static void visit(final String path, final List<String> names) { final File root = new File( path ); final File[] list = root.listFiles(); if (list == null) return; for (final File file : list) { if (file.isDirectory()) { visit(path + file.getName() + File.separator, names); } else { if (file.getName().contains(".svg")) { // Add this game name to the list of choices final String name = new String(file.getName()); if (containsSVG(path + File.separator + file.getName())) names.add(path.substring(path.indexOf(File.separator + "svg" + File.separator)) + name); } } } } }
3,617
24.125
94
java
Ludii
Ludii-master/Common/src/graphics/svg/SVGParser.java
package graphics.svg; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Collections; import java.util.Comparator; import graphics.svg.element.BaseElement; import graphics.svg.element.Element; import graphics.svg.element.ElementFactory; //----------------------------------------------------------------------------- /** * Class for parsing SVG files. * @author cambolbro */ public class SVGParser { private String fileName = ""; private final SVG svg = new SVG(); //------------------------------------------------------------------------- public SVGParser() { } public SVGParser(final String filePath) { try { loadAndParse(filePath); } catch (final IOException e) { e.printStackTrace(); } } //------------------------------------------------------------------------- public String fileName() { return fileName; } public SVG svg() { return svg; } //------------------------------------------------------------------------- /** * Load and parse SVG content from the specified file. * @param fname * @throws IOException */ public void loadAndParse(final String fname) throws IOException { fileName = new String(fname); // Load the file String content = ""; // BufferedReader reader; // reader = new BufferedReader(new FileReader(fileName)); // // // Read its content into a string // String line = reader.readLine(); // while (line != null) // { // content += line; // line = reader.readLine(); // } // reader.close(); final InputStream in = getClass().getResourceAsStream(fileName); try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { // Read its content into a string String line = reader.readLine(); while (line != null) { content += line; line = reader.readLine(); } reader.close(); } //System.out.println("SVG content is: " + content); parse(content); } //------------------------------------------------------------------------- /** * Load the specified SVG content from the file with the given name. * @param content */ public boolean parse(final String content) { svg.clear(); // // Extract width and height from header // if (content.contains(" width=")) // { // final Double result = SVGParser.extractDouble(content, " width="); // if (result == null) // return false; // svg.setWidth(result.doubleValue()); // } // // if (content.contains(" height=")) // { // final Double result = SVGParser.extractDouble(content, " height="); // if (result == null) // return false; // svg.setHeight(result.doubleValue()); // } // Load SVG elements for (final Element prototype : ElementFactory.get().prototypes()) { // Load all occurrences of this prototype final String label = prototype.label(); int pos = 0; while (pos < content.length()) { pos = content.indexOf("<"+label, pos); if (pos == -1) break; final int to = content.indexOf(">", pos); if (to == -1) { System.out.println("* Failed to close expression: " + content.substring(pos)); break; } String expr = content.substring(pos, to+1); // System.out.println("expr: " + expr); expr = expr.replaceAll(",", " "); expr = expr.replaceAll(";", " "); expr = expr.replaceAll("\n", " "); expr = expr.replaceAll("\r", " "); expr = expr.replaceAll("\t", " "); expr = expr.replaceAll("\b", " "); expr = expr.replaceAll("\f", " "); expr = expr.replaceAll("-", " -"); while (expr.contains(" ")) expr = expr.replaceAll(" ", " "); final Element element = ElementFactory.get().generate(label); if (!element.load(expr)) return false; ((BaseElement)element).setFilePos(pos); svg.elements().add(element); pos = to; } } sortElements(); svg.setBounds(); // System.out.println(toString()); return true; } //------------------------------------------------------------------------- /** * Sort elements in order of occurrence. */ void sortElements() { Collections.sort ( svg.elements(), new Comparator<Element>() { @Override public int compare(final Element a, final Element b) { final int filePosA = ((BaseElement)a).filePos(); final int filePosB = ((BaseElement)b).filePos(); if (filePosA < filePosB) return -1; if (filePosA > filePosB) return 1; return 0; } } ); } //------------------------------------------------------------------------- /** * @param ch * @return Whether ch is possibly part of a numeric string. */ public static boolean isNumeric(final char ch) { return ch >= '0' && ch <= '9' || ch == '-' || ch == '.'; } // public static boolean isDoubleChar(final char ch) // { // return ch >= '0' && ch <= '9' || ch == '.' || ch == '-'; // } //------------------------------------------------------------------------- /** * @param expr * @param from * @return Extract double from expression, else return null. */ public static Double extractDoubleAt(final String expr, final int from) { // final StringBuilder sb = new StringBuilder(); // // int c = from; // char ch; // while (c < expr.length()) // { // ch = expr.charAt(c); // if (!isNumeric(ch)) // break; // sb.append(ch); // c++; // } int c = from; while (c < expr.length() && !isNumeric(expr.charAt(c))) c++; int cc = c+1; while (cc < expr.length() && isNumeric(expr.charAt(cc))) cc++; //cc--; final String sub = expr.substring(c, cc); // System.out.println("sub=" + sub + ", expr=" + expr); Double result = null; try { result = Double.parseDouble(sub); } catch (final Exception e) { e.printStackTrace(); } return result; } //------------------------------------------------------------------------- /** * @param expr * @param heading * @return Extract double from expression, else return null. */ public static Double extractDouble(final String expr, final String heading) { int c = 0; while (c < expr.length() && !isNumeric(expr.charAt(c))) c++; int cc = c+1; while (cc < expr.length() && isNumeric(expr.charAt(cc))) cc++; //cc--; final String sub = expr.substring(c, cc); // System.out.println("sub=" + sub + ", expr=" + expr); // // Extract the substring enclosed by quotation marks // final int pos = expr.indexOf(heading); // final int from = expr.indexOf("\"", pos); // opening quote // final int to = expr.indexOf("\"", from+1); // closing quote // final String sub = expr.substring(from+1, to); Double result = null; try { result = Double.parseDouble(sub); } catch (final Exception e) { e.printStackTrace(); } return result; } //------------------------------------------------------------------------- /** * @param str * @param pos * @return String at the specified position, else null if none. */ public static String extractStringAt(final String str, final int pos) { final StringBuilder sb = new StringBuilder(); if (str.charAt(pos) == '"') { // Is a string, look for closing quote marks for (int c = pos+1; c < str.length() && str.charAt(c) != '"'; c++) sb.append(str.charAt(c)); } else { // Is not a string, look for other terminator for (int c = pos; c < str.length() && str.charAt(c) != ';' && str.charAt(c) != ' ' && str.charAt(c) != '"'; c++) sb.append(str.charAt(c)); } return sb.toString(); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(fileName + " has "); sb.append(svg); return sb.toString(); } //------------------------------------------------------------------------- }
7,991
21.965517
115
java
Ludii
Ludii-master/Common/src/graphics/svg/SVGPathOp.java
package graphics.svg; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collections; import java.util.List; //----------------------------------------------------------------------------- /** * An SVG operation. * @author cambolbro */ public class SVGPathOp { public static enum PathOpType { ArcTo, MoveTo, LineTo, HLineTo, VLineTo, CurveTo, QuadraticTo, ShortCurveTo, ShortQuadraticTo, ClosePath, } private final PathOpType type; private final boolean absolute; private final List<Point2D.Double> pts = new ArrayList<Point2D.Double>(); private double xAxisRotation = 0; private double largeArcSweep = 0; private int sweepFlag = 0; //------------------------------------------------------------------------- public SVGPathOp(final PathOpType type, final boolean absolute, final String[] subs) { this.type = type; this.absolute = absolute; // System.out.print("Parsed:"); // for (String sub : subs) // System.out.print(" " + sub); // System.out.println(); parseNumbers(subs); } //------------------------------------------------------------------------- public PathOpType type() { return type; } public boolean absolute() { return absolute; } public List<Point2D.Double> pts() { return Collections.unmodifiableList(pts); } public double xAxisRotation() { return xAxisRotation; } public double largeArcSweep() { return largeArcSweep; } public int sweepFlag() { return sweepFlag; } //------------------------------------------------------------------------- // /** // * @return SVG character code (case sensitive). // */ // public abstract char code(); // // //------------------------------------------------------------------------- // // /** // * @return SVG character code (lower case). // */ // public abstract int process(final String[] subs, final int s, final List<SVGop> ops); //------------------------------------------------------------------------- boolean parseNumbers(final String[] subs) { if (subs == null) return true; // nothing to do if (subs.length % 2 != 0 && subs.length != 7) { System.out.println("** Odd number of substrings."); return false; } for (int s = 0; s < subs.length; s += 2) { //if (subs[s] == null) // continue; //System.out.println("subs[" + s + "] is: " + subs[s]); double da = -1; double db = -1; // Get first (x) value String str = subs[s].trim(); try { da = Double.parseDouble(str); } catch (final Exception e) { System.out.println("** '" + str + "' is not a double (x, " + s + ")."); e.printStackTrace(); return false; } if (s < subs.length - 1) { // Get second (y) value String str1 = subs[s+1].trim(); try { db = Double.parseDouble(str1); } catch (final Exception e) { System.out.println("** '" + str1 + "' is not a double (y, " + s + ")."); e.printStackTrace(); return false; } } pts.add(new Point2D.Double(da, db)); } if (subs.length == 7) { // Is an ArcTo xAxisRotation = pts.get(2).x; largeArcSweep = pts.get(2).y; sweepFlag = (int)pts.get(3).x; pts.remove(2); } return true; } //------------------------------------------------------------------------- }
3,347
18.928571
88
java
Ludii
Ludii-master/Common/src/graphics/svg/SVGtoImage.java
package graphics.svg; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import graphics.svg.SVGPathOp.PathOpType; import main.StringRoutines; import main.math.MathRoutines; //----------------------------------------------------------------------------- /** * Create an image from an SVG file. * @author cambolbro and Matthew */ public class SVGtoImage { public static final char[] SVG_Symbols = { 'a', 'c', 'h', 'l', 'm', 'q', 's', 't', 'v', 'z' }; //------------------------------------------------------------------------- public SVGtoImage() { } //------------------------------------------------------------------------- /** * @param ch * @return Whether the specified char, lowercased, is an SVG symbol. */ public static boolean isSVGSymbol(final char ch) { final char chLower = Character.toLowerCase(ch); for (int s = 0; s < SVG_Symbols.length; s++) if (chLower == SVG_Symbols[s]) return true; return false; } //------------------------------------------------------------------------- /** * Get the SVG string from a given SVG filePath. * @param filePath * @return SVG string. */ public static String getSVGString(final String filePath) { final BufferedReader reader = getBufferedReaderFromImagePath(filePath); // Load the string from file String str = ""; String line = null; try { while ((line = reader.readLine()) != null) str += line + "\n"; reader.close(); } catch (final IOException e) { e.printStackTrace(); } return str; } //------------------------------------------------------------------------- /** * Load SVG from file path and render. * @param g2d * @param filePath * @param rectangle * @param borderColour * @param fillColour * @param rotation */ public static void loadFromFilePath ( final Graphics2D g2d, final String filePath, final Rectangle2D rectangle, final Color borderColour, final Color fillColour, final int rotation ) { final BufferedReader reader = getBufferedReaderFromImagePath(filePath); loadFromReader(g2d, reader, rectangle, borderColour, fillColour, rotation); } //------------------------------------------------------------------------- /** * Load SVG from bufferedReader and render. * Specify how much to shift the image from the center point using the x and y parameters. * @param g2d * @param bufferedReader * @param borderColour * @param fillColour */ public static void loadFromReader ( final Graphics2D g2d, final BufferedReader bufferedReader, final Rectangle2D rectangle, final Color borderColour, final Color fillColour, final int rotation ) { // Load the string from file String svg = ""; String line = null; try { while ((line = bufferedReader.readLine()) != null) svg += line + "\n"; bufferedReader.close(); } catch (final Exception ex) { ex.printStackTrace(); } loadFromSource(g2d, svg, rectangle, borderColour, fillColour, rotation); } //------------------------------------------------------------------------- /** * Load SVG from the SVG source string. * Specify how much to shift the image from the center point using the x and y parameters. * @param g2d * @param svg * @param borderColour * @param fillColour * @param rotation */ public static void loadFromSource ( final Graphics2D g2d, final String svg, final Rectangle2D rectangle, final Color borderColour, final Color fillColour, final int rotation ) { final SVGtoImage temp = new SVGtoImage(); final List<List<SVGPathOp>> paths = new ArrayList<>(); final Rectangle2D.Double bounds = new Rectangle2D.Double(); if (temp.parse(svg, paths)) //, bounds)) { temp.findBounds(paths, bounds); temp.render ( g2d, rectangle, borderColour, fillColour, paths, bounds, rotation ); } } //------------------------------------------------------------------------- /** * Get SVG Bounds * @return Bounds of SVG file. */ public static Rectangle2D getBounds ( final String filePath, final int imgSz ) { final BufferedReader reader = getBufferedReaderFromImagePath(filePath); return getBounds(reader, imgSz); } /** * Get SVG Bounds * @return Bounds of SVG file. */ public static Rectangle2D getBounds ( final BufferedReader reader, final int imgSz ) { final SVGtoImage temp = new SVGtoImage(); // Load the string from file String str = ""; String line = null; try { while ((line = reader.readLine()) != null) str += line + "\n"; reader.close(); } catch (final Exception ex) { ex.printStackTrace(); } final List<List<SVGPathOp>> paths = new ArrayList<>(); final Rectangle2D.Double bounds = new Rectangle2D.Double(); if (temp.parse(str, paths)) //, bounds)) { temp.findBounds(paths, bounds); final int x0 = (int)(bounds.getX()) - 1; final int x1 = (int)(bounds.getX() + bounds.getWidth()) + 1; final int sx = x1 - x0; final int y0 = (int)(bounds.getY()) - 1; final int y1 = (int)(bounds.getY() + bounds.getHeight()) + 1; final int sy = y1 - y0; final double scale = imgSz / (double)Math.max(sx, sy); bounds.width = (int)(scale * sx + 0.5); bounds.height = (int)(scale * sy + 0.5); return bounds; } return null; } /** * Get SVG Bounds * @return Desired scale for SVG file. */ public static double getDesiredScale ( final String filePath, final int imgSz ) { final BufferedReader reader = getBufferedReaderFromImagePath(filePath); try { final SVGtoImage temp = new SVGtoImage(); // Load the string from file String str = ""; String line = null; while ((line = reader.readLine()) != null) str += line + "\n"; reader.close(); final List<List<SVGPathOp>> paths = new ArrayList<>(); final Rectangle2D.Double bounds = new Rectangle2D.Double(); if (temp.parse(str, paths)) //, bounds)) { temp.findBounds(paths, bounds); final int x0 = (int)(bounds.getX()) - 1; final int x1 = (int)(bounds.getX() + bounds.getWidth()) + 1; final int sx = x1 - x0; final int y0 = (int)(bounds.getY()) - 1; final int y1 = (int)(bounds.getY() + bounds.getHeight()) + 1; final int sy = y1 - y0; return imgSz / (double)Math.max(sx, sy); } } catch (final Exception e) { e.printStackTrace(); } return 0; } //---------------------------------------------------------------------------- boolean parse ( final String in, final List<List<SVGPathOp>> paths ) { paths.clear(); String str = new String(in); while (str.contains("<path")) { final int c = str.indexOf("<path"); final int cc = StringRoutines.matchingBracketAt(str, c); final String pathStr = str.substring(c, cc+1); int d = pathStr.indexOf("d="); while (d < pathStr.length() && pathStr.charAt(d) != '"') d++; final int dd = StringRoutines.matchingQuoteAt(pathStr, d); final String data = pathStr.substring(d+1, dd); // Process path data final List<String> tokens = tokenise(data); processPathData(tokens, paths); str = str.substring(cc + 1); } return true; } //------------------------------------------------------------------------- List<String> tokenise(final String data) { final List<String> tokens = new ArrayList<String>(); int c = 0; while (c < data.length()) { final char ch = data.charAt(c); if (isSVGSymbol(ch)) { // Create token for SVG symbol tokens.add(new String("" + ch)); } else if (StringRoutines.isNumeric(ch)) { // Create token for number int cc = c; int numDots = 0; while (cc < data.length()-1 && StringRoutines.isNumeric(data.charAt(cc+1))) { if (data.charAt(cc) == '.') { // Second decimal point in number: is actually start of next number if (numDots > 0) { cc--; break; } numDots++; } cc++; if (cc < data.length() - 1 && cc > c+1 && data.charAt(cc) != 'e' && data.charAt(cc+1) == '-') break; // leading '-' of next number may run on directly if (cc > c && data.charAt(cc-1) != 'e' && data.charAt(cc) == '-') { // Special case: Single digit directly followed by leading '-' of next number cc--; break; } } final String token = data.substring(c, cc+1); if (token.contains("e")) tokens.add("0"); // involves power of 10, assume is negligibly small else tokens.add(token); c = cc; // move to end of numeric sequence } else if (ch == '<') { final int cc = StringRoutines.matchingBracketAt(data, c); c = cc; // move to end of bracketed clause } c++; } return tokens; } //------------------------------------------------------------------------- boolean processPathData(final List<String> tokens, final List<List<SVGPathOp>> paths) { final List<SVGPathOp> path = new ArrayList<>(); paths.add(path); char lastOperator = '?'; int s = 0; while (s < tokens.size()) { String token = tokens.get(s); if (token.isEmpty()) { //System.out.println("** Unexpected empty string."); s++; continue; } // Check whether this token is an SVG symbol char ch = token.charAt(0); final boolean hasSymbol = (token.length() == 1 && isSVGSymbol(ch)); if (hasSymbol) { s++; // step past symbol token to the next (numeric) token if (s >= tokens.size()) return true; // reached final token token = tokens.get(s); } else { ch = lastOperator; // use the last symbol (should already be at numeric token) } lastOperator = ch; // ** // ** Note that token can validly be non-numeric, // ** if it is a MoveTo just after a ClosePath. // ** switch (ch) { case 'a': case 'A': { // Arc to: consume next seven numbers if (s >= tokens.size() - 7) { // System.out.println("** Not enough points for an ArcTo."); return false; } final SVGPathOp op = new SVGPathOp ( PathOpType.ArcTo, ch == 'A', new String[] { tokens.get(s), tokens.get(s+1), // rx, ry tokens.get(s+5), tokens.get(s+6), // x, y tokens.get(s+2), tokens.get(s+3), tokens.get(s+4) } ); path.add(op); s += 7; break; } case 'm': case 'M': { // Move to: consume next two numbers if (s >= tokens.size() - 2) { // System.out.println("** Not enough points for a MoveTo."); return false; } final SVGPathOp op = new SVGPathOp ( PathOpType.MoveTo, ch == 'M', new String[] { tokens.get(s), tokens.get(s+1) } ); path.add(op); s += 2; break; } case 'l': case 'L': { // Line to: consume next two numbers if (s >= tokens.size() - 2) { // System.out.println("** Not enough points for a LineTo."); return false; } final SVGPathOp op = new SVGPathOp ( PathOpType.LineTo, ch == 'L', new String[] { tokens.get(s), tokens.get(s+1) } ); path.add(op); s += 2; break; } case 'h': case 'H': { // H Line to: consume next number if (s >= tokens.size() - 1) { // System.out.println("** Not enough points for a HLineTo."); return false; } final SVGPathOp op = new SVGPathOp ( PathOpType.HLineTo, ch == 'H', new String[] { tokens.get(s), "0" } ); path.add(op); s += 1; break; } case 'v': case 'V': { // V Line to: consume next number if (s >= tokens.size() - 1) { // System.out.println("** Not enough points for a VLineTo."); return false; } final SVGPathOp op = new SVGPathOp ( PathOpType.VLineTo, ch == 'V', new String[] { "0", tokens.get(s) } ); path.add(op); s += 1; break; } case 'q': case 'Q': { // Quadratic to: consume next four numbers if (s >= tokens.size() - 4) { // System.out.println("** Not enough points for a QuadraticTo."); return false; } final SVGPathOp op = new SVGPathOp ( PathOpType.QuadraticTo, ch == 'Q', new String[] { tokens.get(s), tokens.get(s+1), tokens.get(s+2), tokens.get(s+3) } ); path.add(op); s += 4; break; } case 'c': case 'C': { // Curve to: consume next six numbers if (s >= tokens.size() - 6) { // System.out.println("** Not enough points for a CurveTo."); return false; } final SVGPathOp op = new SVGPathOp ( PathOpType.CurveTo, ch == 'C', new String[] { tokens.get(s), tokens.get(s+1), tokens.get(s+2), tokens.get(s+3), tokens.get(s+4), tokens.get(s+5) } ); path.add(op); s += 6; break; } case 's': case 'S': { // Short curve to: consume next four numbers if (s >= tokens.size() - 4) { // System.out.println("** Not enough points for a ShortCurveTo."); return false; } final SVGPathOp op = new SVGPathOp ( PathOpType.ShortCurveTo, ch == 'S', new String[] { tokens.get(s), tokens.get(s+1), tokens.get(s+2), tokens.get(s+3) } ); path.add(op); s += 4; break; } case 't': case 'T': { // Short quadratic to: consume next two numbers if (s >= tokens.size() - 2) { // System.out.println("** Not enough points for a ShortQuadraticTo."); return false; } final SVGPathOp op = new SVGPathOp ( PathOpType.ShortQuadraticTo, ch == 'T', new String[] { tokens.get(s), tokens.get(s+1) } ); path.add(op); s += 2; break; } case 'z': case 'Z': { // Closepath to: consume this item final SVGPathOp op = new SVGPathOp ( PathOpType.ClosePath, ch == 'Z', null ); path.add(op); //s++; break; } default: // System.out.println("** Path entry with no op: " + tokens.get(s) + " " + // tokens.get(s+1)); return false; } } return true; } //------------------------------------------------------------------------- /** * @param in * @param target * @return Number corresponding to label in string, else 0. */ int findPositiveInteger(final String in, final String label) { int from = in.indexOf(label); //findSubstring(in, label); if (from == -1) { System.out.println("** Failed to find '" + label + "' in '" + in + "'."); return 0; } from++; // step past opening quote String str = ""; int cc = from + label.length(); while (cc < in.length() && in.charAt(cc) >= '0' && in.charAt(cc) <= '9') str += in.charAt(cc++); int value = 0; try { value = Integer.parseInt(str); } catch (final Exception e) { e.printStackTrace(); } return value; } //------------------------------------------------------------------------- public void findBounds(final List<List<SVGPathOp>> paths, final Rectangle2D.Double bounds) { double minX = 1000000; double minY = 1000000; double maxX = -1000000; double maxY = -1000000; double lastX = 0; double lastY = 0; double x=0, y=0, x1=0, y1=0, x2=0, y2=0; for (final List<SVGPathOp> path : paths) { lastX = 0; lastY = 0; for (final SVGPathOp op : path) { switch (op.type()) { case ArcTo: final double rx = op.pts().get(0).x; final double ry = op.pts().get(0).y; x = op.pts().get(1).x + (op.absolute() ? 0 : lastX); y = op.pts().get(1).y + (op.absolute() ? 0 : lastY); lastX = x + rx; lastY = y; x1 = x - rx; y1 = y - ry; x2 = x + rx; y2 = y + ry; if (x1 < minX) minX = x1; if (y1 < minY) minY = y1; if (x1 > maxX) maxX = x1; if (y1 > maxY) maxY = y1; if (x2 < minX) minX = x2; if (y2 < minY) minY = y2; if (x2 > maxX) maxX = x2; if (y2 > maxY) maxY = y2; break; case MoveTo: x = op.pts().get(0).x + (op.absolute() ? 0 : lastX); y = op.pts().get(0).y + (op.absolute() ? 0 : lastY); lastX = x; lastY = y; break; case LineTo: x = op.pts().get(0).x + (op.absolute() ? 0 : lastX); y = op.pts().get(0).y + (op.absolute() ? 0 : lastY); lastX = x; lastY = y; break; case HLineTo: x = op.pts().get(0).x + (op.absolute() ? 0 : lastX); lastX = x; break; case VLineTo: y = op.pts().get(0).y + (op.absolute() ? 0 : lastY); lastY = y; break; case QuadraticTo: x = op.pts().get(1).x + (op.absolute() ? 0 : lastX); y = op.pts().get(1).y + (op.absolute() ? 0 : lastY); lastX = x; lastY = y; x1 = op.pts().get(0).x + (op.absolute() ? 0 : lastX); y1 = op.pts().get(0).y + (op.absolute() ? 0 : lastY); break; case CurveTo: x = op.pts().get(2).x + (op.absolute() ? 0 : lastX); y = op.pts().get(2).y + (op.absolute() ? 0 : lastY); lastX = x; lastY = y; x1 = op.pts().get(0).x + (op.absolute() ? 0 : lastX); y1 = op.pts().get(0).y + (op.absolute() ? 0 : lastY); x2 = op.pts().get(1).x + (op.absolute() ? 0 : lastX); y2 = op.pts().get(1).y + (op.absolute() ? 0 : lastY); break; case ShortQuadraticTo: x = op.pts().get(0).x + (op.absolute() ? 0 : lastX); y = op.pts().get(0).y + (op.absolute() ? 0 : lastY); lastX = x; lastY = y; break; case ShortCurveTo: x = op.pts().get(1).x + (op.absolute() ? 0 : lastX); y = op.pts().get(1).y + (op.absolute() ? 0 : lastY); lastX = x; lastY = y; x1 = op.pts().get(0).x + (op.absolute() ? 0 : lastX); y1 = op.pts().get(0).y + (op.absolute() ? 0 : lastY); break; case ClosePath: x = lastX; y = lastY; break; default: // Do nothing } if (x < minX) minX = x; if (y < minY) minY = y; if (x > maxX) maxX = x; if (y > maxY) maxY = y; } } bounds.setRect(minX, minY, maxX-minX, maxY-minY); } //------------------------------------------------------------------------- final boolean verbose = false; /** * Render the SVG code just parsed to a target area. */ public void render ( final Graphics2D g2d, final Rectangle2D targetArea, final Color borderColour, final Color fillColour, final List<List<SVGPathOp>> paths, final Rectangle2D.Double bounds, final int rotation ) { final double targetWidth = targetArea.getWidth(); final double targetHeight = targetArea.getHeight(); final double targetX = targetArea.getX(); final double targetY = targetArea.getY(); double x0 = bounds.getX() - 1; final double x1 = bounds.getX() + bounds.getWidth() + 1; final double sx = x1 - x0; double y0 = bounds.getY() - 1; final double y1 = bounds.getY() + bounds.getHeight() + 1; final double sy = y1 - y0; final double maxDim = Math.max(targetWidth, targetHeight); final double scaleX = targetWidth / Math.max(sx, sy); final double scaleY = targetHeight / Math.max(sx, sy); x0 -= Math.max(sy - sx, 0) / 2.0; y0 -= Math.max(sx - sy, 0) / 2.0; // centering if possible // if (g2d instanceof SVGGraphics2D) { // final SVGGraphics2D svg2d = (SVGGraphics2D) g2d; // x0 -= (((svg2d.getWidth() - imgSx) / 2) + x) / scaleX; // y0 -= (((svg2d.getHeight() - imgSy) / 2) + y) / scaleY; // } else { // x0 -= x / scaleX; // y0 -= y / scaleY; // } x0 -= targetX / scaleX; y0 -= targetY / scaleY; // Rotate the image if needed. if (rotation != 0) g2d.rotate(Math.toRadians(rotation), targetX + maxDim/2, targetY + maxDim/2); // Pass 1: Fill footprint in player colour if (fillColour != null) renderPaths(g2d, x0, y0, scaleX, scaleY, fillColour, null, paths); //, bounds); // Pass 2: Fill border in border colour if (borderColour != null) renderPaths(g2d, x0, y0, scaleX, scaleY, null, borderColour, paths); //, bounds); // Need to rotate back afterwards. if (rotation != 0) g2d.rotate(-Math.toRadians(rotation), targetX + maxDim/2, targetY + maxDim/2); } //------------------------------------------------------------------------- void renderPaths ( final Graphics2D g2d, final double x0, final double y0, final double scaleX, final double scaleY, final Color fillColour, final Color borderColour, final List<List<SVGPathOp>> paths //, final Rectangle2D.Double bounds ) { double x=0, y=0, x1, y1, x2, y2, curX, curY, oldX, oldY; for (final List<SVGPathOp> opList : paths) { final GeneralPath path = new GeneralPath(); //path.moveTo(0, 0); final List<Point2D> pts = new ArrayList<>(); Point2D prev = null; double startX = 0; double startY = 0; double lastX = 0; double lastY = 0; for (final SVGPathOp op : opList) { Point2D current = path.getCurrentPoint(); if (current == null) current = new Point2D.Double(0, 0); //System.out.println("current.x=" + (current == null ? "null" : current.getX()) + ", lastX=" + lastX); switch (op.type()) { case ArcTo: System.out.println("** Warning: Path ArcTo not fully supported yet."); x1 = (lastX - x0) * scaleX; y1 = (lastY - y0) * scaleY; x2 = (op.pts().get(1).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y2 = (op.pts().get(1).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; final double rx = op.pts().get(0).x * scaleX; final double ry = op.pts().get(0).y * scaleY; final double theta = op.xAxisRotation(); final double fa = op.largeArcSweep(); final double fs = op.sweepFlag(); final double xx1 = Math.cos(theta) * (x1 - x2) / 2.0 + Math.sin(theta) * (y1 - y2) / 2.0; final double yy1 = -Math.sin(theta) * (x1 - x2) / 2.0 + Math.cos(theta) * (y1 - y2) / 2.0; final int signF = (fa == fs) ? 1 : -1; final double term = Math.sqrt ( (rx * rx * ry * ry - rx * rx *yy1 * yy1 - ry * ry * xx1 * xx1) / (rx * rx * yy1 * yy1 + ry * ry * xx1 * xx1) ); final double ccx = signF * term * (rx * yy1 / ry); final double ccy = signF * term * (- ry * xx1 / rx); final double cx = (Math.cos(theta) * ccx - Math.sin(theta) * ccy + (x1 + x2) / 2.0 - x0) * scaleX; final double cy = (Math.sin(theta) * ccx + Math.cos(theta) * ccy + (y1 + y2) / 2.0 - y0) * scaleY; path.append(new Ellipse2D.Double(cx-rx, cy-ry, 2*rx, 2*ry), true); path.lineTo(x2, y2); lastX = x2 / scaleX + x0; lastY = y2 / scaleY + y0; prev = new Point2D.Double(x2, y2); pts.add(op.pts().get(1)); // only include destination point, not control points if (verbose) System.out.println(String.format("A%.1f %.1f %.1f %.1f", rx, ry, x, y)); break; case MoveTo: if (fillColour != null && !pts.isEmpty()) { // Draw the path so far if (MathRoutines.isClockwise(pts)) { path.closePath(); g2d.setPaint(fillColour); g2d.fill(path); } pts.clear(); path.reset(); //path.moveTo((lastX - x0) * scale, (lastY - y0) * scale); } x = (op.pts().get(0).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y = (op.pts().get(0).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; lastX = op.pts().get(0).x + (op.absolute() ? 0 : lastX); lastY = op.pts().get(0).y + (op.absolute() ? 0 : lastY); startX = lastX; startY = lastY; path.moveTo(x, y); prev = new Point2D.Double(x, y); pts.add(op.pts().get(0)); if (verbose) System.out.println(String.format("M%.1f %.1f", x, y)); break; case LineTo: x = (op.pts().get(0).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y = (op.pts().get(0).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; lastX = op.pts().get(0).x + (op.absolute() ? 0 : lastX); lastY = op.pts().get(0).y + (op.absolute() ? 0 : lastY); path.lineTo(x, y); prev = new Point2D.Double(current.getX(), current.getY()); pts.add(op.pts().get(0)); if (verbose) System.out.println(String.format("L%.1f %.1f", x, y)); break; case HLineTo: x = (op.pts().get(0).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y = current.getY(); lastX = op.pts().get(0).x + (op.absolute() ? 0 : lastX); path.lineTo(x, y); prev = new Point2D.Double(current.getX(), current.getY()); pts.add(op.pts().get(0)); if (verbose) System.out.println(String.format("H%.1f %.1f", x, y)); break; case VLineTo: x = current.getX(); y = (op.pts().get(0).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; lastY = op.pts().get(0).y + (op.absolute() ? 0 : lastY); path.lineTo(x, y); prev = new Point2D.Double(current.getX(), current.getY()); pts.add(op.pts().get(0)); if (verbose) System.out.println(String.format("V%.1f %.1f", x, y)); break; case QuadraticTo: x1 = (op.pts().get(0).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y1 = (op.pts().get(0).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; x = (op.pts().get(1).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y = (op.pts().get(1).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; lastX = op.pts().get(1).x + (op.absolute() ? 0 : lastX); lastY = op.pts().get(1).y + (op.absolute() ? 0 : lastY); path.quadTo(x1, y1, x, y); prev = new Point2D.Double(x1, y1); pts.add(op.pts().get(1)); // only include destination point, not control points if (verbose) System.out.println(String.format("Q%.1f %.1f %.1f %.1f", x1, y1, x, y)); break; case CurveTo: x1 = (op.pts().get(0).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y1 = (op.pts().get(0).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; x2 = (op.pts().get(1).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y2 = (op.pts().get(1).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; x = (op.pts().get(2).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y = (op.pts().get(2).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; lastX = op.pts().get(2).x + (op.absolute() ? 0 : lastX); lastY = op.pts().get(2).y + (op.absolute() ? 0 : lastY); path.curveTo(x1, y1, x2, y2, x, y); prev = new Point2D.Double(x2, y2); pts.add(op.pts().get(2)); // only include destination point, not control points if (verbose) System.out.println(String.format("C%.1f %.1f %.1f %.1f %.1f %.1f", x1, y1, x2, y2, x, y)); break; case ShortQuadraticTo: x = (op.pts().get(0).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y = (op.pts().get(0).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; lastX = op.pts().get(0).x + (op.absolute() ? 0 : lastX); lastY = op.pts().get(0).y + (op.absolute() ? 0 : lastY); // Calculate x1 and y1: // (newx1, newy1) = (curx - (oldx2 - curx), cury - (oldy2 - cury)) // = (2*curx - oldx2, 2*cury - oldy2) curX = current.getX(); curY = current.getY(); oldX = prev.getX(); oldY = prev.getY(); x1 = 2 * curX - oldX; y1 = 2 * curY - oldY; path.quadTo(x1, y1, x, y); prev = new Point2D.Double(x1, y1); pts.add(op.pts().get(1)); // only include destination point, not control points if (verbose) System.out.println(String.format("Q%.1f %.1f %.1f %.1f", x1, y1, x, y)); break; case ShortCurveTo: x2 = (op.pts().get(0).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y2 = (op.pts().get(0).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; x = (op.pts().get(1).x + (op.absolute() ? 0 : lastX) - x0) * scaleX; y = (op.pts().get(1).y + (op.absolute() ? 0 : lastY) - y0) * scaleY; lastX = op.pts().get(1).x + (op.absolute() ? 0 : lastX); lastY = op.pts().get(1).y + (op.absolute() ? 0 : lastY); // Calculate x1 and y1: // (newx1, newy1) = (curx - (oldx2 - curx), cury - (oldy2 - cury)) // = (2*curx - oldx2, 2*cury - oldy2) curX = current.getX(); curY = current.getY(); oldX = prev.getX(); oldY = prev.getY(); x1 = 2 * curX - oldX; y1 = 2 * curY - oldY; path.quadTo(x1, y1, x, y); prev = new Point2D.Double(x1, y1); pts.add(op.pts().get(1)); // only include destination point, not control points if (verbose) System.out.println(String.format("Q%.1f %.1f %.1f %.1f", x2, y2, x, y)); break; case ClosePath: path.closePath(); if (fillColour != null) { // Fill the full image footprint in the player's colour g2d.setPaint(fillColour); g2d.fill(path); path.reset(); pts.clear(); prev = null; } lastX = startX; lastY = startY; if (verbose) System.out.println("Z"); break; default: // Do nothing } } if (fillColour == null) { // Only fill the border path g2d.setPaint(borderColour); g2d.fill(path); } } } //------------------------------------------------------------------------- /** * Returns the BufferedReader object for a specified filePath. * Works for both resource files, and external files. * @param filePath * @return */ private static BufferedReader getBufferedReaderFromImagePath(final String filePath) { try { final InputStream in = SVGtoImage.class.getResourceAsStream(filePath); return new BufferedReader(new InputStreamReader(in)); } catch (final Exception e) { // Could not find SVG within resource folder, might be an absolute path. try { return new BufferedReader(new FileReader(filePath)); } catch (final FileNotFoundException e1) { e.printStackTrace(); e1.printStackTrace(); } } return null; } //------------------------------------------------------------------------- }
30,240
24.693288
120
java
Ludii
Ludii-master/Common/src/graphics/svg/element/BaseElement.java
package graphics.svg.element; import java.awt.geom.Rectangle2D; //----------------------------------------------------------------------------- /** * Base SVG element type. * @author cambolbro */ public abstract class BaseElement implements Element { private final String label; private int filePos; // start position in SVG file protected final Style style = new Style(); protected Rectangle2D.Double bounds = new Rectangle2D.Double(); //------------------------------------------------------------------------- public BaseElement(final String label) { this.label = new String(label); } //------------------------------------------------------------------------- @Override public String label() { return label; } @Override public int compare(final Element other) { return filePos - ((BaseElement)other).filePos; } //------------------------------------------------------------------------- public int filePos() { return filePos; } public void setFilePos(final int pos) { filePos = pos; } @Override public Style style() { return style; } //------------------------------------------------------------------------- public Rectangle2D.Double bounds() { return bounds; } /** * Set bounds for this shape. */ public abstract void setBounds(); //------------------------------------------------------------------------- /** * @return Stroke width of element (else 0 is none specified). */ public double strokeWidth() { return 0; // default implementation } //------------------------------------------------------------------------- }
1,625
18.357143
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/Element.java
package graphics.svg.element; import java.awt.Color; import java.awt.Graphics2D; //----------------------------------------------------------------------------- /** * SVG element type. * @author cambolbro */ public interface Element { /** * @return Label for this element. */ public String label(); /** * @return Drawing style for this element. */ public Style style(); /** * @param other * @return Comparison with other element (order in file). */ public int compare(final Element other); /** * @return New element of own type. */ public Element newInstance(); /** * @return New element of own type. */ public Element newOne(); /** * Load this element's data from an SVG expression. * @return Whether expression is in the right format and data was loaded. */ public boolean load(final String expr); /** * Render this element to a Graphics2D canvas. */ public abstract void render ( final Graphics2D g2d, final double x0, final double y0, final Color footprintColour, final Color fillColour, final Color strokeColour ); }
1,098
18.280702
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/ElementFactory.java
package graphics.svg.element; import java.util.ArrayList; import java.util.Collections; import java.util.List; import graphics.svg.element.shape.Circle; import graphics.svg.element.shape.Ellipse; import graphics.svg.element.shape.Line; import graphics.svg.element.shape.Polygon; import graphics.svg.element.shape.Polyline; import graphics.svg.element.shape.Rect; import graphics.svg.element.shape.path.Path; import graphics.svg.element.text.Text; //----------------------------------------------------------------------------- /** * Singleton class that holds a factory method for creating new SVG elements. * @author cambolbro */ public class ElementFactory { // List of concrete classes to be instantiated private final static List<Element> prototypes = new ArrayList<Element>(); { // Shape prototypes // ** // ** Must be listed here as app uses this list to find element expressions. // ** prototypes.add(new Circle()); prototypes.add(new Ellipse()); prototypes.add(new Line()); prototypes.add(new Polygon()); prototypes.add(new Polyline()); prototypes.add(new Rect()); prototypes.add(new Path()); // Text prototype prototypes.add(new Text()); } // Singleton occurrence of this class private static ElementFactory singleton = null; //------------------------------------------------------------------------- /** * Private constructor: only this class can construct itself. */ private ElementFactory() { // Nothing to do... } //------------------------------------------------------------------------- public static ElementFactory get() { if (singleton == null) singleton = new ElementFactory(); // lazy initialisation return singleton; } public List<Element> prototypes() { return Collections.unmodifiableList(prototypes); } //------------------------------------------------------------------------- /** * @param label Element type to make. * @return New element of specified type, with fields unset. */ public Element generate(final String label) { // final Shape shape = ShapeFactory.get().generate(label); // if (shape != null) // return shape; for (Element prototype : prototypes) if (prototype.label().equals(label)) return prototype.newInstance(); // return an unset clone System.out.println("* Failed to find prototype for Element " + label + "."); return null; } //------------------------------------------------------------------------- }
2,477
25.645161
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/Style.java
package graphics.svg.element; import java.awt.Color; import graphics.svg.SVGParser; //----------------------------------------------------------------------------- /** * Paint style for SVG element. * @author cambolbro */ public class Style { private Color stroke = null; private Color fill = null; private double strokeWidth = 0; //------------------------------------------------------------------------- public Style() { } //------------------------------------------------------------------------- public Color stroke() { return stroke; } public void setStroke(final Color clr) { stroke = clr; } public Color fill() { return fill; } public void setFill(final Color clr) { fill = clr; } public double strokeWidth() { return strokeWidth; } public void setStrokeWidth(final double val) { strokeWidth = val; } //------------------------------------------------------------------------- public boolean load(final String expr) { boolean okay = true; String str = expr.replaceAll(":", "="); str = str.replaceAll("\"", " "); str = str.replaceAll(",", " "); str = str.replaceAll(";", " "); // System.out.println("Loading style from expression: " + str); int pos = str.indexOf("stroke="); if (pos != -1) { final String result = SVGParser.extractStringAt(str, pos+7); // System.out.println("-- stroke is: " + result); if (result != null) { if (result.equals("red")) stroke = new Color(255, 0, 0); else if (result.equals("green")) stroke = new Color(0, 175, 0); else if (result.equals("blue")) stroke = new Color(0, 0, 255); else if (result.equals("white")) stroke = new Color(255, 255, 255); else if (result.equals("black")) stroke = new Color(0, 0, 0); else if (result.equals("orange")) stroke = new Color(255, 175, 0); else if (result.equals("yellow")) stroke = new Color(255, 240, 0); else if (result.contains("#")) stroke = colourFromCode(result); } } pos = str.indexOf("fill="); if (pos != -1) { final String result = SVGParser.extractStringAt(str, pos+5); // System.out.println("-- fill is: " + result); if (result != null) { if (result.equals("transparent")) fill = null; else if (result.equals("red")) fill = new Color(255, 0, 0); else if (result.equals("green")) fill = new Color(0, 175, 0); else if (result.equals("blue")) fill = new Color(0, 0, 255); else if (result.equals("white")) fill = new Color(255, 255, 255); else if (result.equals("black")) fill = new Color(0, 0, 0); else if (result.equals("orange")) fill = new Color(255, 175, 0); else if (result.equals("yellow")) fill = new Color(255, 240, 0); else if (result.contains("#")) fill = colourFromCode(result); } } if (str.contains("stroke-width=")) { final Double result = SVGParser.extractDouble(str, "stroke-width="); // System.out.println("-- stroke-width is: " + result); if (result != null) { strokeWidth = result.doubleValue(); } } return okay; } //------------------------------------------------------------------------- /** * @return Color object defined in format #RRGGBB */ public static Color colourFromCode(final String strIn) { final String str = strIn.replaceAll("\"", "").trim(); if (str.charAt(0) != '#' || str.length() != 7) return null; final int[] values = new int[7]; for (int c = 1; c < str.length(); c++) { final char ch = Character.toLowerCase(str.charAt(c)); if (ch >= '0' && ch <= '9') values[c] = ch - '0'; else if (ch >= 'a' && ch <= 'f') values[c] = ch - 'a' + 10; else return null; // not a numeric value } final int r = (values[1] << 4) | values[2]; final int g = (values[3] << 4) | values[4]; final int b = (values[5] << 4) | values[6]; return new Color(r, g, b); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("<"); sb.append("fill=(" + fill + ")"); sb.append(" stroke=(" + stroke + ")"); sb.append(" strokeWidth=(" + strokeWidth + ")"); sb.append(">"); return sb.toString(); } //------------------------------------------------------------------------- }
4,414
22.115183
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/Circle.java
package graphics.svg.element.shape; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.SVGParser; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG circle shape. * @author cambolbro */ public class Circle extends Shape { // Format: <circle cx="50" cy="50" r="25" /> private double cx = 0; private double cy = 0; private double r = 0; //------------------------------------------------------------------------- public Circle() { super("circle"); } //------------------------------------------------------------------------- public double cx() { return cx; } public double cy() { return cy; } public double r() { return r; } //------------------------------------------------------------------------- @Override public Element newInstance() { return new Circle(); } //------------------------------------------------------------------------- @Override public void setBounds() { final double x = cx - r; final double y = cy - r; final double width = 2 * r; final double height = 2 * r; bounds.setRect(x, y, width, height); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; if (!super.load(expr)) return false; if (expr.contains(" cx=")) { final Double result = SVGParser.extractDouble(expr, " cx="); if (result == null) return false; cx = result.doubleValue(); } if (expr.contains(" cy=")) { final Double result = SVGParser.extractDouble(expr, " cy="); if (result == null) return false; cy = result.doubleValue(); } if (expr.contains(" r=")) { final Double result = SVGParser.extractDouble(expr, " r="); if (result == null) return false; r = result.doubleValue(); } return okay; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label() + ": fill=" + style.fill() + ", stroke=" + style.stroke() + ", strokeWidth=" + style.strokeWidth()); sb.append(" : cx=" + cx + ", cy=" + cy + ", r=" + r); return sb.toString(); } //------------------------------------------------------------------------- @Override public void render ( final Graphics2D g2d, final double x0, final double y0, final Color footprintColour, final Color fillColour, final Color strokeColour ) { // ... } @Override public Element newOne() { return new Circle(); } //------------------------------------------------------------------------- }
2,734
18.535714
120
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/Ellipse.java
package graphics.svg.element.shape; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.SVGParser; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG ellipse shape. * @author cambolbro */ public class Ellipse extends Shape { // Format: <ellipse cx="75" cy="125" rx="50" ry="25" /> private double cx = 0; private double cy = 0; private double rx = 0; private double ry = 0; //------------------------------------------------------------------------- public Ellipse() { super("ellipse"); } //------------------------------------------------------------------------- public double cx() { return cx; } public double cy() { return cy; } public double rx() { return rx; } public double ry() { return ry; } //------------------------------------------------------------------------- @Override public Element newInstance() { return new Ellipse(); } //------------------------------------------------------------------------- @Override public void setBounds() { final double x = cx - rx; final double y = cy - ry; final double width = 2 * rx; final double height = 2 * ry; bounds.setRect(x, y, width, height); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; if (!super.load(expr)) return false; if (expr.contains(" cx=")) { final Double result = SVGParser.extractDouble(expr, " cx="); if (result == null) return false; cx = result.doubleValue(); } if (expr.contains(" cy=")) { final Double result = SVGParser.extractDouble(expr, " cy="); if (result == null) return false; cy = result.doubleValue(); } if (expr.contains(" rx=")) { final Double result = SVGParser.extractDouble(expr, " rx="); if (result == null) return false; rx = result.doubleValue(); } if (expr.contains(" ry=")) { final Double result = SVGParser.extractDouble(expr, " ry="); if (result == null) return false; ry = result.doubleValue(); } return okay; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label() + ": fill=" + style.fill() + ", stroke=" + style.stroke() + ", strokeWidth=" + style.strokeWidth()); sb.append(" : cx=" + cx + ", cy=" + cy + ", rx=" + rx + ", ry=" + ry); return sb.toString(); } //------------------------------------------------------------------------- @Override public void render ( final Graphics2D g2d, final double x0, final double y0, final Color footprintColour, final Color fillColour, final Color strokeColour ) { // ... } @Override public Element newOne() { return new Ellipse(); } //------------------------------------------------------------------------- }
3,019
18.61039
120
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/Line.java
package graphics.svg.element.shape; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.SVGParser; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG line shape. * @author cambolbro */ public class Line extends Shape { // Format: <line x1="0" y1="150" x2="400" y2="150" stroke-width="2" stroke="blue"/> private double x1 = 0; private double y1 = 0; private double x2 = 0; private double y2 = 0; //------------------------------------------------------------------------- public Line() { super("line"); } //------------------------------------------------------------------------- public double x1() { return x1; } public double y1() { return y1; } public double x2() { return x2; } public double y2() { return y2; } //------------------------------------------------------------------------- @Override public Element newInstance() { return new Line(); } //------------------------------------------------------------------------- @Override public void setBounds() { final double x = Math.min(x1, x2); final double y = Math.min(y1, y2); final double width = Math.max(x1, x2) - x; final double height = Math.max(y1, y2) - y; bounds.setRect(x, y, width, height); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; if (!super.load(expr)) return false; if (expr.contains(" x1=")) { final Double result = SVGParser.extractDouble(expr, " x1="); if (result == null) return false; x1 = result.doubleValue(); } if (expr.contains(" y1=")) { final Double result = SVGParser.extractDouble(expr, " y1="); if (result == null) return false; y1 = result.doubleValue(); } if (expr.contains(" x2=")) { final Double result = SVGParser.extractDouble(expr, " x2="); if (result == null) return false; x2 = result.doubleValue(); } if (expr.contains(" y2=")) { final Double result = SVGParser.extractDouble(expr, " y2="); if (result == null) return false; y2 = result.doubleValue(); } return okay; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label() + ": fill=" + style.fill() + ", stroke=" + style.stroke() + ", strokeWidth=" + style.strokeWidth()); sb.append(" : x1=" + x1 + ", y1=" + y1 + ", x2=" + x2 + ", y2=" + y2); return sb.toString(); } //------------------------------------------------------------------------- @Override public void render ( final Graphics2D g2d, final double x0, final double y0, final Color footprintColour, final Color fillColour, final Color strokeColour ) { // ... } @Override public Element newOne() { return new Line(); } //------------------------------------------------------------------------- }
3,073
18.961039
120
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/Polygon.java
package graphics.svg.element.shape; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG polygon shape. * @author cambolbro */ public class Polygon extends Polyline { //------------------------------------------------------------------------- public Polygon() { super("polygon"); // load using Polyline.load() } //------------------------------------------------------------------------- @Override public Element newInstance() { return new Polygon(); } //------------------------------------------------------------------------- @Override public void render ( final Graphics2D g2d, final double x0, final double y0, final Color footprintColour, final Color fillColour, final Color strokeColour ) { // ... } //------------------------------------------------------------------------- }
957
19.382979
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/Polyline.java
package graphics.svg.element.shape; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collections; import java.util.List; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG polyline shape. * @author cambolbro */ public class Polyline extends Shape { // Format: <polyline points="50,175 150,175 150,125 250,200" /> protected final List<Point2D.Double> points = new ArrayList<Point2D.Double>(); //------------------------------------------------------------------------- public Polyline() { super("polyline"); } public Polyline(final String label) { super(label); } //------------------------------------------------------------------------- public List<Point2D.Double> points() { return Collections.unmodifiableList(points); } //------------------------------------------------------------------------- @Override public Element newInstance() { return new Polyline(); } //------------------------------------------------------------------------- @Override public void setBounds() { double x0 = 10000; double y0 = 10000; double x1 = -10000; double y1 = -10000; for (final Point2D.Double pt : points) { if (pt.x < x0) x0 = pt.x; if (pt.y < y0) y0 = pt.y; if (pt.x > x1) x1 = pt.x; if (pt.y > x1) y1 = pt.y; } bounds.setRect(x0, y0, x1-x0, y1-y0); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; if (!super.load(expr)) return false; final int pos = expr.indexOf(" points=\""); int to = pos+9; while (to < expr.length() && expr.charAt(to) != '\"') to++; if (to >= expr.length()) { System.out.println("* Failed to close points list in Polyline."); return false; } final String[] subs = expr.substring(pos+9, to).split(" "); for (int n = 0; n < subs.length-1; n+=2) { final double x = Double.parseDouble(subs[n]); final double y = Double.parseDouble(subs[n+1]); points.add(new Point2D.Double(x, y)); } return okay; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label() + ": fill=" + style.fill() + ", stroke=" + style.stroke() + ", strokeWidth=" + style.strokeWidth()); sb.append(" :"); for (final Point2D.Double pt : points) sb.append(" (" + pt.x + "," + pt.y + ")"); return sb.toString(); } //------------------------------------------------------------------------- @Override public void render ( final Graphics2D g2d, final double x0, final double y0, final Color footprintColour, final Color fillColour, final Color strokeColour ) { // ... } @Override public Element newOne() { return new Polyline(); } //------------------------------------------------------------------------- }
3,098
20.226027
120
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/Rect.java
package graphics.svg.element.shape; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.SVGParser; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG rectangle shape. * @author cambolbro */ public class Rect extends Shape { // Formats: // <rect x="155" y="5" width="75" height="100"/> // <rect x="250" y="5" width="75" height="100" rx="30" ry="20" /> private double x = 0; private double y = 0; private double width = 0; private double height = 0; private double rx = 0; private double ry = 0; //------------------------------------------------------------------------- public Rect() { super("rect"); } //------------------------------------------------------------------------- public double x() { return x; } public double y() { return y; } public double width() { return width; } public double height() { return height; } public double rx() { return rx; } public double ry() { return ry; } //------------------------------------------------------------------------- @Override public Element newInstance() { return new Rect(); } //------------------------------------------------------------------------- @Override public void setBounds() { bounds.setRect(x, y, width, height); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; if (!super.load(expr)) return false; if (expr.contains(" x=")) { final Double result = SVGParser.extractDouble(expr, " x="); if (result == null) return false; x = result.doubleValue(); } if (expr.contains(" y=")) { final Double result = SVGParser.extractDouble(expr, " y="); if (result == null) return false; y = result.doubleValue(); } if (expr.contains(" rx=")) { final Double result = SVGParser.extractDouble(expr, " rx="); if (result == null) return false; rx = result.doubleValue(); } if (expr.contains(" ry=")) { final Double result = SVGParser.extractDouble(expr, " ry="); if (result == null) return false; ry = result.doubleValue(); } if (expr.contains(" width=")) { final Double result = SVGParser.extractDouble(expr, " width="); if (result == null) return false; width = result.doubleValue(); } if (expr.contains(" height=")) { final Double result = SVGParser.extractDouble(expr, " height="); if (result == null) return false; height = result.doubleValue(); } return okay; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label() + ": fill=" + style.fill() + ", stroke=" + style.stroke() + ", strokeWidth=" + style.strokeWidth()); sb.append(" : x=" + x + ", y=" + y + ", rx=" + rx + ", ry=" + ry + ", width=" + width + ", height=" + height); //str += style.toString(); return sb.toString(); } //------------------------------------------------------------------------- @Override public void render ( final Graphics2D g2d, final double x0, final double y0, final Color footprintColour, final Color fillColour, final Color strokeColour ) { // ... } @Override public Element newOne() { return new Rect(); } //------------------------------------------------------------------------- }
3,552
18.960674
120
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/Shape.java
package graphics.svg.element.shape; import java.awt.geom.Rectangle2D; import graphics.svg.element.BaseElement; //----------------------------------------------------------------------------- /** * Base class for SVG shapes. Shapes are scoped by <angled brackets>. * @author cambolbro */ public abstract class Shape extends BaseElement { //------------------------------------------------------------------------- public Shape(final String label) { super(label); } //------------------------------------------------------------------------- public Rectangle2D.Double bounds() { return bounds; } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { return style.load(expr); } //------------------------------------------------------------------------- @Override public double strokeWidth() { return style.strokeWidth(); } //------------------------------------------------------------------------- }
1,022
19.877551
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/ShapeFactory.java
package graphics.svg.element.shape; import java.util.ArrayList; import java.util.Collections; import java.util.List; import graphics.svg.element.shape.path.Path; //----------------------------------------------------------------------------- /** * Singleton class that holds a factory method for creating new SVG elements. * @author cambolbro */ public class ShapeFactory { // List of concrete classes to be instantiated private final static List<Shape> prototypes = new ArrayList<Shape>(); { // Shape prototypes prototypes.add(new Circle()); prototypes.add(new Ellipse()); prototypes.add(new Line()); prototypes.add(new Polygon()); prototypes.add(new Polyline()); prototypes.add(new Rect()); prototypes.add(new Path()); } // Singleton occurrence of this class private static ShapeFactory singleton = null; //------------------------------------------------------------------------- /** * Private constructor: only this class can construct itself. */ private ShapeFactory() { // Nothing to do... } //------------------------------------------------------------------------- public static ShapeFactory get() { if (singleton == null) singleton = new ShapeFactory(); // lazy initialisation return singleton; } public List<Shape> prototypes() { return Collections.unmodifiableList(prototypes); } //------------------------------------------------------------------------- /** * @param label Element type to make. * @return New element of specified type, with fields unset. */ public Shape generate(final String label) { for (Shape prototype : prototypes) if (prototype.label().equals(label)) //return prototype.newShape(); // return an unset clone return (Shape)prototype.newInstance(); // return an unset clone System.out.println("* Failed to find prototype for Element " + label + "."); return null; } //------------------------------------------------------------------------- }
1,987
24.818182
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/Arc.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; //----------------------------------------------------------------------------- /** * SVG path cubic curve to operation. * @author cambolbro */ public class Arc extends PathOp { // Format: // A 100 100 0 0,1 100 100 // a 100 100 0 0,1 100 100 private double rx = 0; private double ry = 0; private double xAxis = 0; private int largeArc = 0; private int sweep = 0; private double x = 0; private double y = 0; //------------------------------------------------------------------------- public Arc() { super('A'); } //------------------------------------------------------------------------- public double rx() { return rx; } public double ry() { return ry; } public double xAxis() { return xAxis; } public int largeArc() { return largeArc; } public int sweep() { return sweep; } public double x() { return x; } public double y() { return y; } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new Arc(); } //------------------------------------------------------------------------- @Override public Rectangle2D.Double bounds() { final double x0 = x - rx; final double y0 = y - ry; final double width = 2 * rx; final double height = 2 * ry; return new Rectangle2D.Double(x0, y0, width, height); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // System.out.println("+ Loading " + label + ": " + expr + "..."); // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); // int c = 1; // // final Double resultX1 = SVGParser.extractDoubleAt(expr, c); // if (resultX1 == null) // { // System.out.println("* Failed to read X1 from " + expr + "."); // return false; // } // x1 = resultX1.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; // // final Double resultY1 = SVGParser.extractDoubleAt(expr, c); // if (resultY1 == null) // { // System.out.println("* Failed to read Y1 from " + expr + "."); // return false; // } // y1 = resultY1.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; // // final Double resultX2 = SVGParser.extractDoubleAt(expr, c); // if (resultX2 == null) // { // System.out.println("* Failed to read X2 from " + expr + "."); // return false; // } // x2 = resultX2.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; // // final Double resultY2 = SVGParser.extractDoubleAt(expr, c); // if (resultY2 == null) // { // System.out.println("* Failed to read Y2 from " + expr + "."); // return false; // } // y2 = resultY2.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; // // final Double resultX3 = SVGParser.extractDoubleAt(expr, c); // if (resultX3 == null) // { // System.out.println("* Failed to read X3 from " + expr + "."); // return false; // } // x3 = resultX3.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; // // final Double resultY3 = SVGParser.extractDoubleAt(expr, c); // if (resultY3 == null) // { // System.out.println("* Failed to read Y3 from " + expr + "."); // return false; // } // y3 = resultY3.doubleValue(); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 7; } @Override public void setValues(final List<Double> values, final Point2D[] current) { // if (values.size() != expectedNumValues()) // return false; rx = values.get(0).doubleValue(); ry = values.get(1).doubleValue(); xAxis = values.get(2).doubleValue(); largeArc = (int)values.get(3).doubleValue(); // 0 or 1 sweep = (int)values.get(4).doubleValue(); // 0 or 1 x = values.get(5).doubleValue(); y = values.get(6).doubleValue(); current[0] = new Point2D.Double(x, y); current[1] = null; } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { pts.add(new Point2D.Double(x, y)); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label + ": rx=" + rx + ", ry=" + ry + ", xAxis=" + xAxis + ", largeArc=" + largeArc + ", sweep=" + sweep + " +, x=" + x + ", y=" + y ); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { // path.curveTo(x1, y1, x2, y2, x3, y3); } //------------------------------------------------------------------------- }
5,653
22.172131
147
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/Close.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.util.List; //----------------------------------------------------------------------------- /** * SVG path close operation. * @author cambolbro */ public class Close extends PathOp { // Format: // Z // z //------------------------------------------------------------------------- public Close() { super('Z'); } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new Close(); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 0; } @Override public void setValues(final List<Double> values, final Point2D[] current) { current[0] = null; current[1] = null; } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { // ... } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { path.closePath(); } //------------------------------------------------------------------------- }
1,803
19.044444
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/CubicTo.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; import graphics.svg.SVGParser; //----------------------------------------------------------------------------- /** * SVG path cubic curve to operation. * @author cambolbro */ public class CubicTo extends PathOp { // Format: // C 100 100 200 200 300 100 // c 100 100 200 200 300 100 private double x1 = 0; private double y1 = 0; private double x2 = 0; private double y2 = 0; private double x = 0; private double y = 0; //------------------------------------------------------------------------- public CubicTo() { super('C'); } //------------------------------------------------------------------------- public double x1() { return x1; } public double y1() { return y1; } public double x2() { return x2; } public double y2() { return y2; } public double x() { return x; } public double y() { return y; } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new CubicTo(); } //------------------------------------------------------------------------- @Override public Rectangle2D.Double bounds() { final double x0 = Math.min(x1, Math.min(x2, x)); final double y0 = Math.min(y1, Math.min(y2, y)); final double width = Math.max(x1, Math.max(x2, x)) - x0; final double height = Math.max(y1, Math.max(y2, y)) - y0; return new Rectangle2D.Double(x0, y0, width, height); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // System.out.println("+ Loading " + label + ": " + expr + "..."); // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); int c = 1; final Double resultX1 = SVGParser.extractDoubleAt(expr, c); if (resultX1 == null) { System.out.println("* Failed to read X1 from " + expr + "."); return false; } x1 = resultX1.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY1 = SVGParser.extractDoubleAt(expr, c); if (resultY1 == null) { System.out.println("* Failed to read Y1 from " + expr + "."); return false; } y1 = resultY1.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultX2 = SVGParser.extractDoubleAt(expr, c); if (resultX2 == null) { System.out.println("* Failed to read X2 from " + expr + "."); return false; } x2 = resultX2.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY2 = SVGParser.extractDoubleAt(expr, c); if (resultY2 == null) { System.out.println("* Failed to read Y2 from " + expr + "."); return false; } y2 = resultY2.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultX3 = SVGParser.extractDoubleAt(expr, c); if (resultX3 == null) { System.out.println("* Failed to read X3 from " + expr + "."); return false; } x = resultX3.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY3 = SVGParser.extractDoubleAt(expr, c); if (resultY3 == null) { System.out.println("* Failed to read Y3 from " + expr + "."); return false; } y = resultY3.doubleValue(); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 6; } @Override public void setValues(final List<Double> values, final Point2D[] current) { // if (values.size() != expectedNumValues()) // return false; x1 = values.get(0).doubleValue(); y1 = values.get(1).doubleValue(); x2 = values.get(2).doubleValue(); y2 = values.get(3).doubleValue(); x = values.get(4).doubleValue(); y = values.get(5).doubleValue(); current[0] = new Point2D.Double(x, y); current[1] = new Point2D.Double(x2, y2); } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { pts.add(new Point2D.Double(x1, y1)); pts.add(new Point2D.Double(x2, y2)); pts.add(new Point2D.Double(x, y)); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label + ": x1=" + x1 + ", y1=" + y1 + ", x2=" + x2 + ", y2=" + y2 + ", x=" + x + ", y=" + y); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { if (absolute()) { path.curveTo(x0+x1, y0+y1, x0+x2, y0+y2, x0+x, y0+y); } else { final Point2D pt = path.getCurrentPoint(); path.curveTo(pt.getX()+x1, pt.getY()+y1, pt.getX()+x2, pt.getY()+y2, pt.getX()+x, pt.getY()+y); } // return new Point2D.Double(x2, y2); } //------------------------------------------------------------------------- }
5,716
21.959839
105
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/HorzLineTo.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; import graphics.svg.SVGParser; //----------------------------------------------------------------------------- /** * SVG path horizontal line to operation. * @author cambolbro */ public class HorzLineTo extends PathOp { // Format: // H 100 // h 100 private double x = 0; private double y = 0; //------------------------------------------------------------------------- public HorzLineTo() { super('H'); } //------------------------------------------------------------------------- public double x() { return x; } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new HorzLineTo(); } //------------------------------------------------------------------------- @Override public Rectangle2D.Double bounds() { return new Rectangle2D.Double(x, y, 0, 0); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // System.out.println("+ Loading " + label + ": " + expr + "..."); // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); int c = 1; final Double resultX = SVGParser.extractDoubleAt(expr, c); if (resultX == null) { System.out.println("* Failed to read X from " + expr + "."); return false; } x = resultX.doubleValue(); // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; // // final Double resultY = SVGParser.extractDoubleAt(expr, c); // if (resultY == null) // { // System.out.println("* Failed to read Y from " + expr + "."); // return false; // } // y = resultY.doubleValue(); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 1; } @Override public void setValues(final List<Double> values, final Point2D[] current) { // if (values.size() != expectedNumValues()) // return false; x = values.get(0).doubleValue(); y = current[0].getY(); current[0] = new Point2D.Double(x, y); current[1] = null; } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { pts.add(new Point2D.Double(x, y)); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label + ": x=" + x + ", (y)=" + y); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { final Point2D pt = path.getCurrentPoint(); if (absolute()) { path.moveTo(x0+x, pt.getY()); } else { path.moveTo(pt.getX()+x, pt.getY()); } } //------------------------------------------------------------------------- }
3,282
20.180645
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/LineTo.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; import graphics.svg.SVGParser; //----------------------------------------------------------------------------- /** * SVG path line to operation. * @author cambolbro */ public class LineTo extends PathOp { // Format: // L 100 100 // l 100 100 private double x = 0; private double y = 0; //------------------------------------------------------------------------- public LineTo() { super('L'); } //------------------------------------------------------------------------- public double x() { return x; } public double y() { return y; } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new LineTo(); } //------------------------------------------------------------------------- @Override public Rectangle2D.Double bounds() { return new Rectangle2D.Double(x, y, 0, 0); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // System.out.println("+ Loading " + label + ": " + expr + "..."); // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); int c = 1; final Double resultX = SVGParser.extractDoubleAt(expr, c); if (resultX == null) { System.out.println("* Failed to read X from " + expr + "."); return false; } x = resultX.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY = SVGParser.extractDoubleAt(expr, c); if (resultY == null) { System.out.println("* Failed to read Y from " + expr + "."); return false; } y = resultY.doubleValue(); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 2; } @Override public void setValues(final List<Double> values, final Point2D[] current) { // if (values.size() != expectedNumValues()) // return false; x = values.get(0).doubleValue(); y = values.get(1).doubleValue(); current[0] = new Point2D.Double(x, y); current[1] = null; } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { pts.add(new Point2D.Double(x, y)); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label + ": x=" + x + ", y=" + y); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { if (absolute()) { path.lineTo(x0+x, y0+y); } else { final Point2D pt = path.getCurrentPoint(); path.lineTo(pt.getX()+x, pt.getY()+y); } } //------------------------------------------------------------------------- }
3,282
19.647799
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/MoveTo.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; import graphics.svg.SVGParser; //----------------------------------------------------------------------------- /** * SVG path move to operation. * @author cambolbro */ public class MoveTo extends PathOp { // Format: // M 100 100 // m 100 100 private double x = 0; private double y = 0; //------------------------------------------------------------------------- public MoveTo() { super('M'); } //------------------------------------------------------------------------- public double x() { return x; } public double y() { return y; } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new MoveTo(); } //------------------------------------------------------------------------- @Override public Rectangle2D.Double bounds() { return new Rectangle2D.Double(x, y, 0, 0); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // System.out.println("+ Loading " + label + ": " + expr + "..."); // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); int c = 1; final Double resultX = SVGParser.extractDoubleAt(expr, c); if (resultX == null) { System.out.println("* Failed to read X from " + expr + "."); return false; } x = resultX.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY = SVGParser.extractDoubleAt(expr, c); if (resultY == null) { System.out.println("* Failed to read Y from " + expr + "."); return false; } y = resultY.doubleValue(); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 2; } @Override public void setValues(final List<Double> values, final Point2D[] current) { // if (values.size() != expectedNumValues()) // return false; x = values.get(0).doubleValue(); y = values.get(1).doubleValue(); current[0] = new Point2D.Double(x, y); current[1] = null; } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { pts.add(new Point2D.Double(x, y)); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label + ": x=" + x + ", y=" + y); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { if (absolute()) { path.moveTo(x0+x, y0+y); } else { final Point2D pt = path.getCurrentPoint(); path.moveTo(pt.getX()+x, pt.getY()+y); } } //------------------------------------------------------------------------- }
3,281
19.641509
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/Path.java
package graphics.svg.element.shape.path; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.GeneralPath; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Collections; import java.util.List; import graphics.svg.SVGParser; import graphics.svg.element.Element; import graphics.svg.element.shape.Shape; import main.math.MathRoutines; //----------------------------------------------------------------------------- /** * SVG path shape. * @author cambolbro */ public class Path extends Shape { // Format: // <path d="M 100 100 L 300 50 zM 100 100 l 300 50 l 300 250 Z" // fill="red" stroke="blue" stroke-width="3" /> // For a good description of path ops, see: https://www.w3.org/TR/SVG/paths.html private final List<PathOp> ops = new ArrayList<PathOp>(); private final double pathLength = 0; // optional author-specified estimate of path length //------------------------------------------------------------------------- public Path() { super("path"); } //------------------------------------------------------------------------- public List<PathOp> ops() { return Collections.unmodifiableList(ops); } public double pathLength() { return pathLength; } //------------------------------------------------------------------------- @Override public Element newInstance() { return new Path(); } //------------------------------------------------------------------------- @Override public void setBounds() { double x0 = 10000; double y0 = 10000; double x1 = -10000; double y1 = -10000; for (final PathOp op : ops) { final Rectangle2D.Double bound = (Rectangle2D.Double)op.bounds(); if (bound == null) continue; // op has no bounds if (bound.x < x0) x0 = bound.x; if (bound.y < y0) y0 = bound.y; final double x = bound.x + bound.width; final double y = bound.y + bound.height; if (x > x1) x1 = x; if (y > y1) y1 = y; } bounds.setRect(x0, y0, x1-x0, y1-y0); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; if (!super.load(expr)) return false; // System.out.println("Loaded style: " + style); ops.clear(); // Load path ops from expression if (expr.contains(" d=\"")) { // Contains path data final int pos = expr.indexOf(" d=\""); String str = SVGParser.extractStringAt(expr, pos+3); if (str == null) { System.out.println("* Failed to extract string from: " + expr.substring(pos+3)); return false; } // int c = 0; // while (c < str.length()) // { // final char ch = Character.toLowerCase(str.charAt(c)); // if (ch >= 'a' && ch <= 'z') // { // // Is (probably) a path op label // final PathOp op = PathOpFactory.get().generate(ch); // if (op == null) // { // System.out.println("* Couldn't find path op with label: " + op); // return false; // } // // String strOp = str.substring(c); // strOp = strOp.replaceAll("-", " -"); // // op.load(strOp); // ops.add(op); // } // c++; // } // ** // ** BEWARE OF THIS! // ** // ** From: https://www.w3.org/TR/SVG/paths.html // ** // ** A command letter may be eliminated if an identical command letter would otherwise precede it; // ** for instance, the following contains an unnecessary second "L" command: // ** // ** M 100 200 L 200 100 L -100 -200 // ** // ** It may be expressed more compactly as: // ** // ** M 100 200 L 200 100 -100 -200 // ** str = str.replaceAll("-", " -"); PathOp prevOp = null; //Point2D.Double prevCP = null; // current[0] = is the path's current point following the last operation // current[1] = is the last operation last control point (else null) final Point2D.Double[] current = new Point2D.Double[2]; while (!str.isEmpty()) { str = str.trim(); PathOp op = prevOp; final char ch = str.charAt(0); if (Character.toLowerCase(ch) >= 'a' && Character.toLowerCase(ch) <= 'z') { op = PathOpFactory.get().generate(ch); if (op == null) { System.out.println("* Couldn't find path op for leading char: " + str); return false; } str = str.substring(1).trim(); } else if (!SVGParser.isNumeric(ch)) { System.out.println("* Non-numeric leading char: " + str); return false; } final List<Double> values = new ArrayList<Double>(); str = extractValues(str, op.expectedNumValues(), values); if (str == null) { // Done //System.out.println("* Error extracting values."); //return false; return true; } op.setValues(values, current); //if (!op.setValues(values)) //{ // System.out.println("* Couldn't set values for op: " + values + " (" + op.expectedNumValues() + " expected)."); // return false; //} ops.add(op); prevOp = op; // remember in case next command is duplicated and omitted } } return okay; } //------------------------------------------------------------------------- /** * Extracts the specified number of values and removes them from the string. * @param strIn * @param numExpected * @param values * @return String with values removed. */ public static String extractValues(final String strIn, final int numExpected, final List<Double> values) { values.clear(); String str = new String(strIn); //System.out.println("Extracting " + numExpected + " values from: " + strIn); while (values.size() < numExpected) { str = str.trim(); if (str.isEmpty()) return null; if (!SVGParser.isNumeric(str.charAt(0))) return null; if (str.charAt(0) == '0' && str.charAt(1) != '.') { // Single digit number for 0 values.add(Double.valueOf(0.0)); str = str.substring(1); } else { String sub = ""; int c; for (c = 0; c < str.length() && SVGParser.isNumeric(str.charAt(c)); c++) sub += str.charAt(c); // System.out.println("-- sub: " + sub); final Double result; try { result = Double.parseDouble(sub); } catch (final Exception e) { System.out.println("* Error extracting Double from: " + sub); e.printStackTrace(); return null; } // System.out.println("-- result: " + result); values.add(result); str = str.substring(c); } } return str; } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label() + ": fill=" + style.fill() + ", stroke=" + style.stroke() + ", strokeWidth=" + style.strokeWidth()); for (final PathOp op : ops) sb.append("\n " + op + (op.absolute() ? " *" : "")); return sb.toString(); } //------------------------------------------------------------------------- public static boolean isMoveTo(final PathOp op) { return Character.toLowerCase(op.label()) == 'm'; } //------------------------------------------------------------------------- @Override public void render ( final Graphics2D g2d, final double x0, final double y0, final Color footprintColour, final Color fillColour, final Color strokeColour ) { if (footprintColour != null) { // Fill this path's total footprint, including holes g2d.setPaint(footprintColour); int c = 0; while (c < ops.size()) { // Move to start of next run while (c < ops.size() && !ops.get(c).isMoveTo()) c++; if (c >= ops.size()) break; // Check whether next run is clockwise final List<Point2D> run = nextRunFrom(c); if (MathRoutines.isClockwise(run)) { // Close this sub-path and fill it final GeneralPath subPath = new GeneralPath(Path2D.WIND_NON_ZERO); do { ops.get(c).apply(subPath, x0, y0); c++; } while (c < ops.size() && !ops.get(c).isMoveTo()); subPath.closePath(); g2d.fill(subPath); } else { // Skip this counterclockwise run c++; while (c < ops.size() && !ops.get(c).isMoveTo()) c++; } if (c >= ops.size()) break; } } if (fillColour != null) { // Fill this path as god intended final GeneralPath path = new GeneralPath(Path2D.WIND_EVEN_ODD); for (final PathOp op : ops) op.apply(path, x0, y0); g2d.setPaint(fillColour); g2d.fill(path); } if (strokeColour != null && style.strokeWidth() > 0) { // Stroke this path as god intended final GeneralPath path = new GeneralPath(Path2D.WIND_EVEN_ODD); for (final PathOp op : ops) op.apply(path, x0, y0); final BasicStroke stroke = new BasicStroke((float)style.strokeWidth(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER); g2d.setPaint(strokeColour); g2d.setStroke(stroke); g2d.draw(path); } } //------------------------------------------------------------------------- /** * @return Run of points from the specified PathOp to the next MoveTo. */ List<Point2D> nextRunFrom(final int from) { final List<Point2D> pts = new ArrayList<Point2D>(); int c = from; do { ops.get(c).getPoints(pts); c++; } while (c < ops.size() && !ops.get(c).isMoveTo()); return pts; } @Override public Element newOne() { return new Path(); } //------------------------------------------------------------------------- }
9,738
22.581114
121
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/PathOp.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; //----------------------------------------------------------------------------- /** * An SVG path operation. * @author cambolbro */ public abstract class PathOp { /** Single char label. Can change upper/lower case when loaded. */ protected char label; //------------------------------------------------------------------------- /** * Note: Label will be passed in as upper case, but visible case * will depend on whether it's absolute or relative. */ public PathOp(final char label) { this.label = label; } //------------------------------------------------------------------------- /** * @return Op is absolute if its label is uppercase. */ public boolean absolute() { return label == Character.toUpperCase(label); } //------------------------------------------------------------------------- /** * @return Bounds for this path op, or null if none. */ public Rectangle2D bounds() { return null; } //------------------------------------------------------------------------- public char label() { return label; //absolute ? Character.toUpperCase(label) : Character.toLowerCase(label); } public void setLabel(final char ch) { label = ch; } public boolean matchesLabel(final char ch) { return Character.toUpperCase(ch) == Character.toUpperCase(label); } //------------------------------------------------------------------------- public boolean isMoveTo() { return Character.toLowerCase(label) == 'm'; } //------------------------------------------------------------------------- /** * @return Expected number of number arguments. */ public abstract int expectedNumValues(); //------------------------------------------------------------------------- /** * @return New element of own type. */ public abstract PathOp newInstance(); /** * Load this shape's data from an SVG expression. * @return Whether expression is in the right format and data was loaded. */ public abstract boolean load(final String expr); //------------------------------------------------------------------------- /** * Load this shape's data from a list of Doubles. */ public abstract void setValues(final List<Double> values, final Point2D[] current); /** * Load this shape's data from a list of Doubles. */ public abstract void getPoints(final List<Point2D> pts); //------------------------------------------------------------------------- /** * Apply this operation to the given path. */ public abstract void apply(final GeneralPath path, final double x0, final double y0); //------------------------------------------------------------------------- }
2,835
23.448276
90
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/PathOpFactory.java
package graphics.svg.element.shape.path; import java.util.ArrayList; import java.util.Collections; import java.util.List; //----------------------------------------------------------------------------- /** * Class that holds a factory method for creating new SVG path operations. * @author cambolbro */ public class PathOpFactory { // For a good description of path ops, see: https://www.w3.org/TR/SVG/paths.html // List of concrete classes to be instantiated private final static List<PathOp> prototypes = new ArrayList<PathOp>(); { // Path operation prototypes prototypes.add(new MoveTo()); prototypes.add(new LineTo()); prototypes.add(new HorzLineTo()); prototypes.add(new VertLineTo()); prototypes.add(new QuadTo()); prototypes.add(new CubicTo()); prototypes.add(new ShortQuadTo()); prototypes.add(new ShortCubicTo()); prototypes.add(new Arc()); prototypes.add(new Close()); } // Singleton occurrence of this class private static PathOpFactory singleton = null; //------------------------------------------------------------------------- /** * Private constructor: only this class can construct itself. */ private PathOpFactory() { // Nothing to do... } //------------------------------------------------------------------------- public static PathOpFactory get() { if (singleton == null) singleton = new PathOpFactory(); // lazy initialisation return singleton; } public List<PathOp> prototypes() { return Collections.unmodifiableList(prototypes); } //------------------------------------------------------------------------- /** * @param label Element type to make. * @return New element of specified type, with fields unset. */ public PathOp generate(final char label) { // Find the appropriate prototype PathOp prototype = null; for (PathOp prototypeN : prototypes) if (prototypeN.matchesLabel(label)) { prototype = prototypeN; break; } if (prototype == null) { System.out.println("* Failed to find prototype for PathOp " + label + "."); return null; } final PathOp op = prototype.newInstance(); // create new unset clone op.setLabel(label); return op; } //------------------------------------------------------------------------- }
2,282
24.087912
81
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/QuadTo.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; import graphics.svg.SVGParser; //----------------------------------------------------------------------------- /** * SVG path quadratic curve to operation. * @author cambolbro */ public class QuadTo extends PathOp { // Format: // Q 100 100 200 200 // q 100 100 200 200 private double x1 = 0; private double y1 = 0; private double x = 0; private double y = 0; //------------------------------------------------------------------------- public QuadTo() { super('Q'); } //------------------------------------------------------------------------- public double x1() { return x1; } public double y1() { return y1; } public double x() { return x; } public double y() { return y; } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new QuadTo(); } //------------------------------------------------------------------------- @Override public Rectangle2D.Double bounds() { final double x0 = Math.min(x1, x); final double y0 = Math.min(y1, y); final double width = Math.max(x1, x) - x0; final double height = Math.max(y1, y) - y0; return new Rectangle2D.Double(x0, y0, width, height); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // System.out.println("+ Loading " + label + ": " + expr + "..."); // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); int c = 1; final Double resultX1 = SVGParser.extractDoubleAt(expr, c); if (resultX1 == null) { System.out.println("* Failed to read X1 from " + expr + "."); return false; } x1 = resultX1.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY1 = SVGParser.extractDoubleAt(expr, c); if (resultY1 == null) { System.out.println("* Failed to read Y1 from " + expr + "."); return false; } y1 = resultY1.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultX2 = SVGParser.extractDoubleAt(expr, c); if (resultX2 == null) { System.out.println("* Failed to read X2 from " + expr + "."); return false; } x = resultX2.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY2 = SVGParser.extractDoubleAt(expr, c); if (resultY2 == null) { System.out.println("* Failed to read Y2 from " + expr + "."); return false; } y = resultY2.doubleValue(); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 4; } @Override public void setValues(final List<Double> values, final Point2D[] current) { // if (values.size() != expectedNumValues()) // return false; x1 = values.get(0).doubleValue(); y1 = values.get(1).doubleValue(); x = values.get(2).doubleValue(); y = values.get(3).doubleValue(); current[0] = new Point2D.Double(x, y); current[1] = new Point2D.Double(x1, y1); } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { pts.add(new Point2D.Double(x1, y1)); pts.add(new Point2D.Double(x, y)); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label + ": x1=" + x1 + ", y1=" + y1 + ", x=" + x + ", y=" + y); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { if (absolute()) { path.quadTo(x0+x1, y0+y1, x0+x, y0+y); } else { final Point2D pt = path.getCurrentPoint(); path.quadTo(pt.getX()+x1, pt.getY()+y1, pt.getX()+x, pt.getY()+y); } // return new Point2D.Double(x1, y1); } //------------------------------------------------------------------------- }
4,604
21.139423
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/ShortCubicTo.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; import graphics.svg.SVGParser; //----------------------------------------------------------------------------- /** * SVG path shorthand cubic curve to operation. * @author cambolbro */ public class ShortCubicTo extends PathOp { // Format: // S 200 200 300 100 // s 200 200 300 100 private double x1 = 0; private double y1 = 0; private double x2 = 0; private double y2 = 0; private double x = 0; private double y = 0; //------------------------------------------------------------------------- public ShortCubicTo() { super('S'); } //------------------------------------------------------------------------- public double x2() { return x2; } public double y2() { return y2; } public double x() { return x; } public double y() { return y; } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new ShortCubicTo(); } //------------------------------------------------------------------------- @Override public Rectangle2D.Double bounds() { final double x0 = Math.min(x1, Math.min(x2, x)); final double y0 = Math.min(y1, Math.min(y2, y)); final double width = Math.max(x1, Math.max(x2, x)) - x0; final double height = Math.max(y1, Math.max(y2, y)) - y0; return new Rectangle2D.Double(x0, y0, width, height); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // System.out.println("+ Loading " + label + ": " + expr + "..."); // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); int c = 1; // final Double resultX1 = SVGParser.extractDoubleAt(expr, c); // if (resultX1 == null) // { // System.out.println("* Failed to read X1 from " + expr + "."); // return false; // } // x1 = resultX1.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; // // final Double resultY1 = SVGParser.extractDoubleAt(expr, c); // if (resultY1 == null) // { // System.out.println("* Failed to read Y1 from " + expr + "."); // return false; // } // y1 = resultY1.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; final Double resultX2 = SVGParser.extractDoubleAt(expr, c); if (resultX2 == null) { System.out.println("* Failed to read X2 from " + expr + "."); return false; } x2 = resultX2.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY2 = SVGParser.extractDoubleAt(expr, c); if (resultY2 == null) { System.out.println("* Failed to read Y2 from " + expr + "."); return false; } y2 = resultY2.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultX3 = SVGParser.extractDoubleAt(expr, c); if (resultX3 == null) { System.out.println("* Failed to read X3 from " + expr + "."); return false; } x = resultX3.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY3 = SVGParser.extractDoubleAt(expr, c); if (resultY3 == null) { System.out.println("* Failed to read Y3 from " + expr + "."); return false; } y = resultY3.doubleValue(); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 4; } @Override public void setValues(final List<Double> values, final Point2D[] current) { // if (values.size() != expectedNumValues()) // return false; x2 = values.get(0).doubleValue(); y2 = values.get(1).doubleValue(); x = values.get(2).doubleValue(); y = values.get(3).doubleValue(); // Calculate x1 and y1: // (newx1, newy1) = (curx - (oldx2 - curx), cury - (oldy2 - cury)) // = (2*curx - oldx2, 2*cury - oldy2) final double currentX = current[0].getX(); final double currentY = current[0].getY(); final double oldX = (current[1] == null) ? currentX : current[1].getX(); final double oldY = (current[1] == null) ? currentY : current[1].getY(); x1 = 2 * currentX - oldX; y1 = 2 * currentY - oldY; current[0] = new Point2D.Double(x, y); current[1] = new Point2D.Double(x1, y1); } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { pts.add(new Point2D.Double(x1, y1)); pts.add(new Point2D.Double(x2, y2)); pts.add(new Point2D.Double(x, y)); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label + ": (x1)=" + x1 + ", (y1)=" + y1 + ", x2=" + x2 + ", y2=" + y2 + ", x=" + x + ", y=" + y); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { // final Point2D pt = path.getCurrentPoint(); // // // Calculate x1 and y1: // // (newx1, newy1) = (curx - (oldx2 - curx), cury - (oldy2 - cury)) // // = (2*curx - oldx2, 2*cury - oldy2) // // final double oldX = (prevCP == null) ? pt.getX() : prevCP.getX(); // final double oldY = (prevCP == null) ? pt.getY() : prevCP.getY(); // // final double x1 = 2 * pt.getX() - oldX; // final double y1 = 2 * pt.getY() - oldY; // // if (absolute()) // { // path.curveTo(x0+x1, y0+y1, x0+x2, y0+y2, x0+x, y0+y); // } // else // { // path.curveTo(pt.getX()+x1, pt.getY()+y1, pt.getX()+x2, pt.getY()+y2, pt.getX()+x, pt.getY()+y); // } // return new Point2D.Double(x2, y2); if (absolute()) { path.curveTo(x0+x1, y0+y1, x0+x2, y0+y2, x0+x, y0+y); } else { final Point2D pt = path.getCurrentPoint(); path.curveTo(pt.getX()+x1, pt.getY()+y1, pt.getX()+x2, pt.getY()+y2, pt.getX()+x, pt.getY()+y); } // return new Point2D.Double(x2, y2); } //------------------------------------------------------------------------- }
6,821
23.989011
109
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/ShortQuadTo.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; import graphics.svg.SVGParser; //----------------------------------------------------------------------------- /** * SVG path quadratic curve to operation. * @author cambolbro */ public class ShortQuadTo extends PathOp { // Format: // T 200 200 // t 200 200 private double x = 0; private double y = 0; private double x1 = 0; private double y1 = 0; //------------------------------------------------------------------------- public ShortQuadTo() { super('T'); } //------------------------------------------------------------------------- public double x() { return x; } public double y() { return y; } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new ShortQuadTo(); } //------------------------------------------------------------------------- @Override public Rectangle2D.Double bounds() { final double x0 = Math.min(x1, x); final double y0 = Math.min(y1, y); final double width = Math.max(x1, x) - x0; final double height = Math.max(y1, y) - y0; return new Rectangle2D.Double(x0, y0, width, height); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // System.out.println("+ Loading " + label + ": " + expr + "..."); // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); int c = 1; // final Double resultX1 = SVGParser.extractDoubleAt(expr, c); // if (resultX1 == null) // { // System.out.println("* Failed to read X1 from " + expr + "."); // return false; // } // x1 = resultX1.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; // // final Double resultY1 = SVGParser.extractDoubleAt(expr, c); // if (resultY1 == null) // { // System.out.println("* Failed to read Y1 from " + expr + "."); // return false; // } // y1 = resultY1.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; final Double resultX2 = SVGParser.extractDoubleAt(expr, c); if (resultX2 == null) { System.out.println("* Failed to read X2 from " + expr + "."); return false; } x = resultX2.doubleValue(); while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) c++; while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) c++; final Double resultY2 = SVGParser.extractDoubleAt(expr, c); if (resultY2 == null) { System.out.println("* Failed to read Y2 from " + expr + "."); return false; } y = resultY2.doubleValue(); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 2; } @Override public void setValues(final List<Double> values, final Point2D[] current) { // if (values.size() != expectedNumValues()) // return false; x = values.get(0).doubleValue(); y = values.get(1).doubleValue(); // Calculate x1 and y1: // (newx1, newy1) = (curx - (oldx2 - curx), cury - (oldy2 - cury)) // = (2*curx - oldx2, 2*cury - oldy2) final double currentX = current[0].getX(); final double currentY = current[0].getY(); final double oldX = (current[1] == null) ? currentX : current[1].getX(); final double oldY = (current[1] == null) ? currentY : current[1].getY(); x1 = 2 * currentX - oldX; y1 = 2 * currentY - oldY; current[0] = new Point2D.Double(x, y); current[1] = new Point2D.Double(x1, y1); } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { pts.add(new Point2D.Double(x1, y1)); pts.add(new Point2D.Double(x, y)); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label + ": (x1=)=" + x1 + ", (y1)=" + y1 + ", x=" + x + ", y=" + y); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { // final Point2D pt = path.getCurrentPoint(); // // // Calculate x1 and y1: // // (newx1, newy1) = (curx - (oldx2 - curx), cury - (oldy2 - cury)) // // = (2*curx - oldx2, 2*cury - oldy2) // // final double oldX = (prevCP == null) ? pt.getX() : prevCP.getX(); // final double oldY = (prevCP == null) ? pt.getY() : prevCP.getY(); // // final double x1 = 2 * pt.getX() - oldX; // final double y1 = 2 * pt.getY() - oldY; // // if (absolute()) // { // path.quadTo(x0+x1, y0+y1, x0+x, y0+y); // } // else // { // path.quadTo(pt.getX()+x1, pt.getY()+y1, pt.getX()+x, pt.getY()+y); // } // return new Point2D.Double(x1, y1); if (absolute()) { path.quadTo(x0+x1, y0+y1, x0+x, y0+y); } else { final Point2D pt = path.getCurrentPoint(); path.quadTo(pt.getX()+x1, pt.getY()+y1, pt.getX()+x, pt.getY()+y); } // return new Point2D.Double(x1, y1); } //------------------------------------------------------------------------- }
5,645
23.547826
80
java
Ludii
Ludii-master/Common/src/graphics/svg/element/shape/path/VertLineTo.java
package graphics.svg.element.shape.path; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.List; import graphics.svg.SVGParser; //----------------------------------------------------------------------------- /** * SVG path vertical line to operation. * @author cambolbro */ public class VertLineTo extends PathOp { // Format: // V 100 // v 100 private double x = 0; private double y = 0; //------------------------------------------------------------------------- public VertLineTo() { super('V'); } //------------------------------------------------------------------------- public double y() { return y; } //------------------------------------------------------------------------- @Override public PathOp newInstance() { return new VertLineTo(); } //------------------------------------------------------------------------- @Override public Rectangle2D bounds() { return new Rectangle2D.Double(y, y, 0, 0); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { // System.out.println("+ Loading " + label + ": " + expr + "..."); // Is absolute if label is upper case label = expr.charAt(0); // absolute = (label == Character.toUpperCase(label)); int c = 1; // final Double resultX = SVGParser.extractDoubleAt(expr, c); // if (resultX == null) // { // System.out.println("* Failed to read X from " + expr + "."); // return false; // } // x = resultX.doubleValue(); // // while (c < expr.length() && SVGParser.isNumeric(expr.charAt(c))) // c++; // // while (c < expr.length() && !SVGParser.isNumeric(expr.charAt(c))) // c++; final Double resultY = SVGParser.extractDoubleAt(expr, c); if (resultY == null) { System.out.println("* Failed to read Y from " + expr + "."); return false; } y = resultY.doubleValue(); return true; } //------------------------------------------------------------------------- @Override public int expectedNumValues() { return 1; } @Override public void setValues(final List<Double> values, final Point2D[] current) { // if (values.size() != expectedNumValues()) // return false; y = values.get(0).doubleValue(); x = current[0].getX(); current[0] = new Point2D.Double(x, y); current[1] = null; } //------------------------------------------------------------------------- @Override public void getPoints(final List<Point2D> pts) { pts.add(new Point2D.Double(x, y)); } //------------------------------------------------------------------------- @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(label + ": (x)=" + x + ", y=" + y); return sb.toString(); } //------------------------------------------------------------------------- @Override public void apply(final GeneralPath path, final double x0, final double y0) { final Point2D pt = path.getCurrentPoint(); if (absolute()) { path.moveTo(pt.getX(), y0+y); } else { path.moveTo(pt.getX(), pt.getY()+y); } } //------------------------------------------------------------------------- }
3,264
20.480263
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/style/Fill.java
package graphics.svg.element.style; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG fill colour property. * @author cambolbro */ public class Fill extends Style { // Format: fill="rgb(255,0,0)" private final Color colour = new Color(0, 0, 0); //------------------------------------------------------------------------- public Fill() { super("fill"); } //------------------------------------------------------------------------- public Color colour() { return colour; } //------------------------------------------------------------------------- @Override public Element newOne() { return new Fill(); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; // ... return okay; } @Override public Element newInstance() { return null; } @Override public void render ( Graphics2D g2d, double x0, double y0, Color footprintColour, Color fillColour, Color strokeColour ) { // ... } @Override public void setBounds() { // ... } //------------------------------------------------------------------------- }
1,322
15.746835
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/style/FillOpacity.java
package graphics.svg.element.style; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG fill opacity property. * @author cambolbro */ public class FillOpacity extends Style { // Format: fill-opacity=".5" private final double opacity = 1; //------------------------------------------------------------------------- public FillOpacity() { super("fill-opacity"); } //------------------------------------------------------------------------- public double opacity() { return opacity; } //------------------------------------------------------------------------- @Override public Element newOne() { return new FillOpacity(); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; // ... return okay; } @Override public Element newInstance() { return null; } @Override public void render ( Graphics2D g2d, double x0, double y0, Color footprintColour, Color fillColour, Color strokeColour ) { // ... } @Override public void setBounds() { // ... } //------------------------------------------------------------------------- }
1,338
15.949367
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/style/Stroke.java
package graphics.svg.element.style; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG stroke colour property. * @author cambolbro */ public class Stroke extends Style { // Format: // stroke="rgb(255,0,0)" // Handle stroke types here private final Color colour = new Color(0, 0, 0); //------------------------------------------------------------------------- // ** // ** BEWARE: Label "stroke" will also match "stroke-width" etc. // ** public Stroke() { super("stroke"); } //------------------------------------------------------------------------- public Color colour() { return colour; } //------------------------------------------------------------------------- @Override public Element newOne() { return new Stroke(); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; // ... return okay; } @Override public Element newInstance() { return null; } @Override public void render(Graphics2D g2d, double x0, double y0, Color footprintColour, Color fillColour, Color strokeColour) { // ... } @Override public void setBounds() { // ... } //------------------------------------------------------------------------- }
1,447
16.658537
98
java
Ludii
Ludii-master/Common/src/graphics/svg/element/style/StrokeDashArray.java
package graphics.svg.element.style; import java.awt.Color; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.Collections; import java.util.List; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG dash array property. * @author cambolbro */ public class StrokeDashArray extends Style { // Format: stroke-dasharray= ? private final List<Integer> dash = new ArrayList<Integer>(); //------------------------------------------------------------------------- public StrokeDashArray() { super("stroke-dasharray"); } //------------------------------------------------------------------------- public List<Integer> dash() { return Collections.unmodifiableList(dash); } //------------------------------------------------------------------------- @Override public Element newOne() { return new StrokeDashArray(); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; // ... return okay; } @Override public Element newInstance() { return null; } @Override public void render ( Graphics2D g2d, double x0, double y0, Color footprintColour, Color fillColour, Color strokeColour ) { // ... } @Override public void setBounds() { // ... } //------------------------------------------------------------------------- }
1,491
17.195122
79
java
Ludii
Ludii-master/Common/src/graphics/svg/element/style/StrokeDashOffset.java
package graphics.svg.element.style; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG dash offset property. * @author cambolbro */ public class StrokeDashOffset extends Style { // Format: stroke-dashoffset="1" private final double offset = 1; //------------------------------------------------------------------------- public StrokeDashOffset() { super("stroke-dashoffset"); } //------------------------------------------------------------------------- public double offset() { return offset; } //------------------------------------------------------------------------- @Override public Element newOne() { return new StrokeDashOffset(); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; // ... return okay; } @Override public Element newInstance() { return null; } @Override public void render(Graphics2D g2d, double x0, double y0, Color footprintColour, Color fillColour, Color strokeColour) { // ... } @Override public void setBounds() { // ... } //------------------------------------------------------------------------- }
1,349
16.763158
98
java
Ludii
Ludii-master/Common/src/graphics/svg/element/style/StrokeLineCap.java
package graphics.svg.element.style; import java.awt.Color; import java.awt.Graphics2D; import graphics.svg.element.Element; //----------------------------------------------------------------------------- /** * SVG line cap property. * @author cambolbro */ public class StrokeLineCap extends Style { // Format: stroke-linecap="round" private final String lineCap = "butt"; //------------------------------------------------------------------------- public StrokeLineCap() { super("stroke-linecap"); } //------------------------------------------------------------------------- public String lineCap() { return lineCap; } //------------------------------------------------------------------------- @Override public Element newOne() { return new StrokeLineCap(); } //------------------------------------------------------------------------- @Override public boolean load(final String expr) { final boolean okay = true; // ... return okay; } @Override public Element newInstance() { return null; } @Override public void render ( Graphics2D g2d, double x0, double y0, Color footprintColour, Color fillColour, Color strokeColour ) { // ... } @Override public void setBounds() { // ... } //------------------------------------------------------------------------- }
1,350
16.101266
79
java