index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/ChooseKAugSpaceSampler.java
package ai.libs.jaicore.ml.weka.rangequery; import java.util.ArrayList; import java.util.Random; import weka.core.Instance; import weka.core.Instances; /** * Samples interval-valued data from a dataset of precise points by sampling k precise points (with replacement) * and generating a point in the interval-valued augmented space by only considering those k points, i.e. choosing * respective minima and maxima for each attribute from the chosen precise points. * @author Michael * */ public class ChooseKAugSpaceSampler extends AbstractAugmentedSpaceSampler { private int k; public ChooseKAugSpaceSampler(Instances preciseInsts, Random rng, int k) { super(preciseInsts, rng); this.k = k; } @Override public Instance augSpaceSample() { Instances preciseInsts = this.getPreciseInsts(); ArrayList<Instance> sampledPoints = new ArrayList(k); for (int i = 0; i < k; i++) { sampledPoints.add(preciseInsts.get( this.getRng().nextInt(preciseInsts.size()))); } return generateAugPoint(sampledPoints); } /** * @return the k */ public int getK() { return k; } /** * @param k the k to set */ public void setK(int k) { this.k = k; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/ExactIntervalAugSpaceSampler.java
package ai.libs.jaicore.ml.weka.rangequery; import java.util.ArrayList; import java.util.Random; import weka.core.Instance; import weka.core.Instances; /** * Samples interval-valued data from a dataset of precise points. * First chooses two precise points of random to define an interval. * Then finds all other points that lie in this interval to generate the interval-valued point in the augmented space. * May be very inefficient for even medium-sized datasets. * * @author Michael * */ public class ExactIntervalAugSpaceSampler extends AbstractAugmentedSpaceSampler { public ExactIntervalAugSpaceSampler(final Instances preciseInsts, final Random rng) { super(preciseInsts, rng); } @Override public Instance augSpaceSample() { Instances preciseInsts = this.getPreciseInsts(); int numInsts = preciseInsts.size(); ArrayList<Instance> sampledPoints = new ArrayList<>(); Instance x1 = preciseInsts.get(this.getRng().nextInt(numInsts)); Instance x2 = preciseInsts.get(this.getRng().nextInt(numInsts)); // Assume last attribute is the class int numFeatures = preciseInsts.numAttributes() - 1; for (Instance inst : preciseInsts) { boolean inInterval = true; for (int att = 0; att < numFeatures && inInterval; att++) { if (inst.value(att) < Math.min(x1.value(att), x2.value(att)) || inst.value(att) > Math.max(x1.value(att), x2.value(att))) { inInterval = false; } } if (inInterval) { sampledPoints.add(inst); } } return generateAugPoint(sampledPoints); } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/IAugSpaceSamplingFunction.java
package ai.libs.jaicore.ml.weka.rangequery; import com.google.common.base.Function; import weka.core.Instances; public interface IAugSpaceSamplingFunction extends Function<Instances, Instances> { }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/IAugmentedSpaceSampler.java
package ai.libs.jaicore.ml.weka.rangequery; import weka.core.Instance; /** * Interface representing a class that samples interval-valued data from a set of precise data points. * @author Michael * */ public interface IAugmentedSpaceSampler { /** * Generates a point in the augmented space from the AugmentedSpaceSampler's precise dataset. * * @return A point in the augmented space consisting of upper and lower bounds for each attribute, including the target. */ public Instance augSpaceSample(); }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/KNNAugSpaceSampler.java
package ai.libs.jaicore.ml.weka.rangequery; import java.util.ArrayList; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import weka.core.DistanceFunction; import weka.core.EuclideanDistance; import weka.core.Instance; import weka.core.Instances; import weka.core.neighboursearch.NearestNeighbourSearch; /** * Samples interval-valued data from a dataset of precise points. * First chooses one point uniformly at random and then generates a point in the interval-valued augmented space * from it and its (exact) K nearest neighbors according to euclidean distance on the attributes, excluding the class, * which is assumed to be the last attribute. * @author Michael * */ public class KNNAugSpaceSampler extends AbstractAugmentedSpaceSampler { private static final Logger logger = LoggerFactory.getLogger(KNNAugSpaceSampler.class); private final NearestNeighbourSearch nearestNeighbour; private int k; /** * @param nearestNeighbour The nearest neighbour search algorithm to use. * @author Michael * */ public KNNAugSpaceSampler(final Instances preciseInsts, final Random rng, final int k, final NearestNeighbourSearch nearestNeighbour) { super(preciseInsts, rng); this.k = k; DistanceFunction dist = new EuclideanDistance(preciseInsts); String distOptionColumns = String.format("-R first-%d", preciseInsts.numAttributes() - 1); String[] distOptions = { distOptionColumns }; try { dist.setOptions(distOptions); nearestNeighbour.setDistanceFunction(dist); nearestNeighbour.setInstances(preciseInsts); } catch (Exception e) { logger.error("Could not configure distance function or setup nearest neighbour.", e); } nearestNeighbour.setMeasurePerformance(false); this.nearestNeighbour = nearestNeighbour; } @Override public Instance augSpaceSample() { Instances preciseInsts = this.getPreciseInsts(); int numInsts = preciseInsts.size(); Instance x = preciseInsts.get(this.getRng().nextInt(numInsts)); Instances kNNs = null; try { kNNs = this.nearestNeighbour.kNearestNeighbours(x, this.k); } catch (Exception e) { logger.error("Creating the augmented space sample failed with exception.", e); } ArrayList<Instance> sampledPoints = new ArrayList<>(); sampledPoints.add(x); sampledPoints.addAll(kNNs); return generateAugPoint(sampledPoints); } /** * @return the k */ public int getK() { return this.k; } /** * @param k the k to set */ public void setK(final int k) { this.k = k; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/ExtendedM5Forest.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.geometry.euclidean.oned.Interval; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.AggressiveAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.IntervalAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.QuantileAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.util.RQPHelper.IntervalAndHeader; import weka.classifiers.meta.Bagging; import weka.core.Instance; public class ExtendedM5Forest extends Bagging implements RangeQueryPredictor { /** * For serialization purposes. */ private static final long serialVersionUID = 8774800172762290733L; private final IntervalAggregator forestAggregator; public ExtendedM5Forest() { this(new QuantileAggregator(0.15), new AggressiveAggregator()); } public ExtendedM5Forest(final IntervalAggregator treeAggregator, final IntervalAggregator forestAggregator) { ExtendedM5Tree rTree = new ExtendedM5Tree(treeAggregator); rTree.setDoNotCheckCapabilities(false); super.setClassifier(rTree); super.setRepresentCopiesUsingWeights(false); this.setNumIterations(this.defaultNumberOfIterations()); this.forestAggregator = forestAggregator; } public ExtendedM5Forest(final int seed) { this(); this.setSeed(seed); } @Override protected String defaultClassifierString() { return "jaicore.ml.intervaltree.ExtendedM5Tree"; } @Override public Interval predictInterval(final Instance rangeQuery) { // collect the different predictions List<Double> predictions = new ArrayList<>(this.m_Classifiers.length * 2); for (int i = 0; i < this.m_Classifiers.length; i++) { ExtendedM5Tree classifier = (ExtendedM5Tree) this.m_Classifiers[i]; Interval prediction = classifier.predictInterval(rangeQuery); predictions.add(prediction.getInf()); predictions.add(prediction.getSup()); } // aggregate them return this.forestAggregator.aggregate(predictions); } @Override public Interval predictInterval(final IntervalAndHeader intervalAndHeader) { // collect the different predictions List<Double> predictions = new ArrayList<>(this.m_Classifiers.length * 2); for (int i = 0; i < this.m_Classifiers.length; i++) { ExtendedM5Tree classifier = (ExtendedM5Tree) this.m_Classifiers[i]; Interval prediction = classifier.predictInterval(intervalAndHeader); predictions.add(prediction.getInf()); predictions.add(prediction.getSup()); } // aggregate them return this.forestAggregator.aggregate(predictions); } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/ExtendedM5Tree.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.Map.Entry; import org.apache.commons.math3.geometry.euclidean.oned.Interval; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.AggressiveAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.IntervalAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.util.RQPHelper; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.util.RQPHelper.IntervalAndHeader; import weka.classifiers.trees.m5.M5Base; import weka.classifiers.trees.m5.PreConstructedLinearModel; import weka.classifiers.trees.m5.RuleNode; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; public class ExtendedM5Tree extends M5Base implements RangeQueryPredictor { /** * For serialization purposes. */ private static final long serialVersionUID = 6099808075887732225L; private final IntervalAggregator intervalAggregator; public ExtendedM5Tree() { this(new AggressiveAggregator()); } public ExtendedM5Tree(final IntervalAggregator intervalAggregator) { super(); try { this.setOptions(new String[] { "-U" }); } catch (Exception e) { throw new IllegalStateException("Couldn't unprune the tree"); } this.intervalAggregator = intervalAggregator; } @Override public Interval predictInterval(final IntervalAndHeader intervalAndHeader) { Interval[] queriedInterval = intervalAndHeader.getIntervals(); // the stack of elements that still have to be processed. Deque<Entry<Interval[], RuleNode>> stack = new ArrayDeque<>(); // initially, the root and the queried interval stack.push(RQPHelper.getEntry(queriedInterval, this.getM5RootNode())); // the list of all leaf values ArrayList<Double> list = new ArrayList<>(); while (stack.peek() != null) { // pick the next node to process Entry<Interval[], RuleNode> toProcess = stack.pop(); RuleNode nextTree = toProcess.getValue(); double threshold = nextTree.splitVal(); int attribute = nextTree.splitAtt(); // process node if (nextTree.isLeaf()) { this.predictLeaf(list, toProcess, nextTree, intervalAndHeader.getHeaderInformation()); } else { Interval intervalForAttribute = queriedInterval[attribute]; // no leaf node... RuleNode leftChild = nextTree.leftNode(); RuleNode rightChild = nextTree.rightNode(); // traverse the tree if (intervalForAttribute.getInf() <= threshold) { if (threshold <= intervalForAttribute.getSup()) { // scenario: x_min <= threshold <= x_max // query [x_min, threshold] on the left child // query [threshold, x_max] on the right child Interval[] leftInterval = RQPHelper.substituteInterval(toProcess.getKey(), new Interval(intervalForAttribute.getInf(), threshold), attribute); stack.push(RQPHelper.getEntry(leftInterval, leftChild)); Interval[] rightInterval = RQPHelper.substituteInterval(toProcess.getKey(), new Interval(threshold, intervalForAttribute.getSup()), attribute); stack.push(RQPHelper.getEntry(rightInterval, rightChild)); } else { // scenario: x_min <= x_max < threshold // query [x_min, x_max] on the left child stack.push(RQPHelper.getEntry(toProcess.getKey(), leftChild)); } } else { stack.push(RQPHelper.getEntry(toProcess.getKey(), rightChild)); } } } return this.intervalAggregator.aggregate(list); } private void predictLeaf(final ArrayList<Double> list, final Entry<Interval[], RuleNode> toProcess, final RuleNode nextTree, final Instances header) { Interval[] usedBounds = toProcess.getKey(); PreConstructedLinearModel model = nextTree.getModel(); // calculate the values at the edges of the interval // we know that by linearity this will yield the extremal values Instance instanceLower = new DenseInstance(usedBounds.length + 1); Instance instanceUpper = new DenseInstance(usedBounds.length + 1); double[] coefficients = model.coefficients(); for (int i = 0; i < usedBounds.length; i++) { double coefficient = coefficients[i]; if (coefficient < 0) { instanceLower.setValue(i + 1, usedBounds[i].getInf()); instanceUpper.setValue(i + 1, usedBounds[i].getSup()); } else { instanceLower.setValue(i + 1, usedBounds[i].getSup()); instanceUpper.setValue(i + 1, usedBounds[i].getInf()); } } instanceLower.setValue(0, 1); instanceUpper.setValue(0, 1); instanceLower.setDataset(header); instanceUpper.setDataset(header); try { double predictionLower = model.classifyInstance(instanceLower); double predictionUpper = model.classifyInstance(instanceUpper); list.add(predictionLower); list.add(predictionUpper); } catch (Exception e) { throw new PredictionFailedException(e); } } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/ExtendedRandomForest.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.commons.math3.geometry.euclidean.oned.Interval; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.AggressiveAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.IntervalAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.QuantileAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace.FeatureSpace; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.util.RQPHelper.IntervalAndHeader; import weka.classifiers.Classifier; import weka.classifiers.trees.RandomForest; import weka.core.Instance; import weka.core.Instances; /** * * @author mirkoj, jonash * */ public class ExtendedRandomForest extends RandomForest implements RangeQueryPredictor { /** * For serialization purposes. */ private static final long serialVersionUID = 8774800172762290733L; private static final Logger log = LoggerFactory.getLogger(ExtendedRandomForest.class); private final IntervalAggregator forestAggregator; private FeatureSpace featureSpace; public ExtendedRandomForest() { this(new QuantileAggregator(0.15), new AggressiveAggregator()); } public ExtendedRandomForest(final IntervalAggregator treeAggregator, final IntervalAggregator forestAggregator) { super(); ExtendedRandomTree rTree = new ExtendedRandomTree(treeAggregator); this.setClassifier(rTree); this.forestAggregator = forestAggregator; } public ExtendedRandomForest(final FeatureSpace featureSpace) { this(); this.featureSpace = featureSpace; ExtendedRandomTree erTree = (ExtendedRandomTree) this.getClassifier(); erTree.setFeatureSpace(featureSpace); } public ExtendedRandomForest(final IntervalAggregator treeAggregator, final IntervalAggregator forestAggregator, final FeatureSpace featureSpace) { super(); this.forestAggregator = forestAggregator; this.featureSpace = featureSpace; ExtendedRandomTree erTree = new ExtendedRandomTree(treeAggregator); erTree.setFeatureSpace(featureSpace); this.setClassifier(erTree); } /** * Needs to be called before predicting marginal variance contributions! * * @param Instances * for which marginal variance contributions are to be estimated * @throws InterruptedException */ public void prepareForest(final Instances data) throws InterruptedException { this.featureSpace = new FeatureSpace(data); for (Classifier classifier : this.m_Classifiers) { ExtendedRandomTree curTree = (ExtendedRandomTree) classifier; curTree.setFeatureSpace(this.featureSpace); curTree.preprocess(); } } public void printVariances() { for (Classifier classifier : this.m_Classifiers) { ExtendedRandomTree curTree = (ExtendedRandomTree) classifier; log.debug("cur var: {}", curTree.getTotalVariance()); } } public double computeMarginalVarianceContributionForFeatureSubset(final Set<Integer> features) { double avg = 0; for (Classifier classifier : this.m_Classifiers) { ExtendedRandomTree curTree = (ExtendedRandomTree) classifier; double curMarg = curTree.computeMarginalVarianceContributionForSubsetOfFeatures(features); avg += curMarg * 1.0 / this.m_Classifiers.length; } return avg; } public double computeMarginalVarianceContributionForFeatureSubsetNotNormalized(final Set<Integer> features) { double avg = 0; for (Classifier classifier : this.m_Classifiers) { ExtendedRandomTree curTree = (ExtendedRandomTree) classifier; double curMarg = curTree.computeMarginalVarianceContributionForSubsetOfFeaturesNotNormalized(features); avg += curMarg * 1.0 / this.m_Classifiers.length; } return avg; } /** * * @return Size of */ public int getSize() { return this.m_Classifiers.length; } /** * * @return Feature space on which this forest operates on */ public FeatureSpace getFeatureSpace() { return this.featureSpace; } @Override protected String defaultClassifierString() { return "jaicore.ml.intervaltree.ExtendedRandomTree"; } public ExtendedRandomForest(final int seed) { this(); this.setSeed(seed); } @Override public Interval predictInterval(final Instance rangeQuery) { // collect the different predictions List<Double> predictions = new ArrayList<>(this.m_Classifiers.length * 2); for (int i = 0; i < this.m_Classifiers.length; i++) { ExtendedRandomTree classifier = (ExtendedRandomTree) this.m_Classifiers[i]; Interval prediction = classifier.predictInterval(rangeQuery); predictions.add(prediction.getInf()); predictions.add(prediction.getSup()); } // aggregate them return this.forestAggregator.aggregate(predictions); } @Override public Interval predictInterval(final IntervalAndHeader intervalAndHeader) { // collect the different predictions List<Double> predictions = new ArrayList<>(this.m_Classifiers.length * 2); for (int i = 0; i < this.m_Classifiers.length; i++) { ExtendedRandomTree classifier = (ExtendedRandomTree) this.m_Classifiers[i]; Interval prediction = classifier.predictInterval(intervalAndHeader); predictions.add(prediction.getInf()); predictions.add(prediction.getSup()); } // aggregate them return this.forestAggregator.aggregate(predictions); } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/ExtendedRandomTree.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.math3.geometry.euclidean.oned.Interval; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.AggressiveAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation.IntervalAggregator; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace.CategoricalFeatureDomain; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace.FeatureDomain; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace.FeatureSpace; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace.NumericFeatureDomain; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.util.RQPHelper; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.util.RQPHelper.IntervalAndHeader; import weka.classifiers.trees.RandomTree; /** * Extension of a classic RandomTree to predict intervals. This class also * provides an implementaion of fANOVA based on Hutter et al.s implementation * https://github.com/frank-hutter/fanova * * @author mirkoj * */ public class ExtendedRandomTree extends RandomTree implements RangeQueryPredictor { private static final Logger LOGGER = LoggerFactory.getLogger(ExtendedRandomTree.class); private static final String LOG_WARN_VARIANCE_ZERO = "The trees total variance is zero, predictions make no sense at this point!"; private static final String LOG_WARN_NOT_PREPARED = "Tree is not prepared, preprocessing may take a while"; private static final String LOG_INDIVIDUAL_VAR = "Individual var for {} = {}"; private static final String LOG_TOTAL_VAR = "current total variance for {} = {}"; /** * * For serialization purposes */ private static final long serialVersionUID = -467555221387281335L; private final IntervalAggregator intervalAggregator; private FeatureSpace featureSpace; private HashMap<Tree, FeatureSpace> partitioning; private ArrayList<Tree> leaves; private ArrayList<Set<Double>> splitPoints; private double totalVariance; private transient Observation[][] allObservations; private HashMap<Set<Integer>, Double> varianceOfSubsetIndividual; private HashMap<Set<Integer>, Double> varianceOfSubsetTotal; private HashMap<Tree, Double> mapForEmptyLeaves; private boolean isPrepared; public ExtendedRandomTree() { this(new AggressiveAggregator()); this.partitioning = new HashMap<>(); this.leaves = new ArrayList<>(); // important, otherwise some classdistributions may be null this.setAllowUnclassifiedInstances(false); this.varianceOfSubsetTotal = new HashMap<>(); this.varianceOfSubsetIndividual = new HashMap<>(); this.mapForEmptyLeaves = new HashMap<>(); this.isPrepared = false; } public ExtendedRandomTree(final FeatureSpace featureSpace) { this(); this.featureSpace = featureSpace; this.isPrepared = false; } public ExtendedRandomTree(final IntervalAggregator intervalAggregator) { super(); try { this.setOptions(new String[] { "-U" }); } catch (Exception e) { throw new IllegalStateException("Couldn't unprune the tree"); } this.intervalAggregator = intervalAggregator; this.partitioning = new HashMap<>(); this.leaves = new ArrayList<>(); // important, otherwise some classdistributions may be null this.setAllowUnclassifiedInstances(false); this.varianceOfSubsetTotal = new HashMap<>(); this.varianceOfSubsetIndividual = new HashMap<>(); this.mapForEmptyLeaves = new HashMap<>(); this.isPrepared = false; } @Override public Interval predictInterval(final IntervalAndHeader intervalAndHeader) { Interval[] queriedInterval = intervalAndHeader.getIntervals(); // the stack of elements that still have to be processed. Deque<Entry<Interval[], Tree>> stack = new ArrayDeque<>(); // initially, the root and the queried interval stack.push(RQPHelper.getEntry(queriedInterval, this.m_Tree)); // the list of all leaf values ArrayList<Double> list = new ArrayList<>(); while (stack.peek() != null) { // pick the next node to process Entry<Interval[], Tree> toProcess = stack.pop(); Tree nextTree = toProcess.getValue(); double threshold = nextTree.getM_SplitPoint(); int attribute = nextTree.getM_Attribute(); Tree[] children = nextTree.getM_Successors(); double[] classDistribution = nextTree.getM_Classdistribution(); // process node if (attribute == -1) { // node is a leaf // for now, assume that we have regression! list.add(classDistribution[0]); } else { Interval intervalForAttribute = queriedInterval[attribute]; // no leaf node... Tree leftChild = children[0]; Tree rightChild = children[1]; // traverse the tree if (intervalForAttribute.getInf() <= threshold) { if (threshold <= intervalForAttribute.getSup()) { // scenario: x_min <= threshold <= x_max // query [x_min, threshold] on the left child // query [threshold, x_max] right Interval[] newInterval = RQPHelper.substituteInterval(toProcess.getKey(), new Interval(intervalForAttribute.getInf(), threshold), attribute); Interval[] newMaxInterval = RQPHelper.substituteInterval(toProcess.getKey(), new Interval(threshold, intervalForAttribute.getSup()), attribute); stack.push(RQPHelper.getEntry(newInterval, leftChild)); stack.push(RQPHelper.getEntry(newMaxInterval, rightChild)); } else { // scenario: threshold <= x_min <= x_max // query [x_min, x_max] on the left child stack.push(RQPHelper.getEntry(toProcess.getKey(), leftChild)); } } // analogously... if (intervalForAttribute.getSup() > threshold) { stack.push(RQPHelper.getEntry(toProcess.getKey(), rightChild)); } } } return this.intervalAggregator.aggregate(list); } public void setFeatureSpace(final FeatureSpace featureSpace) { this.featureSpace = featureSpace; } public FeatureSpace getFeatureSpace() { return this.featureSpace; } /** * Computes the variance contribution of a subset of features. * * @param features * @return Variance contribution of the feature subset */ public double computeMarginalStandardDeviationForSubsetOfFeatures(Set<Integer> features) { if (!this.isPrepared) { LOGGER.warn(LOG_WARN_NOT_PREPARED); this.preprocess(); } // as we use a set as a key, we should at least make it immutable features = Collections.unmodifiableSet(features); if (this.totalVariance == 0.0d) { LOGGER.warn(LOG_WARN_VARIANCE_ZERO); return Double.NaN; } double vU; if (this.varianceOfSubsetTotal.containsKey(features)) { vU = this.varianceOfSubsetTotal.get(features); } else { vU = this.computeTotalVarianceOfSubset(features); } LOGGER.trace(LOG_TOTAL_VAR, features, vU); for (int k = 1; k < features.size(); k++) { // generate all subsets of size k Set<Set<Integer>> subsets = Sets.combinations(features, k); for (Set<Integer> subset : subsets) { if (subset.isEmpty()) { continue; } LOGGER.trace("Subtracting {} for {}", this.varianceOfSubsetIndividual.get(subset), subset); vU -= this.varianceOfSubsetIndividual.get(subset); } } LOGGER.trace(LOG_INDIVIDUAL_VAR, features, vU); if (vU < 0.0d) { vU = 0.0d; } this.varianceOfSubsetIndividual.put(features, vU); return Math.sqrt(vU); } /** * Computes the variance contribution of a subset of features. * * @param features * @return Variance contribution of the feature subset */ public double computeMarginalVarianceContributionForSubsetOfFeatures(Set<Integer> features) { if (!this.isPrepared) { LOGGER.warn(LOG_WARN_NOT_PREPARED); this.preprocess(); } features = Collections.unmodifiableSet(features); if (this.totalVariance == 0.0d) { LOGGER.warn(LOG_WARN_VARIANCE_ZERO); return Double.NaN; } double vU; if (this.varianceOfSubsetTotal.containsKey(features)) { vU = this.varianceOfSubsetTotal.get(features); } else { vU = this.computeTotalVarianceOfSubset(features); } LOGGER.trace(LOG_TOTAL_VAR, features, vU); for (int k = 1; k < features.size(); k++) { // generate all subsets of size k Set<Set<Integer>> subsets = Sets.combinations(features, k); for (Set<Integer> subset : subsets) { if (subset.isEmpty()) { continue; } LOGGER.trace("Subtracting {} for {} ", this.varianceOfSubsetIndividual.get(subset), subset); vU -= this.varianceOfSubsetIndividual.get(subset); } } LOGGER.trace(LOG_INDIVIDUAL_VAR, features, vU); vU = Math.max(vU, 0); this.varianceOfSubsetIndividual.put(features, vU); return vU / this.totalVariance; } /** * Computes the variance contribution of a subset of features without * normalizing. * * @param features * @return Variance contribution of the feature subset */ public double computeMarginalVarianceContributionForSubsetOfFeaturesNotNormalized(Set<Integer> features) { if (!this.isPrepared) { LOGGER.warn(LOG_WARN_NOT_PREPARED); this.preprocess(); } features = Collections.unmodifiableSet(features); if (this.totalVariance == 0.0d) { LOGGER.warn(LOG_WARN_VARIANCE_ZERO); return Double.NaN; } double vU; if (this.varianceOfSubsetTotal.containsKey(features)) { vU = this.varianceOfSubsetTotal.get(features); } else { vU = this.computeTotalVarianceOfSubset(features); } LOGGER.trace(LOG_TOTAL_VAR, features, vU); for (int k = 1; k < features.size(); k++) { // generate all subsets of size k Set<Set<Integer>> subsets = Sets.combinations(features, k); for (Set<Integer> subset : subsets) { if (subset.isEmpty()) { continue; } LOGGER.trace("Subtracting {} for {} ", this.varianceOfSubsetIndividual.get(subset), subset); vU -= this.varianceOfSubsetIndividual.get(subset); } } LOGGER.trace(LOG_INDIVIDUAL_VAR, features, vU); if (vU < 0.0d) { vU = 0.0d; } this.varianceOfSubsetIndividual.put(features, vU); return vU; } /** * Computes a marginal prediction for a subset of features and a set of * observations (\hat{a}_U in the paper) * * @param indices * @param observations * @return Marginal prediction for the subset of features. */ private double getMarginalPrediction(final List<Integer> indices, final List<Observation> observations) { double result = 0; Set<Integer> subset = new HashSet<>(); subset.addAll(indices); List<Double> obsList = new ArrayList<>(observations.size()); for (Observation obs : observations) { obsList.add(obs.midPoint); } boolean consistentWithAnyLeaf = false; for (Entry<Tree, FeatureSpace> leafEntry : this.partitioning.entrySet()) { Tree leaf = leafEntry.getKey(); if (this.partitioning.get(leaf).containsPartialInstance(indices, obsList)) { double sizeOfLeaf = this.partitioning.get(leaf).getRangeSizeOfAllButSubset(subset); double sizeOfDomain = this.featureSpace.getRangeSizeOfAllButSubset(subset); double fractionOfSpaceForThisLeaf = sizeOfLeaf / sizeOfDomain; double prediction; if (leaf.getM_Classdistribution() != null) { prediction = leaf.getM_Classdistribution()[0]; } else if (this.mapForEmptyLeaves.containsKey(leaf)) { prediction = this.mapForEmptyLeaves.get(leaf); } else { LOGGER.warn("No prediction found anywhere!"); prediction = Double.NaN; } assert prediction != Double.NaN : "Prediction must not be NaN"; result += prediction * fractionOfSpaceForThisLeaf; consistentWithAnyLeaf = true; } } if (!consistentWithAnyLeaf) { LOGGER.warn("Observation {} is not consistent with any leaf with indices: {}", obsList, indices); } return result; } /** * Computes a partitioning of the feature space for this random tree * * @param subSpace * @param node * @throws Exception */ private void computePartitioning(final FeatureSpace subSpace, final Tree node) { double splitPoint = node.getM_SplitPoint(); int attribute = node.getM_Attribute(); Tree[] children = node.getM_Successors(); // check if any child is leaf and has empty class distribution, if so add the current node // if node is leaf add partition to the map or if (attribute == -1) { this.leaves.add(node); this.partitioning.put(node, subSpace); } // if the split attribute is categorical, remove all but one from the feature space and continue else if (subSpace.getFeatureDomain(attribute) instanceof CategoricalFeatureDomain) { for (int i = 0; i < children.length; i++) { if (children[i].getM_Classdistribution() == null && children[i].getM_Attribute() == -1) { this.mapForEmptyLeaves.put(children[i], node.getM_Classdistribution()[0]); } // important! if the children are leaves and do not contain a class distribution, treat this node as a leaf. If the split that leads // a leaf happens on a categorical feature, the leaf does not contain a class distribution in the WEKA RandomTree FeatureSpace childSubSpace = new FeatureSpace(subSpace); ((CategoricalFeatureDomain) childSubSpace.getFeatureDomain(attribute)).setValues(new double[] { i }); this.computePartitioning(childSubSpace, children[i]); } } // if the split attribute is numeric, set the new interval ranges of the resulting feature space accordingly and continue else if (subSpace.getFeatureDomain(attribute) instanceof NumericFeatureDomain) { FeatureSpace leftSubSpace = new FeatureSpace(subSpace); ((NumericFeatureDomain) leftSubSpace.getFeatureDomain(attribute)).setMax(splitPoint); FeatureSpace rightSubSpace = new FeatureSpace(subSpace); ((NumericFeatureDomain) rightSubSpace.getFeatureDomain(attribute)).setMin(splitPoint); this.computePartitioning(leftSubSpace, children[0]); this.computePartitioning(rightSubSpace, children[1]); } } /** * Collect all split points of a given tree * * @param root */ private void collectSplitPointsAndIntervalSizes(final Tree root) { // One HashSet of split points for each feature this.splitPoints = new ArrayList<>(this.featureSpace.getDimensionality()); List<List<Double>> splitPointsList = new ArrayList<>(this.featureSpace.getDimensionality()); for (int i = 0; i < this.featureSpace.getDimensionality(); i++) { this.splitPoints.add(i, new HashSet<>()); splitPointsList.add(i, new ArrayList<>()); } Queue<Tree> queueOfNodes = new LinkedList<>(); queueOfNodes.add(root); // While the queue is not empty while (!queueOfNodes.isEmpty()) { Tree node = queueOfNodes.poll(); // Is node a leaf? if (node.getM_Attribute() <= -1) { continue; } this.splitPoints.get(node.getM_Attribute()).add(node.getM_SplitPoint()); splitPointsList.get(node.getM_Attribute()).add(node.getM_SplitPoint()); // Add successors to queue for (int i = 0; i < node.getM_Successors().length; i++) { queueOfNodes.add(node.getM_Successors()[i]); } } } /** * Compute observations, i.e. representatives of each equivalence class of * partitions */ private void computeObservations() { this.allObservations = new Observation[this.featureSpace.getDimensionality()][]; for (int featureIndex = 0; featureIndex < this.featureSpace.getDimensionality(); featureIndex++) { List<Double> curSplitPoints = new ArrayList<>(); curSplitPoints.addAll(this.splitPoints.get(featureIndex)); // curSplitPoints FeatureDomain curDomain = this.featureSpace.getFeatureDomain(featureIndex); if (curDomain instanceof NumericFeatureDomain) { NumericFeatureDomain curNumDomain = (NumericFeatureDomain) curDomain; curSplitPoints.add(curNumDomain.getMin()); curSplitPoints.add(curNumDomain.getMax()); Collections.sort(curSplitPoints); // if the tree does not split on this value, it is not important if (curSplitPoints.isEmpty()) { this.allObservations[featureIndex] = new Observation[0]; } else { this.allObservations[featureIndex] = new Observation[curSplitPoints.size() - 1]; Observation obs; for (int lowerIntervalId = 0; lowerIntervalId < curSplitPoints.size() - 1; lowerIntervalId++) { if (curSplitPoints.get(lowerIntervalId + 1) - curSplitPoints.get(lowerIntervalId) > 0) { obs = new Observation((curSplitPoints.get(lowerIntervalId) + curSplitPoints.get(lowerIntervalId + 1)) / 2, curSplitPoints.get(lowerIntervalId + 1) - curSplitPoints.get(lowerIntervalId)); } else { obs = new Observation((curSplitPoints.get(lowerIntervalId) + curSplitPoints.get(lowerIntervalId + 1)) / 2, 1); } this.allObservations[featureIndex][lowerIntervalId] = obs; } } } else if (curDomain instanceof CategoricalFeatureDomain) { CategoricalFeatureDomain cDomain = (CategoricalFeatureDomain) curDomain; this.allObservations[featureIndex] = new Observation[cDomain.getValues().length]; for (int i = 0; i < this.allObservations[featureIndex].length; i++) { this.allObservations[featureIndex][i] = new Observation(cDomain.getValues()[i], 1.0d); } } } } /** * Computes the total variance of marginal predictions for a given set of * features. * * @param features * @return */ public double computeTotalVarianceOfSubset(Set<Integer> features) { features = Collections.unmodifiableSet(features); if (this.varianceOfSubsetTotal.containsKey(features)) { return this.varianceOfSubsetTotal.get(features); } List<List<Observation>> observationList = new LinkedList<>(); List<Set<Observation>> observationSet = new LinkedList<>(); for (int featureIndex : features) { List<Observation> list = Arrays.stream(this.allObservations[featureIndex]).collect(Collectors.toList()); HashSet<Observation> hSet = new HashSet<>(); hSet.addAll(list); observationList.add(list); observationSet.add(hSet); } List<List<Observation>> observationProduct = Lists.cartesianProduct(observationList); double vU; WeightedVarianceHelper stat = new WeightedVarianceHelper(); for (List<Observation> curObs : observationProduct) { ArrayList<Integer> featureList = new ArrayList<>(); featureList.addAll(features); Collections.sort(featureList); double marginalPrediction = this.getMarginalPrediction(featureList, curObs); double prodOfIntervalSizes = 1.0d; for (Observation obs : curObs) { if (obs.intervalSize != 0) { prodOfIntervalSizes *= obs.intervalSize; } } double sizeOfAllButFeatures = this.getFeatureSpace().getRangeSizeOfAllButSubset(features); if (!Double.isNaN(marginalPrediction)) { stat.push(marginalPrediction, sizeOfAllButFeatures * prodOfIntervalSizes); } } vU = stat.getPopulaionVariance(); this.varianceOfSubsetTotal.put(features, vU); return vU; } public double getTotalVariance() { return this.totalVariance; } /** * Sets up the tree for fANOVA */ public void preprocess() { this.computePartitioning(this.featureSpace, this.m_Tree); this.collectSplitPointsAndIntervalSizes(this.m_Tree); this.computeObservations(); HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < this.featureSpace.getDimensionality(); i++) { set.add(i); } this.totalVariance = this.computeTotalVarianceOfSubset(set); this.isPrepared = true; } public void printObservations() { for (int i = 0; i < this.allObservations.length; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < this.allObservations[i].length; j++) { sb.append(this.allObservations[i][j].midPoint + ", "); } LOGGER.debug("Observations for feature {}: {}", i, sb); } } public void printSplitPoints() { for (int i = 0; i < this.splitPoints.size(); i++) { Set<Double> points = this.splitPoints.get(i); List<Double> sorted = new ArrayList<>(points); if (this.getFeatureSpace().getFeatureDomain(i) instanceof NumericFeatureDomain) { sorted.add(((NumericFeatureDomain) this.getFeatureSpace().getFeatureDomain(i)).getMin()); sorted.add(((NumericFeatureDomain) this.getFeatureSpace().getFeatureDomain(i)).getMax()); } Collections.sort(sorted); } } public void printSizeOfFeatureSpaceAndPartitioning() { LOGGER.debug("Size of feature space: {}", this.featureSpace.getRangeSize()); double sizeOfPartitioning = 0.0d; for (Entry<Tree, FeatureSpace> leafEntry : this.partitioning.entrySet()) { sizeOfPartitioning += this.partitioning.get(leafEntry.getKey()).getRangeSize(); } LOGGER.debug("Complete size of partitioning: {}", sizeOfPartitioning); double sizeOfIntervals = 1.0d; for (int i = 0; i < this.allObservations.length; i++) { double temp = 0.0d; for (int j = 0; j < this.allObservations[i].length; j++) { temp += this.allObservations[i][j].intervalSize; } sizeOfIntervals *= temp; } LOGGER.debug("Complete size of intervals: {}", sizeOfIntervals); } /** * Helper to compute weighted variances * * @author jmhansel * */ private class WeightedVarianceHelper { private double average; private double squaredDistanceToMean; private double sumOfWeights; public WeightedVarianceHelper() { this.average = 0.0d; this.squaredDistanceToMean = 0.0d; this.sumOfWeights = 0.0d; } public void push(final double x, final double weight) { if (weight <= 0.0d) { throw new IllegalArgumentException("Weights have to be strictly positive!"); } double delta = x - this.average; this.sumOfWeights += weight; this.average += delta * weight / this.sumOfWeights; this.squaredDistanceToMean += weight * delta * (x - this.average); } public double getPopulaionVariance() { if (this.sumOfWeights > 0.0d) { return Math.max(0.0d, this.squaredDistanceToMean / this.sumOfWeights); } else { return Double.NaN; } } } /** * private class for dealing with observations, basically a tuple of doubles. * * @author jmhansel * */ private class Observation { private double midPoint; private double intervalSize; public Observation(final double midPoint, final double intervalSize) { this.midPoint = midPoint; this.intervalSize = intervalSize; } } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/PredictionFailedException.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree; public class PredictionFailedException extends RuntimeException { /** * */ private static final long serialVersionUID = -802385780037700995L; public PredictionFailedException(final String msg) { super(msg); } public PredictionFailedException(final String msg, final Throwable cause) { super(msg, cause); } public PredictionFailedException(final Throwable cause) { super(cause); } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/RangeQueryPredictor.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree; import org.apache.commons.math3.geometry.euclidean.oned.Interval; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.util.RQPHelper; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.util.RQPHelper.IntervalAndHeader; import weka.core.Instance; /** * * @author elppa * */ public interface RangeQueryPredictor { default Interval predictInterval(final Instance data) { IntervalAndHeader intervalAndHeader = RQPHelper.mapWEKAToTree(data); return predictInterval(intervalAndHeader); } public Interval predictInterval(IntervalAndHeader intervalAndHeader); }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/aggregation/AggressiveAggregator.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation; import java.util.List; import org.apache.commons.math3.geometry.euclidean.oned.Interval; /** * An {@link IntervalAggregator} that makes predictions using the minimum of the * predictions as the lower bound and the maximum as the upper bound. These * predictions are, generally speaking, favorable if the correctness property * of the RQP is desired over the precision property. * * @author elppa * */ public class AggressiveAggregator implements IntervalAggregator { /** * For serialization purposes. */ private static final long serialVersionUID = -1354655063228985606L; @Override public Interval aggregate(final List<Double> toAggregate) { double min = toAggregate.stream().mapToDouble(x -> x).min().getAsDouble(); double max = toAggregate.stream().mapToDouble(x -> x).max().getAsDouble(); return new Interval(min, max); } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/aggregation/IntervalAggregator.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation; import java.io.Serializable; import java.util.List; import org.apache.commons.math3.geometry.euclidean.oned.Interval; /** * An IntervalAggeregator can aggregate from a list of intervals, more precisely * given a list of predictions in the leaf node, it can predict a range. * * The basic Aggregators that we introduce are based on minimal and maximal * values (we call these the <i>Aggressive Predictors</i>) and based on * quantiles. * * @author elppa * */ public interface IntervalAggregator extends Serializable{ public Interval aggregate(List<Double> toAggregate); }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/aggregation/QuantileAggregator.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.aggregation; import java.util.List; import org.apache.commons.math3.geometry.euclidean.oned.Interval; import org.apache.commons.math3.stat.descriptive.rank.Percentile; /** * A {@link IntervalAggregator} that works based on quantiles. That is, if a * quantile with value 0.15 is chosen, the aggregator would choose the 0.85 * quantile of the predictions as the maximum and the 0.15 quantile as the * minimum. * * @author elppa * */ public class QuantileAggregator implements IntervalAggregator { /** * For serialization purposes. */ private static final long serialVersionUID = -6765279710955694443L; private final Percentile maxQuantile; private final Percentile minQuantile; public QuantileAggregator(final double quantile) { if (quantile < 0 || quantile > 1) { throw new IllegalArgumentException("Quantile values have to be in [0, 1]"); } this.maxQuantile = new Percentile(1 - quantile); this.minQuantile = new Percentile(quantile); } @Override public Interval aggregate(final List<Double> toAggregate) { // since Double is a wrapper type we have to copy manually :/ double[] mappedValues = new double[toAggregate.size()]; for (int i = 0; i < toAggregate.size(); i++) { mappedValues[i] = toAggregate.get(i); } double min = this.minQuantile.evaluate(mappedValues); double max = this.maxQuantile.evaluate(mappedValues); return new Interval(min, max); } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/featurespace/CategoricalFeatureDomain.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace; import java.util.Arrays; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.ExtendedRandomTree; /** * Description of a categorical feature domain. Needed for fANOVA application in * the {@link ExtendedRandomTree}. * * @author jmhansel * */ public class CategoricalFeatureDomain extends FeatureDomain { /** * Automatically generated version uid for serialization. */ private static final long serialVersionUID = 5890074168706122933L; private double[] values; public CategoricalFeatureDomain(final double[] values) { super(); this.values = values; } public CategoricalFeatureDomain(final CategoricalFeatureDomain domain) { super(); this.values = domain.values; } public double[] getValues() { return this.values; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(this.values); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } CategoricalFeatureDomain other = (CategoricalFeatureDomain) obj; return Arrays.equals(this.values, other.values); } @Override public String toString() { return "CategoricalFeatureDomain [values=" + Arrays.toString(this.values) + "]"; } @Override public double getRangeSize() { // For safety, if the domain is empty, it shouldn't effect the range size of the feature space if (this.values.length == 0) { return 1; } return this.values.length; } public void setValues(final double[] values) { this.values = values; } @Override public boolean containsInstance(final double value) { for (int i = 0; i < this.values.length; i++) { if (this.values[i] == value) { return true; } } return false; } @Override public boolean contains(final Object item) { double value = (double) item; for (int i = 0; i < this.values.length; i++) { if (this.values[i] == value) { return true; } } return false; } @Override public String compactString() { return "yet to implement"; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/featurespace/FeatureDomain.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace; import java.io.Serializable; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.ExtendedRandomTree; /** * Abstract description of a feature domain. Needed for fANOVA application in * the {@link ExtendedRandomTree}. * * @author jmhansel * */ public abstract class FeatureDomain implements Serializable { /** * */ private static final long serialVersionUID = -2314884533144162940L; private String name; /** * Setter for name attribute. * @param name */ public void setName(final String name) { this.name = name; } /** * Getter for name attribute. * @return */ public String getName() { return this.name; } /** * Checks if the domain contains an item. * * @param Item * to be checked * @return */ public abstract boolean contains(Object item); /** * Computes the size of the domain. For categorical features it returns the * number of catogeries, for numeric features upper interval bound - lower * interval bound. * * @return Size of feature domain */ public abstract double getRangeSize(); /** * Checks whether a given weka instance is contained in the feature domain * * @param instance * @return true iff contained in the domain */ public abstract boolean containsInstance(double value); public abstract String compactString(); }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/featurespace/FeatureSpace.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; public class FeatureSpace implements Serializable { /** * */ private static final long serialVersionUID = -4130427099174860007L; private List<FeatureDomain> featureDomains; public FeatureSpace() { this.featureDomains = new ArrayList<>(); } public FeatureSpace(final Instances data) throws InterruptedException { this(); for (int i = 0; i < data.numAttributes(); i++) { Attribute attr = data.attribute(i); if (data.classIndex() == i) { continue; } if (attr.isNumeric()) { double min; double max; if (attr.getLowerNumericBound() < attr.getUpperNumericBound()) { min = attr.getLowerNumericBound(); max = attr.getUpperNumericBound(); } // if no range is specified, use minimum and maximum of datapoints else { min = data.attributeStats(i).numericStats.min; max = data.attributeStats(i).numericStats.max; } NumericFeatureDomain domain = new NumericFeatureDomain(true, min, max); domain.setName(attr.name()); this.featureDomains.add(domain); } else if (attr.isNominal()) { String[] attrVals = new String[attr.numValues()]; double[] internalVals = new double[attr.numValues()]; for (int valIndex = 0; valIndex < attr.numValues(); valIndex++) { attrVals[valIndex] = attr.value(valIndex); internalVals[valIndex] = valIndex; } CategoricalFeatureDomain domain = new CategoricalFeatureDomain(internalVals); domain.setName(attr.name()); this.featureDomains.add(domain); } else { throw new IllegalArgumentException("Attribute type not supported!"); } } } /** * copy constructor * * @param domains */ public FeatureSpace(final List<FeatureDomain> domains) { this.featureDomains = new ArrayList<>(); for (FeatureDomain domain : domains) { if (domain instanceof NumericFeatureDomain) { NumericFeatureDomain numDomain = (NumericFeatureDomain) domain; this.featureDomains.add(new NumericFeatureDomain(numDomain)); } else if (domain instanceof CategoricalFeatureDomain) { CategoricalFeatureDomain catDomain = (CategoricalFeatureDomain) domain; this.featureDomains.add(new CategoricalFeatureDomain(catDomain)); } } } public FeatureSpace(final FeatureSpace space) { this(Arrays.asList(space.getFeatureDomains())); } public FeatureSpace(final FeatureDomain[] domains) { this(Arrays.asList(domains)); } public FeatureDomain[] toArray() { return this.featureDomains.toArray(new FeatureDomain[0]); } public void add(final FeatureDomain domain) { this.featureDomains.add(domain); } public FeatureDomain[] getFeatureDomains() { return this.featureDomains.toArray(new FeatureDomain[this.featureDomains.size()]); } public double getRangeSize() { double size = 1.0d; for (FeatureDomain domain : this.featureDomains) { size *= domain.getRangeSize(); } return size; } public double getRangeSizeOfFeatureSubspace(final Set<Integer> featureIndices) { double size = 1.0d; for (int featureIndex : featureIndices) { size *= this.featureDomains.get(featureIndex).getRangeSize(); } return size; } public double getRangeSizeOfAllButSubset(final Set<Integer> featureIndices) { double size = 1.0d; for (int i = 0; i < this.getDimensionality(); i++) { if (!featureIndices.contains(i)) { size *= this.featureDomains.get(i).getRangeSize(); } } return size; } public int getDimensionality() { return this.featureDomains.size(); } public FeatureDomain getFeatureDomain(final int index) { return this.featureDomains.get(index); } public boolean containsPartialInstance(final List<Integer> indices, final List<Double> values) { for (int i = 0; i < indices.size(); i++) { int featureIndex = indices.get(i); double value = values.get(i); if (!this.featureDomains.get(featureIndex).containsInstance(value)) { return false; } } return true; } public boolean containsInstance(final Instance instance) { boolean val = true; for (int i = 0; i < this.featureDomains.size(); i++) { FeatureDomain domain = this.featureDomains.get(i); val &= domain.contains(instance.value(i)); } return val; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/featurespace/NumericFeatureDomain.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace; import ai.libs.jaicore.basic.sets.Interval; import ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.ExtendedRandomTree; /** * Description of a numeric feature domain. Needed for fANOVA application in the {@link ExtendedRandomTree}. * * @author Felix Mohr, jmhansel * */ public class NumericFeatureDomain extends FeatureDomain { private static final long serialVersionUID = 7137323856374433244L; private final Interval interval; public NumericFeatureDomain(final boolean isInteger, final double min, final double max) { super(); this.interval = new Interval(isInteger, min, max); } public NumericFeatureDomain(final NumericFeatureDomain domain) { this(domain.isInteger(), domain.getMin(), domain.getMax()); } public boolean isInteger() { return this.interval.isInteger(); } public double getMin() { return this.interval.getMin(); } public double getMax() { return this.interval.getMax(); } public void setMin(final double min) { this.interval.setMin(min); } public void setMax(final double max) { this.interval.setMax(max); } @Override public String toString() { return "NumericFeatureDomain [isInteger=" + this.isInteger() + ", min=" + this.getMin() + ", max=" + this.getMax() + "]"; } @Override public boolean contains(final Object item) { return this.interval.contains(item); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.interval == null) ? 0 : this.interval.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } NumericFeatureDomain other = (NumericFeatureDomain) obj; if (this.interval == null) { if (other.interval != null) { return false; } } else if (!this.interval.equals(other.interval)) { return false; } return true; } @Override public double getRangeSize() { double temp = this.getMax() - this.getMin(); // For safety, if the interval is empty, it shouldn't effect the range size of the feature space if (temp == 0.0d) { return 1.0d; } return temp; } @Override public boolean containsInstance(final double value) { return this.contains(value); } @Override public String compactString() { return "[" + this.getMin() + "," + this.getMax() + "]"; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/featurespace/package-info.java
/** * */ /** * @author mwever * */ package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.featurespace;
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/rangequery/learner/intervaltree/util/RQPHelper.java
package ai.libs.jaicore.ml.weka.rangequery.learner.intervaltree.util; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Map.Entry; import org.apache.commons.math3.geometry.euclidean.oned.Interval; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; public class RQPHelper { private RQPHelper() { // prevent instantiation of this util class. } /** * Maps the WEKA query to a tree-friendly query while also preserving the header * information of the query, this is important for M5 trees. * * @param data * @return */ public static final IntervalAndHeader mapWEKAToTree(final Instance data) { Interval[] mappedData = new Interval[data.numAttributes() / 2]; int counter = 0; ArrayList<Attribute> attributes = new ArrayList<>(); attributes.add(new Attribute("bias")); for (int attrNum = 0; attrNum < data.numAttributes(); attrNum = attrNum + 2) { mappedData[counter] = new Interval(data.value(attrNum), data.value(attrNum + 1)); attributes.add(new Attribute("xVal" + counter)); counter++; } Instances header = new Instances("queriedInterval", attributes, 2); header.setClassIndex(-1); return new IntervalAndHeader(mappedData, header); } public static final Interval[] substituteInterval(final Interval[] original, final Interval toSubstitute, final int index) { Interval[] copy = Arrays.copyOf(original, original.length); copy[index] = toSubstitute; return copy; } public static final <T> Entry<Interval[], T> getEntry(final Interval[] interval, final T tree) { return new AbstractMap.SimpleEntry<>(interval, tree); } public static class IntervalAndHeader { private final Interval[] intervals; private final Instances headerInformation; public IntervalAndHeader(final Interval[] intervals, final Instances headerInformation) { super(); this.intervals = intervals; this.headerInformation = headerInformation; } public Interval[] getIntervals() { return this.intervals; } public Instances getHeaderInformation() { return this.headerInformation; } } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/dyad/learner
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/dyad/learner/activelearning/ConfidenceIntervalClusteringBasedActiveDyadRanker.java
package ai.libs.jaicore.ml.weka.ranking.dyad.learner.activelearning; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Random; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.api4.java.ai.ml.core.exception.TrainingException; import org.api4.java.ai.ml.ranking.dyad.dataset.IDyad; import org.api4.java.ai.ml.ranking.dyad.dataset.IDyadRankingInstance; import org.api4.java.common.math.IVector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.ml.ranking.dyad.dataset.DyadRankingDataset; import ai.libs.jaicore.ml.ranking.dyad.dataset.SparseDyadRankingInstance; import ai.libs.jaicore.ml.ranking.dyad.learner.activelearning.ARandomlyInitializingDyadRanker; import ai.libs.jaicore.ml.ranking.dyad.learner.activelearning.IDyadRankingPoolProvider; import ai.libs.jaicore.ml.ranking.dyad.learner.algorithm.PLNetDyadRanker; import weka.clusterers.Clusterer; import weka.core.Attribute; import weka.core.DenseInstance; import weka.core.Instance; import weka.core.Instances; /** * A prototypical active dyad ranker based on clustering of pseudo confidence * intervals. During the learning procedure, it keeps track over the standard * deviation of the skill values predicted for a dyad. First a constant number * of random queries is sampled at the beginning. Then the sampling strategy * clusteres the skill values of all alternatives for each instance according to * the lower and upper bounds of the confidence intervals of the skill for all * corresponding dyads. Confidence intervals are given by [skill - std, skill + * std] where skill denotes the skill and std denotes the empirical standard * deviaition of the skill for a dyad. Afterwards, it picks one of the largest * clusters and then selects the two dyads for which the confidence intervals * overlap the most within the cluster for pairwise comparison, until a * minibatch of constant size is filled. * * @author Jonas Hanselle * */ public class ConfidenceIntervalClusteringBasedActiveDyadRanker extends ARandomlyInitializingDyadRanker { private static final Logger log = LoggerFactory.getLogger(ConfidenceIntervalClusteringBasedActiveDyadRanker.class); private Clusterer clusterer; public ConfidenceIntervalClusteringBasedActiveDyadRanker(final PLNetDyadRanker ranker, final IDyadRankingPoolProvider poolProvider, final int seed, final int numberRandomQueriesAtStart, final int minibatchSize, final Clusterer clusterer) { super(ranker, poolProvider, seed, numberRandomQueriesAtStart, minibatchSize); this.clusterer = clusterer; } @Override public void activelyTrainWithOneInstance() throws InterruptedException { PriorityQueue<List<IDyad>> clusterQueue = new PriorityQueue<>(new ListComparator()); DyadRankingDataset minibatch = new DyadRankingDataset(); Map<IDyad, SummaryStatistics> dyadStats = this.getDyadStats(); for (IVector inst : this.getInstanceFeatures()) { // Create instances for clustering Attribute upperAttr = new Attribute("upper_bound"); Attribute lowerAttr = new Attribute("lower_bound"); ArrayList<Attribute> attributes = new ArrayList<>(); attributes.add(upperAttr); attributes.add(lowerAttr); Instances intervalInstances = new Instances("confidence_intervalls", attributes, this.poolProvider.getDyadsByInstance(inst).size()); for (IDyad dyad : this.poolProvider.getDyadsByInstance(inst)) { double skill = this.ranker.getSkillForDyad(dyad); dyadStats.get(dyad).addValue(skill); double[] attValues = new double[2]; attValues[0] = skill + dyadStats.get(dyad).getStandardDeviation(); attValues[1] = skill - dyadStats.get(dyad).getStandardDeviation(); Instance intervalInstance = new DenseInstance(1.0d, attValues); intervalInstances.add(intervalInstance); } try { this.clusterer.buildClusterer(intervalInstances); List<List<IDyad>> instanceClusters = new ArrayList<>(); int numClusters = this.clusterer.numberOfClusters(); for (int clusterIndex = 0; clusterIndex < numClusters; clusterIndex++) { instanceClusters.add(new ArrayList<>()); } for (IDyad dyad : this.poolProvider.getDyadsByInstance(inst)) { double skill = this.ranker.getSkillForDyad(dyad); double[] attValues = new double[2]; attValues[0] = skill + dyadStats.get(dyad).getStandardDeviation(); attValues[1] = skill - dyadStats.get(dyad).getStandardDeviation(); Instance intervalInstance = new DenseInstance(1.0d, attValues); int cluster = this.clusterer.clusterInstance(intervalInstance); instanceClusters.get(cluster).add(dyad); } for (int j = 0; j < instanceClusters.size(); j++) { clusterQueue.add(instanceClusters.get(j)); } } catch (Exception e1) { log.error(e1.getMessage()); } } Random random = this.getRandom(); for (int minibatchIndex = 0; minibatchIndex < this.getMinibatchSize(); minibatchIndex++) { // get the largest cluster List<IDyad> curDyads = clusterQueue.poll(); if (curDyads.size() < 2) { continue; } // check overlap for all pairs of dyads in the current cluster double curMax = -1; int[] curPair = { 0, 1 }; boolean changed = false; for (int j = 1; j < curDyads.size(); j++) { for (int k = 0; k < j; k++) { IDyad dyad1 = curDyads.get(j); IDyad dyad2 = curDyads.get(k); double overlap = this.getConfidenceIntervalOverlapForDyads(dyad1, dyad2); if (overlap > curMax) { curPair[0] = j; curPair[1] = k; curMax = overlap; changed = true; } } } // if the pair hasn't changed, i.e. there are no overlapping intervals, sample a random pair if (!changed) { curPair[0] = random.nextInt(curDyads.size()); curPair[1] = random.nextInt(curDyads.size()); while (curPair[0] == curPair[1]) { curPair[1] = random.nextInt(curDyads.size()); } } // query them LinkedList<IVector> alternatives = new LinkedList<>(); alternatives.add(curDyads.get(curPair[0]).getAlternative()); alternatives.add(curDyads.get(curPair[1]).getAlternative()); SparseDyadRankingInstance queryInstance = new SparseDyadRankingInstance(curDyads.get(curPair[0]).getContext(), alternatives); IDyadRankingInstance trueRanking = this.poolProvider.query(queryInstance); minibatch.add(trueRanking); } // update the ranker try { this.updateRanker(minibatch); } catch (TrainingException e) { log.error(e.getMessage()); } } private double getConfidenceIntervalOverlapForDyads(final IDyad dyad1, final IDyad dyad2) { double skill1 = this.ranker.getSkillForDyad(dyad1); double skill2 = this.ranker.getSkillForDyad(dyad2); Map<IDyad, SummaryStatistics> dyadStats = this.getDyadStats(); double lower1 = skill1 - dyadStats.get(dyad1).getStandardDeviation(); double upper1 = skill1 + dyadStats.get(dyad1).getStandardDeviation(); double lower2 = skill2 - dyadStats.get(dyad2).getStandardDeviation(); double upper2 = skill2 + dyadStats.get(dyad2).getStandardDeviation(); // if the intervals dont intersect, return 0 if (lower1 > upper2 || upper1 < lower2) { return 0.0d; } // else compute intersection double upperlower = Math.max(lower1, lower2); double lowerupper = Math.min(upper1, upper2); return Math.abs((lowerupper - upperlower)); } private class ListComparator implements Comparator<List<IDyad>> { @Override public int compare(final List<IDyad> o1, final List<IDyad> o2) { if (o1.size() > o2.size()) { return -1; } if (o1.size() < o2.size()) { return 1; } return 0; } } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/dyad/learner/zeroshot
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/dyad/learner/zeroshot/util/ZeroShotUtil.java
package ai.libs.jaicore.ml.weka.ranking.dyad.learner.zeroshot.util; import org.nd4j.linalg.api.ndarray.INDArray; import ai.libs.jaicore.ml.ranking.dyad.learner.util.DyadMinMaxScaler; import ai.libs.jaicore.ml.ranking.dyad.learner.zeroshot.inputoptimization.PLNetInputOptimizer; import weka.core.Utils; /** * A collection of utility methods used to map the results of a input optimization of {@link PLNetInputOptimizer} back to Weka options for the respective classifiers. * @author Michael Braun * */ public class ZeroShotUtil { private ZeroShotUtil() { // Intentionally left blank } public static String[] mapJ48InputsToWekaOptions(double c, double m) throws Exception { long roundedM = Math.round(m); return Utils.splitOptions("-C " + c + " -M " + roundedM); } public static String[] mapSMORBFInputsToWekaOptions(double cExp, double rbfGammaExp) throws Exception { double c = Math.pow(10, cExp); double g = Math.pow(10, rbfGammaExp); String cComplexityConstOption = "-C " + c; String rbfGammaOption = " -K \"weka.classifiers.functions.supportVector.RBFKernel -C 250007 -G " + g + "\""; String options = cComplexityConstOption + rbfGammaOption; return Utils.splitOptions(options); } public static String[] mapMLPInputsToWekaOptions(double lExp, double mExp, double n) throws Exception { double l = Math.pow(10, lExp); double m = Math.pow(10, mExp); long roundedN = Math.round(n); return Utils.splitOptions("-L " + l + " -M " + m + " -N " + roundedN); } public static String[] mapRFInputsToWekaOptions(double i, double kFraction, double m, double depth, double kNumAttributes) throws Exception { int iRounded = (int) Math.round(i); int k = (int) Math.ceil(kNumAttributes * kFraction); int mRounded = (int) Math.round(m); int depthRounded = (int) Math.round(depth); return Utils.splitOptions(" -I " + iRounded + " -K " + k + " -M " + mRounded + " -depth " + depthRounded); } public static INDArray unscaleParameters(INDArray parameters, DyadMinMaxScaler scaler, int numHyperPars) { int[] hyperParIndices = new int[numHyperPars]; for (int i = 0; i < numHyperPars; i++) { hyperParIndices[i] = (int) parameters.length() - numHyperPars + i; } INDArray unscaled = parameters.getColumns(hyperParIndices); for (int i = 0; i < unscaled.length(); i++) { unscaled.putScalar(i, unscaled.getDouble(i) * (scaler.getStatsY()[i].getMax() - scaler.getStatsY()[i].getMin()) + scaler.getStatsY()[i].getMin()); } return unscaled; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/ClassifierRankingForGroup.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; import java.util.ArrayList; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.GroupIdentifier; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.RankingForGroup; @SuppressWarnings("serial") public class ClassifierRankingForGroup extends RankingForGroup<double[],String> { /** * This class saves a classifier ranking in form of their names as string for a group of problem instances. The group is identified by a group identifier here in form of * of point. * @param identifier * @param solutionsForGroup */ ClassifierRankingForGroup(final GroupIdentifier<double[]> identifier, final ArrayList<String> solutionsForGroup) { super(identifier, solutionsForGroup); } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/Cluster.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; import java.util.List; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.Group; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.GroupIdentifier; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.ProblemInstance; import weka.core.Instance; public class Cluster extends Group<double[], Instance> { /** Saves a cluster in two components. First, a list of the elements in the cluster * here in form of list of problem instnaces. Second, the identifier of the cluster * in form of the cluster center as a point. * @param instanlist * @param id */ Cluster(final List<ProblemInstance<Instance>> instanlist, final GroupIdentifier<double[]> id) { super(instanlist, id); } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/IDistanceMetric.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; /** * @author Helen * * Computes a distance of type D between a starting point of type A to an ending point B * * @param <D> The type of the distance * @param <A> The type of the starting point * @param <B> The type of the ending point */ public interface IDistanceMetric<D, A, B> { public D computeDistance(A start, B end); }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/Kmeans.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Helen * * @param <A> The to cluster points * @param <D> The Type of the distance measure. */ public abstract class Kmeans<A,D> { protected List<A> points; protected List<A> center; protected int k; protected IDistanceMetric<D, A, A> metric; public Kmeans(final List<A> toClusterPoints, final IDistanceMetric<D, A, A> dist) { this.points = toClusterPoints; this.metric = dist; this.center = new ArrayList<>(); } public abstract Map<double[], List<double[]>> kmeanscluster(int k); public abstract void initializeKMeans(); }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/L1DistanceMetric.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; /** * @author Helen * implements the Manhattan distance metric */ public class L1DistanceMetric implements IDistanceMetric<Double, double[], double[]> { /* (non-Javadoc) * @see jaicore.modifiedISAC.IDistanceMetric#computeDistance(java.lang.Object, java.lang.Object) */ @Override public Double computeDistance(final double[] start, final double[] end) { if (start.length != end.length) { throw new IllegalArgumentException("Arrays must have same length"); } double distance = 0; // takes each entry of the two vectors and computes the difference between // the entry in the start vector and the end vector in absolute value. for (int i = 0; i < start.length; i++) { // If the entry is Nan nothing will be added. if (Double.isNaN(start[i]) || Double.isNaN(end[i])) { distance += 0; } else { distance += Math.abs((start[i] - end[i])); } } return distance; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/ModifiedISAC.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.api4.java.ai.ml.core.exception.PredictionException; import org.api4.java.ai.ml.core.exception.TrainingException; import org.api4.java.ai.ml.ranking.IRanking; import org.api4.java.ai.ml.ranking.IRankingPredictionBatch; import org.api4.java.ai.ml.ranking.label.dataset.ILabelRankingDataset; import org.api4.java.ai.ml.ranking.label.dataset.ILabelRankingInstance; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.ml.core.learner.ASupervisedLearner; import ai.libs.jaicore.ml.ranking.RankingPredictionBatch; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.IGroupBasedRanker; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.Group; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.ProblemInstance; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.RankingForGroup; import weka.core.Instance; /** * @author Helen * ModifiedISAC handles the preparation of the data and the clustering of it as well as the * the search for a cluster for a new instance. */ public class ModifiedISAC extends ASupervisedLearner<ILabelRankingInstance, ILabelRankingDataset, IRanking<String>, IRankingPredictionBatch> implements IGroupBasedRanker<String, ILabelRankingInstance, ILabelRankingDataset, double[]> { // Saves the position of the points in the original list to save their relation to the corresponding // instance. private Map<double[], Integer> positionOfInstance = new HashMap<>(); // Saves the rankings for the found cluster in form of the cluster center and the ranking of Classifier by their name. private ArrayList<ClassifierRankingForGroup> rankings = new ArrayList<>(); // Saves the found cluster private List<Group<double[], Instance>> foundCluster; // Saves the used normalizer private Normalizer norm; /* (non-Javadoc) * @see jaicore.Ranker.Ranker#bulidRanker() */ @Override public void fit(final ILabelRankingDataset dTrain) throws TrainingException { ModifiedISACInstanceCollector collector; try { collector = new ModifiedISACInstanceCollector(); } catch (Exception e) { throw new TrainingException("Could not build the ranker.", e); } List<ProblemInstance<Instance>> collectedInstances = collector.getProblemInstances(); List<double[]> toClusterpoints = new ArrayList<>(); this.norm = new Normalizer(collectedInstances); this.norm.setupnormalize(); for (ProblemInstance<Instance> tmp : collectedInstances) { toClusterpoints.add(this.norm.normalize(tmp.getInstance().toDoubleArray())); } ModifiedISACGroupBuilder builder = new ModifiedISACGroupBuilder(); builder.setPoints(toClusterpoints); int tmp = 0; for (ProblemInstance<Instance> i : collectedInstances) { this.positionOfInstance.put(i.getInstance().toDoubleArray(), tmp); tmp++; } this.foundCluster = builder.buildGroup(collectedInstances); this.constructRanking(collector); } /** * given the collector and the used Classifier it construct a ranking for the found classifer * * @param collector */ private void constructRanking(final ModifiedISACInstanceCollector collector) { for (Group<double[], Instance> c : this.foundCluster) { ArrayList<String> ranking = new ArrayList<>(); int[] tmp = new int[collector.getNumberOfClassifier()]; double[] clusterMean = new double[collector.getNumberOfClassifier()]; for (ProblemInstance<Instance> prob : c.getInstances()) { int myIndex = 0; for (Entry<double[], Integer> instancePositionWithNumber : this.positionOfInstance.entrySet()) { if (Arrays.equals(instancePositionWithNumber.getKey(), prob.getInstance().toDoubleArray())) { myIndex = instancePositionWithNumber.getValue(); break; } } ArrayList<Pair<String, Double>> solutionsOfPoint = collector.getCollectedClassifierandPerformance().get(myIndex); for (int i = 0; i < solutionsOfPoint.size(); i++) { double perfo = solutionsOfPoint.get(i).getY(); if (!Double.isNaN(perfo)) { clusterMean[i] += perfo; tmp[i]++; } } } for (int i = 0; i < clusterMean.length; i++) { clusterMean[i] = clusterMean[i] / tmp[i]; } List<String> allClassifier = collector.getAllClassifier(); Map<String, Double> remainingCandidiates = new HashMap<>(); for (int i = 0; i < clusterMean.length; i++) { remainingCandidiates.put(allClassifier.get(i), clusterMean[i]); } while (!remainingCandidiates.isEmpty()) { double min = Double.MIN_VALUE; String classi = null; for (Entry<String, Double> nameWithCandidate : remainingCandidiates.entrySet()) { double candidate = nameWithCandidate.getValue(); if (candidate > min) { classi = nameWithCandidate.getKey(); min = candidate; } } if (classi == null) { for (String str : remainingCandidiates.keySet()) { ranking.add(str); } remainingCandidiates.clear(); } else { ranking.add(classi); remainingCandidiates.remove(classi); } } this.rankings.add(new ClassifierRankingForGroup(c.getId(), ranking)); } } /* (non-Javadoc) * @see jaicore.GroupBasedRanker.GroupBasedRanker#getRanking(java.lang.Object) */ @Override public RankingForGroup<double[], String> getRanking(final ILabelRankingInstance prob) { RankingForGroup<double[], String> myRanking = null; double[] point = this.norm.normalize(prob.getPoint()); L1DistanceMetric dist = new L1DistanceMetric(); double minDist = Double.MAX_VALUE; for (RankingForGroup<double[], String> rank : this.rankings) { double computedDist = dist.computeDistance(rank.getIdentifierForGroup().getIdentifier(), point); if (computedDist <= minDist) { myRanking = rank; minDist = computedDist; } } return myRanking; } /** * @return */ public List<ClassifierRankingForGroup> getRankings() { return this.rankings; } @Override public IRanking<String> predict(final ILabelRankingInstance xTest) throws PredictionException, InterruptedException { return this.getRanking(xTest); } @Override public IRankingPredictionBatch predict(ILabelRankingInstance[] dTest) throws PredictionException, InterruptedException { List<IRanking<?>> rankingPredictions = new ArrayList<>(); for (ILabelRankingInstance instance : dTest) { rankingPredictions.add(predict(instance)); } return new RankingPredictionBatch(rankingPredictions); } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/ModifiedISACGroupBuilder.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; import java.util.ArrayList; import java.util.List; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.IGroupBuilder; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.Group; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.ProblemInstance; import weka.core.Instance; public class ModifiedISACGroupBuilder implements IGroupBuilder<double[], Instance> { private List<double[]> points; @Override public List<Group<double[], Instance>> buildGroup(final List<ProblemInstance<Instance>> allInstances) { ModifiedISACgMeans groupBuilder = new ModifiedISACgMeans(this.points, allInstances); return new ArrayList<>(groupBuilder.clusterDeprecated()); } public void setPoints(final List<double[]> toSetPoints) { this.points = toSetPoints; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/ModifiedISACInstanceCollector.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.ProblemInstance; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.datamanager.IInstanceCollector; import weka.core.Instance; import weka.core.Instances; import weka.core.converters.ConverterUtils.DataSource; /** * @author Helen * This class should collect Instances in form of metafeatures form a file. */ public class ModifiedISACInstanceCollector implements IInstanceCollector<Instance> { /** * The collected and processed Instances */ private ArrayList<ArrayList<Pair<String,Double>>> collectedClassifierandPerformance; private int numberOfClassifier; private ArrayList<String> allClassifier = new ArrayList<>(); private ArrayList<ProblemInstance<Instance>> collectedInstances = new ArrayList<>(); private static ArrayList<String> atributesofTrainingsdata = new ArrayList<>(); /** * @return Returns the attributes of the collected and processed Instances as well * as their order */ public static List<String> getAtributesofTrainingsdata() { return atributesofTrainingsdata; } public List<ArrayList<Pair<String,Double>>> getCollectedClassifierandPerformance() { return this.collectedClassifierandPerformance; } public int getNumberOfClassifier() { return this.numberOfClassifier; } public List<String> getAllClassifier() { return this.allClassifier; } public ModifiedISACInstanceCollector(final Instances data, final int startOfClassifierPerformanceValues, final int endOfClassifierPerformanceValues) { this.collectedClassifierandPerformance = new ArrayList<>(); this.numberOfClassifier = (((endOfClassifierPerformanceValues+1)-(startOfClassifierPerformanceValues+1))+1); for(Instance i : data) { ArrayList<Pair<String,Double>> pandc = new ArrayList<>(); for(int j = endOfClassifierPerformanceValues; j>=startOfClassifierPerformanceValues; j--) { String classi = i.attribute(j).name(); double perfo = i.value(j); Pair<String, Double> tup = new Pair<>(classi,perfo); pandc.add(tup); } this.collectedClassifierandPerformance.add(pandc); } Instance inst = data.get(0); for(int i = endOfClassifierPerformanceValues;i>=startOfClassifierPerformanceValues;i--) { this.allClassifier.add(inst.attribute(i).name()); data.deleteAttributeAt(i); } data.deleteAttributeAt(0); for(int i = 0; i<data.numAttributes();i++) { atributesofTrainingsdata.add(data.attribute(i).toString()); } for (Instance i : data) { this.collectedInstances.add(new ProblemInstance<>(i)); } } private static Instances loadDefaultInstances() throws Exception { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("metaData_smallDataSets_computed.arff"); DataSource source = new DataSource(inputStream); return source.getDataSet(); } /** This constructor is used if the default file should be used. Parts of the Instances * have to be removed for the further computation. (The dataset-ID, Classifers with performance ) * @throws Exception */ public ModifiedISACInstanceCollector() throws Exception { this(loadDefaultInstances(), 104, 125); } public void setNumberOfClassifier(final int number) { this.numberOfClassifier = number; } @Override public List<ProblemInstance<Instance>> getProblemInstances() { return this.collectedInstances; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/ModifiedISACgMeans.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import org.apache.commons.math3.ml.clustering.DoublePoint; import ai.libs.jaicore.ml.clustering.learner.GMeans; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.GroupIdentifier; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.ProblemInstance; import weka.core.Instance; public class ModifiedISACgMeans extends GMeans<DoublePoint> { private List<Cluster> gmeansCluster; private List<double[]> intermediateCenter; private Map<double[], List<double[]>> currentPoints; private Map<double[], List<double[]>> intermediatePoints; private List<double[]> loopPoints; private Map<double[], ProblemInstance<Instance>> pointToInstance; private L1DistanceMetric dist = new L1DistanceMetric(); /** * inilizes toClusterPoints with the points that are to Cluster and are * normalized metafeatures * * @param toClusterPoints * @param instances */ public ModifiedISACgMeans(final List<double[]> toClusterPoints, final List<ProblemInstance<Instance>> instances) { super(toClusterPoints.stream().map(DoublePoint::new).collect(Collectors.toList())); this.pointToInstance = new HashMap<>(); for (int i = 0; i < instances.size(); i++) { this.pointToInstance.put(toClusterPoints.get(i), instances.get(i)); } this.gmeansCluster = new ArrayList<>(); } public List<Cluster> clusterDeprecated() { HashMap<Integer, double[]> positionOfCenter = new HashMap<>(); int tmp = 1; int k = 1; int i = 1; // creates a k means clustering instance with all points and an L1 distance // metric as metric ModifiedISACkMeans test = new ModifiedISACkMeans(this.getPoints().stream().map(DoublePoint::getPoint).collect(Collectors.toList()), this.dist); // clusters all points with k = 1 this.currentPoints = test.kmeanscluster(k); // puts the first center into the list of center for (double[] d : this.currentPoints.keySet()) { this.getCentersModifiable().add(d); } // saves the position of the center for the excess during the g-means clustering // algorithm for (double[] c : this.getCentersModifiable()) { positionOfCenter.put(tmp, c); tmp++; } while (i <= k) { // looppoints are S_i the points are the points of the considered center C_i this.loopPoints = this.currentPoints.get(positionOfCenter.get(i)); // makes a new instance with of kmeans with S_i as base ModifiedISACkMeans loopCluster = new ModifiedISACkMeans(this.loopPoints, this.dist); // clusters S_I into to cluster intermediate points is a HashMap of center with an ArrayList of thier corresponding points this.intermediatePoints = loopCluster.kmeanscluster(2); // intermediate Center saves the found two Center C`_1 und C`_2 this.intermediateCenter = loopCluster.getCenter(); // the difference between the two new Center double[] v = this.difference(this.intermediateCenter.get(0), this.intermediateCenter.get(1)); double w = 0; // w is calculated as the summed squares of the entries of the difference // between the center // if the entry is NaN it is ignored in the sum for (int l = 0; l < v.length; l++) { if (!Double.isNaN(v[l])) { w += Math.pow(v[l], 2); } } double[] y = new double[this.loopPoints.size()]; // All points are projected onto a points by multiplying every entry of point // with the corresponding // entry of v and divide by the w. // For every point the all entrys modified that way are than summed. // if the entry of v is Nan or the entry of the point the entry is ignored for (int r = 0; r < this.loopPoints.size(); r++) { for (int p = 0; p < this.loopPoints.get(r).length; p++) { if (!Double.isNaN(this.loopPoints.get(r)[p])) { if (!Double.isNaN(v[p]) && w != 0) { y[r] += (v[p] * this.loopPoints.get(r)[p]) / w; } else { throw new UnsupportedOperationException("We have not covered this case yet!"); } } } } // if the Anderson Darling test is failed the the center C_i is replaced by C`_1 // and S_i is replaced by the points of C`_1. k is raised by 1. // C_k is replaced by C`_2 and the points of C_k S_k are replaced by the one // from C`_2 S`_2 if the test is passed i is raised. if (!this.andersonDarlingTest(y)) { this.currentPoints.remove(positionOfCenter.get(i)); this.currentPoints.put(this.intermediateCenter.get(0), this.intermediatePoints.get(this.intermediateCenter.get(0))); positionOfCenter.replace(i, this.intermediateCenter.get(0)); k++; this.currentPoints.put(this.intermediateCenter.get(1), this.intermediatePoints.get(this.intermediateCenter.get(1))); positionOfCenter.put(k, this.intermediateCenter.get(1)); } else { i++; } } /* make datapoints for merge */ Map<double[], List<DoublePoint>> mapOfCurrentPoints = new HashMap<>(); for (Entry<double[], List<double[]>> currentPointMap : this.currentPoints.entrySet()) { mapOfCurrentPoints.put(currentPointMap.getKey(), currentPointMap.getValue().stream().map(DoublePoint::new).collect(Collectors.toList())); } this.mergeCluster(mapOfCurrentPoints); for (Entry<double[], List<double[]>> d : this.currentPoints.entrySet()) { List<double[]> pointsInCluster = d.getValue(); List<ProblemInstance<Instance>> instancesInCluster = new ArrayList<>(); for (double[] point : pointsInCluster) { instancesInCluster.add(this.pointToInstance.get(point)); } this.gmeansCluster.add(new Cluster(instancesInCluster, new GroupIdentifier<>(d.getKey()))); } return this.gmeansCluster; } public List<double[]> getIntermediateCenter() { return this.intermediateCenter; } public Map<double[], List<double[]>> getCurrentPoints() { return this.currentPoints; } public Map<double[], List<double[]>> getIntermediatePoints() { return this.intermediatePoints; } public List<double[]> getLoopPoints() { return this.loopPoints; } public Map<double[], ProblemInstance<Instance>> getPointToInstance() { return this.pointToInstance; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/ModifiedISACkMeans.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class ModifiedISACkMeans extends Kmeans<double[], Double> { private Map<double[], Integer> positionOfPointInList = new HashMap<>(); private Map<double[], List<double[]>> pointsInCenter = new HashMap<>(); private Map<double[], double[]> centerOfPoint = new HashMap<>(); private List<double[]> initpoints = new ArrayList<>(); public ModifiedISACkMeans(final List<double[]> toClusterPoints, final IDistanceMetric<Double, double[], double[]> dist) { super(toClusterPoints, dist); for (int i = 0; i < toClusterPoints.size(); i++) { this.positionOfPointInList.put(toClusterPoints.get(i), i); } this.initpoints = new ArrayList<>(toClusterPoints); } @Override public Map<double[], List<double[]>> kmeanscluster(final int k) { this.k = k; this.initializeKMeans(); boolean test = true; while (test) { this.relocateCenter(); test = this.relocatePoints(); } return this.pointsInCenter; } @Override public void initializeKMeans() { this.initializeFirstCenter(); this.initializeFollowingCenter(); this.locateFirstPoints(); } private void initializeFirstCenter() { double[] firstCenter = new double[this.points.get(0).length]; for (int i = 0; i < this.points.get(0).length; i++) { int totalvalue = this.points.size(); for (double[] d : this.points) { if (Double.isNaN(d[i])) { totalvalue--; } else { firstCenter[i] += d[i]; } } firstCenter[i] = firstCenter[i] / totalvalue; } this.center.add(firstCenter); this.pointsInCenter.put(firstCenter, new ArrayList<>()); } private void locateFirstPoints() { for (double[] point : this.points) { int indexOfMyCenter = 0; double maxCenterDist = this.metric.computeDistance(point, this.center.get(0)); for (int i = 1; i < this.center.size(); i++) { double tmp = this.metric.computeDistance(point, this.center.get(i)); if (tmp <= maxCenterDist) { indexOfMyCenter = i; maxCenterDist = tmp; } } this.centerOfPoint.put(point, this.center.get(indexOfMyCenter)); this.pointsInCenter.get(this.center.get(indexOfMyCenter)).add(point); } } private boolean relocatePoints() { boolean hasSomethingChanged = false; for (double[] c : this.center) { this.pointsInCenter.get(c).clear(); } for (double[] point : this.points) { double minDist = this.metric.computeDistance(point, this.center.get(0)); int indexOfMyCenter = 0; for (int i = 1; i < this.center.size(); i++) { double tmp = this.metric.computeDistance(point, this.center.get(i)); if (tmp < minDist) { indexOfMyCenter = i; minDist = tmp; } } if (!Arrays.equals(this.centerOfPoint.get(point), this.center.get(indexOfMyCenter))) { hasSomethingChanged = true; this.centerOfPoint.replace(point, this.center.get(indexOfMyCenter)); } this.pointsInCenter.get(this.center.get(indexOfMyCenter)).add(point); } return hasSomethingChanged; } private void relocateCenter() { for (int i = 0; i < this.center.size(); i++) { int size = this.center.get(i).length; double[] sumarray = new double[size]; double[] totalvalue = new double[size]; if (!this.pointsInCenter.get(this.center.get(i)).isEmpty()) { for (double[] d : this.pointsInCenter.get(this.center.get(i))) { for (int j = 0; j < d.length; j++) { if (!Double.isNaN(d[j])) { sumarray[j] += d[j]; totalvalue[j]++; } } } for (int l = 0; l < sumarray.length; l++) { if (Double.isNaN(sumarray[l])) { sumarray[l] = 0; } else { if (!(sumarray[l] == 0 || totalvalue[l] == 0)) { sumarray[l] = sumarray[l] / totalvalue[l]; } else { if (totalvalue[l] == 0) { sumarray[l] = Double.NaN; } } } } } List<double[]> myPoints = this.pointsInCenter.remove(this.center.get(i)); this.pointsInCenter.put(sumarray, myPoints); this.center.set(i, sumarray); } } private void initializeFollowingCenter() { for (int i = 1; i < this.k; i++) { double maxsum = 0; int indexOfnewCenter = 0; int indexofnewCenterinInit = 0; for (int j = 0; j < this.initpoints.size(); j++) { double tmp = 0; for (double[] c : this.center) { tmp += this.metric.computeDistance(this.initpoints.get(j), c); } if (tmp >= maxsum) { maxsum = tmp; indexOfnewCenter = this.positionOfPointInList.get(this.initpoints.get(j)); indexofnewCenterinInit = j; } } this.initpoints.remove(indexofnewCenterinInit); this.center.add(this.points.get(indexOfnewCenter)); this.pointsInCenter.put(this.points.get(indexOfnewCenter), new ArrayList<>()); } } public List<double[]> getCenter() { return this.center; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/ranking/label/learner/clusterbased/modifiedisac/Normalizer.java
package ai.libs.jaicore.ml.weka.ranking.label.learner.clusterbased.modifiedisac; import java.util.List; import ai.libs.jaicore.ml.ranking.label.learner.clusterbased.customdatatypes.ProblemInstance; import weka.core.Instance; public class Normalizer { private int numbervaluesToNormalize; private double[] maxvalues; private List<ProblemInstance<Instance>> basisForNormalization; /** * @param list */ public Normalizer(final List<ProblemInstance<Instance>> list) { this.numbervaluesToNormalize = list.get(0).getInstance().numAttributes(); this.maxvalues = new double[this.numbervaluesToNormalize]; this.basisForNormalization = list; } /** * */ public void setupnormalize() { for (ProblemInstance<Instance> i : this.basisForNormalization) { double[] instacnevector = i.getInstance().toDoubleArray(); for (int j = 0; j < instacnevector.length; j++) { if (Double.isNaN(instacnevector[j])) { if (Double.isNaN(this.maxvalues[j])) { this.maxvalues[j] = Double.NaN; } } else { if (Double.isNaN(this.maxvalues[j])) { this.maxvalues[j] = Math.abs(instacnevector[j]); } else { if (Math.abs(instacnevector[j]) > this.maxvalues[j]) { this.maxvalues[j] = Math.abs(instacnevector[j]); } } } } } } /** * @param vectorToNormalize * @return */ public double[] normalize(final double[] vectorToNormalize) { for (int i = 0; i < vectorToNormalize.length; i++) { if (Double.isNaN(this.maxvalues[i])) { if (Double.isNaN(vectorToNormalize[i])) { vectorToNormalize[i] = Double.NaN; } else { if(vectorToNormalize[i]<0) { vectorToNormalize[i]=-1; } else { vectorToNormalize[i]=1; } } } else { if(Double.isNaN(vectorToNormalize[i])) { vectorToNormalize[i] = Double.NaN; } if(Math.abs(vectorToNormalize[i])>this.maxvalues[i]) { if(vectorToNormalize[i]>=0) { vectorToNormalize[i]=1; } else { vectorToNormalize[i]=-1; } } if(vectorToNormalize[i]<0) { vectorToNormalize[i] = (((Math.abs(vectorToNormalize[i]) / this.maxvalues[i]) * 2) - 1)*(-1); } else { vectorToNormalize[i] = ((Math.abs(vectorToNormalize[i]) / this.maxvalues[i]) * 2) - 1; } } } return vectorToNormalize; } }
0
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/regression
java-sources/ai/libs/jaicore-ml-weka/0.2.7/ai/libs/jaicore/ml/weka/regression/learner/WekaRegressor.java
package ai.libs.jaicore.ml.weka.regression.learner; import java.util.List; import org.api4.java.ai.ml.core.dataset.supervised.ILabeledInstance; import org.api4.java.ai.ml.core.exception.PredictionException; import org.api4.java.ai.ml.regression.evaluation.IRegressionPrediction; import org.api4.java.ai.ml.regression.evaluation.IRegressionResultBatch; import ai.libs.jaicore.ml.regression.singlelabel.SingleTargetRegressionPrediction; import ai.libs.jaicore.ml.regression.singlelabel.SingleTargetRegressionPredictionBatch; import ai.libs.jaicore.ml.weka.classification.learner.AWekaLearner; import weka.classifiers.Classifier; public class WekaRegressor extends AWekaLearner<IRegressionPrediction, IRegressionResultBatch> { public WekaRegressor(final String name, final String... options) { super(name, options); } public WekaRegressor(final Classifier classifier) { super(classifier); } @Override protected IRegressionResultBatch getPredictionListAsBatch(final List<IRegressionPrediction> predictionList) { return new SingleTargetRegressionPredictionBatch(predictionList); } @Override public IRegressionPrediction predict(final ILabeledInstance xTest) throws PredictionException, InterruptedException { try { double reg = this.wrappedLearner.classifyInstance(this.getWekaInstance(xTest).getElement()); return new SingleTargetRegressionPrediction(reg); } catch (InterruptedException e) { throw e; } catch (Exception e) { throw new PredictionException("Could not make a prediction since an exception occurred in the wrapped weka classifier.", e); } } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips/forward/ISTRIPSPlanningGraphGeneratorDeriver.java
package ai.libs.jaicore.planning.classical.algorithms.strips.forward; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.planning.classical.problems.strips.StripsPlanningProblem; import ai.libs.jaicore.planning.core.Plan; import ai.libs.jaicore.search.model.other.SearchGraphPath; public interface ISTRIPSPlanningGraphGeneratorDeriver<N, A> extends AlgorithmicProblemReduction<StripsPlanningProblem, Plan, IGraphGenerator<N, A>, SearchGraphPath<N, A>> { }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips/forward/STRIPSForwardSearchReducer.java
package ai.libs.jaicore.planning.classical.algorithms.strips.forward; import java.util.Objects; import java.util.stream.Collectors; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import ai.libs.jaicore.planning.classical.problems.strips.StripsAction; import ai.libs.jaicore.planning.classical.problems.strips.StripsPlanningProblem; import ai.libs.jaicore.planning.core.Plan; import ai.libs.jaicore.search.model.other.SearchGraphPath; public class STRIPSForwardSearchReducer implements ISTRIPSPlanningGraphGeneratorDeriver<StripsForwardPlanningNode, String> { @Override public IGraphGenerator<StripsForwardPlanningNode, String> encodeProblem(final StripsPlanningProblem problem) { return new StripsForwardPlanningGraphGenerator(problem); } @Override public Plan decodeSolution(final SearchGraphPath<StripsForwardPlanningNode, String> solution) { return new Plan(solution.getNodes().stream().map(n -> (StripsAction)n.getActionToReachState()).filter(Objects::nonNull).collect(Collectors.toList())); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips/forward/STRIPSPlanner.java
package ai.libs.jaicore.planning.classical.algorithms.strips.forward; import java.util.Collection; import java.util.stream.Collectors; import org.api4.java.algorithm.IAlgorithmFactory; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.classical.problems.strips.Operation; import ai.libs.jaicore.planning.classical.problems.strips.StripsOperation; import ai.libs.jaicore.planning.classical.problems.strips.StripsPlanningProblem; import ai.libs.jaicore.planning.core.interfaces.IGraphSearchBasedPlan; import ai.libs.jaicore.planning.hierarchical.algorithms.GraphSearchBasedPlanningAlgorithm; import ai.libs.jaicore.search.model.other.SearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; public class STRIPSPlanner<V extends Comparable<V>> extends GraphSearchBasedPlanningAlgorithm<StripsPlanningProblem, IGraphSearchBasedPlan<StripsForwardPlanningNode, String>, GraphSearchInput<StripsForwardPlanningNode, String>, SearchGraphPath<StripsForwardPlanningNode, String>, StripsForwardPlanningNode, String> { public STRIPSPlanner(final StripsPlanningProblem problem, final AlgorithmicProblemReduction<StripsPlanningProblem, IGraphSearchBasedPlan<StripsForwardPlanningNode, String>, GraphSearchInput<StripsForwardPlanningNode, String>, SearchGraphPath<StripsForwardPlanningNode, String>> problemTransformer, final IAlgorithmFactory<GraphSearchInput<StripsForwardPlanningNode, String>, SearchGraphPath<StripsForwardPlanningNode, String>, ?> baseFactory) { super(problem, problemTransformer, baseFactory); } @Override public void runPreCreationHook() { StripsPlanningProblem problem = this.getInput(); /* conduct some consistency checks */ if (!problem.getInitState().getVariableParams().isEmpty()) { throw new IllegalArgumentException("The initial state contains variable parameters but must only contain constants!\nList of found variables: " + problem.getInitState().getVariableParams().stream().map(n -> "\n\t" + n.getName()).collect(Collectors.joining())); } if (!problem.getGoalState().getVariableParams().isEmpty()) { throw new IllegalArgumentException("The goal state contains variable parameters but must only contain constants!\nList of found variables: " + problem.getGoalState().getVariableParams().stream().map(n -> "\n\t" + n.getName()).collect(Collectors.joining())); } /* * check that every operation has only arguments in its preconditions, add lists * and delete lists, that are also explicitly defined in the param list */ for (Operation o : problem.getDomain().getOperations()) { StripsOperation so = (StripsOperation) o; Collection<VariableParam> undeclaredParamsInPrecondition = SetUtil.difference(so.getPrecondition().getVariableParams(), so.getParams()); if (!undeclaredParamsInPrecondition.isEmpty()) { throw new IllegalArgumentException("The precondition of operation " + so.getName() + " contains variables that are not defined in the parameter list: " + undeclaredParamsInPrecondition); } Collection<VariableParam> undeclaredParamsInAddList = SetUtil.difference(so.getAddList().getVariableParams(), so.getParams()); if (!undeclaredParamsInAddList.isEmpty()) { throw new IllegalArgumentException("The add list of operation " + so.getName() + " contains variables that are not defined in the parameter list: " + undeclaredParamsInAddList); } Collection<VariableParam> undeclaredParamsInDelList = SetUtil.difference(so.getDeleteList().getVariableParams(), so.getParams()); if (!undeclaredParamsInDelList.isEmpty()) { throw new IllegalArgumentException("The del list of operation " + so.getName() + " contains variables that are not defined in the parameter list: " + undeclaredParamsInDelList); } } /* logging problem */ if (this.getLogger().isInfoEnabled()) { // have explicit check here, because we have so many computations in the argument of the info call this.getLogger().info("Initializing planner for the following problem:\n\tOperations:{}\n\tInitial State: {}\n\tGoal State: {}", problem.getDomain().getOperations().stream() .map(o -> "\n\t - " + o.getName() + "\n\t\tParams: " + o.getParams() + "\n\t\tPre: " + o.getPrecondition() + "\n\t\tAdd: " + ((StripsOperation) o).getAddList() + "\n\t\tDel: " + ((StripsOperation) o).getDeleteList()) .collect(Collectors.joining()), problem.getInitState(), problem.getGoalState()); } } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips/forward/StripsForwardPlanningGraphGenerator.java
package ai.libs.jaicore.planning.classical.algorithms.strips.forward; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import org.api4.java.datastructure.graph.implicit.INewNodeDescription; import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator; import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.classical.problems.strips.StripsAction; import ai.libs.jaicore.planning.classical.problems.strips.StripsPlanningProblem; import ai.libs.jaicore.search.model.NodeExpansionDescription; public class StripsForwardPlanningGraphGenerator implements IGraphGenerator<StripsForwardPlanningNode, String> { private final StripsPlanningProblem problem; private static final Logger logger = LoggerFactory.getLogger(StripsForwardPlanningGraphGenerator.class); private final Monom initState; private final Set<StripsForwardPlanningNode> completelyExpandedNodes = new HashSet<>(); public StripsForwardPlanningGraphGenerator(final StripsPlanningProblem problem) { this.problem = problem; this.initState = problem.getInitState(); } @Override public ISingleRootGenerator<StripsForwardPlanningNode> getRootGenerator() { return () -> { StripsForwardPlanningNode root = new StripsForwardPlanningNode(new Monom(), new Monom(), null); return root; }; } private List<StripsAction> getApplicableActionsInNode(final StripsForwardPlanningNode node) throws InterruptedException { logger.info("Computing successors for node {}", node); long start = System.currentTimeMillis(); Monom state = node.getStateRelativeToInitState(this.initState); List<StripsAction> applicableActions = StripsUtil.getApplicableActionsInState(state, this.problem.getDomain()); logger.debug("Computation of applicable actions took {}ms", System.currentTimeMillis() - start); return applicableActions; } @Override public ISuccessorGenerator<StripsForwardPlanningNode, String> getSuccessorGenerator() { return new ISuccessorGenerator<StripsForwardPlanningNode, String>() { @Override public List<INewNodeDescription<StripsForwardPlanningNode, String>> generateSuccessors(final StripsForwardPlanningNode node) throws InterruptedException { if (StripsForwardPlanningGraphGenerator.this.completelyExpandedNodes.contains(node)) { throw new IllegalArgumentException("Successors of node " + node + " have already been computed."); } long start = System.currentTimeMillis(); List<INewNodeDescription<StripsForwardPlanningNode, String>> successors = new ArrayList<>(); List<StripsAction> applicableActions = StripsForwardPlanningGraphGenerator.this.getApplicableActionsInNode(node); for (StripsAction action : applicableActions) { long t = System.currentTimeMillis(); Monom del = new Monom(node.getDel()); Monom add = new Monom(node.getAdd()); del.addAll(action.getDeleteList()); add.removeAll(action.getDeleteList()); add.addAll(action.getAddList()); StripsForwardPlanningNode newNode = new StripsForwardPlanningNode(add, del, action); successors.add(new NodeExpansionDescription<>(newNode, "edge label")); if (logger.isTraceEnabled()) { logger.trace("Created the node expansion description within {}ms. New state size is {}.", System.currentTimeMillis() - t, newNode.getStateRelativeToInitState(StripsForwardPlanningGraphGenerator.this.initState).size()); } } logger.info("Generated {} successors in {}ms.", successors.size(), System.currentTimeMillis() - start); StripsForwardPlanningGraphGenerator.this.completelyExpandedNodes.add(node); return successors; } }; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips/forward/StripsForwardPlanningNode.java
package ai.libs.jaicore.planning.classical.algorithms.strips.forward; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.core.Action; /** * We only store the difference to the init state, i.e. what needs to be added or remove from the init state to get the state * * @author fmohr * */ public class StripsForwardPlanningNode { private final Monom add; private final Monom del; private final Action actionToReachState; public StripsForwardPlanningNode(final Monom add, final Monom del, final Action actionToReachState) { super(); if (add == null) { throw new IllegalArgumentException("Add list must not be NULL"); } if (del == null) { throw new IllegalArgumentException("Del list must not be NULL"); } this.add = add; this.del = del; this.actionToReachState = actionToReachState; } public Monom getAdd() { return this.add; } public Monom getDel() { return this.del; } public Monom getStateRelativeToInitState(final Monom initState) { Monom state = new Monom(initState); state.removeAll(this.del); state.addAll(this.add); return state; } public Action getActionToReachState() { return this.actionToReachState; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.add == null) ? 0 : this.add.hashCode()); result = prime * result + ((this.del == null) ? 0 : this.del.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } StripsForwardPlanningNode other = (StripsForwardPlanningNode) obj; if (this.add == null) { if (other.add != null) { return false; } } else if (!this.add.equals(other.add)) { return false; } if (this.del == null) { if (other.del != null) { return false; } } else if (!this.del.equals(other.del)) { return false; } return true; } @Override public String toString() { return "StripsForwardPlanningNode [addSize=" + this.add.size() + ", delSize=" + this.del.size() + ", actionToReachState=" + (this.actionToReachState != null ? this.actionToReachState.getEncoding() : null) + "]"; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips/forward/StripsNodeInfoGenerator.java
package ai.libs.jaicore.planning.classical.algorithms.strips.forward; import java.util.List; import java.util.stream.Collectors; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoGenerator; public class StripsNodeInfoGenerator<V extends Comparable<V>> implements NodeInfoGenerator<StripsForwardPlanningNode> { @Override public String generateInfoForNode(final StripsForwardPlanningNode node) { StringBuilder sb = new StringBuilder(); if (node.getActionToReachState() != null) { sb.append("<h2>Applied Action</h2>"); sb.append(node.getActionToReachState().getEncoding()); } sb.append("<h2>Current Add List</h2>"); List<String> addMonomStrings = node.getAdd().stream().sorted((l1, l2) -> l1.getPropertyName().compareTo(l2.getPropertyName())).map(l -> l.toString(false)).collect(Collectors.toList()); sb.append("<ul>"); for (String literal : addMonomStrings) { sb.append("<li>"); sb.append(literal); sb.append("</li>"); } sb.append("</ul>"); sb.append("<h2>Current Delete List</h2>"); List<String> delMonomStrings = node.getDel().stream().sorted((l1, l2) -> l1.getPropertyName().compareTo(l2.getPropertyName())).map(l -> l.toString(false)).collect(Collectors.toList()); sb.append("<ul>"); for (String literal : delMonomStrings) { sb.append("<li>"); sb.append(literal); sb.append("</li>"); } sb.append("</ul>"); return sb.toString(); } @Override public String getName() { return StripsNodeInfoGenerator.class.getName(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/algorithms/strips/forward/StripsUtil.java
package ai.libs.jaicore.planning.classical.algorithms.strips.forward; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Clause; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.logic.fol.util.ForwardChainer; import ai.libs.jaicore.logic.fol.util.ForwardChainingProblem; import ai.libs.jaicore.logic.fol.util.NextBindingFoundEvent; import ai.libs.jaicore.planning.classical.problems.ce.CEAction; import ai.libs.jaicore.planning.classical.problems.ce.CEOperation; import ai.libs.jaicore.planning.classical.problems.strips.Operation; import ai.libs.jaicore.planning.classical.problems.strips.StripsAction; import ai.libs.jaicore.planning.classical.problems.strips.StripsOperation; import ai.libs.jaicore.planning.classical.problems.strips.StripsPlanningDomain; import ai.libs.jaicore.planning.core.Action; import ai.libs.jaicore.planning.core.Plan; public class StripsUtil { private static final Logger logger = LoggerFactory.getLogger(StripsUtil.class); public static List<StripsAction> getApplicableActionsInState(final Monom state, final StripsPlanningDomain domain) throws InterruptedException { return getApplicableActionsInState(state, domain, false, -1); } public static List<StripsAction> getApplicableActionsInState(final Monom state, final StripsPlanningDomain domain, final boolean randomized, final int pLimit) throws InterruptedException { long start = System.currentTimeMillis(); int limit = pLimit; logger.debug("Computing applicable actions for state with {} items (activate TRACE for exact state)", state.size()); logger.trace("Exact state is {}", state); List<StripsAction> applicableDerivedActions = new ArrayList<>(); Collection<Operation> operations = domain.getOperations(); /* if the computation should be randomized, shuffle operations first */ if (randomized) { if (!(operations instanceof List)) { operations = new ArrayList<>(operations); } Collections.shuffle((List<Operation>) operations); } /* now walk over the operations and collect actions until the limit is reached */ long timeToOrderOps = System.currentTimeMillis() - start; for (Operation op : domain.getOperations()) { Collection<StripsAction> candidates = getPossibleOperationGroundingsForState(state, (StripsOperation) op, limit); applicableDerivedActions.addAll(candidates); if (limit >= 0) { limit = Math.max(0, limit - candidates.size()); } } long duration = System.currentTimeMillis() - start; logger.debug("Done. Computation of {} applicable actions took {}ms of which {}ms were used to order the operations", applicableDerivedActions.size(), duration, timeToOrderOps); return applicableDerivedActions; } public static Collection<StripsAction> getPossibleOperationGroundingsForState(final Monom state, final StripsOperation operation, final int limit) throws InterruptedException { Collection<StripsAction> applicableDerivedActions = new ArrayList<>(); /* decompose premise in positive and negative literals */ logger.debug("Compute all groundings of {}-premise that can be inferred from state with {} items (activate TRACE for exact premise and state)", operation.getPrecondition().size(), state.size()); logger.trace("Exact premise is {}", operation.getPrecondition()); logger.trace("Exact state is {}", state); long start = System.currentTimeMillis(); ForwardChainer fc = new ForwardChainer(new ForwardChainingProblem(state, operation.getPrecondition(), true)); long fcPreparationTime = System.currentTimeMillis() - start; NextBindingFoundEvent event; try { int i = 0; while ((event = fc.nextBinding()) != null && (limit < 0 || (i++ < limit))) { Map<VariableParam, LiteralParam> grounding = event.getGrounding(); /* refactor grounding to constants only and add the respective action */ Map<VariableParam, ConstantParam> rGrounding = new HashMap<>(); for (Entry<VariableParam, LiteralParam> groundingEntry : grounding.entrySet()) { ConstantParam cp = (ConstantParam) groundingEntry.getValue(); rGrounding.put(groundingEntry.getKey(), cp); } StripsAction a = new StripsAction(operation, rGrounding); applicableDerivedActions.add(a); logger.debug("Found action {} to be applicable after {}ms.", a.getEncoding(), System.currentTimeMillis() - start); } } catch (InterruptedException e) { throw e; } catch (Exception e) { logger.error("Error in grounding computation: {}", e); } logger.info("Determined {}/{} applicable actions within {}ms of which preparing the FC algorithm consumed {}ms.", applicableDerivedActions.size(), limit, System.currentTimeMillis() - start, fcPreparationTime); return applicableDerivedActions; } public static void updateState(final Monom state, final Action appliedAction) { /* apply effects of action (STRIPS) */ if (appliedAction.getOperation() instanceof StripsOperation) { Action a = new StripsAction((StripsOperation) appliedAction.getOperation(), appliedAction.getGrounding()); state.removeAll(((StripsAction) a).getDeleteList()); state.addAll(((StripsAction) a).getAddList()); } /* apply effects of action (ConditionalEffect operations) */ else if (appliedAction.getOperation() instanceof CEOperation) { CEAction a = new CEAction((CEOperation) appliedAction.getOperation(), appliedAction.getGrounding()); Map<CNFFormula, Monom> addLists = a.getAddLists(); /* determine literals to remove */ Map<CNFFormula, Monom> deleteLists = a.getDeleteLists(); Collection<Literal> toRemove = new ArrayList<>(); for (CNFFormula condition : deleteLists.keySet()) { if (condition.entailedBy(state)) { toRemove.addAll(deleteLists.get(condition)); } } /* determine literals to add */ Collection<Literal> toAdd = new ArrayList<>(); for (CNFFormula condition : addLists.keySet()) { /* evaluate interpreted predicates */ CNFFormula modifiedCondition = new CNFFormula(); boolean conditionIsSatisfiable = true; for (Clause c : condition) { Clause modifiedClause = new Clause(); boolean clauseContainsTrue = false; for (Literal l : c) { modifiedClause.add(l); /* if the clause is not empty, add it to the condition */ if (!clauseContainsTrue) { if (!modifiedClause.isEmpty()) { modifiedCondition.add(modifiedClause); } else { conditionIsSatisfiable = false; break; } } } } if (conditionIsSatisfiable && modifiedCondition.entailedBy(state)) { toAdd.addAll(addLists.get(condition)); } } /* now conduct update */ state.removeAll(toRemove); state.addAll(toAdd); } else { logger.error("No support for operations of class {}", appliedAction.getOperation().getClass()); } } public static Monom getStateAfterPlanExecution(final Monom initState, final Plan plan) { Monom state = new Monom(initState); plan.getActions().forEach(a -> updateState(state, a)); return state; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/ce/CEAction.java
package ai.libs.jaicore.planning.classical.problems.ce; import java.util.HashMap; import java.util.Map; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.core.Action; @SuppressWarnings("serial") public class CEAction extends Action { public CEAction(final CEOperation operation, final Map<VariableParam, ConstantParam> grounding) { super(operation, grounding); } public Map<CNFFormula, Monom> getAddLists() { Map<CNFFormula, Monom> addLists = new HashMap<>(); CEOperation operation = ((CEOperation)this.getOperation()); Map<VariableParam, ConstantParam> grounding = this.getGrounding(); for (CNFFormula key : operation.getAddLists().keySet()) { CNFFormula condition = new CNFFormula(key, grounding); if (!condition.isObviouslyContradictory()) { addLists.put(condition, new Monom(operation.getAddLists().get(key), grounding)); } } return addLists; } public Map<CNFFormula, Monom> getDeleteLists() { CEOperation operation = ((CEOperation)this.getOperation()); Map<VariableParam, ConstantParam> grounding = this.getGrounding(); Map<CNFFormula, Monom> deleteLists = new HashMap<>(); for (CNFFormula key : operation.getDeleteLists().keySet()) { CNFFormula condition = new CNFFormula(key, grounding); if (!condition.isObviouslyContradictory()) { deleteLists.put(condition, new Monom(operation.getDeleteLists().get(key), grounding)); } } return deleteLists; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/ce/CEOperation.java
package ai.libs.jaicore.planning.classical.problems.ce; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import ai.libs.jaicore.basic.StringUtil; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.classical.problems.strips.Operation; @SuppressWarnings("serial") public class CEOperation extends Operation { private final Map<CNFFormula, Monom> addLists; private final Map<CNFFormula, Monom> deleteLists; public CEOperation(final String name, final String params, final Monom precondition, final Map<CNFFormula, Monom> addLists, final Map<CNFFormula, Monom> deleteLists) { this(name, Arrays.asList(StringUtil.explode(params, ",")).stream().map(s -> new VariableParam(s.trim())).collect(Collectors.toList()), precondition, addLists, deleteLists); } public CEOperation(final String name, final List<VariableParam> params, final Monom precondition, final Map<CNFFormula, Monom> addLists, final Map<CNFFormula, Monom> deleteLists) { super(name, params, precondition); this.addLists = addLists; this.deleteLists = deleteLists; } public Map<CNFFormula, Monom> getAddLists() { return this.addLists; } public Map<CNFFormula, Monom> getDeleteLists() { return this.deleteLists; } @Override public int hashCode() { return new HashCodeBuilder().append(this.addLists).append(this.deleteLists).toHashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof CEOperation)) { return false; } CEOperation other = (CEOperation) obj; return new EqualsBuilder().append(other.addLists, this.addLists).append(other.deleteLists, this.deleteLists).isEquals(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/ce/CEPlanningDomain.java
package ai.libs.jaicore.planning.classical.problems.ce; import java.util.ArrayList; import java.util.Collection; import ai.libs.jaicore.planning.classical.problems.strips.Operation; import ai.libs.jaicore.planning.classical.problems.strips.PlanningDomain; public class CEPlanningDomain extends PlanningDomain { public CEPlanningDomain(Collection<CEOperation> operations) { super(new ArrayList<Operation>(operations)); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/ce/CEPlanningProblem.java
package ai.libs.jaicore.planning.classical.problems.ce; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.classical.problems.strips.PlanningProblem; public class CEPlanningProblem extends PlanningProblem { public CEPlanningProblem(CEPlanningDomain domain, Monom initState, Monom goalState) { super(domain, initState, goalState); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/ceoc/CEOCAction.java
package ai.libs.jaicore.planning.classical.problems.ceoc; import java.util.Map; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.classical.problems.ce.CEAction; @SuppressWarnings("serial") public class CEOCAction extends CEAction { public CEOCAction(CEOCOperation operation, Map<VariableParam, ConstantParam> grounding) { super(operation, grounding); } public CEOCOperation getOperation() { return (CEOCOperation)super.getOperation(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/ceoc/CEOCOperation.java
package ai.libs.jaicore.planning.classical.problems.ceoc; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import ai.libs.jaicore.basic.StringUtil; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.classical.problems.ce.CEOperation; @SuppressWarnings("serial") public class CEOCOperation extends CEOperation { private final List<VariableParam> outputs; public CEOCOperation(final String name, final String params, final Monom precondition, final Map<CNFFormula, Monom> addLists, final Map<CNFFormula, Monom> deleteLists, final String outputs) { super(name, params, precondition, addLists, deleteLists); this.outputs = Arrays.asList(StringUtil.explode(outputs, ",")).stream().map(s -> new VariableParam(s.trim())).collect(Collectors.toList()); Collection<VariableParam> allParams = new ArrayList<>(); allParams.addAll(this.getParams()); allParams.addAll(this.outputs); for (Entry<CNFFormula, Monom> entry : addLists.entrySet()) { Collection<VariableParam> missingParamsInPremise = SetUtil.difference(entry.getKey().getVariableParams(), allParams); if (!missingParamsInPremise.isEmpty()) { throw new IllegalArgumentException("Undeclared parameters in effect premise of operation " + name + ": " + missingParamsInPremise); } Collection<VariableParam> missingParamsInConclusion = SetUtil.difference(entry.getValue().getVariableParams(), allParams); if (!missingParamsInConclusion.isEmpty()) { throw new IllegalArgumentException("Undeclared parameters in effect conclusion of operation " + name + ": " + missingParamsInConclusion); } } } public CEOCOperation(final String name, final List<VariableParam> params, final Monom precondition, final Map<CNFFormula, Monom> addLists, final Map<CNFFormula, Monom> deleteLists, final List<VariableParam> outputs) { super(name, params, precondition, addLists, deleteLists); this.outputs = outputs; } public List<VariableParam> getOutputs() { return this.outputs; } @Override public int hashCode() { return new HashCodeBuilder().append(super.hashCode()).append(this.outputs).toHashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof CEOCOperation)) { return false; } CEOCOperation other = (CEOCOperation) obj; return new EqualsBuilder().append(other.outputs, this.outputs).isEquals(); } @Override public String toString() { return "CEOCOperation [name=" + this.getName() + ", params=" + this.getParams() + ", outputs=" + this.outputs + ", precondition=" + this.getPrecondition() + ", addlists=" + this.getAddLists() + ", dellists=" + this.getDeleteLists() + "]"; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/ceoc/CEOCPlanningDomain.java
package ai.libs.jaicore.planning.classical.problems.ceoc; import java.util.ArrayList; import java.util.Collection; import ai.libs.jaicore.planning.classical.problems.strips.Operation; import ai.libs.jaicore.planning.classical.problems.strips.PlanningDomain; public class CEOCPlanningDomain extends PlanningDomain { public CEOCPlanningDomain(Collection<CEOCOperation> operations) { super(new ArrayList<Operation>(operations)); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/ceoc/CEOCPlanningProblem.java
package ai.libs.jaicore.planning.classical.problems.ceoc; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.classical.problems.strips.PlanningProblem; public class CEOCPlanningProblem extends PlanningProblem { public CEOCPlanningProblem(CEOCPlanningDomain domain, Monom initState, Monom goalState) { super(domain, initState, goalState); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/strips/GoalStateFunction.java
package ai.libs.jaicore.planning.classical.problems.strips; import ai.libs.jaicore.logic.fol.structure.Monom; public interface GoalStateFunction { public boolean isGoalState(Monom state); }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/strips/Operation.java
package ai.libs.jaicore.planning.classical.problems.strips; import java.io.Serializable; import java.util.Collection; import java.util.List; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; public class Operation implements Serializable { /** * */ private static final long serialVersionUID = 1381223700100462982L; private final String name; private final Monom precondition; private final List<VariableParam> params; public Operation(final String name, final List<VariableParam> params, final Monom precondition) { super(); this.name = name; this.params = params; this.precondition = precondition; for (Literal l : precondition) { Collection<VariableParam> missingParams = SetUtil.difference(l.getVariableParams(), params); if (!missingParams.isEmpty()) { throw new IllegalArgumentException("Operation " + name + " has parameters in the precondition that are not defined in the param list: " + missingParams); } } } public String getName() { return this.name; } public Monom getPrecondition() { return this.precondition; } public List<VariableParam> getParams() { return this.params; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); result = prime * result + ((this.params == null) ? 0 : this.params.hashCode()); result = prime * result + ((this.precondition == null) ? 0 : this.precondition.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Operation other = (Operation) obj; if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } if (this.params == null) { if (other.params != null) { return false; } } else if (!this.params.equals(other.params)) { return false; } if (this.precondition == null) { if (other.precondition != null) { return false; } } else if (!this.precondition.equals(other.precondition)) { return false; } return true; } @Override public String toString() { return "Operation [name=" + this.name + ", precondition=" + this.precondition + ", params=" + this.params + "]"; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/strips/PlanningDomain.java
package ai.libs.jaicore.planning.classical.problems.strips; import java.util.Collection; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; public class PlanningDomain { private final Collection<Operation> operations; public PlanningDomain(final Collection<Operation> operations) { super(); this.operations = operations; } public Collection<Operation> getOperations() { return this.operations; } @Override public int hashCode() { return new HashCodeBuilder().append(this.operations).toHashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof PlanningDomain)) { return false; } PlanningDomain other = (PlanningDomain) obj; return new EqualsBuilder().append(other.operations, this.operations).isEquals(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/strips/PlanningProblem.java
package ai.libs.jaicore.planning.classical.problems.strips; import ai.libs.jaicore.logic.fol.structure.Monom; public class PlanningProblem { private final PlanningDomain domain; private final Monom initState; private final Monom goalState; private final GoalStateFunction goalStateFunction; public PlanningProblem(final PlanningDomain domain, final Monom initState, final Monom goalState) { this.domain = domain; this.initState = initState; this.goalState = goalState; this.goalStateFunction = s -> s.containsAll(goalState); } public PlanningProblem(final PlanningDomain domain, final Monom initState, final GoalStateFunction goalStateFunction) { super(); this.domain = domain; this.initState = initState; this.goalStateFunction = goalStateFunction; this.goalState = null; } public PlanningDomain getDomain() { return this.domain; } public Monom getInitState() { return this.initState; } public GoalStateFunction getGoalStateFunction() { return this.goalStateFunction; } public Monom getGoalState() { return this.goalState; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.domain == null) ? 0 : this.domain.hashCode()); result = prime * result + ((this.goalStateFunction == null) ? 0 : this.goalStateFunction.hashCode()); result = prime * result + ((this.initState == null) ? 0 : this.initState.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } PlanningProblem other = (PlanningProblem) obj; if (this.domain == null) { if (other.domain != null) { return false; } } else if (!this.domain.equals(other.domain)) { return false; } if (this.goalStateFunction == null) { if (other.goalStateFunction != null) { return false; } } else if (!this.goalStateFunction.equals(other.goalStateFunction)) { return false; } if (this.initState == null) { if (other.initState != null) { return false; } } else if (!this.initState.equals(other.initState)) { return false; } return true; } @Override public String toString() { return "PlanningProblem [domain=" + this.domain + ", initState=" + this.initState + ", goalStateFunction=" + this.goalStateFunction + "]"; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/strips/StandardProblemFactory.java
package ai.libs.jaicore.planning.classical.problems.strips; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; public class StandardProblemFactory { private StandardProblemFactory() { /* no instantiation desired */ } public static StripsPlanningProblem getBlocksWorldProblem() { /* create planning domain */ List<StripsOperation> operations = new ArrayList<>(); operations.add(new StripsOperation("pickup", Arrays.asList(new VariableParam("x")), new Monom("clear(x) & ontable(x) & handempty()"), new Monom("holding(x) "), new Monom("clear(x) & ontable(x) & handempty()"))); operations.add(new StripsOperation("putdown", Arrays.asList(new VariableParam("x")), new Monom("holding(x)"), new Monom("clear(x) & handempty() & ontable(x)"), new Monom("holding(x)"))); operations.add(new StripsOperation("stack", Arrays.asList(new VariableParam("x"), new VariableParam("y")), new Monom("holding(x) & clear(y)"), new Monom("clear(x) & handempty() & on(x,y)"), new Monom("holding(x) & clear(y)"))); operations.add(new StripsOperation("unstack", Arrays.asList(new VariableParam("x"), new VariableParam("y")), new Monom("handempty() & clear(x) & on(x,y)"), new Monom("clear(y) & holding(x)"), new Monom("handempty() & on(x,y) & clear(x)"))); StripsPlanningDomain domain = new StripsPlanningDomain(operations); /* create planning problem */ Monom init = new Monom("clear('c') & clear('a') & clear('b') & clear('d') & ontable('c') & ontable('a') & ontable('b') & ontable('d') & handempty()"); Monom goal = new Monom("on('d','c') & on('c','b') & on('b','a')"); return new StripsPlanningProblem(domain, init, goal); } public static StripsPlanningProblem getDockworkerProblem() { /* create planning domain */ List<StripsOperation> operations = new ArrayList<>(); operations.add(new StripsOperation("move", Arrays.asList(new VariableParam("l"), new VariableParam("m"), new VariableParam("r")), new Monom("adjacent(l,m) & at(r,l) & !occupied(m)"), new Monom("at(r,m) & occupied(m)"), new Monom("at(r,l) & occupied(l)"))); operations.add( new StripsOperation("load", Arrays.asList(new VariableParam("l"), new VariableParam("k"), new VariableParam("r"), new VariableParam("c")), new Monom("belong(k,l) & holding(k,c) & at(r,l) & unloaded(r)"), new Monom("empty(k) & loaded(r,c)"), new Monom("holding(k,c) & unloaded(r)"))); operations.add( new StripsOperation("unload", Arrays.asList(new VariableParam("l"), new VariableParam("k"), new VariableParam("r"), new VariableParam("c")), new Monom("belong(k,l) & empty(k) & at(r,l) & loaded(r,c)"), new Monom("holding(k,c) & unloaded(r)"), new Monom("empty(k) & loaded(r,c)"))); operations.add(new StripsOperation("put", Arrays.asList(new VariableParam("k"), new VariableParam("l"), new VariableParam("c"), new VariableParam("d"), new VariableParam("p")), new Monom("belong(k,l) & attached(p,l) & holding(k,c) & top(d,p)"), new Monom("empty(k) & in(c,p) & top(c,p) & on(c,d)"), new Monom("holding(k,c) & top(d,p)"))); operations.add(new StripsOperation("take", Arrays.asList(new VariableParam("k"), new VariableParam("l"), new VariableParam("c"), new VariableParam("d"), new VariableParam("p")), new Monom("belong(k,l) & attached(p,l) & empty(k) & on(c,d) & top(c,p)"), new Monom("holding(k,c) & top(d,p)"), new Monom("empty(k) & in(c,p) & top(c,p) & on(c,d)"))); StripsPlanningDomain domain = new StripsPlanningDomain(operations); /* create planning problem */ Monom init = new Monom( "attached('p1','l1') & attached('p2','l2') & in('c1','p1') & in('c3','p1') & top('c3','p1') & on('c3','c1') & on('c1','pallet') & in('c2','p2') & top('c2','p2') & on('c2','pallet') & belong('crane1','l1') & empty('crane1') & adjacent('l1','l2') & adjacent('l2','l1') & at('r1','l2') & occupied('l2') & unloaded('r1')"); Monom goal = new Monom("loaded('r1','c3') & at('r1','l1')"); return new StripsPlanningProblem(domain, init, goal); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/strips/StripsAction.java
package ai.libs.jaicore.planning.classical.problems.strips; import java.util.Map; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.core.Action; @SuppressWarnings("serial") public class StripsAction extends Action { private final Monom addList; private final Monom deleteList; public StripsAction(final StripsOperation operation, final Map<VariableParam, ConstantParam> grounding) { super(operation, grounding); this.addList = new Monom(operation.getAddList(), grounding); this.deleteList = new Monom(operation.getDeleteList(), grounding); } public Monom getAddList() { return this.addList; } public Monom getDeleteList() { return this.deleteList; } @Override public int hashCode() { return new HashCodeBuilder().append(this.getOperation()).append(this.getGrounding()).append(this.addList).append(this.deleteList).toHashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof StripsAction)) { return false; } StripsAction other = (StripsAction) obj; return new EqualsBuilder().append(other.addList, this.addList).append(other.deleteList, this.deleteList).isEquals(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/strips/StripsOperation.java
package ai.libs.jaicore.planning.classical.problems.strips; import java.util.List; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; @SuppressWarnings("serial") public class StripsOperation extends Operation { private final Monom addList; private final Monom deleteList; public StripsOperation(final String name, final List<VariableParam> params, final Monom precondition, final Monom addList, final Monom deleteList) { super(name, params, precondition); this.addList = addList; this.deleteList = deleteList; } public Monom getAddList() { return this.addList; } public Monom getDeleteList() { return this.deleteList; } @Override public String toString() { return "StripsOperation [precondition=" + this.getPrecondition() + ", addList=" + this.addList + ", deleteList=" + this.deleteList + "]"; } @Override public int hashCode() { return new HashCodeBuilder().append(super.hashCode()).append(this.addList).append(this.deleteList).toHashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof StripsOperation)) { return false; } StripsOperation other = (StripsOperation) obj; return new EqualsBuilder().append(other.addList, this.addList).append(other.deleteList, this.deleteList).isEquals(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/strips/StripsPlanningDomain.java
package ai.libs.jaicore.planning.classical.problems.strips; import java.util.ArrayList; import java.util.Collection; public class StripsPlanningDomain extends PlanningDomain { public StripsPlanningDomain(Collection<StripsOperation> operations) { super(new ArrayList<Operation>(operations)); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/classical/problems/strips/StripsPlanningProblem.java
package ai.libs.jaicore.planning.classical.problems.strips; import ai.libs.jaicore.logic.fol.structure.Monom; public class StripsPlanningProblem extends PlanningProblem { public StripsPlanningProblem(final StripsPlanningProblem problem) { this(problem.getDomain(), problem.getInitState(), problem.getGoalStateFunction()); } public StripsPlanningProblem(final StripsPlanningDomain domain, final Monom initState, final Monom goalState) { super(domain, initState, goalState); } public StripsPlanningProblem(final StripsPlanningDomain domain, final Monom initState, final GoalStateFunction goalChecker) { super(domain, initState, goalChecker); } @Override public StripsPlanningDomain getDomain() { return (StripsPlanningDomain) super.getDomain(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/Action.java
package ai.libs.jaicore.planning.core; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import ai.libs.jaicore.logging.ToJSONStringUtil; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.classical.problems.strips.Operation; public class Action implements Serializable { /** * */ private static final long serialVersionUID = -2685277085885131650L; private final Operation operation; private final Map<VariableParam, ConstantParam> grounding; public Action(final Operation operation, final Map<VariableParam, ConstantParam> grounding) { super(); this.operation = operation; this.grounding = grounding; if (!this.grounding.keySet().containsAll(operation.getParams())) { throw new IllegalArgumentException("Planning actions must contain a grounding for ALL params of the operation " + operation.getName() + ". Here, op params: " + operation.getParams() + ". Given grounding: " + grounding); } } public List<ConstantParam> getParameters() { return this.operation.getParams().stream().map(p -> this.grounding.get(p)).collect(Collectors.toList()); } public Map<VariableParam, ConstantParam> getGrounding() { return this.grounding; } public Operation getOperation() { return this.operation; } public Monom getPrecondition() { return new Monom(this.operation.getPrecondition(), this.grounding); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.grounding == null) ? 0 : this.grounding.hashCode()); result = prime * result + ((this.operation == null) ? 0 : this.operation.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Action other = (Action) obj; if (this.grounding == null) { if (other.grounding != null) { return false; } } else if (!this.grounding.equals(other.grounding)) { return false; } if (this.operation == null) { if (other.operation != null) { return false; } } else if (!this.operation.equals(other.operation)) { return false; } return true; } public String getEncoding() { StringBuilder b = new StringBuilder(); b.append(this.operation.getName()); b.append("("); List<VariableParam> params = this.operation.getParams(); int size = params.size(); for (int i = 0; i < params.size(); i++) { b.append(this.grounding.get(params.get(i))); if (i < size - 1) { b.append(", "); } } b.append(")"); return b.toString(); } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("operation", this.operation); fields.put("grounding", this.grounding); return ToJSONStringUtil.toJSONString(fields); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/EvaluatedPlan.java
package ai.libs.jaicore.planning.core; import java.util.List; import ai.libs.jaicore.planning.core.interfaces.IEvaluatedPlan; import ai.libs.jaicore.planning.core.interfaces.IPlan; public class EvaluatedPlan<V extends Comparable<V>> extends Plan implements IEvaluatedPlan<V> { private final V score; public EvaluatedPlan(final IPlan plan, final V score) { this (plan.getActions(), score); } public EvaluatedPlan(final List<Action> plan, final V score) { super(plan); this.score = score; } @Override public V getScore() { return this.score; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/EvaluatedSearchGraphBasedPlan.java
package ai.libs.jaicore.planning.core; import java.util.List; import ai.libs.jaicore.planning.core.interfaces.IEvaluatedGraphSearchBasedPlan; import ai.libs.jaicore.planning.core.interfaces.IEvaluatedPlan; import ai.libs.jaicore.planning.core.interfaces.IPlan; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.model.other.SearchGraphPath; public class EvaluatedSearchGraphBasedPlan<N, A, V extends Comparable<V>> extends EvaluatedPlan<V> implements IEvaluatedGraphSearchBasedPlan<N, A, V> { private final SearchGraphPath<N, A> searchGraphPath; public EvaluatedSearchGraphBasedPlan(final IPlan plan, final EvaluatedSearchGraphPath<N, A, V> searchGraphPath) { this(plan, searchGraphPath.getScore(), searchGraphPath); } public EvaluatedSearchGraphBasedPlan(final IPlan plan, final V score, final SearchGraphPath<N, A> searchGraphPath) { super(plan, score); this.searchGraphPath = searchGraphPath; } public EvaluatedSearchGraphBasedPlan(final IEvaluatedPlan<V> plan, final SearchGraphPath<N, A> searchGraphPath) { super(plan, plan.getScore()); this.searchGraphPath = searchGraphPath; } public EvaluatedSearchGraphBasedPlan(final List<Action> plan, final V score, final SearchGraphPath<N, A> searchGraphPath) { super(plan, score); this.searchGraphPath = searchGraphPath; } @Override public SearchGraphPath<N, A> getSearchGraphPath() { return this.searchGraphPath; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/Plan.java
package ai.libs.jaicore.planning.core; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.classical.algorithms.strips.forward.StripsUtil; import ai.libs.jaicore.planning.core.interfaces.IPlan; public class Plan implements IPlan { private final List<Action> actions; private final Map<String,Object> annotations; public Plan(final List<Action> actions) { this(actions, new HashMap<>()); } public Plan(final List<Action> actions, final Map<String, Object> annotations) { super(); this.actions = actions; this.annotations = annotations; } @Override public List<Action> getActions() { return this.actions; } public void setAnnotation(final String key, final Object value) { this.annotations.put(key, value); } public void setAnnotation(final Map<String, Object> annotations) { annotations.putAll(annotations); } public Map<String, Object> getAnnotations() { return this.annotations; } public Monom getStateAfterApplicationGivenInitState(final Monom initState) { Monom newState = new Monom(initState); for (Action action : this.actions) { StripsUtil.updateState(newState, action); } return newState; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.actions == null) ? 0 : this.actions.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Plan other = (Plan) obj; if (this.actions == null) { if (other.actions != null) { return false; } } else if (!this.actions.equals(other.actions)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/SearchGraphBasedPlan.java
package ai.libs.jaicore.planning.core; import ai.libs.jaicore.search.model.other.SearchGraphPath; public class SearchGraphBasedPlan<N, A> extends Plan { private final SearchGraphPath<N, A> searchGraphPath; public SearchGraphBasedPlan(final Plan plan, final SearchGraphPath<N, A> searchGraphPath) { super(plan.getActions()); this.searchGraphPath = searchGraphPath; } public SearchGraphPath<N, A> getSearchGraphPath() { return this.searchGraphPath; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.searchGraphPath == null) ? 0 : this.searchGraphPath.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } SearchGraphBasedPlan other = (SearchGraphBasedPlan) obj; if (this.searchGraphPath == null) { if (other.searchGraphPath != null) { return false; } } else if (!this.searchGraphPath.equals(other.searchGraphPath)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/events/PlanFoundEvent.java
package ai.libs.jaicore.planning.core.events; import org.api4.java.algorithm.IAlgorithm; import org.api4.java.algorithm.events.result.IScoredSolutionCandidateFoundEvent; import ai.libs.jaicore.basic.algorithm.ASolutionCandidateFoundEvent; import ai.libs.jaicore.planning.core.EvaluatedPlan; public class PlanFoundEvent<V extends Comparable<V>> extends ASolutionCandidateFoundEvent<EvaluatedPlan<V>> implements IScoredSolutionCandidateFoundEvent<EvaluatedPlan<V>, V> { public PlanFoundEvent(final IAlgorithm<?, ?> algorithm, final EvaluatedPlan<V> solutionCandidate) { super(algorithm, solutionCandidate); } @Override public V getScore() { return this.getSolutionCandidate().getScore(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/interfaces/IEvaluatedGraphSearchBasedPlan.java
package ai.libs.jaicore.planning.core.interfaces; public interface IEvaluatedGraphSearchBasedPlan<N, A, V extends Comparable<V>> extends IEvaluatedPlan<V>, IGraphSearchBasedPlan<N, A> { }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/interfaces/IEvaluatedPlan.java
package ai.libs.jaicore.planning.core.interfaces; import org.api4.java.common.attributedobjects.ScoredItem; public interface IEvaluatedPlan<V extends Comparable<V>> extends IPlan, ScoredItem<V> { }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/interfaces/IGraphSearchBasedPlan.java
package ai.libs.jaicore.planning.core.interfaces; import ai.libs.jaicore.search.model.other.SearchGraphPath; public interface IGraphSearchBasedPlan<N, A> extends IPlan { public SearchGraphPath<N, A> getSearchGraphPath(); }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/interfaces/IPlan.java
package ai.libs.jaicore.planning.core.interfaces; import java.util.List; import ai.libs.jaicore.planning.core.Action; public interface IPlan { public List<Action> getActions(); }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/core/interfaces/SolutionPathConverter.java
package ai.libs.jaicore.planning.core.interfaces; import java.util.List; import ai.libs.jaicore.planning.core.Action; public interface SolutionPathConverter<T> { public T convertPathToSolution(List<Action> path); }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/CostSensitiveGraphSearchBasedHTNPlanningAlgorithm.java
package ai.libs.jaicore.planning.hierarchical.algorithms; import org.api4.java.algorithm.IAlgorithmFactory; import org.slf4j.Logger; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.planning.classical.problems.strips.Operation; import ai.libs.jaicore.planning.core.interfaces.IEvaluatedGraphSearchBasedPlan; import ai.libs.jaicore.planning.hierarchical.problems.htn.IHTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.stn.Method; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; /** * * @author fmohr * * @param <P> * class of the HTN planning problem * @param <S> * class of the graph search problem input to which the HTN problem is reduced * @param <N> * class of the nodes in the search problem * @param <A> * class of the edges in the search problem * @param <V> * evaluation of solutions */ public class CostSensitiveGraphSearchBasedHTNPlanningAlgorithm<P extends IHTNPlanningProblem, S extends GraphSearchInput<N, A>, N, A, V extends Comparable<V>> extends CostSensitiveGraphSearchBasedPlanningAlgorithm<P, S, N, A, V> { public CostSensitiveGraphSearchBasedHTNPlanningAlgorithm(final P problem, final AlgorithmicProblemReduction<P, IEvaluatedGraphSearchBasedPlan<N, A, V>, S, EvaluatedSearchGraphPath<N, A, V>> problemTransformer, final IAlgorithmFactory<S, EvaluatedSearchGraphPath<N, A, V>, ?> baseFactory) { super(problem, problemTransformer, baseFactory); } @Override public void runPreCreationHook() { super.runPreCreationHook(); Logger logger = this.getLogger(); logger.info("Starting HTN planning process."); if (logger.isDebugEnabled()) { StringBuilder opSB = new StringBuilder(); for (Operation op : this.getInput().getDomain().getOperations()) { opSB.append("\n\t\t"); opSB.append(op); } StringBuilder methodSB = new StringBuilder(); for (Method method : this.getInput().getDomain().getMethods()) { methodSB.append("\n\t\t"); methodSB.append(method); } logger.debug("The HTN problem is defined as follows:\n\tOperations:{}\n\tMethods:{}", opSB, methodSB); } } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/CostSensitiveGraphSearchBasedPlanningAlgorithm.java
package ai.libs.jaicore.planning.hierarchical.algorithms; import org.api4.java.algorithm.IAlgorithmFactory; import org.api4.java.algorithm.IOptimizationAlgorithm; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.planning.core.interfaces.IEvaluatedGraphSearchBasedPlan; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; /** * * @author fmohr * * @param <I1> Class of the planning problem * @param <I2> Class of the search problem * @param <N> node type in search problem * @param <A> edge type in search problem * @param <V> cost associated with plans (and paths) */ public class CostSensitiveGraphSearchBasedPlanningAlgorithm<I1, I2 extends GraphSearchInput<N, A>, N, A, V extends Comparable<V>> extends GraphSearchBasedPlanningAlgorithm<I1, IEvaluatedGraphSearchBasedPlan<N, A, V>, I2, EvaluatedSearchGraphPath<N, A, V>, N, A> implements IOptimizationAlgorithm<I1, IEvaluatedGraphSearchBasedPlan<N, A, V>, V> { public CostSensitiveGraphSearchBasedPlanningAlgorithm(final I1 problem, final AlgorithmicProblemReduction<I1, IEvaluatedGraphSearchBasedPlan<N, A, V>, I2, EvaluatedSearchGraphPath<N, A, V>> problemTransformer, final IAlgorithmFactory<I2, EvaluatedSearchGraphPath<N, A, V>, ?> baseFactory) { super(problem, problemTransformer, baseFactory); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/GraphSearchBasedPlanningAlgorithm.java
package ai.libs.jaicore.planning.hierarchical.algorithms; import org.api4.java.algorithm.IAlgorithm; import org.api4.java.algorithm.IAlgorithmFactory; import org.api4.java.common.event.IRelaxedEventEmitter; import com.google.common.eventbus.Subscribe; import ai.libs.jaicore.basic.algorithm.reduction.AReducingSolutionIterator; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.graphvisualizer.events.graph.GraphEvent; import ai.libs.jaicore.planning.core.interfaces.IGraphSearchBasedPlan; import ai.libs.jaicore.search.model.other.SearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; /** * * @author fmohr * * @param <I1> Class of the planning problem * @param <O1> Class of the planning problem solutions (plans) * @param <I2> Class of the search problem * @param <O2> Class of the search problem solutions (paths) * @param <N> node type in search problem * @param <A> edge type in search problem */ public class GraphSearchBasedPlanningAlgorithm<I1, O1 extends IGraphSearchBasedPlan<N, A>, I2 extends GraphSearchInput<N, A>, O2 extends SearchGraphPath<N, A>, N, A> extends AReducingSolutionIterator<I1, O1, I2, O2> { public GraphSearchBasedPlanningAlgorithm(final I1 problem, final AlgorithmicProblemReduction<I1, O1, I2, O2> problemTransformer, final IAlgorithmFactory<I2, O2, ?> baseFactory) { super(problem, problemTransformer, baseFactory); } @Override public void runPreCreationHook() { IAlgorithm<I2, O2> algo = this.getBaseAlgorithm(); if (algo instanceof IRelaxedEventEmitter) { algo.registerListener(new Object() { @Subscribe public void receiveEvent(final GraphEvent e) { GraphSearchBasedPlanningAlgorithm.this.post(e); } }); } } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/AForwardDecompositionReducer.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition; import java.util.stream.Collectors; import org.api4.java.datastructure.graph.ILabeledPath; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import ai.libs.jaicore.planning.core.Plan; import ai.libs.jaicore.planning.core.interfaces.IPlan; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.ceociptfd.CEOCIPTFDGraphGenerator; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.ceoctfd.CEOCTFDGraphGenerator; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDGraphGenerator; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDNode; import ai.libs.jaicore.planning.hierarchical.problems.ceocipstn.CEOCIPSTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.ceocstn.CEOCSTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.htn.IHTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.htn.IHierarchicalPlanningToGraphSearchReduction; import ai.libs.jaicore.planning.hierarchical.problems.stn.STNPlanningProblem; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; public abstract class AForwardDecompositionReducer<I1 extends IHTNPlanningProblem, O1 extends IPlan, I2 extends GraphSearchInput<TFDNode, String>, O2 extends ILabeledPath<TFDNode, String>> implements IHierarchicalPlanningToGraphSearchReduction<TFDNode, String, I1, O1, I2, O2> { public GraphSearchInput<TFDNode, String> getGraphSearchInput(final I1 planningProblem) { IGraphGenerator<TFDNode, String> graphGenerator; if (planningProblem instanceof CEOCIPSTNPlanningProblem) { graphGenerator = new CEOCIPTFDGraphGenerator((CEOCIPSTNPlanningProblem) planningProblem); } else if (planningProblem instanceof CEOCSTNPlanningProblem) { graphGenerator = new CEOCTFDGraphGenerator((CEOCSTNPlanningProblem) planningProblem); } else if (planningProblem.getClass().equals(STNPlanningProblem.class)) { graphGenerator = new TFDGraphGenerator(planningProblem); } else { throw new IllegalArgumentException("HTN problems of class \"" + planningProblem.getClass().getName() + "\" are currently not supported."); } return new GraphSearchInput<>(graphGenerator, l -> l.getHead().getRemainingTasks().isEmpty()); } public Plan getPlanForSolution(final ILabeledPath<TFDNode, String> solution) { return new Plan(solution.getNodes().stream().filter(n -> n.getAppliedAction() != null).map(TFDNode::getAppliedAction).collect(Collectors.toList())); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/BestFirstForwardDecompositionReducer.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import ai.libs.jaicore.planning.core.EvaluatedSearchGraphBasedPlan; import ai.libs.jaicore.planning.core.interfaces.IEvaluatedGraphSearchBasedPlan; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDNode; import ai.libs.jaicore.planning.hierarchical.problems.htn.CostSensitiveHTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.htn.IHTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.htn.PlanEvaluationBasedSearchEvaluator; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchWithPathEvaluationsInput; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; import ai.libs.jaicore.search.problemtransformers.GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformer; import ai.libs.jaicore.search.problemtransformers.GraphSearchProblemInputToGraphSearchWithSubpathEvaluationViaUninformedness; public class BestFirstForwardDecompositionReducer<V extends Comparable<V>> extends AForwardDecompositionReducer<CostSensitiveHTNPlanningProblem<? extends IHTNPlanningProblem, V>, IEvaluatedGraphSearchBasedPlan<TFDNode, String, V>, GraphSearchWithSubpathEvaluationsInput<TFDNode, String, V>, EvaluatedSearchGraphPath<TFDNode, String, V>> { private final SimpleForwardDecompositionReducer planProblemToGraphSearchReducer = new SimpleForwardDecompositionReducer(); // this reduces only to graph search with (solution) path evaluations but not sub-path evaluations private GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformer<TFDNode, String, V> toSubPathEvaluationTransformer; // conducts the transformation inside graph search public BestFirstForwardDecompositionReducer() { this(new GraphSearchProblemInputToGraphSearchWithSubpathEvaluationViaUninformedness()); // this assumes that the type is double } public BestFirstForwardDecompositionReducer(final GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformer<TFDNode, String, V> transformer) { super(); this.toSubPathEvaluationTransformer = transformer; } public BestFirstForwardDecompositionReducer(final IPathEvaluator<TFDNode, String, V> nodeEvaluator) { this(); this.toSubPathEvaluationTransformer.setNodeEvaluator(nodeEvaluator); } @Override public GraphSearchWithSubpathEvaluationsInput<TFDNode, String, V> encodeProblem(final CostSensitiveHTNPlanningProblem<? extends IHTNPlanningProblem, V> problem) { /* first derive a problem with path evaluations */ IPathSearchInput<TFDNode, String> ordinarySearchProblem = this.planProblemToGraphSearchReducer.encodeProblem(problem.getCorePlanningProblem()); IPathEvaluator<TFDNode, String, V> pathEvaluator = new PlanEvaluationBasedSearchEvaluator<>(problem.getPlanEvaluator(), this.planProblemToGraphSearchReducer); IPathSearchWithPathEvaluationsInput<TFDNode, String, V> searchProblem = new GraphSearchWithPathEvaluationsInput<>(ordinarySearchProblem, pathEvaluator); /* now reduce the search problem to one with sub-path evaluation */ return this.toSubPathEvaluationTransformer.encodeProblem(searchProblem); } @Override public EvaluatedSearchGraphBasedPlan<TFDNode, String, V> decodeSolution(final EvaluatedSearchGraphPath<TFDNode, String, V> solution) { return new EvaluatedSearchGraphBasedPlan<>(this.getPlanForSolution(solution), solution); } public GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformer<TFDNode, String, V> getTransformer() { return this.toSubPathEvaluationTransformer; } public void setTransformer(final GraphSearchProblemInputToGraphSearchWithSubpathEvaluationInputTransformer<TFDNode, String, V> transformer) { this.toSubPathEvaluationTransformer = transformer; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/BlindForwardDecompositionHTNPlanner.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDNode; import ai.libs.jaicore.planning.hierarchical.problems.htn.CostSensitiveHTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.htn.IHTNPlanningProblem; import ai.libs.jaicore.search.algorithms.standard.bestfirst.BestFirstFactory; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; public class BlindForwardDecompositionHTNPlanner<V extends Comparable<V>> extends ForwardDecompositionHTNPlanner<CostSensitiveHTNPlanningProblem<? extends IHTNPlanningProblem, V>, V, GraphSearchWithSubpathEvaluationsInput<TFDNode, String, V>> { public BlindForwardDecompositionHTNPlanner(final CostSensitiveHTNPlanningProblem<? extends IHTNPlanningProblem, V> problem, final IPathEvaluator<TFDNode, String, V> nodeEvaluator) { super(problem, new BestFirstForwardDecompositionReducer<V>(), new BestFirstFactory<>()); BestFirstForwardDecompositionReducer<V> reducer = (BestFirstForwardDecompositionReducer<V>)this.getProblemTransformer(); reducer.getTransformer().setNodeEvaluator(nodeEvaluator); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/ForwardDecompositionHTNPlanner.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition; import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearchFactory; import ai.libs.jaicore.planning.core.interfaces.IEvaluatedGraphSearchBasedPlan; import ai.libs.jaicore.planning.hierarchical.algorithms.CostSensitiveGraphSearchBasedHTNPlanningAlgorithm; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDNode; import ai.libs.jaicore.planning.hierarchical.problems.htn.IHTNPlanningProblem; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; /** * @author fmohr * */ public class ForwardDecompositionHTNPlanner<P extends IHTNPlanningProblem, V extends Comparable<V>, S extends GraphSearchInput<TFDNode, String>> extends CostSensitiveGraphSearchBasedHTNPlanningAlgorithm<P, S, TFDNode, String, V> { public ForwardDecompositionHTNPlanner(final P problem, final AForwardDecompositionReducer<P, IEvaluatedGraphSearchBasedPlan<TFDNode, String, V>, S, EvaluatedSearchGraphPath<TFDNode, String, V>> reducer, final IOptimalPathInORGraphSearchFactory<S, EvaluatedSearchGraphPath<TFDNode, String, V>, TFDNode, String, V, ?> searchFactory) { super(problem, reducer, searchFactory); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/ForwardDecompositionHTNPlannerBasedOnBestFirst.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDNode; import ai.libs.jaicore.planning.hierarchical.problems.htn.CostSensitiveHTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.htn.IHTNPlanningProblem; import ai.libs.jaicore.search.algorithms.standard.bestfirst.BestFirstFactory; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; public class ForwardDecompositionHTNPlannerBasedOnBestFirst<V extends Comparable<V>> extends ForwardDecompositionHTNPlanner<CostSensitiveHTNPlanningProblem<? extends IHTNPlanningProblem, V>, V, GraphSearchWithSubpathEvaluationsInput<TFDNode, String, V>> { public ForwardDecompositionHTNPlannerBasedOnBestFirst(final CostSensitiveHTNPlanningProblem<? extends IHTNPlanningProblem, V> problem, final IPathEvaluator<TFDNode, String, V> nodeEvaluator) { super(problem, new BestFirstForwardDecompositionReducer<>(nodeEvaluator), new BestFirstFactory<>()); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/SimpleForwardDecompositionReducer.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.planning.core.Plan; import ai.libs.jaicore.planning.core.interfaces.IPlan; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDNode; import ai.libs.jaicore.planning.hierarchical.problems.htn.IHTNPlanningProblem; import ai.libs.jaicore.search.probleminputs.GraphSearchInput; public class SimpleForwardDecompositionReducer extends AForwardDecompositionReducer<IHTNPlanningProblem, IPlan, GraphSearchInput<TFDNode, String>, ILabeledPath<TFDNode, String>> { @Override public GraphSearchInput<TFDNode, String> encodeProblem(final IHTNPlanningProblem problem) { return this.getGraphSearchInput(problem); } @Override public Plan decodeSolution(final ILabeledPath<TFDNode, String> solution) { return this.getPlanForSolution(solution); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/TaskPlannerUtil.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.logic.fol.theories.EvaluablePredicate; import ai.libs.jaicore.logic.fol.util.ForwardChainer; import ai.libs.jaicore.logic.fol.util.ForwardChainingProblem; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCAction; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCOperation; import ai.libs.jaicore.planning.classical.problems.strips.Operation; import ai.libs.jaicore.planning.core.Action; import ai.libs.jaicore.planning.hierarchical.problems.ceocipstn.OCIPMethod; import ai.libs.jaicore.planning.hierarchical.problems.ceocstn.OCMethod; import ai.libs.jaicore.planning.hierarchical.problems.stn.Method; import ai.libs.jaicore.planning.hierarchical.problems.stn.MethodInstance; import ai.libs.jaicore.planning.hierarchical.problems.stn.STNPlanningDomain; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; public class TaskPlannerUtil implements ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(TaskPlannerUtil.class); private Map<String, EvaluablePredicate> evaluablePlanningPredicates; public TaskPlannerUtil(final Map<String, EvaluablePredicate> evaluablePlanningPredicates) { super(); this.evaluablePlanningPredicates = evaluablePlanningPredicates; } public Collection<MethodInstance> getMethodInstancesForTaskThatAreApplicableInState(final CNFFormula knowledge, final Collection<? extends Method> methods, final Literal task, final Monom state, final List<Literal> remainingProblems) throws InterruptedException { Collection<MethodInstance> applicableDerivedMethods = new ArrayList<>(); List<Method> potentiallySuitableMethod = methods.stream().filter(m -> m.getTask().getPropertyName().equals(task.getPropertyName())).collect(Collectors.toList()); if (potentiallySuitableMethod.isEmpty()) { this.logger.warn("There are NO methods that can resolve the task {}. This points to an ill-defined planning problem!", task); return applicableDerivedMethods; } this.logger.debug("Identified {} methods that are suitable based on their name.", potentiallySuitableMethod.size()); for (Method m : potentiallySuitableMethod) { this.logger.debug("Method {} is potentially suited to solve this task. Checking its applicability.", m.getName()); Collection<MethodInstance> additionalInstances = this.getMethodInstancesForTaskThatAreApplicableInState(knowledge, m, task, state, remainingProblems); assert !m.isLonely() || additionalInstances.size() <= 1 : "Computed more than one instantiations for lonely method: \n\t" + additionalInstances.stream().map(MethodInstance::toString).collect(Collectors.joining("\n\t")); applicableDerivedMethods.addAll(additionalInstances); } return applicableDerivedMethods; } public Collection<MethodInstance> getMethodInstancesForTaskThatAreApplicableInState(final CNFFormula knowledge, final Method method, final Literal task, final Monom state, final List<Literal> remainingProblems) throws InterruptedException { this.logger.info("Determine instances of method {} that are applicable in current state for task {}. Complete agenda: {}. Enable TRACE to see current state.", method.getName(), task, remainingProblems); this.logger.trace("State is {}", state); Collection<MethodInstance> applicableDerivedMethodInstances = new ArrayList<>(); Collection<Map<VariableParam, LiteralParam>> maps = this.getMappingsThatMatchTasksAndMakesItApplicable(knowledge, method.getTask(), task, method.getPrecondition(), state); for (Map<VariableParam, LiteralParam> grounding : maps) { this.logger.debug("Now considering partial grounding {}", grounding); /* create a copy of the grounding */ Map<VariableParam, ConstantParam> basicConstantGrounding = new HashMap<>(); for (Entry<VariableParam,LiteralParam> groundingEntry : grounding.entrySet()) { basicConstantGrounding.put(groundingEntry.getKey(), (ConstantParam) groundingEntry.getValue()); } /* up to where, we only have considered the "normal" parameters. Now check whether additional inputs bindings are indicated by interpreted predicates */ Collection<Map<VariableParam, ConstantParam>> extendedGroundings = new ArrayList<>(); /* this block is to cater for methods that have interpreted predicates and need to be oracled for valid groundings */ if (method instanceof OCIPMethod) { OCIPMethod castedMethod = (OCIPMethod) method; Collection<VariableParam> ungroundParamsInEvaluablePrecondition = SetUtil.difference(castedMethod.getEvaluablePrecondition().getVariableParams(), basicConstantGrounding.keySet()); Map<Literal, EvaluablePredicate> evaluablePredicatesForLiterals = new HashMap<>(); for (Literal l : castedMethod.getEvaluablePrecondition()) { if (this.evaluablePlanningPredicates == null || !this.evaluablePlanningPredicates.containsKey(l.getPropertyName())) { throw new IllegalArgumentException("The literal " + l + " is used in an evaluated precondition, but no evaluator has been specified for it."); } evaluablePredicatesForLiterals.put(l, this.evaluablePlanningPredicates.get(l.getPropertyName())); } /* now try to ground still unground parameters */ if (!ungroundParamsInEvaluablePrecondition.isEmpty()) { /* * We first try that by using oracles sort the literals in the precondition by (a) oracable vs. not oracable and (b) among the oracable, sort by number of params that need to be * oracled this will allow us to use oracle results of earlier predicates for later ones **/ Queue<Literal> literalsOrderedByOracability = new LinkedList<>(castedMethod.getEvaluablePrecondition().stream().sorted((l1, l2) -> { EvaluablePredicate el1 = evaluablePredicatesForLiterals.get(l1); EvaluablePredicate el2 = evaluablePredicatesForLiterals.get(l2); if (el1.isOracable() != el2.isOracable()) { return el1.isOracable() ? -1 : 1; } if (!el1.isOracable()) { return 0; } int ungroundParamsInL1 = SetUtil.intersection(ungroundParamsInEvaluablePrecondition, l1.getParameters()).size(); int ungroundParamsInL2 = SetUtil.intersection(ungroundParamsInEvaluablePrecondition, l2.getParameters()).size(); return ungroundParamsInL1 - ungroundParamsInL2; }).collect(Collectors.toList())); /* just a brief check whether there are oracable literals */ if (!evaluablePredicatesForLiterals.get(literalsOrderedByOracability.peek()).isOracable()) { throw new IllegalArgumentException("None of the literals " + literalsOrderedByOracability + " is oracable"); } List<Map<VariableParam, ConstantParam>> oracleGroundings = new ArrayList<>(); oracleGroundings.add(basicConstantGrounding); this.getOracleGroundings(ungroundParamsInEvaluablePrecondition, literalsOrderedByOracability, state, new HashSet<>(), oracleGroundings, basicConstantGrounding); extendedGroundings.addAll(oracleGroundings); } /* all parameters are ground, we just need to test the predicate */ else { boolean allSatisfied = true; for (Literal l : castedMethod.getEvaluablePrecondition()) { ConstantParam[] params = new ConstantParam[l.getParameters().size()]; for (int i = 0; i < params.length; i++) { LiteralParam param = l.getParameters().get(i); params[i] = (param instanceof ConstantParam) ? (ConstantParam) param : basicConstantGrounding.get(param); } if (evaluablePredicatesForLiterals.get(l).test(state, params) != l.isPositive()) { allSatisfied = false; break; } } if (allSatisfied) { extendedGroundings.add(basicConstantGrounding); } } } else { extendedGroundings.add(basicConstantGrounding); } /* now add a method application for each of the extended groundings */ for (Map<VariableParam, ConstantParam> extendedGrounding : extendedGroundings) { /* create new objects for unassigned open output variables */ Set<ConstantParam> knownConstants = new HashSet<>(state.getConstantParams()); knownConstants.addAll(extendedGrounding.values()); for (Literal l : remainingProblems) { knownConstants.addAll(l.getConstantParams()); } Collection<VariableParam> unboundParams = SetUtil.difference(method.getParameters(), extendedGrounding.keySet()); this.logger.debug("Unbound parameters at this point: {}. Known constants: {}", unboundParams, knownConstants); if (method instanceof OCMethod) { Collection<VariableParam> unboundOutputParams = SetUtil.intersection(unboundParams, ((OCMethod) method).getOutputs()); if (!unboundOutputParams.equals(unboundParams)) { throw new IllegalStateException("Some of the inputs of method " + method.getName() + " have not been ground. Unground inputs: " + SetUtil.difference(unboundParams, unboundOutputParams)); } int indexForNewVariable = 1; for (VariableParam v : unboundOutputParams) { ConstantParam p; do { p = new ConstantParam("newVar" + (indexForNewVariable++)); } while (knownConstants.contains(p)); extendedGrounding.put(v, p); unboundParams.remove(v); } if (!unboundParams.isEmpty()) { throw new IllegalStateException("Method " + method.getName() + " must be ground completely before processing. Here, " + unboundParams + " are unground."); } } else if (!unboundParams.isEmpty()) { throw new IllegalStateException("Could not compute a complete grounding for method " + method.getName() + ". The following parameters were not ground until the end: " + unboundParams); } applicableDerivedMethodInstances.add(new MethodInstance(method, extendedGrounding)); if (method.isLonely()) { this.logger.info("Determined {} applicable method instances of method {} for task {}", applicableDerivedMethodInstances.size(), method.getName(), task); return applicableDerivedMethodInstances; } } } this.logger.info("Determined {} applicable method instances of method {} for task {}", applicableDerivedMethodInstances.size(), method.getName(), task); return applicableDerivedMethodInstances; } private void getOracleGroundings(final Collection<VariableParam> ungroundParamsInEvaluablePrecondition, final Queue<Literal> literalsOrderedByOracability, final Monom state, final Set<VariableParam> paramsGroundSoFar, final Collection<Map<VariableParam, ConstantParam>> groundingsFixedSoFar, final Map<VariableParam, ConstantParam> basicConstantGrounding) { if (literalsOrderedByOracability.isEmpty()) { return; } Literal l = literalsOrderedByOracability.poll(); /* check whether the literal only needs to be queried for one param */ Collection<LiteralParam> paramsThatNeedGrounding = SetUtil.intersection(SetUtil.difference(ungroundParamsInEvaluablePrecondition, paramsGroundSoFar), l.getParameters()); this.logger.info("Now checking validity of {}. Set of params that still need grounding: {}", l, paramsThatNeedGrounding); if (paramsThatNeedGrounding.size() > 1) { throw new UnsupportedOperationException("Currently only support for at most one unground variable! Here, the following variables of \"" + l + "\"need grounding: " + paramsThatNeedGrounding); } /* now go over all previous groundings and check them */ List<Map<VariableParam, ConstantParam>> localCopyOfCurrentGrounding = new ArrayList<>(groundingsFixedSoFar); VariableParam paramToBeGround = null; /* create an array with the parameters of the literal defined by the basic grounding, and determine the one to be oracled */ ConstantParam[] params = new ConstantParam[l.getParameters().size()]; int indexOfParam = -1; Map<VariableParam, Integer> positionsOfVariableParams = new HashMap<>(); for (int i = 0; i < params.length; i++) { LiteralParam param = l.getParameters().get(i); boolean parameterIsConstant = param instanceof ConstantParam; boolean parameterIsGround = basicConstantGrounding.containsKey(param); boolean parameterHasBeenDecidedByOracle = !(parameterIsConstant || parameterIsGround) && paramsGroundSoFar.contains(param); if (parameterIsConstant) { params[i] = (ConstantParam) param; } else if (parameterIsGround) { params[i] = basicConstantGrounding.get(param); } else { positionsOfVariableParams.put((VariableParam) param, i); if (!parameterHasBeenDecidedByOracle) { indexOfParam = i; paramToBeGround = (VariableParam) l.getParameters().get(i); } } } /* update list of solutions */ groundingsFixedSoFar.clear(); for (Map<VariableParam, ConstantParam> previouslyOracledGrounding : localCopyOfCurrentGrounding) { this.logger.info("Considering combination of previously fixed oracle decisions: {}", previouslyOracledGrounding); /* completing the param array */ for (VariableParam oracledParam : paramsGroundSoFar) { if (!positionsOfVariableParams.containsKey(oracledParam)) { this.logger.debug("Ignoring ground value {} of param {}, because this param does not occur in the literal", previouslyOracledGrounding.get(oracledParam), oracledParam); continue; } this.logger.debug("Inserting {} at position {} in the param array.", previouslyOracledGrounding.get(oracledParam), positionsOfVariableParams.get(oracledParam)); params[positionsOfVariableParams.get(oracledParam)] = previouslyOracledGrounding.get(oracledParam); } if (this.logger.isInfoEnabled()) { this.logger.info("Params for literal are {}", Arrays.toString(params)); } /* recover the parameter to ground */ final int finalizedIndexOfParam = indexOfParam; if ((finalizedIndexOfParam >= 0) != (paramToBeGround != null)) { throw new IllegalStateException("Param to be ground is " + paramToBeGround + ", but the index in the literal is " + finalizedIndexOfParam); } /* determine currently valid candidates */ EvaluablePredicate predicate = this.evaluablePlanningPredicates.get(l.getPropertyName()); /* if this param is checked for the first time, aquire an oracle */ if (paramToBeGround != null) { this.logger.info("No valid grounding for param {} are known, so apply oracle.", paramToBeGround); Collection<List<ConstantParam>> possibleGroundingsOfThisPredicate = l.isPositive() ? predicate.getParamsForPositiveEvaluation(state, params) : predicate.getParamsForNegativeEvaluation(state, params); if (possibleGroundingsOfThisPredicate == null) { this.logger.warn("Predicate {} returned NULL for params {} in state {}. Canceling grounding process.", l.getPropertyName(), params, state); return; } Collection<ConstantParam> possibleValuesForNewParamInThisGrounding = possibleGroundingsOfThisPredicate.stream().map(s -> s.get(finalizedIndexOfParam)).collect(Collectors.toSet()); for (ConstantParam oracledParamOfThisLiteral : possibleValuesForNewParamInThisGrounding) { Map<VariableParam, ConstantParam> extendedOracleGrounding = new HashMap<>(previouslyOracledGrounding); extendedOracleGrounding.put(paramToBeGround, oracledParamOfThisLiteral); groundingsFixedSoFar.add(extendedOracleGrounding); } this.logger.info("Candidates for grounding is now {}", groundingsFixedSoFar); paramsGroundSoFar.add(paramToBeGround); } /* otherwise just test the predicate against the choices already made */ else { if (this.logger.isInfoEnabled()) { this.logger.info("No new parameters to ground. Only testing {} (evaluated by {}) against params {} given groundings {}.", l, predicate.getClass().getName(), Arrays.toString(params), groundingsFixedSoFar); } localCopyOfCurrentGrounding.stream().filter(grounding -> predicate.test(state, params) == l.isPositive()).forEach(groundingsFixedSoFar::add); } } this.logger.info("Proceeding with extended oracle grounding: {}", groundingsFixedSoFar); this.getOracleGroundings(ungroundParamsInEvaluablePrecondition, literalsOrderedByOracability, state, paramsGroundSoFar, groundingsFixedSoFar, basicConstantGrounding); } public Collection<Action> getActionsForPrimitiveTaskThatAreApplicableInState(final CNFFormula knowledge, final Operation op, final Literal task, final Monom state) throws InterruptedException { Collection<Action> applicableDerivedActions = new ArrayList<>(); List<VariableParam> allParams = new ArrayList<>(); allParams.addAll(op.getParams()); StringBuilder sbTaskNameOfOperation = new StringBuilder(op.getName()); sbTaskNameOfOperation.append("("); for (int i = 0; i < allParams.size(); i++) { if (i > 0) { sbTaskNameOfOperation.append(", "); } sbTaskNameOfOperation.append(allParams.get(i).getName()); } sbTaskNameOfOperation.append(")"); Literal taskOfOperation = new Literal(sbTaskNameOfOperation.toString()); for (Map<VariableParam, LiteralParam> grounding : this.getMappingsThatMatchTasksAndMakesItApplicable(knowledge, taskOfOperation, task, op.getPrecondition(), state)) { Map<VariableParam, ConstantParam> constantGrounding = new HashMap<>(); for (Entry<VariableParam,LiteralParam> groundingEntry : grounding.entrySet()) { constantGrounding.put(groundingEntry.getKey(), (ConstantParam) groundingEntry.getValue()); } if (op instanceof CEOCOperation) { applicableDerivedActions.add(new CEOCAction((CEOCOperation) op, constantGrounding)); } else { applicableDerivedActions.add(new Action(op, constantGrounding)); } } return applicableDerivedActions; } private Collection<Map<VariableParam, LiteralParam>> getMappingsThatMatchTasksAndMakesItApplicable(final CNFFormula knowledge, final Literal methodOrPrimitiveTask, final Literal target, final Monom preconditionOfMethodOrPrimitive, final Monom state) throws InterruptedException { assert preconditionOfMethodOrPrimitive != null : "precondition of methode or primitive task " + methodOrPrimitiveTask + " is null"; this.logger.info("Now computing the possible applications of method {} for task {}", methodOrPrimitiveTask, target); /* if no precondition is to be matched, just match the params and return this binding */ if (preconditionOfMethodOrPrimitive.isEmpty()) { int numParams = target.getParameters().size(); if (methodOrPrimitiveTask.getParameters().size() != numParams) { throw new IllegalArgumentException("The target " + target + " has " + numParams + " parameters but the method or primitive task " + methodOrPrimitiveTask + " has " + methodOrPrimitiveTask.getParameters().size()); } Map<VariableParam, LiteralParam> grounding = new HashMap<>(); for (int i = 0; i < numParams; i++) { VariableParam paramOfPreconditionLiteral = (VariableParam) methodOrPrimitiveTask.getParameters().get(i); LiteralParam targetParam = target.getParameters().get(i); grounding.put(paramOfPreconditionLiteral, targetParam); } Collection<Map<VariableParam, LiteralParam>> groundings = new ArrayList<>(); groundings.add(grounding); this.logger.debug("There are no preconditions, so the valid groundings are {}", groundings); return groundings; } /* consistency check */ if (!methodOrPrimitiveTask.getPropertyName().equals(target.getPropertyName())) { throw new IllegalArgumentException("The method used to refine task \"" + target + "\" must be compatible with it, i.e. designed for that task, but it is designed for \"" + methodOrPrimitiveTask.getPropertyName() + "\""); } /* * compute map between argument names of the method or primitive task literal and the target literal. Primitive tasks are completely bound here, but methods may have other parameters that do * not occur in their task. */ final List<LiteralParam> taskParams = target.getParameters(); final List<VariableParam> methodTaskParams = methodOrPrimitiveTask.getVariableParams(); // there should be no constants actually if (taskParams.size() != methodTaskParams.size() || methodTaskParams.size() != methodOrPrimitiveTask.getParameters().size()) { throw new IllegalArgumentException("A method or operation associated with task \"" + methodOrPrimitiveTask + "\" is used to refine task \"" + target + "\". There is a parameter count clash!"); } final Map<VariableParam, LiteralParam> taskParameterMapping = new HashMap<>(); for (int i = 0; i < taskParams.size(); i++) { taskParameterMapping.put(methodTaskParams.get(i), taskParams.get(i)); } final List<Map<VariableParam, LiteralParam>> groundings = new ArrayList<>(); /* create knowledge for the check */ assert knowledge == null || !knowledge.hasDisjunctions() : "Currently no support for non-factbase knowledge!"; Monom unitedKnowledge = new Monom(state); if (knowledge != null) { unitedKnowledge.addAll(knowledge.extractMonom()); } /* determine potential output parameters of the task */ final Collection<VariableParam> outputs = SetUtil.difference(target.getVariableParams(), preconditionOfMethodOrPrimitive.getVariableParams()); final Collection<VariableParam> parametersThatNeedGrounding = SetUtil.difference(target.getVariableParams(), outputs); /* first compute the possible groundings of the TASK to the state objects; if the task is already ground, add the empty completion */ final Collection<Map<VariableParam, ConstantParam>> groundingsOfTargetTask = SetUtil.allTotalMappings(parametersThatNeedGrounding, unitedKnowledge.getConstantParams()); if (groundingsOfTargetTask.isEmpty()) { groundingsOfTargetTask.add(new HashMap<>()); } /* now check the instances of the method for each grounding completion */ for (Map<VariableParam, ConstantParam> targetTaskGrounding : groundingsOfTargetTask) { /* * transfer the grounding of the target predicate to the parameters occurring in the method task/primitive task respectively. NOTE: There may be parameters of the target task (e.g. * outputs) that will not be ground here. So also the instance will be ground only partially. */ final Map<VariableParam, ConstantParam> groundingForMethodOrPrimitiveTask = new HashMap<>(); for (VariableParam var : methodTaskParams) { LiteralParam correspondingVarInTaskLiteral = taskParameterMapping.get(var); if (correspondingVarInTaskLiteral instanceof ConstantParam) { groundingForMethodOrPrimitiveTask.put(var, (ConstantParam) correspondingVarInTaskLiteral); } else if (targetTaskGrounding.containsKey(correspondingVarInTaskLiteral)) { groundingForMethodOrPrimitiveTask.put(var, targetTaskGrounding.get(correspondingVarInTaskLiteral)); } } /* now create the part of the grounding of the METHOD related to params NOT occurring in the task. if no such exists, consider just one empty completion */ Monom positiveRequirements = new Monom(preconditionOfMethodOrPrimitive.stream().filter(Literal::isPositive).collect(Collectors.toList()), groundingForMethodOrPrimitiveTask); Collection<Map<VariableParam, LiteralParam>> restMaps; if (!positiveRequirements.isEmpty()) { ForwardChainer fc = new ForwardChainer(new ForwardChainingProblem(unitedKnowledge, positiveRequirements, true)); try { restMaps = fc.call(); } catch (AlgorithmExecutionCanceledException | TimeoutException e) { this.logger.warn("The forward chainer was canceled or timed out, so maybe not all bindings could be computed!"); return groundings; } } else { restMaps = new ArrayList<>(); } if (restMaps.isEmpty()) { restMaps.add(new HashMap<>()); } /* now compute the resulting complete groundings */ for (Map<VariableParam, LiteralParam> restMap : restMaps) { Map<VariableParam, LiteralParam> completeGroundingMethod = new HashMap<>(); completeGroundingMethod.putAll(groundingForMethodOrPrimitiveTask); completeGroundingMethod.putAll(restMap); /* now check applicability of the GROUND method */ this.logger.debug("Now considering grounding {}", completeGroundingMethod); Monom precondition = new Monom(preconditionOfMethodOrPrimitive, completeGroundingMethod); if (precondition.isContradictory()) { this.logger.debug("Ignoring this grounding because it makes the precondition contradictory."); continue; } List<Literal> positiveLiterals = precondition.stream().filter(Literal::isPositive).collect(Collectors.toList()); List<Literal> negativeLiterals = precondition.stream().filter(Literal::isNegated).map(l -> l.clone().toggleNegation()).collect(Collectors.toList()); if (unitedKnowledge.containsAll(positiveLiterals) && SetUtil.intersection(unitedKnowledge, negativeLiterals).isEmpty()) { this.logger.debug("Adding the grounding."); groundings.add(completeGroundingMethod); } else if (this.logger.isDebugEnabled()) { for (Literal l : positiveLiterals) { if (!unitedKnowledge.contains(l)) { this.logger.debug("Ignoring this grounding because the united knowledge {} does not contain the positive literal {}", unitedKnowledge, l); if (this.logger.isTraceEnabled()) { for (Literal l2 : unitedKnowledge) { this.logger.trace("Comparing {} of signature {}{} with {} of signature{}{}: {}/{}", l, l.getClass().getName(), l.getParameters().stream().map(p -> p.getName() + ":" + p.getType()).collect(Collectors.toList()), l2, l2.getClass().getName(), l2.getParameters().stream().map(p -> p.getName() + ":" + p.getType()).collect(Collectors.toList()), l.equals(l2), l2.equals(l)); } } break; } } if (!SetUtil.intersection(unitedKnowledge, negativeLiterals).isEmpty()) { this.logger.debug("Ignoring this grounding because of an non-empty intersection of the united knowledge {} and the negative literals {}", unitedKnowledge, negativeLiterals); } } } } this.logger.info("Admissible groundings for {} with precondition {} on {} are: {}", methodOrPrimitiveTask, preconditionOfMethodOrPrimitive, target, groundings); return groundings; } public List<Literal> getTaskChainOfTotallyOrderedNetwork(final TaskNetwork network) { List<Literal> taskSequence = new ArrayList<>(); if (network.getSources().isEmpty()) { return taskSequence; } Literal current = network.getSources().iterator().next(); while (current != null) { taskSequence.add(current); Collection<Literal> successors = network.getSuccessors(current); current = successors.isEmpty() ? null : successors.iterator().next(); } return taskSequence; } public Map<String, EvaluablePredicate> getEvaluablePlanningPredicates() { return this.evaluablePlanningPredicates; } public void setEvaluablePlanningPredicates(final Map<String, EvaluablePredicate> evaluablePlanningPredicates) { this.evaluablePlanningPredicates = evaluablePlanningPredicates; } public Optional<? extends Operation> getOperationWithName(final STNPlanningDomain domain, final String nameOfOperation) { Objects.requireNonNull(domain); Objects.requireNonNull(nameOfOperation); return domain.getOperations().stream().filter(o -> o.getName().equals(nameOfOperation)).findAny(); } public List<CEOCAction> recoverPlanFromActionEncoding(final STNPlanningDomain domain, final List<String> actionEncodings) { List<CEOCAction> plan = new ArrayList<>(); Pattern p = Pattern.compile("([^(]+)\\(([^,]*|([^,]*(?:,[^,]*)+))\\)"); for (String actionEncoding : actionEncodings) { Matcher m = p.matcher(actionEncoding); if (!m.find()) { throw new IllegalArgumentException("Cannot match the action encoding " + actionEncoding); } /* compute operation */ Optional<? extends Operation> op = this.getOperationWithName(domain, m.group(1)); if (!op.isPresent()) { throw new IllegalArgumentException("Invalid action " + actionEncoding + ", because no operation with name \"" + m.group(1) + "\" is known in the given domain."); } /* compute grounding */ List<ConstantParam> args = Arrays.asList(m.group(2).split(",")).stream().map(param -> new ConstantParam(param.trim())).collect(Collectors.toList()); Map<VariableParam, ConstantParam> grounding = new HashMap<>(); List<VariableParam> params = op.get().getParams(); for (int i = 0; i < params.size(); i++) { grounding.put(params.get(i), args.get(i)); } plan.add(new CEOCAction((CEOCOperation) op.get(), grounding)); } return plan; } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/ceociptfd/CEOCIPTFDGraphGenerator.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.ceociptfd; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.TaskPlannerUtil; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.ceoctfd.CEOCTFDGraphGenerator; import ai.libs.jaicore.planning.hierarchical.problems.ceocipstn.CEOCIPSTNPlanningProblem; /** * Graph Generator for HTN planning where (i) operations have conditional effects, (ii) operations may create new objects, and (iii) method preconditions may contain evaluable predicates. * * @author fmohr * */ public class CEOCIPTFDGraphGenerator extends CEOCTFDGraphGenerator { public CEOCIPTFDGraphGenerator(final CEOCIPSTNPlanningProblem problem) { super(problem); /* now overwrite util to get access to the evaluable predicates */ this.util = new TaskPlannerUtil(problem.getEvaluablePlanningPredicates()); } @Override public String toString() { return "CEOCIPTFDGraphGenerator [problem=" + this.problem + ", primitiveTasks=" + this.primitiveTasks + "]"; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/ceociptfd/OracleTaskResolver.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.ceociptfd; import java.util.Collection; import java.util.List; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.core.Action; public interface OracleTaskResolver { public Collection<List<Action>> getSubSolutions(Monom state, Literal task) throws Exception; }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/ceoctfd/CEOCTFDGraphGenerator.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.ceoctfd; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.core.Action; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDGraphGenerator; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDNode; import ai.libs.jaicore.planning.hierarchical.problems.ceocstn.CEOCSTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.stn.MethodInstance; public class CEOCTFDGraphGenerator extends TFDGraphGenerator { private Logger logger = LoggerFactory.getLogger(CEOCTFDGraphGenerator.class); public CEOCTFDGraphGenerator(final CEOCSTNPlanningProblem problem) { super(problem); } @Override protected TFDNode postProcessPrimitiveTaskNode(final TFDNode node) { Monom state = node.getState(); state.getParameters().stream().filter(p -> p.getName().startsWith("newVar") && !state.contains(new Literal("def('" + p.getName() + "')"))).forEach(p -> state.add(new Literal("def('" + p.getName() + "')"))); return node; } @Override public boolean isPathSemanticallySubsumed(final List<TFDNode> path, final List<TFDNode> compl) throws InterruptedException { if (compl.size() < path.size()) { this.logger.debug("Ignoring this partial path, because its completion is shorter than the path we already have."); return false; } if (path.equals(compl)) { this.logger.debug("Return true, because the paths are even equal."); return true; } Map<ConstantParam, ConstantParam> map = new HashMap<>(); boolean allUnifiable = true; for (int i = 0; i < path.size(); i++) { TFDNode current = path.get(i); TFDNode partner = compl.get(i); /* check whether the chosen method or operation is the same */ final Action a1 = current.getAppliedAction(); final Action a2 = partner.getAppliedAction(); if ((a1 == null) != (a2 == null)) { allUnifiable = false; this.logger.trace("Not unifiable because one node applies an action and the other not (either it applies nothing or a method instance)."); break; } if (a1 != null && !a1.getOperation().equals(a2.getOperation())) { allUnifiable = false; this.logger.trace("Not unifiable because operations {} and {} of a1 and a2 respectively deviate", a1.getOperation(), a2.getOperation()); break; } if (a1 == null) { final MethodInstance mi1 = current.getAppliedMethodInstance(); final MethodInstance mi2 = partner.getAppliedMethodInstance(); /* the nodes just don't do anything (should be the root) */ if (mi1 == null && mi2 == null) { continue; } if ((mi1 == null) != (mi2 == null)) { allUnifiable = false; this.logger.trace("Not unifiable because one node applies a method instance and the other not (either an action or nothing)"); break; } if (!mi1.getMethod().equals(mi2.getMethod())) { allUnifiable = false; this.logger.trace("Not unifiable because methods {} and {} of m1 and m2 respectively deviate", mi1.getMethod(), mi2.getMethod()); break; } } /* compute substitutions of new vars */ Collection<ConstantParam> varsInCurrent = new HashSet<>(current.getState().getConstantParams()); for (Literal l : current.getRemainingTasks()) { varsInCurrent.addAll(l.getConstantParams()); } Collection<ConstantParam> varsInPartner = new HashSet<>(partner.getState().getConstantParams()); for (Literal l : partner.getRemainingTasks()) { varsInPartner.addAll(l.getConstantParams()); } Collection<ConstantParam> unboundVars = SetUtil.difference(varsInCurrent, map.keySet()); Collection<ConstantParam> possibleTargets = SetUtil.difference(varsInPartner, map.values()); for (ConstantParam p : new ArrayList<>(unboundVars)) { if (possibleTargets.contains(p)) { map.put(p, p); unboundVars.remove(p); possibleTargets.remove(p); } } /* if the relation between vars in the nodes is completely known, we can easily decide whether they are unifiable */ if (unboundVars.isEmpty()) { if (this.getRenamedState(current.getState(), map).equals(partner.getState()) && this.getRenamedRemainingList(current.getRemainingTasks(), map).equals(partner.getRemainingTasks())) { continue; } else { allUnifiable = false; break; } } /* otherwise, we must check possible mappings between the still unbound vars */ boolean unified = false; Collection<Map<ConstantParam, ConstantParam>> possibleMappingCompletions = SetUtil.allMappings(unboundVars, possibleTargets, true, true, true); for (Map<ConstantParam, ConstantParam> mappingCompletion : possibleMappingCompletions) { /* first check whether the state is equal */ Monom copy = this.getRenamedState(current.getState(), mappingCompletion); if (!copy.equals(partner.getState())) { continue; } /* if this is the case, check whether the remaining tasks are equal */ List<Literal> copyOfTasks = this.getRenamedRemainingList(current.getRemainingTasks(), mappingCompletion); if (!copyOfTasks.equals(partner.getRemainingTasks())) { continue; } /* now we know that this node can be unified. We add the respective map and quit the current node pair */ map.putAll(mappingCompletion); unified = true; break; } if (!unified) { allUnifiable = false; break; } } /* if all nodes were unifiable, return this path */ if (allUnifiable) { this.logger.info("Returning true, because this path is unifiable with the given one."); return true; } else { return false; } } private Monom getRenamedState(final Monom state, final Map<ConstantParam, ConstantParam> map) { return new Monom(state, map); } private List<Literal> getRenamedRemainingList(final List<Literal> remainingList, final Map<ConstantParam, ConstantParam> map) { List<Literal> copyOfTasks = new ArrayList<>(); for (Literal l : remainingList) { copyOfTasks.add(new Literal(l, map)); } return copyOfTasks; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/rtn/RTNEdge.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.rtn; import java.util.Map; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCAction; import ai.libs.jaicore.planning.hierarchical.problems.stn.MethodInstance; public class RTNEdge { private final Map<ConstantParam, ConstantParam> contextRecreator; private final MethodInstance methodInstance; private final CEOCAction appliedAction; public RTNEdge(Map<ConstantParam, ConstantParam> contextRecreator, MethodInstance methodInstance, CEOCAction appliedAction) { super(); this.contextRecreator = contextRecreator; this.methodInstance = methodInstance; this.appliedAction = appliedAction; } public Map<ConstantParam, ConstantParam> getContextRecreator() { return contextRecreator; } public MethodInstance getMethodInstance() { return methodInstance; } public CEOCAction getAppliedAction() { return appliedAction; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/rtn/RTNGraphGenerator.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.rtn; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import org.api4.java.datastructure.graph.implicit.INewNodeDescription; import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator; import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.classical.algorithms.strips.forward.StripsUtil; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCAction; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCOperation; import ai.libs.jaicore.planning.classical.problems.strips.Operation; import ai.libs.jaicore.planning.core.Action; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.TaskPlannerUtil; import ai.libs.jaicore.planning.hierarchical.problems.rtn.RTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.stn.Method; import ai.libs.jaicore.planning.hierarchical.problems.stn.MethodInstance; import ai.libs.jaicore.search.model.NodeExpansionDescription; public class RTNGraphGenerator implements IGraphGenerator<RTNNode, RTNEdge> { private static final Logger logger = LoggerFactory.getLogger(RTNGraphGenerator.class); private final RTNPlanningProblem problem; private final Map<String, Operation> primitiveTasks = new HashMap<>(); private final TaskPlannerUtil util = new TaskPlannerUtil(null); public RTNGraphGenerator(final RTNPlanningProblem problem) { this.problem = problem; for (Operation op : problem.getDomain().getOperations()) { this.primitiveTasks.put(op.getName(), op); } } @Override public ISingleRootGenerator<RTNNode> getRootGenerator() { return () -> new RTNNode(false, this.problem.getInit(), new ArrayList<>(this.util.getTaskChainOfTotallyOrderedNetwork(this.problem.getNetwork()))); } @Override public ISuccessorGenerator<RTNNode, RTNEdge> getSuccessorGenerator() { return l -> { final List<INewNodeDescription<RTNNode, RTNEdge>> successors = new ArrayList<>(); final Monom state = l.getState(); final List<Literal> currentlyRemainingTasks = l.getRemainingTasks(); final Literal nextTaskTmp = currentlyRemainingTasks.get(0); if (nextTaskTmp == null) { return successors; } final Literal nextTask = new Literal(nextTaskTmp.getPropertyName().substring(nextTaskTmp.getPropertyName().indexOf('-') + 1, nextTaskTmp.getPropertyName().length()), nextTaskTmp.getParameters()); final String actualTaskName = nextTask.getPropertyName(); /* if this is an or-node, perform the split as always */ if (!l.isAndNode()) { /* if the task is primitive */ if (this.primitiveTasks.containsKey(actualTaskName)) { logger.info("Computing successors for PRIMITIVE task {} in state {}", nextTask, state); final Collection<Action> applicableActions = this.util.getActionsForPrimitiveTaskThatAreApplicableInState(null, this.primitiveTasks.get(actualTaskName), nextTask, state); for (Action applicableAction : applicableActions) { logger.info("Adding successor for PRIMITIVE task {} in state {}: {}", nextTask, state, applicableAction.getEncoding()); assert state.containsAll(applicableAction.getPrecondition().stream().filter(Literal::isPositive).collect(Collectors.toList())) && SetUtil.disjoint(state, applicableAction.getPrecondition().stream().filter(Literal::isNegated).collect(Collectors.toList())) : ("Action " + applicableAction + " is supposed to be aplpicable in state " + state + " but it is not!"); /* if the depth is % k == 0, then compute the rest problem explicitly */ final Monom updatedState = new Monom(state, false); final CEOCOperation op = (CEOCOperation) applicableAction.getOperation(); final CEOCAction relevantAction = new CEOCAction(op, applicableAction.getGrounding()); try { StripsUtil.updateState(updatedState, applicableAction); } catch (Exception e) { logger.error("apply {} to state: {}", applicableAction.getEncoding(), state); logger.error("addlists: {}", relevantAction.getAddLists()); logger.error("Observed exception: {}", e); } final List<Literal> remainingTasks = new ArrayList<>(currentlyRemainingTasks); remainingTasks.remove(0); boolean isAndNode = this.remainingTasksInitializeANDNode(remainingTasks); successors.add(new NodeExpansionDescription<>(new RTNNode(isAndNode, updatedState, remainingTasks), new RTNEdge(null, null, relevantAction))); } assert checkDoubleNodes(successors); logger.info("Computed {} successors", successors.size()); } /* otherwise determine methods for the task */ else { logger.info("Computing successors for COMPLEX task {} in state {}", nextTask, state); final Set<Method> usedMethods = new HashSet<>(); /* if this is an OR-Node */ final Collection<MethodInstance> instances = this.util.getMethodInstancesForTaskThatAreApplicableInState(null, this.problem.getDomain().getMethods(), nextTask, state, currentlyRemainingTasks); for (MethodInstance instance : instances) { /* skip this instance if the method is lonely and we already used it */ if (!usedMethods.contains(instance.getMethod())) { usedMethods.add(instance.getMethod()); } else if (instance.getMethod().isLonely()) { continue; } assert state.containsAll(instance.getPrecondition().stream().filter(Literal::isPositive).collect(Collectors.toList())) && SetUtil.disjoint(state, instance.getPrecondition().stream().filter(Literal::isNegated).collect(Collectors.toList())) : ("Instance " + instance + " is supposed to be aplpicable in state " + state + " but it is not!"); logger.info("Adding successor {}", instance); final List<Literal> remainingTasks = new ArrayList<>(this.util.getTaskChainOfTotallyOrderedNetwork(instance.getNetwork())); final int indexForRemoval = remainingTasks.size(); remainingTasks.addAll(currentlyRemainingTasks); remainingTasks.remove(indexForRemoval); // remove the first literal of the 2ndly appended list /* hard code the and-or-stuff for a moment */ boolean isAndNode = this.remainingTasksInitializeANDNode(remainingTasks); successors.add(new NodeExpansionDescription<>(new RTNNode(isAndNode, state, remainingTasks), new RTNEdge(null, instance, null))); } } } /* if this is an AND-node, create one successor for each refine action and the first after them */ else { /* determine the next k tasks that are parallelizable */ final List<Literal> parallelizableTasks = new ArrayList<>(); final List<Literal> tasksForLastNode = new ArrayList<>(currentlyRemainingTasks); for (int i = 0; i < currentlyRemainingTasks.size(); i++) { Literal task = currentlyRemainingTasks.get(i); if (task.getPropertyName().contains("refine")) { parallelizableTasks.add(task); tasksForLastNode.remove(0); } } /* now create one successor for each of the refine-statements */ for (Literal task : parallelizableTasks) { /* compute the reduced state */ final Monom reducedState = new Monom(); final Set<ConstantParam> relevantConstants = new HashSet<>(task.getConstantParams()); for (String c : RTNUtil.getClassesThatExistInState(l)) { relevantConstants.add(new ConstantParam(c)); } for (Literal lit : state) { if (relevantConstants.containsAll(lit.getConstantParams())) { reducedState.add(lit); } } /* rename clusters in reduced state */ Map<String, Collection<String>> clusters = new HashMap<>(); for (Literal lit : reducedState) { if (lit.getPropertyName().equals("in")) { String item = lit.getConstantParams().get(0).getName(); String cluster = lit.getConstantParams().get(1).getName(); if (!clusters.containsKey(cluster)) { clusters.put(cluster, new ArrayList<>()); } clusters.get(cluster).add(item); } } for (Entry<String,Collection<String>> nameWithItems : clusters.entrySet()) { clusters.put(nameWithItems.getKey(), nameWithItems.getValue().stream().sorted().collect(Collectors.toList())); } final List<Literal> toRemove = new ArrayList<>(); final List<Literal> toInsert = new ArrayList<>(); for (Literal lit : reducedState) { if (lit.getPropertyName().equals("biggest")) { toRemove.add(lit); continue; } else if (!SetUtil.intersection(lit.getConstantParams().stream().map(ConstantParam::getName).collect(Collectors.toList()), clusters.keySet()).isEmpty()) { toRemove.add(lit); final List<ConstantParam> params = new ArrayList<>(); for (ConstantParam p : lit.getConstantParams()) { params.add(clusters.containsKey(p.getName()) ? new ConstantParam(clusters.get(p.getName()).toString()) : p); } toInsert.add(new Literal(lit.getPropertyName(), params)); } } reducedState.removeAll(toRemove); reducedState.addAll(toInsert); /* add the ground knowledge to the state (even about objects that are not there anymore) */ for (Literal lit : state) { if (lit.getPropertyName().equals("bigger") && !reducedState.contains(lit)) { reducedState.add(lit); } } /* define the remaining task */ final List<Literal> remainingTask = new ArrayList<>(); final List<ConstantParam> paramsForTask = new ArrayList<>(); for (ConstantParam p : task.getConstantParams()) { paramsForTask.add(clusters.containsKey(p.getName()) ? new ConstantParam(clusters.get(p.getName()).toString()) : p); } /* define mapping for renaiming the subproblem solutions afterwards */ Map<ConstantParam, ConstantParam> mapping = new HashMap<>(); for (Entry<String, Collection<String>> nameWithItems : clusters.entrySet()) { mapping.put(new ConstantParam(nameWithItems.getValue().toString()), new ConstantParam(nameWithItems.getKey())); } remainingTask.add(new Literal(task.getPropertyName().substring(task.getPropertyName().indexOf('-') + 1), paramsForTask)); successors.add(new NodeExpansionDescription<>(new RTNNode(false, reducedState, remainingTask), new RTNEdge(mapping, null, null))); } /* now create one node for the remaining tasks */ if (!tasksForLastNode.isEmpty()) { successors.add(new NodeExpansionDescription<>(new RTNNode(false, state, tasksForLastNode), new RTNEdge(null, null, null))); } } logger.info("Computed {} successors", successors.size()); return successors; }; } private boolean remainingTasksInitializeANDNode(final List<Literal> tasks) { if (tasks.isEmpty()) { return false; } Literal followingTask = tasks.get(0); return followingTask.getPropertyName().contains("refine"); } private static boolean checkDoubleNodes(final List<INewNodeDescription<RTNNode, RTNEdge>> successors) { if (successors.size() != new HashSet<>(successors).size()) { logger.error("Doppelte Knoten im Nachfolger!"); return false; } return true; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/rtn/RTNNode.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.rtn; import java.util.List; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; public class RTNNode { private static int counter = 0; private final int id = counter ++; private final boolean andNode; private Monom state; private List<Literal> remainingTasks; public RTNNode(final boolean andNode, final Monom state, final List<Literal> remainingTasks) { super(); this.andNode = andNode; this.state = state; this.remainingTasks = remainingTasks; } public Monom getState() { return this.state; } public void setState(final Monom state) { this.state = state; } public List<Literal> getRemainingTasks() { return this.remainingTasks; } public void setRemainingTasks(final List<Literal> remainingTasks) { this.remainingTasks = remainingTasks; } public boolean isAndNode() { return this.andNode; } @Override public int hashCode() { return new HashCodeBuilder().append(this.state).append(this.remainingTasks).toHashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof RTNNode)) { return false; } RTNNode other = (RTNNode) obj; return new EqualsBuilder().append(other.state, this.state).append(other.remainingTasks, this.remainingTasks).isEquals(); } @Override public String toString() { return "RTNNode [id=" + this.id + ", state=" + this.state + ", remainingTasks=" + this.remainingTasks + "]"; } public int getId() { return this.id; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/rtn/RTNUtil.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.rtn; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import ai.libs.jaicore.graph.LabeledGraph; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCAction; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDNode; import ai.libs.jaicore.planning.hierarchical.problems.stn.MethodInstance; public class RTNUtil { private RTNUtil() { /* no instantiation desired */ } public static List<TFDNode> serializeGraph(final LabeledGraph<RTNNode, RTNEdge> g) { RTNNode root = g.getSources().iterator().next(); return serializeGraphUnderNode(g, root, new HashMap<>(), null, null); } private static List<TFDNode> serializeGraphUnderNode(final LabeledGraph<RTNNode, RTNEdge> g, final RTNNode n, final Map<ConstantParam,ConstantParam> context, final MethodInstance nextAppliedMethodInstance, final CEOCAction nextAppliedAction) { List<TFDNode> serialization = new ArrayList<>(); for (RTNNode np : g.getSuccessors(n)) { /* define context */ Map<ConstantParam, ConstantParam> mapExtension = g.getEdgeLabel(n, np).getContextRecreator(); Map<ConstantParam,ConstantParam> newContext = new HashMap<>(); newContext.putAll(context); if (mapExtension != null) { newContext.putAll(mapExtension); } Monom state = new Monom(); for (Literal l : n.getState()) { state.add(new Literal(l, newContext)); } List<Literal> tasks = new ArrayList<>(); for (Literal l : n.getRemainingTasks()) { tasks.add(new Literal(l, newContext)); } /* recover actual grounding for the action/method */ RTNEdge edge = g.getEdgeLabel(n, np); MethodInstance appliedMethodInstance = null; CEOCAction appliedAction = null; if (edge.getMethodInstance() != null) { Map<VariableParam,ConstantParam> grounding = new HashMap<>(edge.getMethodInstance().getGrounding()); for (Entry<VariableParam,ConstantParam> groundingEntry : grounding.entrySet()) { if (newContext.containsKey(groundingEntry.getValue())) { grounding.put(groundingEntry.getKey(), newContext.get(groundingEntry.getValue())); } } appliedMethodInstance = new MethodInstance(edge.getMethodInstance().getMethod(), grounding); } if (edge.getAppliedAction() != null) { Map<VariableParam,ConstantParam> grounding = new HashMap<>(edge.getAppliedAction().getGrounding()); for (Entry<VariableParam, ConstantParam> groundingEntry : grounding.entrySet()) { if (newContext.containsKey(groundingEntry.getValue())) { grounding.put(groundingEntry.getKey(), newContext.get(groundingEntry.getValue())); } } appliedAction = new CEOCAction(edge.getAppliedAction().getOperation(), grounding); } /* now FIRST insert this node (and the attributes on the edge will be attributed to the successor node) */ serialization.add(new TFDNode(state, tasks, nextAppliedMethodInstance, nextAppliedAction)); serialization.addAll(serializeGraphUnderNode(g, np, newContext, appliedMethodInstance, appliedAction)); } return serialization; } public static Collection<String> getClassesThatRemainToBeSeparated(final RTNNode node) { if (!getClustersThatWillBeRefined(node).isEmpty()) { return getClassesThatAreNotIsolated(node); } return node.getRemainingTasks().stream().filter(l -> l.getPropertyName().contains("declareClusterRepresentant")).map(l -> l.getConstantParams().get(1).getName()).collect(Collectors.toList()); } public static Collection<String> getClassesThatAreInAnyCluster(final RTNNode node) { return getClassesThatExistInState(node).stream().filter(c -> node.getState().stream().anyMatch(l -> l.getPropertyName().equals("in") && l.getConstantParams().get(0).getName().equals(c))).collect(Collectors.toList()); } public static Collection<String> getClassesThatAreInAClusterThatNeedsToBeRefined(final RTNNode node) { final Collection<String> clustersToBeRefined = getClustersThatWillBeRefined(node); Collection<String> remainingClasses = new HashSet<>(); for (Literal l : node.getState()) { if (l.getPropertyName().equals("in") && clustersToBeRefined.contains(l.getConstantParams().get(1).getName())) { remainingClasses.add(l.getConstantParams().get(0).getName()); } } return remainingClasses; } public static Collection<String> getClassesThatAreNotIsolated(final RTNNode node) { return getClassesThatAreInAnyCluster(node).stream().filter(c -> node.getState().stream().noneMatch(l -> l.getPropertyName().equals("represents") && l.getConstantParams().get(0).getName().equals(c))).collect(Collectors.toList()); } public static Collection<String> getClassesThatAreIsolated(final RTNNode node) { return getClassesThatAreInAnyCluster(node).stream().filter(c -> node.getState().stream().anyMatch(l -> l.getPropertyName().equals("represents") && l.getConstantParams().get(0).getName().equals(c))).collect(Collectors.toList()); } public static Collection<String> getClassesThatExistInState(final RTNNode node) { return node.getState().stream().filter(l -> l.getPropertyName().equals("in")).map(l -> l.getConstantParams().get(0).getName()).collect(Collectors.toList()); } public static Collection<String> getClustersThatExistInState(final RTNNode node) { return node.getState().stream().filter(l -> l.getPropertyName().equals("in")).map(l -> l.getConstantParams().get(1).getName()).collect(Collectors.toList()); } public static Collection<String> getClustersThatWillBeRefined(final RTNNode node) { Collection<String> clusters = new ArrayList<>(); for (Literal l : node.getRemainingTasks()) { if (l.getPropertyName().contains("refine")) { clusters.add(l.getConstantParams().get(0).getName()); } } return clusters; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/tfd/TFDGraphGenerator.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import org.api4.java.datastructure.graph.implicit.ISingleRootGenerator; import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.logging.ToJSONStringUtil; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.classical.algorithms.strips.forward.StripsUtil; import ai.libs.jaicore.planning.classical.problems.strips.Operation; import ai.libs.jaicore.planning.core.Action; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.TaskPlannerUtil; import ai.libs.jaicore.planning.hierarchical.problems.htn.IHTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.stn.Method; import ai.libs.jaicore.planning.hierarchical.problems.stn.MethodInstance; import ai.libs.jaicore.search.model.NodeExpansionDescription; public class TFDGraphGenerator implements IGraphGenerator<TFDNode, String>, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(TFDGraphGenerator.class); protected TaskPlannerUtil util = new TaskPlannerUtil(null); protected final IHTNPlanningProblem problem; protected final Map<String, Operation> primitiveTasks = new HashMap<>(); public TFDGraphGenerator(final IHTNPlanningProblem problem) { this.problem = problem; for (Operation op : problem.getDomain().getOperations()) { this.primitiveTasks.put(op.getName(), op); } } protected Collection<TFDNode> getSuccessorsResultingFromResolvingPrimitiveTask(final Monom state, final Literal taskToBeResolved, final List<Literal> remainingOtherTasks) throws InterruptedException { Collection<TFDNode> successors = new ArrayList<>(); for (Action applicableAction : this.util.getActionsForPrimitiveTaskThatAreApplicableInState(null, this.primitiveTasks.get(taskToBeResolved.getPropertyName()), taskToBeResolved, state)) { Monom stateCopy = new Monom(state); StripsUtil.updateState(stateCopy, applicableAction); successors.add(this.postProcessPrimitiveTaskNode(new TFDNode(stateCopy, remainingOtherTasks, null, applicableAction))); } return successors; } protected Collection<TFDNode> getSuccessorsResultingFromResolvingComplexTask(final Monom state, final Literal taskToBeResolved, final List<Literal> remainingOtherTasks) throws InterruptedException { Collection<TFDNode> successors = new ArrayList<>(); Collection<MethodInstance> applicableMethodInstances = this.util.getMethodInstancesForTaskThatAreApplicableInState(null, this.problem.getDomain().getMethods(), taskToBeResolved, state, remainingOtherTasks); if (this.logger.isDebugEnabled()) { this.logger.debug("Identified {} applicable method instances: {}" , applicableMethodInstances.size(), applicableMethodInstances.stream().map(mi -> mi.getMethod().getName() + "(" + mi.getGrounding() + ")").collect(Collectors.joining(", "))); } assert this.areLonelyMethodsContainedAtMostOnce(applicableMethodInstances); for (MethodInstance instance : applicableMethodInstances) { /* derive remaining network for this instance */ List<Literal> remainingTasks = this.stripTNPrefixes(this.util.getTaskChainOfTotallyOrderedNetwork(instance.getNetwork())); remainingTasks.addAll(remainingOtherTasks); successors.add(this.postProcessComplexTaskNode(new TFDNode(state, remainingTasks, instance, null))); } return successors; } private boolean areLonelyMethodsContainedAtMostOnce(final Collection<MethodInstance> instances) { List<Method> usedMethods = new ArrayList<>(); for (MethodInstance mi : instances) { if (!mi.getMethod().isLonely()) { continue; } boolean doubleUseDetected = usedMethods.contains(mi.getMethod()); assert !doubleUseDetected : "Lonely method " + mi.getMethod() + " has been generated several times as being applicable!"; usedMethods.add(mi.getMethod()); } return true; } protected List<Literal> stripTNPrefixes(final List<Literal> taskList) { return taskList.stream().map(l -> { String taskName = l.getPropertyName().substring(l.getPropertyName().indexOf('-') + 1, l.getPropertyName().length()); return new Literal(taskName, l.getParameters(), l.isPositive()); }).collect(Collectors.toList()); } /** * A hook for extending classes that can be used to change the nodes before they are attached * * @param node * @return */ protected TFDNode postProcessPrimitiveTaskNode(final TFDNode node) { return node; } /** * A hook for extending classes that can be used to change the nodes before they are attached * * @param node * @return */ protected TFDNode postProcessComplexTaskNode(final TFDNode node) { return node; } @Override public ISingleRootGenerator<TFDNode> getRootGenerator() { return () -> new TFDNode(this.problem.getInit(), this.stripTNPrefixes(new TaskPlannerUtil(null).getTaskChainOfTotallyOrderedNetwork(this.problem.getNetwork()))); } @Override public ISuccessorGenerator<TFDNode, String> getSuccessorGenerator() { return l -> { this.logger.debug("Starting node generation for node with tasks {}", l.getRemainingTasks()); Monom state = l.getState(); List<Literal> currentlyRemainingTasks = new ArrayList<>(l.getRemainingTasks()); if (currentlyRemainingTasks.isEmpty()) { return new ArrayList<>(); } Literal nextTask = currentlyRemainingTasks.get(0); currentlyRemainingTasks.remove(0); /* get the child nodes */ long creationStartTime = System.currentTimeMillis(); Collection<TFDNode> successors = this.primitiveTasks.containsKey(nextTask.getPropertyName()) ? this.getSuccessorsResultingFromResolvingPrimitiveTask(state, nextTask, currentlyRemainingTasks) : this.getSuccessorsResultingFromResolvingComplexTask(state, nextTask, currentlyRemainingTasks); if (successors.isEmpty()) { this.logger.warn("Could not produce any successors for next task {}", nextTask); return Arrays.asList(); } this.logger.info("Node generation finished and took {}ms. Generated {} successors.", System.currentTimeMillis() - creationStartTime, successors.size()); /* change order in remaining tasks based on numbered prefixes */ successors = successors.stream().map(this::orderRemainingTasksByPriority).collect(Collectors.toList()); /* derive successor descriptions from the nodes */ return successors.stream().map(n -> new NodeExpansionDescription<>(n, n.getAppliedAction() != null ? n.getAppliedAction().getEncoding() : n.getAppliedMethodInstance().getEncoding())).collect(Collectors.toList()); }; } public TFDNode orderRemainingTasksByPriority(final TFDNode node) { /* determine order of tasks based on the prefixes */ Pattern p = Pattern.compile("(\\d+)_"); List<Literal> unorderedLiterals = new ArrayList<>(); Map<Integer, List<Literal>> orderedLiterals = new HashMap<>(); node.getRemainingTasks().forEach(t -> { Matcher m = p.matcher(t.getPropertyName()); if (m.find()) { int order = Integer.parseInt(m.group(1)); if (!orderedLiterals.containsKey(order)) { orderedLiterals.put(order, new ArrayList<>()); } List<Literal> tasksWithorder = orderedLiterals.get(order); tasksWithorder.add(t); } else { unorderedLiterals.add(t); } }); /* reorganize task network */ List<Literal> newLiteralList = new ArrayList<>(); orderedLiterals.keySet().stream().sorted().forEach(order -> newLiteralList.addAll(orderedLiterals.get(order))); newLiteralList.addAll(unorderedLiterals); return new TFDNode(node.getState(), newLiteralList, node.getAppliedMethodInstance(), node.getAppliedAction()); } public boolean isPathSemanticallySubsumed(final List<TFDNode> path, final List<TFDNode> potentialSuperPath) throws InterruptedException { int n = path.size(); for (int i = 0; i < n; i++) { if (!path.get(i).equals(potentialSuperPath.get(i))) { return false; } } return true; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("util", this.util); fields.put("problem", this.problem); fields.put("primitiveTasks", this.primitiveTasks); return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); this.util.setLoggerName(name + ".util"); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/tfd/TFDNode.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.libs.jaicore.logging.ToJSONStringUtil; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.core.Action; import ai.libs.jaicore.planning.hierarchical.problems.stn.MethodInstance; public class TFDNode implements Serializable { private static final long serialVersionUID = 7710905829501897491L; private TFDRestProblem problem; private final MethodInstance appliedMethodInstance; private final Action appliedAction; private final boolean isGoal; public TFDNode(final Monom initialState, final List<Literal> remainingTasks) { this(initialState, remainingTasks, null, null); } public TFDNode(final MethodInstance appliedMethodInstance, final boolean isGoal) { super(); this.problem = null; this.appliedMethodInstance = appliedMethodInstance; this.appliedAction = null; this.isGoal = isGoal; } public TFDNode(final Action appliedAction, final boolean isGoal) { super(); this.problem = null; this.appliedAction = appliedAction; this.appliedMethodInstance = null; this.isGoal = isGoal; } public TFDNode(final Monom state, final List<Literal> remainingTasks, final MethodInstance appliedMethodInstance, final Action appliedAction) { super(); this.problem = new TFDRestProblem(state, remainingTasks); this.appliedMethodInstance = appliedMethodInstance; this.appliedAction = appliedAction; this.isGoal = remainingTasks.isEmpty(); } public TFDRestProblem getProblem() { return this.problem; } public Monom getState() { return this.problem.getState(); } public List<Literal> getRemainingTasks() { return this.problem.getRemainingTasks(); } public Action getAppliedAction() { return this.appliedAction; } public MethodInstance getAppliedMethodInstance() { return this.appliedMethodInstance; } public boolean isGoal() { return this.isGoal; } public void clear() { this.problem = null; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("isGoal", this.isGoal); fields.put("problem", this.problem); fields.put("appliedMethodInstance", this.appliedMethodInstance); fields.put("appliedAction", this.appliedAction); return ToJSONStringUtil.toJSONString("TFDNode", fields); // return "TFDNode [problem=" + this.problem + ", appliedMethodInstance=" + this.appliedMethodInstance + ", appliedAction=" + this.appliedAction + ", isGoal=" + this.isGoal + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.appliedAction == null) ? 0 : this.appliedAction.hashCode()); result = prime * result + ((this.appliedMethodInstance == null) ? 0 : this.appliedMethodInstance.hashCode()); result = prime * result + (this.isGoal ? 1231 : 1237); result = prime * result + ((this.problem == null) ? 0 : this.problem.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } TFDNode other = (TFDNode) obj; if (this.appliedAction == null) { if (other.appliedAction != null) { return false; } } else if (!this.appliedAction.equals(other.appliedAction)) { return false; } if (this.appliedMethodInstance == null) { if (other.appliedMethodInstance != null) { return false; } } else if (!this.appliedMethodInstance.equals(other.appliedMethodInstance)) { return false; } if (this.isGoal != other.isGoal) { return false; } if (this.problem == null) { if (other.problem != null) { return false; } } else if (!this.problem.equals(other.problem)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/tfd/TFDNodeInfoGenerator.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import ai.libs.jaicore.graphvisualizer.plugin.nodeinfo.NodeInfoGenerator; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.planning.core.Action; public class TFDNodeInfoGenerator implements NodeInfoGenerator<List<TFDNode>> { private static final String HTML_LI_OPEN = "<li>"; private static final String HTML_LI_CLOSE = "</li>"; private static final String HTML_UL_OPEN = "<ul>"; private static final String HTML_UL_CLOSE = "</ul>"; @Override public String generateInfoForNode(final List<TFDNode> path) { TFDNode head = path.get(path.size() - 1); StringBuilder sb = new StringBuilder(); if (head.getAppliedMethodInstance() != null || head.getAppliedAction() != null) { sb.append("<h2>Applied Instance</h2>"); sb.append(head.getAppliedMethodInstance() != null ? head.getAppliedMethodInstance().getEncoding() : head.getAppliedAction().getEncoding()); } sb.append("<h2>Remaining Tasks</h2>"); sb.append(HTML_UL_OPEN); for (Literal l : head.getRemainingTasks()) { sb.append(HTML_LI_OPEN); sb.append(l); sb.append(HTML_LI_CLOSE); } sb.append(HTML_UL_CLOSE); sb.append("<h2>Current State</h2>"); List<String> monomStrings = head.getProblem().getState().stream().sorted((l1, l2) -> l1.getPropertyName().compareTo(l2.getPropertyName())).map(Literal::toString).collect(Collectors.toList()); sb.append(HTML_UL_OPEN); for (String literal : monomStrings) { sb.append(HTML_LI_OPEN); sb.append(literal); sb.append(HTML_LI_CLOSE); } sb.append(HTML_UL_CLOSE); sb.append("<h2>Current Plan</h2>"); sb.append(HTML_UL_OPEN); for (Action a : path.stream().map(TFDNode::getAppliedAction).filter(Objects::nonNull).collect(Collectors.toList())) { sb.append(HTML_LI_OPEN); sb.append(a.getEncoding()); sb.append(HTML_LI_CLOSE); } sb.append(HTML_UL_CLOSE); return sb.toString(); } @Override public String getName() { return TFDNodeInfoGenerator.class.getName(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/tfd/TFDNodeUtil.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.StringUtil; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.theories.EvaluablePredicate; import ai.libs.jaicore.planning.classical.algorithms.strips.forward.StripsUtil; import ai.libs.jaicore.planning.core.Action; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.TaskPlannerUtil; import ai.libs.jaicore.planning.hierarchical.problems.stn.MethodInstance; public class TFDNodeUtil { private static Map<List<TFDNode>, Integer> cache = new HashMap<>(); private Logger logger = LoggerFactory.getLogger(TFDNodeUtil.class); private final TaskPlannerUtil util; private boolean checkArguments = true; public TFDNodeUtil(final Map<String, EvaluablePredicate> evaluablePlanningPredicates) { super(); this.util = new TaskPlannerUtil(evaluablePlanningPredicates); } private boolean checkDoubleRestProblemComputationOccurrence(final List<TFDNode> path) { if (cache.containsKey(path)) { this.logger.info("already seen path {} times", cache.get(path)); return false; } cache.put(path, 0); return true; } public List<TFDNode> getPathOfNode(final TFDNode node, final Map<TFDNode, TFDNode> parentMap) { /* compute path for node */ List<TFDNode> path = new ArrayList<>(); TFDNode current = node; while (current != null) { assert !path.contains(current) : "There is a loop in the path! Node " + node + " has been visited twice!\n\tThe full path is: \n\t\t" + StringUtil.implode(SetUtil.getInvertedCopyOfList(SetUtil.addAndGet(path, current)).stream().map(n -> n.toString()).collect(Collectors.toList()), "\n\t\t"); path.add(current); current = parentMap.get(current); } Collections.reverse(path); return path; } public TFDRestProblem getRestProblem(final List<TFDNode> path) { /* get last node in list with explicit rest problem formulation */ if (this.checkArguments && !this.checkDoubleRestProblemComputationOccurrence(path)) { throw new IllegalArgumentException("We must not generate the information of a node twice!"); } /* identify latest node that has an explicit rest problem attached */ TFDNode latest = null; for (TFDNode n : path) { if (n.getProblem() != null) { latest = n; } } /* set iterator to the last check point node */ Iterator<TFDNode> i = path.iterator(); TFDNode init = null; do { TFDNode n = i.next(); if (n == latest) { init = n; } } while (init == null); /* compute the rest problem going from there */ Monom state = new Monom(init.getState(), false); List<Literal> remainingTasks = new ArrayList<>(init.getRemainingTasks()); while (i.hasNext()) { TFDNode n = i.next(); /* compute updated state */ Action appliedAction = n.getAppliedAction(); if (appliedAction != null) { StripsUtil.updateState(state, appliedAction); } /* compute remaining tasks */ remainingTasks.remove(0); MethodInstance appliedMethodInstance = n.getAppliedMethodInstance(); if (appliedMethodInstance != null) { int j = 0; for (Literal remainingTask : this.util.getTaskChainOfTotallyOrderedNetwork(appliedMethodInstance.getNetwork())) { remainingTasks.add(j++, remainingTask); } } } return new TFDRestProblem(state, new ArrayList<>(remainingTasks)); } public Monom getState(final List<TFDNode> path) { return this.getRestProblem(path).getState(); } @SuppressWarnings("unused") private boolean checkConsistency(final Monom state, final Map<CNFFormula, Monom> addLists) { for (Literal lit : state) { if (lit.getPropertyName().equals("cluster")) { String clusterName = lit.getConstantParams().get(0).getName(); boolean foundSmallest = false; boolean foundRepresentant = false; for (Literal lit2 : state) { if (lit2.getPropertyName().equals("smallest") && lit2.getConstantParams().get(1).getName().equals(clusterName)) { foundSmallest = true; String smallestItem = lit2.getConstantParams().get(0).getName(); List<ConstantParam> params = new ArrayList<>(); params.add(new ConstantParam(smallestItem)); params.add(new ConstantParam(clusterName)); Literal lit3 = new Literal("in", params); if (!state.contains(lit3)) { throw new IllegalStateException("Smallest item in cluster " + clusterName + " is " + smallestItem + ", which is not even contained according to state " + state + "!"); } for (Literal lit4 : state) { if (lit4.getPropertyName().equals("in") && lit4.getConstantParams().get(1).getName().equals(clusterName) && state.contains(new Literal("bigger('" + smallestItem + "','" + lit4.getConstantParams().get(0).getName() + "')"))) { throw new IllegalStateException("Cluster " + clusterName + " has " + smallestItem + " as smallest item, but " + lit4.getConstantParams().get(0).getName() + " is smaller"); } } break; } if (lit2.getPropertyName().equals("represents") && lit2.getConstantParams().get(1).getName().equals(clusterName)) { foundRepresentant = true; break; } } if (!foundSmallest && !foundRepresentant) { throw new IllegalStateException("State " + state + " does not specify a smallest element for cluster " + clusterName + " after applying addList " + addLists); } } } return true; } public List<Literal> getRemainingTasks(final List<TFDNode> path) { return this.getRestProblem(path).getRemainingTasks(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/algorithms/forwarddecomposition/graphgenerators/tfd/TFDRestProblem.java
package ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.libs.jaicore.logging.ToJSONStringUtil; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; public class TFDRestProblem implements Serializable { private static final long serialVersionUID = 6946349883053172033L; private final Monom state; private final List<Literal> remainingTasks; public TFDRestProblem(final Monom state, final List<Literal> remainingTasks) { super(); this.state = state; this.remainingTasks = remainingTasks; } public Monom getState() { return this.state; } public List<Literal> getRemainingTasks() { return this.remainingTasks; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("state", this.state); fields.put("remainingTasks", remainingTasks); return ToJSONStringUtil.toJSONString(fields); // return "TFDRestProblem [state=" + this.state + ", remainingTasks=" + this.remainingTasks + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.remainingTasks == null) ? 0 : this.remainingTasks.hashCode()); result = prime * result + ((this.state == null) ? 0 : this.state.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } TFDRestProblem other = (TFDRestProblem) obj; if (this.remainingTasks == null) { if (other.remainingTasks != null) { return false; } } else if (!this.remainingTasks.equals(other.remainingTasks)) { return false; } if (this.state == null) { if (other.state != null) { return false; } } else if (!this.state.equals(other.state)) { return false; } return true; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocipstn/CEOCIPSTNPlanningDomain.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocipstn; import java.io.Serializable; import java.util.Collection; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCOperation; import ai.libs.jaicore.planning.hierarchical.problems.ceocstn.CEOCSTNPlanningDomain; @SuppressWarnings("serial") public class CEOCIPSTNPlanningDomain extends CEOCSTNPlanningDomain implements Serializable { public CEOCIPSTNPlanningDomain(Collection<? extends CEOCOperation> operations, Collection<? extends OCIPMethod> methods) { super(operations, methods); } @SuppressWarnings("unchecked") public Collection<? extends OCIPMethod> getMethods() { return (Collection<? extends OCIPMethod>)super.getMethods(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocipstn/CEOCIPSTNPlanningProblem.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocipstn; import java.util.HashMap; import java.util.Map; import ai.libs.jaicore.logging.ToJSONStringUtil; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.theories.EvaluablePredicate; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.ceociptfd.OracleTaskResolver; import ai.libs.jaicore.planning.hierarchical.problems.ceocstn.CEOCSTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; @SuppressWarnings("serial") public class CEOCIPSTNPlanningProblem extends CEOCSTNPlanningProblem { private final Map<String, EvaluablePredicate> evaluablePlanningPredicates; private final Map<String, OracleTaskResolver> oracleResolvers; public CEOCIPSTNPlanningProblem(CEOCIPSTNPlanningDomain domain, CNFFormula knowledge, Monom init, TaskNetwork network, Map<String, EvaluablePredicate> evaluablePredicates, Map<String, OracleTaskResolver> oracleResolvers) { super(domain, knowledge, init, network); this.evaluablePlanningPredicates = evaluablePredicates; this.oracleResolvers = oracleResolvers; } @Override public CEOCIPSTNPlanningDomain getDomain() { return (CEOCIPSTNPlanningDomain)super.getDomain(); } public Map<String, EvaluablePredicate> getEvaluablePlanningPredicates() { return evaluablePlanningPredicates; } public Map<String, OracleTaskResolver> getOracleResolvers() { return oracleResolvers; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((evaluablePlanningPredicates == null) ? 0 : evaluablePlanningPredicates.hashCode()); result = prime * result + ((oracleResolvers == null) ? 0 : oracleResolvers.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; CEOCIPSTNPlanningProblem other = (CEOCIPSTNPlanningProblem) obj; if (evaluablePlanningPredicates == null) { if (other.evaluablePlanningPredicates != null) return false; } else if (!evaluablePlanningPredicates.equals(other.evaluablePlanningPredicates)) return false; if (oracleResolvers == null) { if (other.oracleResolvers != null) return false; } else if (!oracleResolvers.equals(other.oracleResolvers)) return false; return true; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("evaluablePlanningPredicates", this.evaluablePlanningPredicates); fields.put("oracleResolvers", this.oracleResolvers); fields.put("super", super.toString()); return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocipstn/OCIPMethod.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocipstn; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import ai.libs.jaicore.basic.StringUtil; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.hierarchical.problems.ceocstn.OCMethod; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; @SuppressWarnings("serial") public class OCIPMethod extends OCMethod { private final Monom evaluablePrecondition; public OCIPMethod(final String name, final String parameters, final Literal task, final Monom precondition, final TaskNetwork network, final boolean lonely, final String outputs, final Monom evaluablePrecondition) { this(name, Arrays.asList(StringUtil.explode(parameters, ",")).stream().map(s -> new VariableParam(s.trim())).collect(Collectors.toList()), task, precondition, network, lonely, Arrays.asList(StringUtil.explode(outputs, ",")).stream().map(s -> new VariableParam(s.trim())).collect(Collectors.toList()), evaluablePrecondition); } public OCIPMethod(final String name, final List<VariableParam> parameters, final Literal task, final Monom precondition, final TaskNetwork network, final boolean lonely, final List<VariableParam> outputs, final Monom evaluablePrecondition) { super(name, parameters, task, precondition, network, lonely, outputs); this.evaluablePrecondition = evaluablePrecondition; } public Monom getEvaluablePrecondition() { return this.evaluablePrecondition; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((this.evaluablePrecondition == null) ? 0 : this.evaluablePrecondition.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (this.getClass() != obj.getClass()) { return false; } OCIPMethod other = (OCIPMethod) obj; if (this.evaluablePrecondition == null) { if (other.evaluablePrecondition != null) { return false; } } else if (!this.evaluablePrecondition.equals(other.evaluablePrecondition)) { return false; } return true; } @Override public String toString() { return "OCIPMethod [" + super.toString() + ", evaluablePrecondition=" + this.evaluablePrecondition + "]"; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocipstn/OCIPMethodInstance.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocipstn; import java.util.Map; import ai.libs.jaicore.logic.fol.structure.ConstantParam; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.hierarchical.problems.ceocstn.OCMethodInstance; import ai.libs.jaicore.planning.hierarchical.problems.stn.Method; @SuppressWarnings("serial") public class OCIPMethodInstance extends OCMethodInstance { public OCIPMethodInstance(Method method, Map<VariableParam, ConstantParam> grounding) { super(method, grounding); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocipstn
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocipstn/converters/CEOCIPSTN2JSHOP2.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocipstn.converters; import java.io.BufferedWriter; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.Map; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.LiteralParam; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCOperation; import ai.libs.jaicore.planning.hierarchical.problems.ceocipstn.CEOCIPSTNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.htn.AShop2Converter; import ai.libs.jaicore.planning.hierarchical.problems.stn.Method; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; public class CEOCIPSTN2JSHOP2 extends AShop2Converter { /** * Writes the given Problem into the output file * * @param problem * the problem form which the domain should be written into a file * @param output * into this file * @throws IOException */ public void printDomain(final Writer writer, final String name) throws IOException { BufferedWriter bw = new BufferedWriter(writer); // Writing of the domain file bw.write("(defdomain " + name + "\n " + this.indent(1) + " (\n"); bw.flush(); bw.write(this.indent(1) + ")\n"); bw.write(")"); bw.flush(); } /** * Prints the operations of the domain into a FIle * * @param bw * @param operation * @param i * @throws IOException */ public void printOperation(final BufferedWriter bw, final CEOCOperation operation, final int i) throws IOException { bw.write(this.indent(i) + "(:operator (!" + this.maskString(operation.getName())); // print the parameter of the operation for (LiteralParam param : operation.getParams()) { bw.write(" ?" + param.getName()); bw.flush(); } bw.write(")\n "); // print Preconditions this.printMonom(bw, operation.getPrecondition(), i + 1); // print the delete List of the operation Map<CNFFormula, Monom> deleteLists = operation.getDeleteLists(); boolean containsUnconditionalDelete = deleteLists.containsKey(new CNFFormula()); if (deleteLists.size() > 1 || deleteLists.size() == 1 && !containsUnconditionalDelete) { throw new IllegalArgumentException("The operation " + operation.getName() + " contains conditional deletes, which cannot be converted to JSHOP2 format."); } Monom deleteList = containsUnconditionalDelete ? deleteLists.get(new CNFFormula()) : new Monom(); this.printMonom(bw, deleteList, i + 1); // print the add List of the operation Map<CNFFormula, Monom> addLists = operation.getAddLists(); boolean containsUnconditionalAdd = deleteLists.containsKey(new CNFFormula()); Monom addList = containsUnconditionalAdd ? addLists.get(new CNFFormula()) : new Monom(); if (addLists.size() > 1 || addLists.size() == 1 && !containsUnconditionalAdd) { throw new IllegalArgumentException("The operation " + operation.getName() + " contains conditional adds, which cannot be converted to JSHOP2 format."); } this.printMonom(bw, addList, i + 1); bw.write(this.indent(i) + ")\n\n"); bw.flush(); } /** * Prints a single literal into the bufferedwriter * * @param bw * the bufferedwriter which determines the output * @param literal * the literal to write * @throws IOException */ public void printLiteral(final BufferedWriter bw, final Literal lit) throws IOException { bw.write(" ("); boolean negated = lit.isNegated(); if (negated) { bw.write("not("); } bw.write(this.maskString(lit.getPropertyName())); for (LiteralParam param : lit.getParameters()) { bw.write(" ?" + this.maskString(param.getName())); } if (negated) { bw.write(")"); } bw.write(")"); bw.flush(); } /** * Prints a mehtod into the given writer * * @param bw * the writer where the method should be written to * @param method * the method to write * @param i * the number of indents infront of the method * @throws IOException */ public void printMethod(final BufferedWriter bw, final Method method, final int i) throws IOException { bw.write(this.indent(i) + "(:method"); this.printLiteral(bw, method.getTask()); bw.write("\n"); bw.write(this.indent(i + 1) + method.getName()); bw.write("\n"); // write the precondition into the file this.printMonom(bw, method.getPrecondition(), i + 1); // print the tasknetwork this.printNetwork(bw, method.getNetwork(), i + 1); bw.write(this.indent(i) + ")\n"); bw.flush(); } /** * prints an arbitrary literal of the network * * @param bw * @param lit * @param network * @param i * @throws IOException */ private void printNetwork(final BufferedWriter bw, final TaskNetwork network, final int i) throws IOException { bw.write(this.indent(i) + "("); Literal next = network.getRoot(); while (next != null) { this.printLiteral(bw, next); Iterator<Literal> it = network.getSuccessors(next).iterator(); next = it.hasNext() ? it.next() : null; } bw.write(")\n"); } public void printProblem(final CEOCIPSTNPlanningProblem problem, final Writer writer, final String name) throws IOException { BufferedWriter bw = new BufferedWriter(writer); // Writing of the domain file bw.write("(defproblem problem " + name + "\n"); bw.write(this.indent(1) + "(\n"); // print inital state this.printMonom(bw, problem.getInit(), 2, true); bw.write(this.indent(1) + ")\n"); bw.write(this.indent(1) + "(\n"); // print tasknetwork this.printNetwork(bw, problem.getNetwork(), 2); bw.write(this.indent(1) + ")\n"); bw.write(")"); bw.flush(); } public String maskString(String str) { str = str.replaceAll("\\.", "_"); str = str.replaceAll(":", "__"); str = str.replaceAll("<", "___"); str = str.replaceAll(">", "___"); str = str.replaceAll("\\[\\]", "Array"); return str; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocstn/CEOCSTNPlanningDomain.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocstn; import java.util.Collection; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCOperation; import ai.libs.jaicore.planning.hierarchical.problems.stn.STNPlanningDomain; public class CEOCSTNPlanningDomain extends STNPlanningDomain { private static final long serialVersionUID = -7462960653106425941L; public CEOCSTNPlanningDomain(final Collection<? extends CEOCOperation> operations, final Collection<? extends OCMethod> methods) { super(operations, methods); } @Override public void checkValidity() { for (CEOCOperation op : this.getOperations()) { boolean isValid = !(op.getAddLists().isEmpty() && op.getDeleteLists().isEmpty()); if (!isValid) { throw new IllegalArgumentException("Degenerated planning problem. Operation \"" + op.getName() + "\" has empty add list and empty delete list!"); } } } @Override @SuppressWarnings("unchecked") public Collection<? extends CEOCOperation> getOperations() { return (Collection<CEOCOperation>)super.getOperations(); } @Override @SuppressWarnings("unchecked") public Collection<? extends OCMethod> getMethods() { return (Collection<? extends OCMethod>)super.getMethods(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocstn/CEOCSTNPlanningProblem.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocstn; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.hierarchical.problems.stn.STNPlanningProblem; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; @SuppressWarnings("serial") public class CEOCSTNPlanningProblem extends STNPlanningProblem { public CEOCSTNPlanningProblem(CEOCSTNPlanningDomain domain, CNFFormula knowledge, Monom init, TaskNetwork network) { super(domain, knowledge, init, network); } @Override public CEOCSTNPlanningDomain getDomain() { return (CEOCSTNPlanningDomain)super.getDomain(); } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocstn/CEOCSTNUtil.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocstn; import java.util.List; import java.util.stream.Collectors; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.classical.algorithms.strips.forward.StripsUtil; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCAction; import ai.libs.jaicore.planning.hierarchical.algorithms.forwarddecomposition.graphgenerators.tfd.TFDNode; public class CEOCSTNUtil { public static List<CEOCAction> extractPlanFromSolutionPath(List<TFDNode> solution) { return solution.stream().map(np -> (CEOCAction) np.getAppliedAction()).filter(a -> a != null).collect(Collectors.toList()); } public static Monom getStateAfterPlanExecution(Monom init, List<CEOCAction> plan) { Monom state = new Monom(init); for (CEOCAction a : plan) StripsUtil.updateState(state, a); return state; } }
0
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocstn/OCMethod.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocstn; import java.util.List; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.hierarchical.problems.stn.Method; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; @SuppressWarnings("serial") public class OCMethod extends Method { private final List<VariableParam> outputs; public OCMethod(final String name, final List<VariableParam> parameters, final Literal task, final Monom precondition, final TaskNetwork network, final boolean lonely, final List<VariableParam> outputs) { super(name, parameters, task, precondition, network, lonely); this.outputs = outputs; } public List<VariableParam> getOutputs() { return this.outputs; } @Override public int hashCode() { return new HashCodeBuilder().append(super.hashCode()).append(this.outputs).toHashCode(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof OCMethod)) { return false; } OCMethod other = (OCMethod) obj; return new EqualsBuilder().append(this.outputs, other.outputs).isEquals(); } }