index
int64
repo_id
string
file_path
string
content
string
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/OCMethodInstance.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocstn; 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.stn.Method; import ai.libs.jaicore.planning.hierarchical.problems.stn.MethodInstance; @SuppressWarnings("serial") public class OCMethodInstance extends MethodInstance { public OCMethodInstance(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/ceocstn
java-sources/ai/libs/jaicore-planning/0.2.7/ai/libs/jaicore/planning/hierarchical/problems/ceocstn/converters/CEOCSTN2Shop2.java
package ai.libs.jaicore.planning.hierarchical.problems.ceocstn.converters; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import javax.swing.JFileChooser; 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.logic.fol.structure.VariableParam; import ai.libs.jaicore.planning.classical.problems.ceoc.CEOCOperation; import ai.libs.jaicore.planning.hierarchical.problems.ceocstn.CEOCSTNPlanningProblem; 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 CEOCSTN2Shop2 extends AShop2Converter { private String packageName; /** * 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 File output) throws IOException { FileWriter fileWriter = new FileWriter(output); try (BufferedWriter bw = new BufferedWriter(fileWriter)) { String fileName = output.getName(); fileName = fileName.substring(0, fileName.indexOf('.')).toLowerCase(); // print the package if one is availiable if (!this.packageName.isEmpty()) { bw.write("(int-package : " + this.packageName + ")"); bw.flush(); } // Writing of the domain file bw.write("(defun define-" + fileName + "-domain()\n"); bw.write(this.indent(1) + "(let (( * define-silently* t))\n"); bw.flush(); bw.write(this.indent(1) + "(defdomain (" + fileName + " :redinfe-ok t)(\n"); bw.flush(); bw.write(this.indent(1) + ")\n"); bw.write("\t)\n)"); 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 (!" + operation.getName()); // print the parameter of the operation for (VariableParam param : operation.getParams()) { bw.write(" ?" + param.getName()); bw.flush(); } bw.write(")\n "); // print Preconditions this.printMonom(bw, operation.getPrecondition(), 4); // print the delete List of the operation this.printMonomMap(bw, operation.getDeleteLists(), 4); // print the add List of the operation this.printMonomMap(bw, operation.getAddLists(), 4); bw.write(this.indent(i) + ")\n\n"); bw.flush(); } /** * Prints a Map with CNFFormula as keys and Monom to the bufferedwriter * * @param bw * the bufferedwriter which determines the goal location * @param map * the map contianing the monoms * @param i * the number if indents to create in front of the map * @throws IOException */ private void printMonomMap(final BufferedWriter bw, final Map<CNFFormula, Monom> map, final int i) throws IOException { for (Monom member : map.values()) { this.printMonom(bw, member, i); } 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 */ @Override public void printLiteral(final BufferedWriter bw, final Literal lit) throws IOException { bw.write(" ("); bw.write(lit.getProperty()); for (LiteralParam param : lit.getParameters()) { bw.write(" ?" + param.getName()); } 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 (" + method.getName()); for (LiteralParam param : method.getParameters()) { bw.write(" ?" + param.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().getRoot(), method.getNetwork(), true, 4); bw.write(this.indent(i) + ")\n"); bw.flush(); } /** * prints the root of the network * * @param bw * @param lit * @param network * @param ordered * @param i * @throws IOException */ private void printNetwork(final BufferedWriter bw, final Literal lit, final TaskNetwork network, final boolean ordered, final int i) throws IOException { bw.write(this.indent(i) + "("); if (lit.equals(network.getRoot())) { if (ordered) { bw.write(":ordered\n"); } else { bw.write(":unordered\n"); } } // write the parameters of the current literal bw.write(this.indent(i + 1) + "(" + lit.getProperty()); bw.flush(); for (LiteralParam param : lit.getParameters()) { bw.write(" ?" + param.getName()); } bw.write(")\n"); for (Literal literal : network.getSuccessors(lit)) { this.printNetwork(bw, literal, 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 Literal lit, final int i) throws IOException { bw.write(this.indent(i) + "(" + lit.getProperty()); for (LiteralParam param : lit.getParameters()) { bw.write(" ?" + param.getName()); } bw.write(")\n"); } public void printProblem(final CEOCSTNPlanningProblem problem, final File output) throws IOException { FileWriter fileWriter = new FileWriter(output); try (BufferedWriter bw = new BufferedWriter(fileWriter)) { String fileName = output.getName(); fileName = fileName.substring(0, fileName.indexOf('.')).toLowerCase(); // print the package if one is availiable if (!this.packageName.isEmpty()) { bw.write("(int-package : " + this.packageName + ")"); bw.flush(); } // Writing of the domain file bw.write("(make-problem '" + fileName + "'-01 ' " + fileName + "\n"); bw.write(this.indent(1) + "(\n"); // print inital state this.printMonom(bw, problem.getInit(), 2, true); // print tasknetwork this.printNetwork(bw, problem.getNetwork().getRoot(), 2); bw.write(this.indent(1) + ")\n"); bw.write(")"); bw.flush(); } } public void print(final CEOCSTNPlanningProblem problem) throws IOException { this.print(problem, ""); } public void print(final CEOCSTNPlanningProblem problem, final String packageName) throws IOException { this.packageName = packageName; JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Domain-File"); chooser.showOpenDialog(null); File domainFile = chooser.getSelectedFile(); this.printDomain(domainFile); chooser.setDialogTitle("Problem-File"); chooser.showOpenDialog(null); File problemFile = chooser.getSelectedFile(); this.printProblem(problem, problemFile); } }
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/htn/AShop2Converter.java
package ai.libs.jaicore.planning.hierarchical.problems.htn; import java.io.BufferedWriter; import java.io.IOException; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.logic.fol.structure.Monom; public abstract class AShop2Converter { /** * Prints a single monom into the bufferedwriter * * @param bw * the bufferedwriter which determines the output * @param monom * the monom to write * @param i * the number if indents infront of the monom * @throws IOException */ public void printMonom(final BufferedWriter bw, final Monom monom, final int i) throws IOException { this.printMonom(bw, monom, i, false); } /** * Prints a single monom into the bufferedwriter * * @param bw * the bufferedwriter which determines the output * @param monom * the monom to write * @param i * the number if indents infront of the monom * @throws IOException */ public void printMonom(final BufferedWriter bw, final Monom monom, final int i, final boolean newline) throws IOException { bw.write(this.indent(i) + "("); for (Literal lit : monom) { this.printLiteral(bw, lit); if (newline) { bw.write("\n" + this.indent(i) + " "); } } bw.write(")\n"); bw.flush(); } public String indent(final int numberOfIntends) { StringBuilder r = new StringBuilder(); for (int i = 0; i < numberOfIntends; i++) { r.append("\t"); } return r.toString(); } public abstract void printLiteral(final BufferedWriter bw, final Literal lit) throws IOException; }
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/htn/CostSensitiveHTNPlanningProblem.java
package ai.libs.jaicore.planning.hierarchical.problems.htn; import java.util.HashMap; import java.util.Map; import org.api4.java.common.attributedobjects.IObjectEvaluator; 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.planning.core.interfaces.IPlan; import ai.libs.jaicore.planning.hierarchical.problems.stn.STNPlanningDomain; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; public class CostSensitiveHTNPlanningProblem<P extends IHTNPlanningProblem, V extends Comparable<V>> implements IHTNPlanningProblem { private final P corePlanningProblem; private final IObjectEvaluator<IPlan, V> planEvaluator; public CostSensitiveHTNPlanningProblem(final P corePlanningProblem, final IObjectEvaluator<IPlan, V> planEvaluator) { super(); this.corePlanningProblem = corePlanningProblem; this.planEvaluator = planEvaluator; } public P getCorePlanningProblem() { return this.corePlanningProblem; } public IObjectEvaluator<IPlan, V> getPlanEvaluator() { return this.planEvaluator; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("corePlanningProblem", this.corePlanningProblem); fields.put("planEvaluator", this.planEvaluator); return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields); } @Override public STNPlanningDomain getDomain() { return this.corePlanningProblem.getDomain(); } @Override public CNFFormula getKnowledge() { return this.corePlanningProblem.getKnowledge(); } @Override public Monom getInit() { return this.corePlanningProblem.getInit(); } @Override public TaskNetwork getNetwork() { return this.corePlanningProblem.getNetwork(); } }
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/htn/CostSensitivePlanningToSearchProblemReduction.java
package ai.libs.jaicore.planning.hierarchical.problems.htn; 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.IEvaluatedPath; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.planning.core.EvaluatedPlan; 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.probleminputs.GraphSearchWithPathEvaluationsInput; public class CostSensitivePlanningToSearchProblemReduction<N, A, V extends Comparable<V>, I1 extends IHTNPlanningProblem, I2 extends IPathSearchWithPathEvaluationsInput<N, A, V>, O2 extends IEvaluatedPath<N, A, V>> implements IHierarchicalPlanningToGraphSearchReduction<N, A, CostSensitiveHTNPlanningProblem<I1, V>, IEvaluatedPlan<V>, I2, O2> { private final IHierarchicalPlanningToGraphSearchReduction<N, A, I1, IPlan, ? extends IPathSearchInput<N, A>, ILabeledPath<N, A>> baseReduction; private final AlgorithmicProblemReduction<? super IPathSearchWithPathEvaluationsInput<N, A, V>, ? super EvaluatedSearchGraphPath<N, A, V>, I2, O2> forwardReduction; public CostSensitivePlanningToSearchProblemReduction(final IHierarchicalPlanningToGraphSearchReduction<N, A, I1, IPlan, ? extends IPathSearchInput<N, A>, ILabeledPath<N, A>> baseReduction, final AlgorithmicProblemReduction<? super IPathSearchWithPathEvaluationsInput<N, A, V>, ? super EvaluatedSearchGraphPath<N, A, V>, I2, O2> forwardReduction) { super(); this.baseReduction = baseReduction; this.forwardReduction = forwardReduction; } /** * This method operates in three steps: * 1) it derives a general graph search problem from the given planning problem * 2) it combines the obtained graph search problem with a path evaluation function into a GrahhSearchWithPathEvaluationsInput * 3) it derives a potentially more informed GraphSearchInput * * The last process is called the forward reduction. The output does not change. */ @Override public I2 encodeProblem(final CostSensitiveHTNPlanningProblem<I1, V> problem) { return this.forwardReduction.encodeProblem(new GraphSearchWithPathEvaluationsInput<>(this.baseReduction.encodeProblem(problem.getCorePlanningProblem()), new PlanEvaluationBasedSearchEvaluator<>(problem.getPlanEvaluator(), this.baseReduction))); } @Override public IEvaluatedPlan<V> decodeSolution(final O2 solution) { return new EvaluatedPlan<>(this.baseReduction.decodeSolution(solution), solution.getScore()); } }
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/htn/CostSensitivePlanningToStandardSearchProblemReduction.java
package ai.libs.jaicore.planning.hierarchical.problems.htn; 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.IEvaluatedPath; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.basic.algorithm.reduction.IdentityReduction; import ai.libs.jaicore.planning.core.interfaces.IPlan; public class CostSensitivePlanningToStandardSearchProblemReduction<I extends IHTNPlanningProblem, N, A, V extends Comparable<V>> extends CostSensitivePlanningToSearchProblemReduction<N, A, V, I, IPathSearchWithPathEvaluationsInput<N, A, V>, IEvaluatedPath<N, A, V>> { public CostSensitivePlanningToStandardSearchProblemReduction(final IHierarchicalPlanningToGraphSearchReduction<N, A, I, IPlan, ? extends IPathSearchInput<N, A>, ILabeledPath<N, A>> baseReduction) { super(baseReduction, new IdentityReduction<>()); } }
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/htn/IHTNPlanningProblem.java
package ai.libs.jaicore.planning.hierarchical.problems.htn; import java.io.Serializable; import ai.libs.jaicore.logic.fol.structure.CNFFormula; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.hierarchical.problems.stn.STNPlanningDomain; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; public interface IHTNPlanningProblem extends Serializable { public STNPlanningDomain getDomain(); public CNFFormula getKnowledge(); public Monom getInit(); public TaskNetwork getNetwork(); }
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/htn/IHierarchicalPlanningToGraphSearchReduction.java
package ai.libs.jaicore.planning.hierarchical.problems.htn; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.planning.core.interfaces.IPlan; public interface IHierarchicalPlanningToGraphSearchReduction<N, A, I1 extends IHTNPlanningProblem, O1 extends IPlan, I2 extends IPathSearchInput<N, A>, O2 extends ILabeledPath<N, A>> extends AlgorithmicProblemReduction<I1, O1, I2, O2> { }
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/htn/PlanEvaluationBasedSearchEvaluator.java
package ai.libs.jaicore.planning.hierarchical.problems.htn; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException; import org.api4.java.common.attributedobjects.IObjectEvaluator; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.datastructure.graph.ILabeledPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.planning.core.interfaces.IPlan; public class PlanEvaluationBasedSearchEvaluator<N, A, V extends Comparable<V>> implements IPathEvaluator<N, A, V>, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(PlanEvaluationBasedSearchEvaluator.class); private final IObjectEvaluator<IPlan, V> planEvaluator; private final IHierarchicalPlanningToGraphSearchReduction<N, A, ?, IPlan, ? extends IPathSearchInput<N, A>, ILabeledPath<N, A>> baseReduction; public PlanEvaluationBasedSearchEvaluator(final IObjectEvaluator<IPlan, V> planEvaluator, final IHierarchicalPlanningToGraphSearchReduction<N, A, ?, IPlan, ? extends IPathSearchInput<N, A>, ILabeledPath<N, A>> baseReduction) { super(); this.planEvaluator = planEvaluator; this.baseReduction = baseReduction; } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); if (this.planEvaluator instanceof ILoggingCustomizable) { ((ILoggingCustomizable) this.planEvaluator).setLoggerName(name + ".pe"); this.logger.info("Setting logger of plan evaluator {} to {}.pe", this.planEvaluator.getClass().getName(), name); } else { this.logger.info("Plan evaluator {} is not configurable for logging, so not configuring it.", this.planEvaluator); } } @Override public V evaluate(final ILabeledPath<N, A> solutionPath) throws InterruptedException, PathEvaluationException { this.logger.info("Forwarding evaluation to plan evaluator {}", this.planEvaluator.getClass().getName()); try { return this.planEvaluator.evaluate(this.baseReduction.decodeSolution(solutionPath)); } catch (ObjectEvaluationFailedException e) { throw new PathEvaluationException("Forwarding exception", e); } } }
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/htn/UniformCostHTNPlanningProblem.java
package ai.libs.jaicore.planning.hierarchical.problems.htn; public class UniformCostHTNPlanningProblem extends CostSensitiveHTNPlanningProblem<IHTNPlanningProblem, Double> { private static final long serialVersionUID = -547118545330012925L; public UniformCostHTNPlanningProblem(final IHTNPlanningProblem corePlanningProblem) { super(corePlanningProblem, n -> n.getActions().size() * 1.0); } }
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/rtn/RTNMethod.java
package ai.libs.jaicore.planning.hierarchical.problems.rtn; import java.util.List; 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; @SuppressWarnings("serial") public class RTNMethod extends OCMethod { public RTNMethod(String name, List<VariableParam> parameters, Literal task, Monom precondition, RTaskNetwork network, boolean lonely, List<VariableParam> outputs) { super(name, parameters, task, precondition, network, lonely, outputs); } }
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/rtn/RTNPlanningDomain.java
package ai.libs.jaicore.planning.hierarchical.problems.rtn; 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 RTNPlanningDomain extends CEOCSTNPlanningDomain { public RTNPlanningDomain(Collection<? extends CEOCOperation> operations, Collection<? extends RTNMethod> methods) { super(operations, methods); } @SuppressWarnings("unchecked") public Collection<RTNMethod> getMethods() { return (Collection<RTNMethod>)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/rtn/RTNPlanningProblem.java
package ai.libs.jaicore.planning.hierarchical.problems.rtn; import ai.libs.jaicore.logic.fol.structure.Monom; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; public class RTNPlanningProblem { private final RTNPlanningDomain domain; private final Monom init; private final TaskNetwork network; public RTNPlanningProblem(final RTNPlanningDomain domain, final Monom init, final TaskNetwork network) { super(); this.domain = domain; this.init = init; this.network = network; } public RTNPlanningDomain getDomain() { return this.domain; } public Monom getInit() { return this.init; } public TaskNetwork getNetwork() { return this.network; } @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.init == null) ? 0 : this.init.hashCode()); result = prime * result + ((this.network == null) ? 0 : this.network.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; } RTNPlanningProblem other = (RTNPlanningProblem) obj; if (this.domain == null) { if (other.domain != null) { return false; } } else if (!this.domain.equals(other.domain)) { return false; } if (this.init == null) { if (other.init != null) { return false; } } else if (!this.init.equals(other.init)) { return false; } if (this.network == null) { if (other.network != null) { return false; } } else if (!this.network.equals(other.network)) { 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/rtn/RTaskNetwork.java
package ai.libs.jaicore.planning.hierarchical.problems.rtn; import java.util.Map; import ai.libs.jaicore.logic.fol.structure.Literal; import ai.libs.jaicore.planning.hierarchical.problems.stn.TaskNetwork; @SuppressWarnings("serial") public class RTaskNetwork extends TaskNetwork { private final Map<Literal,StateReducer> reducers; public RTaskNetwork(TaskNetwork network, Map<Literal, StateReducer> reducers) { super(network); this.reducers = reducers; } public Map<Literal, StateReducer> getReducers() { return reducers; } }
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/rtn/StateReducer.java
package ai.libs.jaicore.planning.hierarchical.problems.rtn; import ai.libs.jaicore.logic.fol.structure.Monom; public interface StateReducer { public Monom reduce(Monom 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/stn/Method.java
package ai.libs.jaicore.planning.hierarchical.problems.stn; import java.io.Serializable; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; 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 Method implements Serializable { private static final long serialVersionUID = 704153871624796863L; private final String name; private final List<VariableParam> parameters; private final Literal task; private final Monom precondition; private final TaskNetwork network; private final boolean lonely; public Method(final String name, final List<VariableParam> parameters, final Literal task, final Monom precondition, final TaskNetwork network, final boolean lonely) { super(); this.name = name; this.parameters = parameters; this.task = task; this.precondition = precondition; this.network = network; this.lonely = lonely; if (!this.doAllParamsPreconditionOccurInParameterList()) { Set<VariableParam> undeclaredVars = new HashSet<>(); for (Literal l : precondition) { undeclaredVars.addAll(SetUtil.difference(l.getVariableParams(), this.parameters)); } throw new IllegalArgumentException("Invalid method " + name + ". There are parameters in the precondition that do not occur in the parameter list:" + undeclaredVars.stream().map(v -> "\n\t- " + v.getName()).collect(Collectors.joining())); } if (!this.doAllParamsInNetworkOccurInParameterList()) { Set<VariableParam> undeclaredVars = new HashSet<>(); for (Literal l : this.network.getItems()) { undeclaredVars.addAll(SetUtil.difference(l.getVariableParams(), this.parameters)); } throw new IllegalArgumentException("Invalid method " + name + ". There are parameters in the task network that do not occur in the parameter list:" + undeclaredVars.stream().map(v -> "\n\t- " + v.getName()).collect(Collectors.joining())); } } private boolean doAllParamsInNetworkOccurInParameterList() { for (Literal l : this.network.getItems()) { if (!SetUtil.difference(l.getVariableParams(), this.parameters).isEmpty()) { return false; } } return true; } private boolean doAllParamsPreconditionOccurInParameterList() { for (Literal l : this.precondition) { if (!SetUtil.difference(l.getVariableParams(), this.parameters).isEmpty()) { return false; } } return true; } public String getName() { return this.name; } public List<VariableParam> getParameters() { return this.parameters; } public Literal getTask() { return this.task; } public Monom getPrecondition() { return this.precondition; } public TaskNetwork getNetwork() { return this.network; } public boolean isLonely() { return this.lonely; } @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.network == null) ? 0 : this.network.hashCode()); result = prime * result + ((this.parameters == null) ? 0 : this.parameters.hashCode()); result = prime * result + ((this.precondition == null) ? 0 : this.precondition.hashCode()); result = prime * result + ((this.task == null) ? 0 : this.task.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; } Method other = (Method) obj; if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } if (this.network == null) { if (other.network != null) { return false; } } else if (!this.network.equals(other.network)) { return false; } if (this.parameters == null) { if (other.parameters != null) { return false; } } else if (!this.parameters.equals(other.parameters)) { return false; } if (this.precondition == null) { if (other.precondition != null) { return false; } } else if (!this.precondition.equals(other.precondition)) { return false; } if (this.task == null) { if (other.task != null) { return false; } } else if (!this.task.equals(other.task)) { return false; } return true; } @Override public String toString() { return "Method [name=" + this.name + ", parameters=" + this.parameters + ", task=" + this.task + ", precondition=" + this.precondition + ", network=" + this.network.getLineBasedStringRepresentation() + ", lonely=" + this.lonely + "]"; } }
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/stn/MethodInstance.java
package ai.libs.jaicore.planning.hierarchical.problems.stn; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.logging.ToJSONStringUtil; 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; public class MethodInstance { private final Method method; private final Map<VariableParam, ConstantParam> grounding; private final Monom precondition; public MethodInstance(final Method method, final Map<VariableParam, ConstantParam> grounding) { super(); this.method = method; this.grounding = grounding; if (!this.grounding.keySet().containsAll(method.getParameters())) { throw new IllegalArgumentException("Planning Method instances must contain a grounding for ALL params of the method. Here, method (" + method.getName() + ") params: " + method.getParameters() + ". Params missing: " + SetUtil.difference(method.getParameters(), this.grounding.keySet())); } this.precondition = new Monom(method.getPrecondition(), grounding); } public Method getMethod() { return this.method; } public Map<VariableParam, ConstantParam> getGrounding() { return this.grounding; } public Monom getPrecondition() { return this.precondition; } public List<ConstantParam> getParameters() { return this.method.getParameters().stream().map(this.grounding::get).collect(Collectors.toList()); } public TaskNetwork getNetwork() { TaskNetwork instanceNetwork = new TaskNetwork(); TaskNetwork methodNetwork = this.getMethod().getNetwork(); Map<Literal, Literal> correspondence = new HashMap<>(); for (Literal task : methodNetwork.getItems()) { Literal groundTask = new Literal(task, this.grounding); correspondence.put(task, groundTask); instanceNetwork.addItem(groundTask); } for (Literal task : methodNetwork.getItems()) { for (Literal succ : methodNetwork.getSuccessors(task)) { instanceNetwork.addEdge(correspondence.get(task), correspondence.get(succ)); } } return instanceNetwork; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.method == null) ? 0 : this.method.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; } MethodInstance other = (MethodInstance) obj; if (this.method == null) { if (other.method != null) { return false; } } else if (!this.method.equals(other.method)) { return false; } return true; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("method", this.method); fields.put("grounding", this.grounding); fields.put("precondition", this.precondition); return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields); } public String getEncoding() { StringBuilder b = new StringBuilder(); b.append(this.method.getName()); b.append("("); List<VariableParam> params = this.method.getParameters(); 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(); } }
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/stn/STNPlanningDomain.java
package ai.libs.jaicore.planning.hierarchical.problems.stn; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import ai.libs.jaicore.logging.ToJSONStringUtil; import ai.libs.jaicore.planning.classical.problems.strips.Operation; @SuppressWarnings("serial") public class STNPlanningDomain implements Serializable { private final Collection<? extends Operation> operations; private final Collection<? extends Method> methods; public STNPlanningDomain(final Collection<? extends Operation> operations, final Collection<? extends Method> methods) { super(); Set<String> names = new HashSet<>(); for (Method m : methods) { if (m.getName().contains("-")) { throw new IllegalArgumentException("Illegal method name " + m.getName() + ". Currently no support for methods with hyphens in the name. Please use only [a-zA-z0-9] to name methods!"); } if (names.contains(m.getName())) { throw new IllegalArgumentException("Double definition of method " + m.getName()); } names.add(m.getName()); } this.operations = operations; this.methods = methods; this.checkValidity(); } public void checkValidity() { /* does nothing by default */ } public Collection<? extends Operation> getOperations() { return Collections.unmodifiableCollection(this.operations); } public Collection<? extends Method> getMethods() { return Collections.unmodifiableCollection(this.methods); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.methods == null) ? 0 : this.methods.hashCode()); result = prime * result + ((this.operations == null) ? 0 : this.operations.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; } STNPlanningDomain other = (STNPlanningDomain) obj; if (this.methods == null) { if (other.methods != null) { return false; } } else if (!this.methods.equals(other.methods)) { return false; } if (this.operations == null) { if (other.operations != null) { return false; } } else if (!this.operations.equals(other.operations)) { return false; } return true; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("operations", this.operations); fields.put("methods", this.methods); 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/stn/STNPlanningProblem.java
package ai.libs.jaicore.planning.hierarchical.problems.stn; 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.planning.hierarchical.problems.htn.IHTNPlanningProblem; @SuppressWarnings("serial") public class STNPlanningProblem implements IHTNPlanningProblem { private final STNPlanningDomain domain; private final CNFFormula knowledge; private final Monom init; private final TaskNetwork network; private static final boolean SORT_NETWORK_BASED_ON_NUMBER_PREFIXES = true; public STNPlanningProblem(final STNPlanningDomain domain, final CNFFormula knowledge, final Monom init, final TaskNetwork network) { super(); this.domain = domain; this.knowledge = knowledge; this.init = init; this.network = network; } @Override public STNPlanningDomain getDomain() { return this.domain; } @Override public CNFFormula getKnowledge() { return this.knowledge; } @Override public Monom getInit() { return this.init; } @Override public TaskNetwork getNetwork() { return this.network; } public boolean isSortNetworkBasedOnNumberPrefixes() { return SORT_NETWORK_BASED_ON_NUMBER_PREFIXES; } @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.init == null) ? 0 : this.init.hashCode()); result = prime * result + ((this.knowledge == null) ? 0 : this.knowledge.hashCode()); result = prime * result + ((this.network == null) ? 0 : this.network.hashCode()); result = prime * result + (SORT_NETWORK_BASED_ON_NUMBER_PREFIXES ? 1231 : 1237); 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; } STNPlanningProblem other = (STNPlanningProblem) obj; if (this.domain == null) { if (other.domain != null) { return false; } } else if (!this.domain.equals(other.domain)) { return false; } if (this.init == null) { if (other.init != null) { return false; } } else if (!this.init.equals(other.init)) { return false; } if (this.knowledge == null) { if (other.knowledge != null) { return false; } } else if (!this.knowledge.equals(other.knowledge)) { return false; } if (this.network == null) { if (other.network != null) { return false; } } else if (!this.network.equals(other.network)) { return false; } return true; } @Override public String toString() { Map<String, Object> fields = new HashMap<>(); fields.put("domain", this.domain); fields.put("knowledge", this.knowledge); fields.put("init", this.init); fields.put("network", this.network); 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/stn/TaskNetwork.java
package ai.libs.jaicore.planning.hierarchical.problems.stn; import java.util.List; import ai.libs.jaicore.basic.StringUtil; import ai.libs.jaicore.graph.Graph; import ai.libs.jaicore.logic.fol.structure.Literal; public class TaskNetwork extends Graph<Literal> { public TaskNetwork() { super(); } public TaskNetwork(final List<Literal> chain) { int n = chain.size(); Literal prev = null; for (int i = 0; i < n; i++) { Literal cur = chain.get(i); this.addItem(cur); if (prev != null) { this.addEdge(prev, cur); } prev = cur; } } public TaskNetwork(final Graph<Literal> graph) { super(graph); } public TaskNetwork(final String chain) { super(); Literal current = null; int id = 1; for (String taskDescription : StringUtil.explode(chain, "->")) { if (!taskDescription.trim().isEmpty()) { Literal task = new Literal("tn" + "_" + id + "-" + taskDescription.trim()); this.addItem(task); if (current != null) { this.addEdge(current, task); } current = task; id++; } } } }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore/processes/CommandExecutionException.java
package ai.libs.jaicore.processes; @SuppressWarnings("serial") public class CommandExecutionException extends Exception { public CommandExecutionException(final Exception e) { super(e); } }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore/processes/EOperatingSystem.java
package ai.libs.jaicore.processes; /** * Enum for operating systems that should be distinguished on the level of process analysis */ public enum EOperatingSystem { WIN, LINUX, MAC }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore/processes/JavaMethodToProcessWrapper.java
package ai.libs.jaicore.processes; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.ProcessBuilder.Redirect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.concurrent.ExecutionException; import org.apache.commons.lang3.reflect.MethodUtils; import org.api4.java.algorithm.Timeout; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.FileUtil; import ai.libs.jaicore.timing.TimedComputation; /** * This class outsources the call to an arbitrary method into a separate process. This is specifically relevant if you work with libraries that do no respect the interrupt-functionality. * * Using this wrapper should allow you to conveniently interrupt any method you like. There are of course some drawbacks one must consider: - Execution is MUCH slower compared to execution in a local * thread (up to a factor of 10) - all items (target object, inputs, and the expected output) must be serializable - communication with the executed logic is highly limited - no call by reference * possible. If the routine to be outsourced needs to update the object on which it is invoked, encapsulate the logic first into a method that returns the object. - there may be strange side effects, * e.g., if the subprocess loads libraries manually, this may happen very often and flood temp directories in the file system * * @author Felix Mohr * */ public class JavaMethodToProcessWrapper { private static final Random random = new Random(System.currentTimeMillis()); private static final Logger logger = LoggerFactory.getLogger(JavaMethodToProcessWrapper.class); private static final List<JavaMethodToProcessWrapper> wrappers = new ArrayList<>(); private String memory = "256M"; private File tmpDir = new File("tmp"); private int pidOfSubProcess; public static List<JavaMethodToProcessWrapper> getWrappers() { return wrappers; } public JavaMethodToProcessWrapper() { super(); wrappers.add(this); } public static String getAbsoluteClasspath() { try { return System.getProperty("java.class.path") + java.io.File.pathSeparatorChar + URLDecoder.decode(JavaMethodToProcessWrapper.class.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("The encoding of the URL is unsupported", e); } return null; } public Object run(final String clazz, final String method, final Object target, final Object... inputs) throws IOException, InterruptedException, InvocationTargetException, ProcessIDNotRetrievableException { return this.run(clazz, method, target, Arrays.asList(inputs)); } /** * * @param clazz * @param method * @param target * @param timeout * @param inputs * @return * @throws IOException * @throws InvocationTargetException * @throws InterruptedException * This is only thrown if the executing thread is interrupted from *outside* but not when it is canceled due to the timeout */ public Optional<Object> runWithTimeout(final String clazz, final String method, final Object target, final Timeout timeout, final Object... inputs) throws AlgorithmTimeoutedException, InvocationTargetException, InterruptedException { Object c; try { c = TimedComputation.compute(() -> this.run(clazz, method, target, inputs), timeout, "Process has timed out!"); } catch (ExecutionException e) { throw new InvocationTargetException(e.getCause()); } if (Thread.interrupted()) { throw new IllegalStateException("We got interrupted but no InterruptedException was thrown!"); } return (c != null) ? Optional.of(c) : Optional.empty(); } public Object run(final String clazz, final String method, final Object target, final List<Object> inputs) throws IOException, InterruptedException, InvocationTargetException, ProcessIDNotRetrievableException { /* create new id for the invocation */ String id = String.valueOf(random.nextLong()); File dir = new File(this.tmpDir.getAbsolutePath() + File.separator + id); dir.mkdirs(); logger.info("Created tmp dir \"{}\" for invocation {}.{}({}).", dir.getAbsolutePath(), target, method, inputs); /* create command list */ final List<String> commands = new ArrayList<>(); commands.add("java"); commands.add("-cp"); commands.add(getAbsoluteClasspath()); commands.add("-Xmx" + this.memory); commands.add(this.getClass().getName()); commands.add(dir.getAbsolutePath()); commands.add(clazz); commands.add(method); logger.info("Serializing object ..."); /* serialize target */ String targetVal = "null"; if (target != null) { targetVal = target.getClass().getName() + ".ser"; FileUtil.serializeObject(target, dir.getAbsolutePath() + File.separator + targetVal); } commands.add(targetVal); /* serialize inputs */ for (int i = 0; i < inputs.size(); i++) { Object input = inputs.get(i); String argval; if (inputs.get(i) != null) { argval = input.getClass().getName() + ".ser"; FileUtil.serializeObject(inputs.get(i), dir.getAbsolutePath() + File.separator + argval); } else { argval = "null"; } commands.add(argval); } /* run process in a new thread */ logger.info("ProcessBuilder started"); ProcessBuilder pb = new ProcessBuilder(commands); pb.redirectOutput(Redirect.INHERIT); pb.redirectError(Redirect.INHERIT); Process process = pb.start(); this.pidOfSubProcess = ProcessUtil.getPID(process); logger.info("Spawned process {}. Currently active java processes:", this.pidOfSubProcess); ProcessUtil.getRunningJavaProcesses().stream().forEach(p -> logger.info("\t{}", p)); /* this hook kills the java process we just created. This is done on the system level, because process.destroy() is not reliable * The hook is invoked either on an interrupt of the executing thread or if the whole application is terminated (not abrubtly) */ Thread killerHook = new Thread(() -> { logger.info("Destroying subprocess {}", JavaMethodToProcessWrapper.this.pidOfSubProcess); if (process.isAlive()) { try { process.destroy(); ProcessUtil.killProcess(JavaMethodToProcessWrapper.this.pidOfSubProcess); } catch (IOException e) { logger.error("An unexpected exception occurred while killing the process with id {}", JavaMethodToProcessWrapper.this.pidOfSubProcess, e); } } logger.info("Subprocess {} destroyed.", JavaMethodToProcessWrapper.this.pidOfSubProcess); }); Runtime.getRuntime().addShutdownHook(killerHook); /* now wait for the process to terminate */ try { logger.info("Awaiting termination."); process.waitFor(); } /* if the process is supposed to be interrupted in the meantime, destroy it */ catch (InterruptedException e) { logger.info("Received interrupt"); killerHook.start(); FileUtil.deleteFolderRecursively(dir); throw e; } finally { try { Runtime.getRuntime().removeShutdownHook(killerHook); } catch (IllegalStateException e) { /* this can be ignored safely */ } } /* now read in result and return it */ logger.info("Processing results ..."); File serializedResult = new File(dir + File.separator + "result.ser"); File nullResult = new File(dir + File.separator + "result.null"); File exceptionResult = new File(dir + File.separator + "result.exception"); if (serializedResult.exists()) { try { Object out = FileUtil.unserializeObject(serializedResult.getAbsolutePath()); FileUtil.deleteFolderRecursively(dir); return out; } catch (ClassNotFoundException e) { logger.error("The class of the deserialized object could not be found", e); } } if (nullResult.exists()) { FileUtil.deleteFolderRecursively(dir); return null; } if (exceptionResult.exists()) { Exception exception = null; try { exception = (Exception) FileUtil.unserializeObject(exceptionResult.getAbsolutePath()); } catch (ClassNotFoundException e) { logger.error("The class of the deserialized object could not be found", e); } FileUtil.deleteFolderRecursively(dir); throw new InvocationTargetException(exception); } logger.warn("Subprocess execution terminated but no result was observed for {}!", id); return null; } private static Object executeCommand(final File folder, final String clazz, final String method_name, final String target, final LinkedList<String> argsArray) throws CommandExecutionException { try { logger.info("Invoking in folder {} method {} on class {}", folder, clazz, method_name); Object targetObject = null; if (!target.equals("null")) { targetObject = FileUtil.unserializeObject(folder.getAbsolutePath() + File.separator + target); } Class<?>[] params = new Class[argsArray.size()]; Object[] objcts = new Object[argsArray.size()]; int counter = 0; while (!argsArray.isEmpty()) { String descriptor = argsArray.poll(); boolean isNull = descriptor.equals(""); objcts[counter] = isNull ? null : FileUtil.unserializeObject(folder.getAbsolutePath() + File.separator + descriptor); params[counter] = isNull ? null : Class.forName(descriptor.substring(0, descriptor.lastIndexOf('.'))); counter++; } /* retrieve method and call it */ Method method = MethodUtils.getMatchingAccessibleMethod(Class.forName(clazz), method_name, params); return method.invoke(targetObject, objcts); } catch (Exception e) { throw new CommandExecutionException(e); } } public static void main(final String[] args) { LinkedList<String> argsArray = new LinkedList<>(Arrays.asList(args)); File folder = new File(argsArray.poll()); if (!folder.exists()) { throw new IllegalArgumentException("The invocation call folder " + folder + " does not exist!"); } String clazz = argsArray.poll(); String methodName = argsArray.poll(); String target = argsArray.poll(); Object result; try { result = executeCommand(folder, clazz, methodName, target, argsArray); FileUtil.serializeObject(result, folder.getAbsolutePath() + File.separator + "result." + (result != null ? "ser" : "null")); } catch (Exception e) { logger.error("An exception occurred while serializing the object", e); try { FileUtil.serializeObject(e, folder.getAbsolutePath() + File.separator + "result.exception"); } catch (IOException e1) { logger.error("An exception occurred while serializing the error message of the occurred exception.", e1); } } logger.info("Finishing subprocess"); } public void setMemory(final String pMemory) { this.memory = pMemory; } public File getTmpDir() { return this.tmpDir; } public void setTmpDir(final File tmpDir) { this.tmpDir = tmpDir; } }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore/processes/ProcessIDNotRetrievableException.java
package ai.libs.jaicore.processes; public class ProcessIDNotRetrievableException extends Exception { /** * */ private static final long serialVersionUID = -719315021772711013L; public ProcessIDNotRetrievableException(final String msg) { super(msg); } public ProcessIDNotRetrievableException(final String msg, final Throwable cause) { super(msg, cause); } }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore/processes/ProcessInfo.java
package ai.libs.jaicore.processes; public class ProcessInfo { private final int pid; private final String descr; private final String memory; public ProcessInfo(int pid, String descr, String memory) { super(); this.pid = pid; this.descr = descr; this.memory = memory; } public int getPid() { return pid; } public String getDescr() { return descr; } public String getMemory() { return memory; } @Override public String toString() { return "ProcessInfo [pid=" + pid + ", descr=" + descr + ", memory=" + memory + "]"; } }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore/processes/ProcessList.java
package ai.libs.jaicore.processes; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; @SuppressWarnings("serial") public class ProcessList extends ArrayList<ProcessInfo> { private final long timestamp = System.currentTimeMillis(); private final List<Integer> fieldSeparationIndices = new ArrayList<>(); public ProcessList() throws IOException { String line; Process p = ProcessUtil.getProcessListProcess(); try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) { boolean tableInitialized = false; int lineNumber = 0; while ((line = input.readLine()) != null) { switch (ProcessUtil.getOS()) { case WIN: if (!tableInitialized) { if (line.startsWith("===")) { int offset = 0; String[] headerLineParts = line.split(" "); for (int i = 0; i < headerLineParts.length; i++) { offset += headerLineParts[i].length(); this.fieldSeparationIndices.add(offset); offset++; } tableInitialized = true; } } else { List<String> entries = new ArrayList<>(); int indexFrom = 0; int indexTo = 0; for (int i = 0; i < this.fieldSeparationIndices.size(); i++) { indexTo = this.fieldSeparationIndices.get(i); entries.add(line.substring(indexFrom, indexTo).trim()); indexFrom = indexTo + 1; } entries.add(line.substring(indexTo).trim()); this.add(new ProcessInfo(Integer.parseInt(entries.get(1)), entries.get(0), entries.get(4))); } break; case LINUX: if (lineNumber > 0) { String remainingLine = line; List<String> entries = new ArrayList<>(); for (int i = 0; i < 6; i++) { int indexOfNextSpace = remainingLine.indexOf(' '); if (indexOfNextSpace >= 0) { entries.add(remainingLine.substring(0, indexOfNextSpace)); remainingLine = remainingLine.substring(indexOfNextSpace).trim(); } else { entries.add(remainingLine); } } this.add(new ProcessInfo(Integer.parseInt(entries.get(1)), entries.get(5), entries.get(4))); } break; default: throw new UnsupportedOperationException("Cannot create process list for OS " + ProcessUtil.getOS()); } lineNumber++; } } } public long getTimestamp() { return this.timestamp; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (int) (this.timestamp ^ (this.timestamp >>> 32)); 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; } ProcessList other = (ProcessList) obj; return (this.timestamp == other.timestamp); } }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/jaicore/processes/ProcessUtil.java
package ai.libs.jaicore.processes; import java.io.IOException; import java.lang.reflect.Field; import java.util.Collection; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.jna.platform.win32.WinUtils; /** * The process util provides convenient methods for securely killing processes of the operating system. For instance, this is useful whenever sub-processes are spawned and shall be killed reliably. * * @author fmohr, mwever * */ public class ProcessUtil { /* Logging */ private static final Logger logger = LoggerFactory.getLogger(ProcessUtil.class); private ProcessUtil() { /* Intentionally left blank, just prevent an instantiation of this class. */ } /** * Retrieves the type of operating system. * * @return Returns the name of the operating system. */ public static EOperatingSystem getOS() { String osName = System.getProperty("os.name").toLowerCase(); if (osName.indexOf("windows") > -1) { return EOperatingSystem.WIN; } if (osName.indexOf("linux") > -1) { return EOperatingSystem.LINUX; } if (osName.contains("mac")) { return EOperatingSystem.MAC; } throw new UnsupportedOperationException("Cannot detect operating system " + osName); } /** * Gets the OS process for the process list. * * @return The process for the process list. * @throws IOException Thrown if a problem occurred while trying to access the process list process. */ public static Process getProcessListProcess() throws IOException { EOperatingSystem os = getOS(); switch (os) { case WIN: return Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\" + "tasklist.exe"); case LINUX: return Runtime.getRuntime().exec("ps -e -o user,pid,ppid,c,size,cmd"); default: throw new UnsupportedOperationException("No action defined for OS " + os); } } /** * Gets a list of running java processes. * * @return The list of running Java processes. * @throws IOException Throwsn if there was an issue accessing the OS's process list. */ public static Collection<ProcessInfo> getRunningJavaProcesses() throws IOException { return new ProcessList().stream().filter(pd -> pd.getDescr().startsWith("java")).collect(Collectors.toList()); } /** * Gets the operating system's process id of the given process. * * @param process The process for which the process id shall be looked up. * @return The process id of the given process. * @throws ProcessIDNotRetrievableException Thrown if the process id cannot be retrieved. */ public static int getPID(final Process process) throws ProcessIDNotRetrievableException { Integer pid; try { if (getOS() == EOperatingSystem.LINUX || getOS() == EOperatingSystem.MAC) { /* get the PID on unix/linux systems */ Field f = process.getClass().getDeclaredField("pid"); f.setAccessible(true); pid = f.getInt(process); return pid; } else if (getOS() == EOperatingSystem.WIN) {/* determine the pid on windows plattforms */ return WinUtils.getWindowsProcessId(process).intValue(); } } catch (Exception e) { throw new ProcessIDNotRetrievableException("Could not retrieve process ID", e); } throw new UnsupportedOperationException(); } /** * Kills the process with the given process id. * * @param pid The id of the process which is to be killed. * @throws IOException Thrown if the system command could not be issued. */ public static void killProcess(final int pid) throws IOException { Runtime rt = Runtime.getRuntime(); if (getOS() == EOperatingSystem.WIN) { rt.exec("taskkill /F /PID " + pid); } else if (getOS() == EOperatingSystem.MAC) { // -2 means keyboard interrupt as hitting ctrl+c in terminal rt.exec("kill -2 " + pid); } else { rt.exec("kill -9 " + pid); } } /** * Kills the provided process with a operating system's kill command. * * @param process The process to be killed. * @throws IOException Thrown if the system command could not be issued. */ public static void killProcess(final Process process) throws IOException { try { killProcess(getPID(process)); } catch (ProcessIDNotRetrievableException e) { logger.warn("Cannot kill process with certainty. Thus try to kill the process via the process' destroy method.", e); process.destroyForcibly(); } } }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/python/AProcessListener.java
package ai.libs.python; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.concurrent.Semaphore; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; import ai.libs.jaicore.processes.EOperatingSystem; import ai.libs.jaicore.processes.ProcessUtil; /** * The process listener may be attached to a process in order to handle its ouputs streams in a controlled way. * For instance, the process listener can be used to pipe all outputs of the invoked process to a logger system. * * @author scheiblm, wever */ public abstract class AProcessListener implements IProcessListener, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(AProcessListener.class); private boolean listenForPIDFromProcess = false; private int processIDObtainedFromListening = -1; protected AProcessListener() { } protected AProcessListener(final boolean listenForPIDFromProcess) { this.listenForPIDFromProcess = listenForPIDFromProcess; } @Override public void listenTo(final Process process) throws IOException, InterruptedException { this.logger.info("Starting to listen to process {}", process); Semaphore sem = new Semaphore(0); Runnable run = () -> { try (BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { // While process is alive the output- and error stream is output. while (process.isAlive()) { if (Thread.interrupted()) { // reset flag since we will throw an exception now throw new InterruptedException("Process execution was interrupted."); } String line; while (this.checkReady(inputReader) && (line = inputReader.readLine()) != null) { if (Thread.interrupted()) { throw new InterruptedException(); } this.handleProcessIDLine(line); if (line.contains("import imp") || line.contains("imp module")) { continue; } this.handleInput(line); } while (this.checkReady(errorReader) && (line = errorReader.readLine()) != null) { if (Thread.interrupted()) { throw new InterruptedException(); } if (line.contains("import imp") || line.contains("imp module")) { continue; } this.handleError(line); } } } catch (IOException e1) { e1.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } finally { sem.release(); } }; Thread t = new Thread(run); t.start(); try { sem.acquire(); } catch (InterruptedException e) { this.logger.info("Detected interrupt on process execution."); if (this.listenForPIDFromProcess && this.processIDObtainedFromListening > 0) { ProcessUtil.killProcess(this.processIDObtainedFromListening); } else { ProcessUtil.killProcess(process); } t.interrupt(); this.logger.info("Killed process, now wait until listener thread returns."); t.join(); throw e; } } private boolean checkReady(final BufferedReader inputReader) throws IOException { if (ProcessUtil.getOS() == EOperatingSystem.MAC) { return inputReader.ready(); } else { return true; } } private void handleProcessIDLine(final String line) { if (this.listenForPIDFromProcess && !Strings.isNullOrEmpty(line)) { if (line.startsWith("CURRENT_PID:")) { this.processIDObtainedFromListening = Integer.parseInt(line.replace("CURRENT_PID:", "").trim()); this.logger.debug("Listen to process id: {}", this.processIDObtainedFromListening); } this.logger.trace("Other console output: {}", line); } } /** * Handle the output of the error output stream. * * @param error The line sent by the process via the error stream. * @throws IOException An IOException is thrown if there is an issue reading from the process's stream. * @throws InterruptedException An interrupted exception is thrown if the thread/process is interrupted while processing the error messages. */ public abstract void handleError(String error) throws IOException, InterruptedException; /** * Handle the output of the standard output stream. * * @param error The line sent by the process via the standard output stream. * @throws IOException An IOException is thrown if there is an issue reading from the process's stream. * @throws InterruptedException An interrupted exception is thrown if the thread/process is interrupted while processing the standard output messages. */ public abstract void handleInput(String input) throws IOException, InterruptedException; @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-processes/0.2.7/ai/libs
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/python/DefaultProcessListener.java
package ai.libs.python; import java.io.IOException; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The DefaultProcessListener might be used to forward any type of outputs of a process to a logger. * * @author wever */ public class DefaultProcessListener extends AProcessListener implements ILoggingCustomizable { /* Logging */ private Logger logger = LoggerFactory.getLogger(DefaultProcessListener.class); private StringBuilder errorSB; private StringBuilder defaultSB; /** * Constructor to initialize the DefaultProcessListener. * * @param verbose Flag whether standard outputs are forwarded to the logger. */ public DefaultProcessListener() { super(); this.errorSB = new StringBuilder(); this.defaultSB = new StringBuilder(); } /** * Constructor to initialize the DefaultProcessListener. * * @param verbose Flag whether standard outputs are forwarded to the logger. */ public DefaultProcessListener(final boolean listenToPIDFromProcess) { super(listenToPIDFromProcess); this.errorSB = new StringBuilder(); this.defaultSB = new StringBuilder(); } @Override public void handleError(final String error) { this.errorSB.append(error + "\n"); this.logger.error(">>> {}", error); } @Override public void handleInput(final String input) throws IOException, InterruptedException { this.defaultSB.append(input + "\n"); this.logger.info(">>> {}", input); } public String getErrorOutput() { return this.errorSB.toString(); } public String getDefaultOutput() { return this.defaultSB.toString(); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); super.setLoggerName(name + ".__listener"); } }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/python/IProcessListener.java
package ai.libs.python; import java.io.IOException; public interface IProcessListener { /** * Lets the process listener listen to the output and error stream of the given process. * @param process The process to be listened to. * @throws IOException * @throws InterruptedException */ public void listenTo(Process process) throws IOException, InterruptedException; }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/python/IPythonConfig.java
package ai.libs.python; import org.aeonbits.owner.Config.Sources; import ai.libs.jaicore.basic.IOwnerBasedConfig; @Sources({ "file:conf/python.properties" }) public interface IPythonConfig extends IOwnerBasedConfig { public static final String KEY_PATH_TO_PYTHON_EXECUTABLE = "pathToPythonExecutable"; public static final String KEY_PYTHON = "pythonCmd"; public static final String KEY_ANACONDA = "anaconda"; public static final String KEY_PATH_TO_ANACONDA_EXECUTABLE = "pathToCondaExecutable"; @Key(KEY_PATH_TO_PYTHON_EXECUTABLE) public String getPathToPythonExecutable(); @Key(KEY_PYTHON) @DefaultValue("python") public String getPythonCommand(); @Key(KEY_ANACONDA) public String getAnacondaEnvironment(); @Key(KEY_PATH_TO_ANACONDA_EXECUTABLE) @DefaultValue("~/anaconda3/etc/profile.d/conda.sh") public String getPathToAnacondaExecutable(); }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/python/PythonRequirementDefinition.java
package ai.libs.python; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.SystemRequirementsNotMetException; import ai.libs.jaicore.basic.sets.SetUtil; public class PythonRequirementDefinition { private static final Logger LOGGER = LoggerFactory.getLogger(PythonRequirementDefinition.class); private final int release; private final int major; private final int minor; private final List<String> requiredModules; private final List<String> optionalModules; public PythonRequirementDefinition(final int release, final int major, final int minor, final String[] requiredModules, final String[] optionalModules) { this(release, major, minor, Arrays.asList(requiredModules), Arrays.asList(optionalModules)); } public PythonRequirementDefinition(final int release, final int major, final int minor, final List<String> requiredModules, final List<String> optionalModules) { super(); this.release = release; this.major = major; this.minor = minor; this.requiredModules = requiredModules; this.optionalModules = optionalModules; } public PythonRequirementDefinition(final int release, final int major, final int minor) { this(release, major, minor, new ArrayList<>(), new ArrayList<>()); } public int getRelease() { return this.release; } public int getMajor() { return this.major; } public int getMinor() { return this.minor; } public List<String> getRequiredModules() { return this.requiredModules; } public List<String> getOptionalModules() { return this.optionalModules; } public void check() throws InterruptedException { this.check(null); } public void check(final IPythonConfig pythonConfig) throws InterruptedException { try { /* Check whether we have all required python modules available*/ PythonUtil pu = pythonConfig != null ? new PythonUtil(pythonConfig) : new PythonUtil(); if (!pu.isInstalledVersionCompatible(this.release, this.major, this.minor)) { throw new SystemRequirementsNotMetException("Python version does not conform the minimum required python version of " + this.release + "." + this.major + "." + this.minor); } List<String> missingRequiredPythonModules = pu.getMissingModules(this.requiredModules); if (!missingRequiredPythonModules.isEmpty()) { throw new SystemRequirementsNotMetException("Could not find required python modules: " + SetUtil.implode(missingRequiredPythonModules, ", ")); } List<String> missingOptionalPythonModules = pu.getMissingModules(this.optionalModules); if (!missingOptionalPythonModules.isEmpty() && LOGGER.isWarnEnabled()) { LOGGER.warn("Could not find optional python modules: {}", SetUtil.implode(missingOptionalPythonModules, ", ")); } } catch (IOException e) { e.printStackTrace(); throw new SystemRequirementsNotMetException("Could not check whether python is installed in the required version. Make sure that \"python\" is available as a command on your command line."); } } }
0
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs
java-sources/ai/libs/jaicore-processes/0.2.7/ai/libs/python/PythonUtil.java
package ai.libs.python; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.aeonbits.owner.ConfigCache; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.SystemRequirementsNotMetException; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.processes.EOperatingSystem; import ai.libs.jaicore.processes.ProcessUtil; public class PythonUtil implements ILoggingCustomizable { private static final String CMD_PYTHON_COMMANDPARAM = "-c"; private static final String PY_IMPORT = "import "; private final File pathToPythonExecutable; private final String pythonCommand; private String pathToAnacondaExecutable; private String anacondaEnvironment; private Logger logger = LoggerFactory.getLogger(PythonUtil.class); public PythonUtil() { this(ConfigCache.getOrCreate(IPythonConfig.class)); } public PythonUtil(final IPythonConfig config) { this.pythonCommand = config.getPythonCommand(); if (config.getAnacondaEnvironment() != null) { if (config.getPathToAnacondaExecutable() != null) { String path = config.getPathToAnacondaExecutable(); this.pathToAnacondaExecutable = (path != null) ? path : null; } this.anacondaEnvironment = config.getAnacondaEnvironment(); } String path = config.getPathToPythonExecutable(); this.pathToPythonExecutable = (path != null) ? new File(path) : null; if (this.pathToPythonExecutable != null) { if (!this.pathToPythonExecutable.exists()) { throw new IllegalArgumentException("The path to python executable " + this.pathToPythonExecutable.getAbsolutePath() + " does not exist."); } if (!new File(this.pathToPythonExecutable + File.separator + this.pythonCommand).exists()) { throw new IllegalArgumentException("The given path does not contain an executable with name " + this.pythonCommand); } } } public String[] getExecutableCommandArray(final boolean executePythonInteractive, final String... command) { List<String> processParameters = new ArrayList<>(); EOperatingSystem os = ProcessUtil.getOS(); if (this.anacondaEnvironment != null) { if (os == EOperatingSystem.MAC) { processParameters.add("source"); processParameters.add(this.pathToAnacondaExecutable); processParameters.add("&&"); } processParameters.add("conda"); processParameters.add("activate"); processParameters.add(this.anacondaEnvironment); processParameters.add("&&"); } if (this.pathToPythonExecutable != null) { processParameters.add(this.pathToPythonExecutable + File.separator + this.pythonCommand); } else { processParameters.add(this.pythonCommand); } if (executePythonInteractive) { processParameters.add(CMD_PYTHON_COMMANDPARAM); } Arrays.stream(command).forEach(processParameters::add); if (os == EOperatingSystem.MAC) { return new String[] { "sh", "-c", SetUtil.implode(processParameters, " ") }; } else { return processParameters.toArray(new String[] {}); } } public int executeScriptFile(final List<String> fileAndParams) throws IOException, InterruptedException { String[] commandArray = this.getExecutableCommandArray(false, fileAndParams.toArray(new String[] {})); Process process = new ProcessBuilder(commandArray).start(); DefaultProcessListener dpl = new DefaultProcessListener(); dpl.listenTo(process); int exitValue = 1; try { exitValue = process.waitFor(); } catch (InterruptedException e) { ProcessUtil.killProcess(process); throw e; } return exitValue; } public String executeScriptFileAndGetOutput(final List<String> fileAndParams) throws IOException, InterruptedException { String[] commandArray = this.getExecutableCommandArray(false, fileAndParams.toArray(new String[] {})); if (this.logger.isInfoEnabled()) { this.logger.info("Invoking {}", Arrays.toString(commandArray)); } Process process = new ProcessBuilder(commandArray).start(); DefaultProcessListener dpl = new DefaultProcessListener(); dpl.listenTo(process); int exitValue = process.waitFor(); if (exitValue == 0) { return dpl.getDefaultOutput(); } else { throw new IOException("Process did not exit smoothly." + dpl.getErrorOutput()); } } public String executeScript(final String script) throws IOException, InterruptedException { // ensure that script is wrapped into quotation marks when being run on MacOS String scriptToExecute; if (ProcessUtil.getOS() == EOperatingSystem.MAC) { scriptToExecute = "'" + script + "'"; } else { scriptToExecute = script; } // build command array String[] command = this.getExecutableCommandArray(true, scriptToExecute); ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.redirectErrorStream(true); Process p = processBuilder.command(command).start(); DefaultProcessListener dpl = new DefaultProcessListener(); dpl.listenTo(p); return dpl.getDefaultOutput(); } public String getInstalledVersion() throws IOException, InterruptedException { return this.executeScript(PY_IMPORT + "platform; print(platform.python_version())").trim(); } public boolean isInstalledVersionCompatible(final int reqRel, final int reqMaj, final int reqMin) throws IOException, InterruptedException { String[] versionSplit = this.getInstalledVersion().trim().split("\\."); if (versionSplit.length != 3) { throw new SystemRequirementsNotMetException("Could not parse python version to be of the shape X.X.X"); } int rel = Integer.parseInt(versionSplit[0]); int maj = Integer.parseInt(versionSplit[1]); int min = Integer.parseInt(versionSplit[2]); return this.isValidVersion(reqRel, reqMaj, reqMin, rel, maj, min); } private boolean isValidVersion(final int reqRel, final int reqMaj, final int reqMin, final int actRel, final int actMaj, final int actMin) { return ((actRel > reqRel) || (actRel == reqRel && actMaj > reqMaj) || (actRel == reqRel && actMaj == reqMaj && actMin >= reqMin)); } public boolean areAllGivenModuleInstalled(final List<String> modules) throws IOException, InterruptedException { StringBuilder imports = new StringBuilder(); for (String module : modules) { if (!imports.toString().isEmpty()) { imports.append(";"); } imports.append(PY_IMPORT + module); } return !this.executeScript(imports.toString()).contains("ModuleNotFoundError"); } public boolean isSingleModuleInstalled(final String moduleName) throws IOException, InterruptedException { return !this.executeScript(PY_IMPORT + moduleName).contains("ModuleNotFoundError"); } public List<String> getMissingModules(final String... modules) throws IOException, InterruptedException { return this.getMissingModules(Arrays.asList(modules)); } public List<String> getMissingModules(final List<String> modules) throws IOException, InterruptedException { if (this.areAllGivenModuleInstalled(modules)) { // first try with a single invocation whether everything required is there. return Arrays.asList(); } List<String> missingModules = new ArrayList<>(); // not realized via streams, because a stream would break the thrown exception! for (String m : modules) { if (!this.isSingleModuleInstalled(m)) { missingModules.add(m); } } return missingModules; } public boolean isModuleInstalled(final String... modules) throws IOException, InterruptedException { return this.getMissingModules(modules).isEmpty(); } @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-processes/0.2.7/com/sun/jna/platform
java-sources/ai/libs/jaicore-processes/0.2.7/com/sun/jna/platform/win32/WinUtils.java
package com.sun.jna.platform.win32; import java.lang.reflect.Field; import com.sun.jna.Pointer; public class WinUtils { private WinUtils() { // prevent instantiation of this class } public static Long getWindowsProcessId(final Process process) throws NoSuchFieldException, IllegalAccessException { /* determine the pid on windows plattforms */ Field f = process.getClass().getDeclaredField("handle"); f.setAccessible(true); long handl = f.getLong(process); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE handle = new WinNT.HANDLE(); handle.setPointer(Pointer.createConstant(handl)); int ret = kernel.GetProcessId(handle); return Long.valueOf(ret); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/ActionPredictionFailedException.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; @SuppressWarnings("serial") public class ActionPredictionFailedException extends Exception { public ActionPredictionFailedException(final Exception e) { super(e); } public ActionPredictionFailedException(final String message, final Exception e) { super(message, e); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/EBehaviorForNotFullyExploredStates.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; public enum EBehaviorForNotFullyExploredStates { BEST, RANDOM, EXCEPTION }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/GraphBasedMDP.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.datastructure.graph.ILabeledPath; import org.api4.java.datastructure.graph.implicit.ILazySuccessorGenerator; 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.Pair; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.search.model.ILazyRandomizableSuccessorGenerator; import ai.libs.jaicore.search.model.other.SearchGraphPath; import ai.libs.jaicore.search.probleminputs.IMDP; public class GraphBasedMDP<N, A> implements IMDP<N, A, Double>, ILoggingCustomizable { private static final int MAX_SUCCESSOR_CACHE_SIZE = 100; private final IPathSearchWithPathEvaluationsInput<N, A, Double> graph; private final N root; private final ISuccessorGenerator<N, A> succGen; private final IPathGoalTester<N, A> goalTester; private final Map<N, Pair<N, A>> backPointers = new HashMap<>(); private Logger logger = LoggerFactory.getLogger(GraphBasedMDP.class); private final Map<N, Map<A, N>> successorCache = new HashMap<>(); private final boolean lazy; private final ILazySuccessorGenerator<N, A> lazySuccGen; public GraphBasedMDP(final IPathSearchWithPathEvaluationsInput<N, A, Double> graph) { super(); this.graph = graph; this.root = ((ISingleRootGenerator<N>) this.graph.getGraphGenerator().getRootGenerator()).getRoot(); this.succGen = graph.getGraphGenerator().getSuccessorGenerator(); this.goalTester = graph.getGoalTester(); this.lazySuccGen = this.succGen instanceof ILazySuccessorGenerator ? (ILazySuccessorGenerator<N, A>) this.succGen : null; this.lazy = this.lazySuccGen != null; } @Override public N getInitState() { return this.root; } @Override public boolean isMaximizing() { // path searches are, by definition, always minimization problems return false; } @Override public Collection<A> getApplicableActions(final N state) throws InterruptedException { this.logger.debug("Computing applicable actions."); Collection<INewNodeDescription<N, A>> successors = this.succGen.generateSuccessors(state); Collection<A> actions = new ArrayList<>(); Map<A, N> cache = new HashMap<>(); if (Thread.interrupted()) { throw new InterruptedException("The computation of applicable actions has been interrupted."); } long lastInterruptCheck = System.currentTimeMillis(); for (INewNodeDescription<N, A> succ : successors) { A action = succ.getArcLabel(); actions.add(action); cache.put(action, succ.getTo()); long now = System.currentTimeMillis(); if (lastInterruptCheck < now - 10) { lastInterruptCheck = now; if (Thread.interrupted()) { throw new InterruptedException("The computation of applicable actions has been interrupted."); } } if (this.backPointers.containsKey(succ.getTo())) { Pair<N, A> backpointer = this.backPointers.get(succ.getTo()); boolean sameParent = backpointer.getX().equals(state); boolean sameAction = backpointer.getY().equals(action); if (!sameParent || !sameAction) { N otherNode = null; for (N key : this.backPointers.keySet()) { now = System.currentTimeMillis(); if (lastInterruptCheck < now - 10) { lastInterruptCheck = now; if (Thread.interrupted()) { throw new InterruptedException("The computation of applicable actions has been interrupted."); } } if (key.equals(succ.getTo())) { otherNode = key; break; } } throw new IllegalStateException("Reaching state " + succ.getTo() + " on a second way, which must not be the case in trees!\n\t1st way: " + backpointer.getX() + "; " + backpointer.getY() + "\n\t2nd way: " + state + "; " + action + "\n\ttoString of existing node: " + otherNode + "\n\tSame parent: " + sameParent + "\n\tSame Action: " + sameAction); } } this.logger.debug("Setting backpointer from {} to {}", succ.getTo(), state); this.backPointers.put(succ.getTo(), new Pair<>(state, action)); } /* clear the cache if we have too many entries */ if (this.successorCache.size() > MAX_SUCCESSOR_CACHE_SIZE) { this.successorCache.clear(); } this.successorCache.put(state, cache); return actions; } @Override public Map<N, Double> getProb(final N state, final A action) throws InterruptedException { /* first determine the successor node (either by cache or by constructing the successors again) */ N successor = null; if (this.successorCache.containsKey(state) && this.successorCache.get(state).containsKey(action)) { successor = this.successorCache.get(state).get(action); } else { Optional<INewNodeDescription<N, A>> succOpt = this.succGen.generateSuccessors(state).stream().filter(nd -> nd.getArcLabel().equals(action)).findAny(); if (!succOpt.isPresent()) { this.logger.error("THERE IS NO SUCCESSOR REACHABLE WITH ACTION {} IN THE MDP!", action); return null; } successor = succOpt.get().getTo(); } /* now equip this successor with probability 1 */ Map<N, Double> out = new HashMap<>(); out.put(successor, 1.0); return out; } @Override public double getProb(final N state, final A action, final N successor) throws InterruptedException { return this.getProb(state, action).containsKey(successor) ? 1 : 0.0; } @Override public Double getScore(final N state, final A action, final N successor) throws PathEvaluationException, InterruptedException { /* now build the whole path using the back-pointer map */ this.logger.info("Getting score for SAS-triple ({}, {}, {})", state, action, successor); N cur = successor; List<N> nodes = new ArrayList<>(); List<A> arcs = new ArrayList<>(); nodes.add(cur); while (cur != this.root) { Pair<N, A> parentEdge = this.backPointers.get(cur); if (parentEdge == null) { throw new NullPointerException("No back pointer defined for non-root node " + cur); // this is INTENTIONALLY not done with Object.requireNonNull, because the string shall not be evaluated otherwise! } cur = parentEdge.getX(); nodes.add(0, cur); arcs.add(0, parentEdge.getY()); } ILabeledPath<N, A> path = new SearchGraphPath<>(nodes, arcs); /* check whether path is a goal path */ if (!this.goalTester.isGoal(path)) { // in the MDP-view of a node, partial paths do not yield a reward but only full paths. boolean isTerminal = this.isTerminalState(path.getHead()); if (isTerminal) { this.logger.debug("Found dead end! Returning null."); return null; } this.logger.info("Path {} is not a goal path, returning 0.0", path); return 0.0; } this.logger.info("Path is a goal path, invoking path evaluator."); double score = this.graph.getPathEvaluator().evaluate(path).doubleValue(); this.logger.info("Obtained score {} for path", score); return score; } @Override public boolean isTerminalState(final N state) throws InterruptedException { if (this.lazy) { this.logger.debug("Determining terminal state condition for lazy graph generator."); return !this.lazySuccGen.getIterativeGenerator(state).hasNext(); } else { return this.succGen.generateSuccessors(state).isEmpty(); } } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); if (this.succGen instanceof ILoggingCustomizable) { this.logger.info("Setting logger of successor generator to {}.gg", name); ((ILoggingCustomizable) this.succGen).setLoggerName(name + ".gg"); } if (this.goalTester instanceof ILoggingCustomizable) { ((ILoggingCustomizable) this.goalTester).setLoggerName(name + ".gt"); } if (this.graph.getPathEvaluator() instanceof ILoggingCustomizable) { ((ILoggingCustomizable) this.graph.getPathEvaluator()).setLoggerName(name + ".pe"); } } @Override public A getUniformlyRandomApplicableAction(final N state, final Random random) throws InterruptedException { if (this.succGen instanceof ILazyRandomizableSuccessorGenerator) { INewNodeDescription<N, A> ne = ((ILazyRandomizableSuccessorGenerator<N, A>) this.succGen).getIterativeGenerator(state, random).next(); if (this.successorCache.size() > MAX_SUCCESSOR_CACHE_SIZE) { this.successorCache.clear(); } this.successorCache.computeIfAbsent(state, n -> new HashMap<>()).put(ne.getArcLabel(), ne.getTo()); this.backPointers.put(ne.getTo(), new Pair<>(state, ne.getArcLabel())); return ne.getArcLabel(); } this.logger.debug("The successor generator {} does not support lazy AND randomized successor generation. Now computing all successors and drawing one at random.", this.succGen.getClass()); Collection<A> actions = this.getApplicableActions(state); if (actions.isEmpty()) { throw new IllegalArgumentException("The given node has no successors: " + state); } return SetUtil.getRandomElement(actions, random); } @Override public boolean isActionApplicableInState(final N state, final A action) throws InterruptedException { if (this.successorCache.containsKey(state) && this.successorCache.get(state).containsKey(action)) { return true; } return this.getApplicableActions(state).contains(action); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/IGraphDependentPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import ai.libs.jaicore.graph.LabeledGraph; public interface IGraphDependentPolicy<N, A> { public void setGraph(LabeledGraph<N, A> graph); }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/IPathLikelihoodProvidingPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import org.api4.java.datastructure.graph.ILabeledPath; public interface IPathLikelihoodProvidingPolicy<N, A> { public double getLikelihood(ILabeledPath<N, A> path); }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/IPathUpdatablePolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import java.util.List; import org.api4.java.datastructure.graph.ILabeledPath; public interface IPathUpdatablePolicy<N, A, V extends Comparable<V>> extends IPolicy<N, A> { public void updatePath(ILabeledPath<N, A> path, List<V> scores); // the scores are the observed scores over the edges of the path }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/IPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import java.util.Collection; public interface IPolicy<N, A> { public A getAction(N node, Collection<A> allowedActions) throws ActionPredictionFailedException, InterruptedException; }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/IRolloutLimitDependentPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; public interface IRolloutLimitDependentPolicy { public void setEstimatedNumberOfRemainingRollouts(int numRollouts); }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/MCTS.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.api4.java.algorithm.Timeout; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.common.event.IEvent; import org.api4.java.common.event.IRelaxedEventEmitter; import org.api4.java.datastructure.graph.ILabeledPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; import ai.libs.jaicore.basic.algorithm.AAlgorithm; import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent; import ai.libs.jaicore.search.model.other.SearchGraphPath; import ai.libs.jaicore.search.probleminputs.IMDP; import ai.libs.jaicore.search.probleminputs.MDPUtils; import ai.libs.jaicore.timing.TimedComputation; /** * * @author Felix Mohr * * @param <N> * Type of states (nodes) * @param <A> * Type of actions */ public class MCTS<N, A> extends AAlgorithm<IMDP<N, A, Double>, IPolicy<N, A>> { private Logger logger = LoggerFactory.getLogger(MCTS.class); private static final Runtime runtime = Runtime.getRuntime(); private final IMDP<N, A, Double> mdp; private final int maxDepth; private final MDPUtils utils = new MDPUtils(); private final IPathUpdatablePolicy<N, A, Double> treePolicy; private final IPolicy<N, A> defaultPolicy; private final boolean uniformSamplingDefaultPolicy; private final Random randomSourceOfUniformSamplyPolicy; private final int maxIterations; /* variables describing the state of the search */ private int iterations = 0; private final Collection<N> tpReadyStates = new HashSet<>(); private final Map<N, Collection<A>> applicableActionsPerState = new HashMap<>(); private final Map<N, List<A>> untriedActionsOfIncompleteStates = new HashMap<>(); private int lastProgressReport = 0; /* stats variables */ private int msSpentInRollouts; private int msSpentInTreePolicyQueries; private int msSpentInTreePolicyUpdates; /* taboo management */ private final boolean tabooExhaustedNodes; private Map<N, Collection<A>> tabooActions = new HashMap<>(); private ILabeledPath<N, A> enforcedPrefixPath = null; public MCTS(final IMDP<N, A, Double> input, final IPathUpdatablePolicy<N, A, Double> treePolicy, final IPolicy<N, A> defaultPolicy, final int maxIterations, final double gamma, final double epsilon, final boolean tabooExhaustedNodes) { super(input); Objects.requireNonNull(input); Objects.requireNonNull(treePolicy); Objects.requireNonNull(defaultPolicy); this.mdp = input; this.treePolicy = treePolicy; this.defaultPolicy = defaultPolicy; this.uniformSamplingDefaultPolicy = defaultPolicy instanceof UniformRandomPolicy; this.randomSourceOfUniformSamplyPolicy = this.uniformSamplingDefaultPolicy ? ((UniformRandomPolicy<?, ?, ?>) defaultPolicy).getRandom() : null; this.maxIterations = maxIterations; this.maxDepth = MDPUtils.getTimeHorizon(gamma, epsilon); this.tabooExhaustedNodes = tabooExhaustedNodes; /* forward event of tree policy or default policy if they send some */ if (treePolicy instanceof IRelaxedEventEmitter) { ((IRelaxedEventEmitter) treePolicy).registerListener(new Object() { @Subscribe public void receiveEvent(final IEvent event) { MCTS.this.post(event); } }); } } public List<A> getPotentialActions(final ILabeledPath<N, A> path, final Collection<A> applicableActions) { N current = path.getHead(); List<A> possibleActions = new ArrayList<>(applicableActions); if (possibleActions.isEmpty()) { this.logger.warn("Computing potential actions for an empty set of applicable actions makes no sense! Returning an empty set for node {}.", current); return possibleActions; } /* determine possible actions */ this.logger.debug("Computing potential actions based on {} applicable ones for state {}", applicableActions.size(), current); if (this.tabooExhaustedNodes) { Collection<A> tabooActionsForThisState = this.tabooActions.get(current); this.logger.debug("Found {} tabooed actions for this state.", tabooActionsForThisState != null ? tabooActionsForThisState.size() : 0); if (tabooActionsForThisState != null) { possibleActions = possibleActions.stream().filter(a -> !tabooActionsForThisState.contains(a)).collect(Collectors.toList()); } if (possibleActions.isEmpty() && path.getNumberOfNodes() > 1) { // otherwise we are in the root and the thing ends this.tabooLastActionOfPath(path); } } return possibleActions; } private Collection<A> getApplicableActions(final N state) throws AlgorithmTimeoutedException, ExecutionException, InterruptedException, AlgorithmExecutionCanceledException { Timeout toForSuccessorComputation = new Timeout(this.getRemainingTimeToDeadline().milliseconds() - 1000, TimeUnit.MILLISECONDS); this.logger.debug("Computing all applicable actions with timeout {}.", toForSuccessorComputation); try { Collection<A> applicableActions = Collections.unmodifiableCollection(TimedComputation.compute(() -> this.mdp.getApplicableActions(state), toForSuccessorComputation, "Timeout bound hit.")); this.logger.debug("Number of applicable actions is {}", applicableActions.size()); return applicableActions; } catch (InterruptedException e) { this.checkAndConductTermination(); // check whether we have been canceled internally throw e; // otherwise just throw new Interrupted exception } } @Override public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { this.logger.debug("Stepping MCTS with thread {}", Thread.currentThread()); this.registerActiveThread(); try { switch (this.getState()) { case CREATED: this.logger.info("Initialized MCTS algorithm {}.\n\tTree Policy: {}\n\tDefault Policy: {}\n\tMax Iterations: {}\n\tMax Depth: {}\n\tTaboo Exhausted Nodes: {}", this.getClass().getName(), this.treePolicy, this.defaultPolicy, this.maxIterations, this.maxDepth, this.tabooExhaustedNodes); return this.activate(); case ACTIVE: if (this.iterations >= this.maxIterations) { this.logger.info("Number of iterations reached limit of {}.", this.maxIterations); return this.terminate(); } else { long timeStart = System.currentTimeMillis(); this.iterations++; /* if the number of (estimated) remaining rollouts is relevant for the tree policy, tell it */ if (this.treePolicy instanceof IRolloutLimitDependentPolicy && this.isTimeoutDefined()) { double avgTimeOfRollouts = this.msSpentInRollouts * 1.0 / this.iterations; int expectedRemainingNumberOfRollouts = (int) Math.floor(this.getRemainingTimeToDeadline().milliseconds() / avgTimeOfRollouts); ((IRolloutLimitDependentPolicy) this.treePolicy).setEstimatedNumberOfRemainingRollouts(expectedRemainingNumberOfRollouts); } /* draw playout */ this.logger.info("Draw next playout: #{}.", this.iterations); int invocationsOfTreePolicyInThisIteration = 0; int invocationsOfDefaultPolicyInThisIteration = 0; long timeSpentInActionApplicabilityComputationThisIteration = 0; long timeSpentInSuccessorGenerationThisIteration = 0; long timeSpentInTreePolicyQueriesThisIteration = 0; long timeSpentInTreePolicyUpdatesThisIteration = 0; long timeSpentInDefaultPolicyThisIteration = 0; List<Double> scores = new ArrayList<>(); ILabeledPath<N, A> path = new SearchGraphPath<>(this.mdp.getInitState()); N current = path.getRoot(); A action = null; int phase = 1; long lastTerminationCheck = 0; int depth = 0; while (path.getNumberOfNodes() < this.maxDepth && !this.mdp.isTerminalState(current)) { this.logger.debug("Now extending the roll-out in depth {}", depth); depth++; /* make sure that we have not been canceled/timeouted/interrupted */ long now = System.currentTimeMillis(); if (now - lastTerminationCheck > 1000) { this.checkAndConductTermination(); lastTerminationCheck = now; } /* first case: Tree policy can be applied */ if (phase == 1 && this.tpReadyStates.contains(current)) { /* here we assume that the set of applicable actions is stored in memory, and we just compute the subset of them for the case that taboo is active */ this.logger.debug("Computing possible actions for node {}", current); assert this.applicableActionsPerState.containsKey(current) && !this.applicableActionsPerState.get(current).isEmpty() : "It makes no sense to apply the TP to a node without applicable actions!"; List<A> possibleActions = this.getPotentialActions(path, this.applicableActionsPerState.get(current)); if (possibleActions.isEmpty()) { if (path.isPoint()) { // if we are in the root and cannot do anything anymore, then stop the algorithm. this.logger.info("There are no possible actions in the root. Finishing."); this.summarizeIteration(System.currentTimeMillis() - timeStart, timeSpentInActionApplicabilityComputationThisIteration, timeSpentInSuccessorGenerationThisIteration, invocationsOfTreePolicyInThisIteration, invocationsOfDefaultPolicyInThisIteration, timeSpentInTreePolicyQueriesThisIteration, timeSpentInTreePolicyUpdatesThisIteration, timeSpentInDefaultPolicyThisIteration); return this.terminate(); } break; } this.logger.debug("Ask tree policy to choose one action of: {}.", possibleActions); long tpStart = System.currentTimeMillis(); action = this.treePolicy.getAction(current, possibleActions); timeSpentInTreePolicyQueriesThisIteration += (System.currentTimeMillis() - tpStart); invocationsOfTreePolicyInThisIteration++; Objects.requireNonNull(action, "Actions in MCTS must never be null, but tree policy returned null!"); this.logger.debug("Tree policy recommended action {}.", action); } else { if (phase == 1) { // switch to next phase this.logger.debug("Switching to roll-out phase 2."); phase = 2; } if (phase == 2) { // this phase is for the first node on the path that is not TP ready. This node has (unless it is a leaf) untried actions /* compute the actions that have not been tried for this node */ List<A> untriedActions; if (!this.untriedActionsOfIncompleteStates.containsKey(current)) { // if this is the first time we see this node, compute *all* its successors /* compute possible actions (this is done first since this may take long/timeout/interrupt, so that we check afterwards whether we are still active */ long startActionTime = System.currentTimeMillis(); if (this.getRemainingTimeToDeadline().milliseconds() < 2000) { if (this.getRemainingTimeToDeadline().milliseconds() > 0) { Thread.sleep(this.getRemainingTimeToDeadline().milliseconds()); } this.checkAndConductTermination(); } Collection<A> applicableActions = this.getApplicableActions(current); untriedActions = new ArrayList<>(applicableActions); timeSpentInActionApplicabilityComputationThisIteration += (System.currentTimeMillis() - startActionTime); this.applicableActionsPerState.put(current, applicableActions); /* if there are no applicable actions for this node (dead-end) conduct back-propagation */ if (untriedActions.isEmpty()) { long tpStart = System.currentTimeMillis(); this.treePolicy.updatePath(path, scores); timeSpentInTreePolicyUpdatesThisIteration += (System.currentTimeMillis() - tpStart); IAlgorithmEvent event = new MCTSIterationCompletedEvent<>(this, this.treePolicy, new SearchGraphPath<>(path), scores); this.post(event); this.summarizeIteration(System.currentTimeMillis() - timeStart, timeSpentInActionApplicabilityComputationThisIteration, timeSpentInSuccessorGenerationThisIteration, invocationsOfTreePolicyInThisIteration, invocationsOfDefaultPolicyInThisIteration, timeSpentInTreePolicyQueriesThisIteration, timeSpentInTreePolicyUpdatesThisIteration, timeSpentInDefaultPolicyThisIteration); return event; } this.untriedActionsOfIncompleteStates.put(current, untriedActions); } else { untriedActions = this.untriedActionsOfIncompleteStates.get(current); } /* now remove the first untried action from the list */ this.logger.debug("There are {} untried actions: {}", untriedActions.size(), untriedActions); assert !untriedActions.isEmpty() : "Untried actions must not be empty!"; action = untriedActions.remove(0); this.logger.debug("Choosing untried action {}. There are {} remaining untried actions: {}", action, untriedActions.size(), untriedActions); Objects.requireNonNull(action, "Actions in MCTS must never be null!"); /* if this was the last untried action, remove it from that field and add it to the tree policy pool */ if (untriedActions.isEmpty()) { this.untriedActionsOfIncompleteStates.remove(current); this.tpReadyStates.add(current); if (path.isPoint()) { this.post(new GraphInitializedEvent<>(this, current)); } else { this.post(new NodeAddedEvent<>(this, path.getPathToParentOfHead().getHead(), current, "none")); } this.logger.debug("Adding state {} to tree policy domain.", current); } phase = 3; this.logger.debug("Switching to roll-out phase 3."); } else if (phase == 3) { long startDP = System.currentTimeMillis(); /* if the default policy is a uniform sampler, just directly ask the MDP */ if (this.uniformSamplingDefaultPolicy) { this.logger.debug("Sample a single action directly from the MDP."); action = this.mdp.getUniformlyRandomApplicableAction(current, this.randomSourceOfUniformSamplyPolicy); } else { /* determine possible actions and ask default policy which one to choose */ long startActionTime = System.currentTimeMillis(); Collection<A> applicableActions = this.getApplicableActions(current); timeSpentInActionApplicabilityComputationThisIteration += (System.currentTimeMillis() - startActionTime); this.logger.debug("Ask default policy to choose one action of: {}.", applicableActions); action = this.defaultPolicy.getAction(current, applicableActions); assert applicableActions.contains(action); } timeSpentInDefaultPolicyThisIteration += (System.currentTimeMillis() - startDP); invocationsOfDefaultPolicyInThisIteration++; Objects.requireNonNull(action, "Actions in MCTS must never be null, but default policy has returned null!"); this.logger.debug("Default policy chose action {}.", action); } else { throw new IllegalStateException("Invalid phase " + phase); } } /* we now have the action chosen for this node. Now draw a successor state */ long startSuccessorComputation = System.currentTimeMillis(); N nextState = this.utils.drawSuccessorState(this.mdp, current, action); timeSpentInSuccessorGenerationThisIteration += System.currentTimeMillis() - startSuccessorComputation; scores.add(this.mdp.getScore(current, action, nextState)); current = nextState; path.extend(current, action); } /* if we touched the ground with the tree policy, add the last action to the taboo list */ if (this.tabooExhaustedNodes && phase == 1) { this.tabooLastActionOfPath(path); } /* decide whether to show a progress report */ int progress = (int) Math.round(this.iterations * 100.0 / this.maxIterations); if (progress > this.lastProgressReport && progress % 5 == 0) { this.logger.info("Progress: {}%", Math.round(this.iterations * 100.0 / this.maxIterations)); this.lastProgressReport = progress; } boolean hasNullScore = scores.contains(null); /* create and publish roll-out event */ boolean isGoalPath = this.mdp.isTerminalState(path.getHead()); double totalUndiscountedScore = hasNullScore ? Double.NaN : scores.stream().reduce(0.0, (a, b) -> a.doubleValue() + b.doubleValue()); this.logger.info("Found playout of length {}. Head is goal: {}. (Undiscounted) score of path is {}.", path.getNumberOfNodes(), isGoalPath, totalUndiscountedScore); this.logger.debug("Found leaf node with score {}. Now propagating this score over the path with actions {}. Leaf state is: {}.", totalUndiscountedScore, path.getArcs(), path.getHead()); if (!path.isPoint()) { long tpStart = System.currentTimeMillis(); this.treePolicy.updatePath(path, scores); timeSpentInTreePolicyUpdatesThisIteration += (System.currentTimeMillis() - tpStart); } IAlgorithmEvent event = new MCTSIterationCompletedEvent<>(this, this.treePolicy, new SearchGraphPath<>(path), scores); this.post(event); this.summarizeIteration(System.currentTimeMillis() - timeStart, timeSpentInActionApplicabilityComputationThisIteration, timeSpentInSuccessorGenerationThisIteration, invocationsOfTreePolicyInThisIteration, invocationsOfDefaultPolicyInThisIteration, timeSpentInTreePolicyQueriesThisIteration, timeSpentInTreePolicyUpdatesThisIteration, timeSpentInDefaultPolicyThisIteration); return event; } default: throw new IllegalStateException("Don't know what to do in state " + this.getState()); } } catch (ActionPredictionFailedException | ObjectEvaluationFailedException e) { throw new AlgorithmException("Could not create playout due to an exception! MCTS cannot deal with this in general. Please modify your MDP such that this kind of exceptions is resolved to some kind of score.", e); } catch (ExecutionException e) { throw new AlgorithmException("Observed error during timed computation.", e); } catch (InterruptedException e) { this.checkAndConductTermination(); // if we have been canceled, throw the corresponding exception throw e; // otherwise re-throw the InterruptedException } finally { this.logger.debug("Unregistering thread {}", Thread.currentThread()); this.unregisterActiveThread(); } } private void summarizeIteration(final long timeForRolloutThisIteration, final long timeSpentInActionApplicability, final long timeSpentInSuccessorGenerationThisIteration, final int numInvocationsOfTP, final int numInvocationsOfDP, final long timeSpentInTreePolicyQueriesThisIteration, final long timeSpentInTreePolicyUpdatesThisIteration, final long timeSpentInDefaultPolicyThisIteration) { this.msSpentInRollouts += timeForRolloutThisIteration; this.msSpentInTreePolicyQueries += timeSpentInTreePolicyQueriesThisIteration; this.msSpentInTreePolicyUpdates += timeSpentInTreePolicyUpdatesThisIteration; this.logger.info( "Finished rollout in {}ms. Time for computing applicable actions was {}ms and for computing successors {}ms. Time for TP {} queries was {}ms, time to update TP {}ms, time for {} DP queries was {}ms. Currently used memory: {}MB.", timeForRolloutThisIteration, timeSpentInActionApplicability, timeSpentInSuccessorGenerationThisIteration, numInvocationsOfTP, timeSpentInTreePolicyQueriesThisIteration, timeSpentInTreePolicyUpdatesThisIteration, numInvocationsOfDP, timeSpentInDefaultPolicyThisIteration, (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024)); } private void tabooLastActionOfPath(final ILabeledPath<N, A> path) { if (path.isPoint()) { throw new IllegalArgumentException("The path is a point, which has no first action to taboo."); } N lastStatePriorToEnd = path.getParentOfHead(); A lastAction = path.getOutArc(lastStatePriorToEnd); this.tabooActions.computeIfAbsent(lastStatePriorToEnd, n -> new HashSet<>()).add(lastAction); this.logger.debug("Adding action {} to taboo list of state {}", lastAction, lastStatePriorToEnd); } public int getNumberOfRealizedPlayouts() { return this.iterations; } public IPathUpdatablePolicy<N, A, Double> getTreePolicy() { return this.treePolicy; } @Override public IPolicy<N, A> call() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { while (this.hasNext()) { this.nextWithException(); } return this.treePolicy; } public void enforcePrefixPathOnAllRollouts(final ILabeledPath<N, A> path) { if (!path.getRoot().equals(this.mdp.getInitState())) { throw new IllegalArgumentException("Illegal prefix, since root does not coincide with algorithm root. Proposed root is: " + path.getRoot()); } this.enforcedPrefixPath = path; N last = null; for (N node : path.getNodes()) { if (last != null) { this.tpReadyStates.remove(last); this.tpReadyStates.add(node); } last = node; } throw new UnsupportedOperationException("Currently, enforced prefixes are ignored!"); } public ILabeledPath<N, A> getEnforcedPrefixPath() { return this.enforcedPrefixPath.getUnmodifiableAccessor(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); super.setLoggerName(name + ".abstract"); /* set logger name in MDP */ if (this.mdp instanceof ILoggingCustomizable) { ((ILoggingCustomizable) this.mdp).setLoggerName(name + ".mdp"); } /* set logger of tree policy */ if (this.treePolicy instanceof ILoggingCustomizable) { this.logger.info("Setting logger of tree policy to {}.treepolicy", name); ((ILoggingCustomizable) this.treePolicy).setLoggerName(name + ".tp"); } else { this.logger.info("Not setting logger of tree policy, because {} is not customizable.", this.treePolicy.getClass().getName()); } /* set logger of default policy */ if (this.defaultPolicy instanceof ILoggingCustomizable) { this.logger.info("Setting logger of default policy to {}.defaultpolicy", name); ((ILoggingCustomizable) this.defaultPolicy).setLoggerName(name + ".dp"); } else { this.logger.info("Not setting logger of default policy, because {} is not customizable.", this.defaultPolicy.getClass().getName()); } this.utils.setLoggerName(name + ".utils"); } public boolean hasTreePolicyReachedLeafs() { throw new UnsupportedOperationException("Currently not implemented."); } @Override public String getLoggerName() { return this.logger.getName(); } public int getNumberOfNodesInMemory() { return this.tpReadyStates.size(); } public int getMsSpentInRollouts() { return this.msSpentInRollouts; } public int getMsSpentInTreePolicyQueries() { return this.msSpentInTreePolicyQueries; } public int getMsSpentInTreePolicyUpdates() { return this.msSpentInTreePolicyUpdates; } public boolean isTabooExhaustedNodes() { return this.tabooExhaustedNodes; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/MCTSFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import java.util.Random; import ai.libs.jaicore.basic.algorithm.AAlgorithmFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public abstract class MCTSFactory<N, A, B extends MCTSFactory<N, A, B>> extends AAlgorithmFactory<IMDP<N, A, Double>, IPolicy<N, A>, MCTS<N, A>> { private int maxIterations = Integer.MAX_VALUE; private double gamma = 1.0; // a gamma value of 1 means that there is no discount private double epsilon = 0.0; private Random random = new Random(0); private boolean tabooExhaustedNodes = false; private boolean maximize = false; private IPolicy<N, A> defaultPolicy; public int getMaxIterations() { return this.maxIterations; } public B withMaxIterations(final int maxIterations) { this.maxIterations = maxIterations; return this.getSelf(); } public double getGamma() { return this.gamma; } public B withGamma(final double gamma) { this.gamma = gamma; return this.getSelf(); } public double getEpsilon() { return this.epsilon; } public B withEpsilon(final double epsilon) { this.epsilon = epsilon; return this.getSelf(); } public B maximize() { this.maximize = true; return this.getSelf(); } public B minimize() { this.maximize = false; return this.getSelf(); } public boolean isMaximize() { return this.maximize; } public Random getRandom() { return this.random; } public B withRandom(final Random random) { this.random = random; return this.getSelf(); } public boolean isTabooExhaustedNodes() { return this.tabooExhaustedNodes; } public B withTabooExhaustedNodes(final boolean tabooExhaustedNodes) { this.tabooExhaustedNodes = tabooExhaustedNodes; return this.getSelf(); } public B withDefaultPolicy(final IPolicy<N, A> defaultPolicy) { this.defaultPolicy = defaultPolicy; return this.getSelf(); } public IPolicy<N, A> getDefaultPolicy() { return this.getDefaultPolicy(false); } public IPolicy<N, A> getDefaultPolicy(final boolean instantiateUniformIfNotSet) { if (this.defaultPolicy != null || !instantiateUniformIfNotSet) { return this.defaultPolicy; } else { return new UniformRandomPolicy<>(this.random); } } @Override public MCTS<N, A> getAlgorithm() { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") public B getSelf() { return (B) this; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/MCTSIterationCompletedEvent.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import java.util.List; import org.api4.java.algorithm.IAlgorithm; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; public class MCTSIterationCompletedEvent<N, A, V extends Comparable<V>> extends AAlgorithmEvent { private final ILabeledPath<N, A> rollout; private final List<V> scores; private final IPolicy<N, A> treePolicy; public MCTSIterationCompletedEvent(final IAlgorithm<?, ?> algorithm, final IPolicy<N, A> treePolicy, final ILabeledPath<N, A> rollout, final List<V> scores) { super(algorithm); this.treePolicy = treePolicy; this.rollout = rollout; this.scores = scores; } public ILabeledPath<N, A> getRollout() { return this.rollout; } public IPolicy<N, A> getTreePolicy() { return this.treePolicy; } public List<V> getScores() { return this.scores; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/NodeLabel.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import java.util.HashMap; import java.util.Map; public class NodeLabel<A> { private int visits = 0; private Map<A, Integer> numberOfChoicesPerAction = new HashMap<>(); private Map<A, Double> accumulatedRewardsOfAction = new HashMap<>(); public int getVisits() { return this.visits; } public void setVisits(final int visits) { this.visits = visits; } public Map<A, Integer> getNumberOfChoicesPerAction() { return this.numberOfChoicesPerAction; } public void setNumberOfChoicesPerAction(final Map<A, Integer> numberOfChoicesPerAction) { this.numberOfChoicesPerAction = numberOfChoicesPerAction; } public double getAccumulatedRewardsOfAction(final A action) { return this.accumulatedRewardsOfAction.computeIfAbsent(action, a -> 0.0); } public void setAccumulatedRewardsOfAction(final Map<A, Double> accumulatedRewardsOfAction) { this.accumulatedRewardsOfAction = accumulatedRewardsOfAction; } public int getNumPulls(final A action) { return this.numberOfChoicesPerAction.computeIfAbsent(action, a -> 0); } public boolean isVirgin(final A action) { return !this.numberOfChoicesPerAction.containsKey(action); } public double getAverageRewardOfAction(final A action) { return this.getAccumulatedRewardsOfAction(action) / this.getNumPulls(action); } public void addRewardForAction(final A action, final double reward) { this.accumulatedRewardsOfAction.put(action, this.getAccumulatedRewardsOfAction(action) + reward); } public void addVisit() { this.visits ++; } public void addPull(final A a) { this.numberOfChoicesPerAction.put(a, this.numberOfChoicesPerAction.computeIfAbsent(a, ac -> 0) + 1); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/RolloutAnalyzer.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import com.google.common.eventbus.Subscribe; import ai.libs.jaicore.graph.Graph; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RolloutEvent; public class RolloutAnalyzer<N> { private Graph<N> explorationGraph = new Graph<>(); private final Map<N, Integer> depths = new HashMap<>(); private final Map<N, DescriptiveStatistics> currentScoreOfNodes = new HashMap<>(); private final Map<N, Integer> iterationOfLastRollout = new HashMap<>(); private final Map<N, Map<N, DescriptiveStatistics>> statsOfChildrenOfNodesAtTimeOfLastRolloutOfNodeWithLessRollouts = new HashMap<>(); private final Map<N, Integer> iterationOfDecision = new HashMap<>(); private final Map<N, List<N>> decisionLists = new HashMap<>(); private int numRollouts = 0; @Subscribe public void receiveRolloutEvent(final RolloutEvent<N, Double> event) { this.explorationGraph.addPath(event.getPath()); this.numRollouts ++; AtomicInteger depth = new AtomicInteger(); N parent = null; for (N node : event.getPath()) { this.depths.computeIfAbsent(node, n -> depth.get()); this.currentScoreOfNodes.computeIfAbsent(node, n -> new DescriptiveStatistics()).addValue(event.getScore()); this.iterationOfLastRollout.put(node, this.numRollouts); depth.getAndIncrement(); if (parent != null) { Set<N> successors = this.explorationGraph.getSuccessors(parent); boolean childWithLessRolloutsIsUpdated = this.getChildrenOfNodesInOrderOfTheNumberOfVisits(parent).get(0).equals(node); if (childWithLessRolloutsIsUpdated) { Map<N, DescriptiveStatistics> mapForParent = this.statsOfChildrenOfNodesAtTimeOfLastRolloutOfNodeWithLessRollouts.computeIfAbsent(parent, n -> new HashMap<>()); for (N child : successors) { mapForParent.put(child, this.currentScoreOfNodes.get(child).copy()); } this.iterationOfDecision.put(parent, this.numRollouts); } this.decisionLists.computeIfAbsent(parent, n -> new ArrayList<>()).add(node); } parent = node; } } public List<N> getMostVisistedSubPath(final int length) { List<N> path = new ArrayList<>(length); path.add(this.explorationGraph.getRoot()); N current = path.get(0); for (int i = 0; i < length; i++) { N mostVisitedChild = null; long numVisitsOfThatChild = 0; for (N child : this.explorationGraph.getSuccessors(current)) { long numVisitsOfThisChild = this.currentScoreOfNodes.get(child).getN(); if (numVisitsOfThisChild > numVisitsOfThatChild) { numVisitsOfThatChild = numVisitsOfThisChild; mostVisitedChild = child; } } current = mostVisitedChild; path.add(current); } return path; } public Map<Integer, int[]> getVisitStatsOfMostVisitedChildrenPerDepth(final int depth, final int memoryLength) { List<N> mostVisistedPath = this.getMostVisistedSubPath(depth); Map<Integer, int[]> stats = new HashMap<>(); for (int i = 0; i <= depth; i++) { /* go back $memoryLength many steps on the path and compute all children up to the current depth in DFS fashion */ int historySize = Math.min(i, memoryLength); N relevantNode = mostVisistedPath.get(i - historySize); List<N> descendants = this.enumerateChildrenOfNodeUpToDepth(relevantNode, historySize); int n = descendants.size(); int[] statsForThisDepth = new int[n]; for (int j = 0; j < n; j++) { statsForThisDepth[j] = (int)this.currentScoreOfNodes.get(descendants.get(j)).getN(); } stats.put(i, statsForThisDepth); } return stats; } public List<N> getChildrenOfNodesInOrderOfTheNumberOfVisits(final N node) { return this.explorationGraph.getSuccessors(node).stream().sorted((s1, s2) -> Long.compare(this.currentScoreOfNodes.get(s1).getN(), this.currentScoreOfNodes.get(s2).getN())).collect(Collectors.toList()); } public Map<Integer, int[]> getLatestRolloutAlongMostVisitedChildrenPerDepth(final int depth, final int memoryLength) { List<N> mostVisistedPath = this.getMostVisistedSubPath(depth); Map<Integer, int[]> stats = new HashMap<>(); for (int i = 0; i <= depth; i++) { /* go back $memoryLength many steps on the path and compute all children up to the current depth in DFS fashion */ int historySize = Math.min(i, memoryLength); N relevantNode = mostVisistedPath.get(i - historySize); List<N> descendants = this.enumerateChildrenOfNodeUpToDepth(relevantNode, historySize); int n = descendants.size(); int[] statsForThisDepth = new int[n]; for (int j = 0; j < n; j++) { statsForThisDepth[j] = this.iterationOfLastRollout.get(descendants.get(j)); } stats.put(i, statsForThisDepth); } return stats; } public Map<Integer, Map<N, DescriptiveStatistics>> getChildrenStatisticsAtPointOfDecisionOfMostVisitedPathPerDepth(final int depth) { List<N> mostVisistedPath = this.getMostVisistedSubPath(depth); Map<Integer, Map<N, DescriptiveStatistics>> stats = new HashMap<>(); for (int i = 0; i <= depth; i++) { N node = mostVisistedPath.get(i); Map<N, DescriptiveStatistics> statsOfChildren = this.statsOfChildrenOfNodesAtTimeOfLastRolloutOfNodeWithLessRollouts.get(node); stats.put(i, statsOfChildren); } return stats; } public List<N> enumerateChildrenOfNodeUpToDepth(final N node, final int depth) { if (depth == 0) { return Arrays.asList(node); } List<N> nodes = new ArrayList<>((int)Math.pow(2, depth)); for (N child : this.explorationGraph.getSuccessors(node)) { nodes.addAll(this.enumerateChildrenOfNodeUpToDepth(child, depth - 1)); } return nodes; } public Map<Integer, DescriptiveStatistics> getVisitStatsPerDepth() { Map<Integer, DescriptiveStatistics> stats = new HashMap<>(); for (N node : this.explorationGraph.getItems()) { stats.computeIfAbsent(this.depths.get(node), n -> new DescriptiveStatistics()).addValue(this.currentScoreOfNodes.get(node).getN()); } return stats; } public Map<N, Integer> getIterationOfDecision() { return this.iterationOfDecision; } public List<N> getDecisionListForNode(final N node) { return this.decisionLists.get(node); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/UniformRandomPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.IRandomizable; /** * * @author Felix Mohr * * @param <N> Type of states (nodes) * @param <A> Type of actions * @param <V> Type of scores */ public class UniformRandomPolicy<N, A, V extends Comparable<V>> implements IPolicy<N, A>, IRandomizable, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(UniformRandomPolicy.class); private final Random r; public UniformRandomPolicy() { this(new Random()); } public UniformRandomPolicy(final Random r) { super(); this.r = r; } @Override public A getAction(final N node, final Collection<A> actions) { this.logger.debug("Deriving action for node {}. Options are: {}", node, actions); if (actions.isEmpty()) { throw new IllegalArgumentException("Cannot determine action if no actions are given!"); } if (actions.size() == 1) { return actions.iterator().next(); } A choice; int chosenIndex = this.r.nextInt(actions.size()); if (actions instanceof List) { choice = ((List<A>)actions).get(chosenIndex); } else { Iterator<A> it = actions.iterator(); for (int i = 0; i < chosenIndex; i++) { it.next(); } choice = it.next(); } this.logger.info("Recommending action {}", choice); return choice; } public void updatePath(final List<N> path, final V score) { this.logger.debug("Updating path {} with score {}", path, score); } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } @Override public Random getRandom() { return this.r; } @Override public void setRandom(final Random random) { throw new UnsupportedOperationException("Random source cannot be overwritten."); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/brue/BRUE.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.brue; import java.util.Random; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.probleminputs.IMDP; import ai.libs.jaicore.search.probleminputs.MDPUtils; public class BRUE<N, A> extends MCTS<N, A> { public BRUE(final IMDP<N, A, Double> input, final IPolicy<N, A> defaultPolicy, final int maxIterations, final double gamma, final double epsilon, final Random random, final boolean tabooExhaustedNodes) { super(input, new BRUEPolicy<>(input.isMaximizing(), MDPUtils.getTimeHorizon(gamma, epsilon), new Random(random.nextLong())), defaultPolicy, maxIterations, gamma, epsilon, tabooExhaustedNodes); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/brue/BRUEFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.brue; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public class BRUEFactory<N, A> extends MCTSFactory<N, A, BRUEFactory<N, A>> { @Override public MCTS<N, A> getAlgorithm(final IMDP<N, A, Double> input) { return new BRUE<>(input, this.getDefaultPolicy(true), this.getMaxIterations(), this.getGamma(), this.getEpsilon(), this.getRandom(), this.isTabooExhaustedNodes()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/brue/BRUEPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.brue; 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.Random; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.search.algorithms.mdp.mcts.ActionPredictionFailedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; /** * * This policy implements the BRUE algorithm presented in * * @article{ title={Simple regret optimization in online planning for Markov decision processes}, author={Feldman, Zohar and Domshlak, Carmel}, journal={Journal of Artificial Intelligence Research}, volume={51}, pages={165--205}, year={2014} } * * @author Felix Mohr * * @param <N> * @param <A> */ public class BRUEPolicy<N, A> implements IPathUpdatablePolicy<N, A, Double> { private final Map<Pair<N, A>, Integer> nCounter = new HashMap<>(); private final Map<Pair<N, A>, Double> qHat = new HashMap<>(); private final Random random; private final int timeHorizon; // H in the paper private final boolean maximize; private int n = 0; // iteration of the algorithm public BRUEPolicy(final boolean maximize, final int timeHorizon, final Random random) { super(); this.maximize = maximize; this.timeHorizon = timeHorizon; this.random = random; } public BRUEPolicy(final boolean maximize) { this(maximize, 1000, new Random(0)); } @Override public A getAction(final N node, final Collection<A> actions) throws ActionPredictionFailedException { if (actions.isEmpty()) { throw new IllegalArgumentException(); } /* compute actions that are optimal for this state */ double bestScore = (this.maximize ? -1 : 1) * Double.MAX_VALUE; double worstValue = bestScore; List<A> bestActions = new ArrayList<>(); for (A action: actions) { Pair<N, A> pair = new Pair<>(node, action); double score = this.qHat.containsKey(pair) ? this.qHat.get(pair) : worstValue; if (score < bestScore) { bestActions.clear(); bestScore = score; bestActions.add(pair.getY()); } else if (score == bestScore) { bestActions.add(pair.getY()); } } /* draw uniformly from them */ if (bestActions.isEmpty()) { throw new IllegalStateException(); } if (bestActions.size() > 1) { Collections.shuffle(bestActions, this.random); } A choice = bestActions.get(0); Pair<N, A> pair = new Pair<>(node, choice); this.nCounter.put(pair, this.nCounter.computeIfAbsent(pair, p -> 0) + 1); return choice; } @Override /** * BRUE only updates ONE SINGLE state-action pair as described in the last bullet point on p.9. * This is the state immediately before the switching point. * */ public void updatePath(final ILabeledPath<N, A> path, final List<Double> scores) { /* BRUE only updates the state previous to the switch point. Compute this state */ int sigmaN = this.getSwitchingPoint(this.n); if (sigmaN < 0) { throw new IllegalStateException("The switching point index must NOT be negative!"); } this.n++; int l = path.getNumberOfNodes(); if (sigmaN > l - 2) { // ignore updates for switching points greather than the actual playout. return; } List<N> nodes = path.getNodes(); List<A> arcs = path.getArcs(); N node = nodes.get(sigmaN - 1); // where we come from A arc = arcs.get(sigmaN - 1); // the action we take Pair<N, A> updatedPair = new Pair<>(node, arc); /* update the state */ double worstValue = (this.maximize ? (-1) : 1) * Double.MAX_VALUE; double currentScore = this.qHat.containsKey(updatedPair) ? this.qHat.get(updatedPair) : worstValue; if (!this.nCounter.containsKey(updatedPair)) { throw new IllegalStateException("No visit stats for updated pair " + updatedPair + " available."); } double observedRewardsFromTheUpdatedAction = 0; for (int i = l - 2; i >= sigmaN - 1; i --) { observedRewardsFromTheUpdatedAction += scores.get(i); // BRUE does not use discounting! } double newScore = currentScore + (observedRewardsFromTheUpdatedAction - currentScore) / this.nCounter.get(updatedPair); this.qHat.put(updatedPair, newScore); } public int getSwitchingPoint(final int n) { return this.timeHorizon - (n % this.timeHorizon); // we start counting n at 0 instead of 1 in order to avoid subtract 1 each time in this computation. } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/CombinedGammaFunction.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; public class CombinedGammaFunction implements IGammaFunction { private final IGammaFunction shortTermGamma; private final IGammaFunction longTermGamma; private static final double MID_WEIGHT = 0.8; private static final double ZERO_OFFSET = -5; private static final double LONG_TERM_BREAK = .1; private final double slope; public CombinedGammaFunction(final IGammaFunction shortTermGamma, final IGammaFunction longTermGamma) { super(); this.shortTermGamma = shortTermGamma; this.longTermGamma = longTermGamma; /* first compute target of linear transformation for mid */ double z = -1 * Math.log(1 / MID_WEIGHT - 1); /* second compute the linear transformation */ this.slope = (ZERO_OFFSET - z) / -.5; } @Override public double getNodeGamma(final int visits, final double nodeProbability, final double relativeDepth) { double longTermWeight = this.getLongTermWeightBasedOnProbability(nodeProbability); double vLongTermGamma = this.longTermGamma.getNodeGamma(visits, nodeProbability, relativeDepth); if (longTermWeight > LONG_TERM_BREAK && vLongTermGamma == 0) { return 0; } double vShortTermGamma = this.shortTermGamma.getNodeGamma(visits, nodeProbability, relativeDepth); return vLongTermGamma * longTermWeight + vShortTermGamma * (1 - longTermWeight); } public double getLongTermWeightBasedOnProbability(final double nodeProbability) { /* compute input for sigmoid */ double xp = this.slope * nodeProbability + ZERO_OFFSET; /* return sigmoid */ return 1 / (1 + Math.exp(-1 * xp)); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/CosLinGammaFunction.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; import java.util.function.DoubleFunction; public class CosLinGammaFunction implements IGammaFunction { private final double maxGamma; private final int visitsToReachOne; private final int initialMinThreshold; private final int absoluteMinThreshold; public CosLinGammaFunction(final double maxGamma, final int visitsToReachOne, final int initialMinThreshold, final int absoluteMinThreshold) { super(); this.maxGamma = maxGamma; this.visitsToReachOne = visitsToReachOne; this.initialMinThreshold = initialMinThreshold; this.absoluteMinThreshold = absoluteMinThreshold; } /* this function describe in general the exploration behavior (in the unit interval) */ private final DoubleFunction<Double> exploitationShape = x -> { if (x < 0 || x > 1) { throw new IllegalArgumentException(); } double val = 0.5 * (Math.cos(x * Math.PI) + 1); if (val > 1 || val < 0) { throw new IllegalStateException("shape range must be within unit interval!"); } return 1 - val; }; /** * This function computes a mapping into the sigmoid where initialMinThreshold is mapped to 1 and absoluteMinThreshold -1 * * @param relativeDepth * @return */ public int getMinRequiredVisits(final double relativeDepth) { final double certaintyBound = 5; final double maxRelativeDepthForMinMinThreshold = 0.8; double slope = (2 * certaintyBound) / maxRelativeDepthForMinMinThreshold; double factor = 1 - 1 / (1 + Math.exp(-1 * (slope * relativeDepth - certaintyBound))); double min = factor * (this.initialMinThreshold - this.absoluteMinThreshold) + this.absoluteMinThreshold; return (int)Math.round(min); } @Override public double getNodeGamma(final int visits, final double nodeProbability, final double relativeDepth) { double g; int minThreshold = this.getMinRequiredVisits(relativeDepth); if (visits <= minThreshold) { return 0.0; } if (visits > this.visitsToReachOne) { g = Math.min(this.maxGamma, Math.pow((double)visits - this.visitsToReachOne, 1.0/3)); } else { double scaledValue = (visits - minThreshold) * 1.0 / (this.visitsToReachOne - minThreshold); if (scaledValue < 0 || scaledValue > 1) { throw new IllegalStateException("Computed intermediate gamma value " + scaledValue); } g = this.exploitationShape.apply(scaledValue); if (g < 0 || g > 1) { throw new IllegalStateException(); } } if (g < 0 || g > this.maxGamma) { throw new IllegalStateException(); } return g; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/FixedCommitmentMCTS.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; import java.util.function.ToDoubleFunction; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.probleminputs.IMDP; public class FixedCommitmentMCTS<N, A> extends MCTS<N, A> { public FixedCommitmentMCTS(final IMDP<N, A, Double> input, final IPolicy<N, A> defaultPolicy, final int k, final ToDoubleFunction<DescriptiveStatistics> metric, final int maxIterations, final double gamma, final double epsilon, final boolean tabooExhaustedNodes) { super(input, new FixedCommitmentPolicy<>(k, metric), defaultPolicy, maxIterations, gamma, epsilon, tabooExhaustedNodes); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/FixedCommitmentMCTSFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; import java.util.function.ToDoubleFunction; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public class FixedCommitmentMCTSFactory<N, A> extends MCTSFactory<N, A, FixedCommitmentMCTSFactory<N, A>> { private ToDoubleFunction<DescriptiveStatistics> metric; private int k = 10; public ToDoubleFunction<DescriptiveStatistics> getMetric() { return this.metric; } public void setMetric(final ToDoubleFunction<DescriptiveStatistics> metric) { this.metric = metric; } public int getK() { return this.k; } public void setK(final int k) { this.k = k; } @Override public MCTS<N, A> getAlgorithm(final IMDP<N, A, Double> input) { if (this.metric == null) { throw new IllegalStateException("Cannot create FixedCommitment MCTS since metric not set!"); } return new FixedCommitmentMCTS<>(input, this.getDefaultPolicy(true), this.k, this.metric, this.getMaxIterations(), this.getGamma(), this.getEpsilon(), this.isTabooExhaustedNodes()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/FixedCommitmentPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.ToDoubleFunction; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.search.algorithms.mdp.mcts.ActionPredictionFailedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; public class FixedCommitmentPolicy<N, A> implements IPathUpdatablePolicy<N, A, Double> { private final Map<N, Map<A, DescriptiveStatistics>> observationsPerNode = new HashMap<>(); private final int k; private final ToDoubleFunction<DescriptiveStatistics> metric; public FixedCommitmentPolicy(final int k, final ToDoubleFunction<DescriptiveStatistics> metric) { super(); this.k = k; this.metric = metric; } @Override public A getAction(final N node, final Collection<A> actions) throws ActionPredictionFailedException { /* determine number of visits of the child with least visits */ A actionWithLeastVisits = null; A actionWithBestVisit = null; int numOfVisitsOfThatChild = Integer.MAX_VALUE; double bestChildScore = Double.MAX_VALUE; for (A action: actions) { DescriptiveStatistics observations = this.observationsPerNode.computeIfAbsent(node, n -> new HashMap<>()).computeIfAbsent(action, a -> new DescriptiveStatistics()); int numOfVisitsOfThisChild = (int)observations.getN(); if (numOfVisitsOfThisChild < numOfVisitsOfThatChild) { actionWithLeastVisits = action; numOfVisitsOfThatChild = numOfVisitsOfThisChild; } double bestScoreOfThisChild = this.metric.applyAsDouble(observations); if (bestScoreOfThisChild < bestChildScore) { bestChildScore = bestScoreOfThisChild; actionWithBestVisit = action; } } /* now decide */ Objects.requireNonNull(actionWithLeastVisits); Objects.requireNonNull(actionWithBestVisit); if (numOfVisitsOfThatChild < this.k) { return actionWithLeastVisits; } else { return actionWithBestVisit; } } @Override public void updatePath(final ILabeledPath<N, A> path, final List<Double> scores) { List<N> nodes = path.getNodes(); List<A> arcs = path.getArcs(); int l = nodes.size(); double accumulatedScores = 0; for (int i = l - 2; i >= 0; i--) { N node = nodes.get(i); A action = arcs.get(i); accumulatedScores += scores.get(i); DescriptiveStatistics statsForNodeActionPair = this.observationsPerNode.computeIfAbsent(node, n -> new HashMap<>()).computeIfAbsent(action,a -> new DescriptiveStatistics()); statsForNodeActionPair.addValue(accumulatedScores); } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/IGammaFunction.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; public interface IGammaFunction { public double getNodeGamma(int visits, double nodeProbability, double relativeDepth); }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/IPreferenceKernel.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; import java.util.Collection; import java.util.List; import org.api4.java.datastructure.graph.ILabeledPath; public interface IPreferenceKernel<N, A> { public A getMostImportantActionToObtainApplicability(final N node, Collection<A> actions); public void signalNewScore(ILabeledPath<N, A> path, double score); public List<List<A>> getRankingsForActions(final N node, Collection<A> actions); public boolean canProduceReliableRankings(final N node, Collection<A> actions); public void signalNodeActiveness(N node); // signals that node is now in principle a candidate for the tree policy public void clearKnowledge(N node); public int getErasedObservationsInTotal(); // allows to ask how many observations have been eliminated }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/ObservationsUpdatedEvent.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; import java.util.Collection; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; public class ObservationsUpdatedEvent<N> extends AAlgorithmEvent { private final N node; private final Collection<Double> scoresLeft; private final Collection<Double> scoresRight; private final int winsLeft; private final int winsRight; private final double pLeft; private final double pRight; private final double pLeftScaled; private final double pRightScaled; private final int visits; public ObservationsUpdatedEvent(final IAlgorithm<?, ?> algorithm, final N node, final int visits, final Collection<Double> scoresLeft, final Collection<Double> scoresRight, final int winsLeft, final int winsRights, final double pLeft, final double pRight, final double pLeftScaled, final double pRightScaled) { super(algorithm); this.visits = visits; this.node = node; this.winsLeft = winsLeft; this.winsRight = winsRights; this.scoresLeft = scoresLeft; this.scoresRight = scoresRight; this.pLeft = pLeft; this.pRight = pRight; this.pLeftScaled = pLeftScaled; this.pRightScaled = pRightScaled; } public N getNode() { return this.node; } public int getVisits() { return this.visits; } public Collection<Double> getScoresLeft() { return this.scoresLeft; } public Collection<Double> getScoresRight() { return this.scoresRight; } public double getpLeft() { return this.pLeft; } public double getpRight() { return this.pRight; } public double getpLeftScaled() { return this.pLeftScaled; } public double getpRightScaled() { return this.pRightScaled; } public int getWinsLeft() { return this.winsLeft; } public int getWinsRight() { return this.winsRight; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/PlackettLuceMCTS.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; import java.util.Random; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.probleminputs.IMDP; public class PlackettLuceMCTS<N, A> extends MCTS<N, A> { public PlackettLuceMCTS(final IMDP<N, A, Double> input, final IPolicy<N, A> defaultPolicy, final IPreferenceKernel<N, A> preferenceKernel, final int maxIterations, final double gamma, final double epsilon, final Random randomForTreePolicy, final boolean tabooExhaustedNodes) { super(input, new PlackettLucePolicy<>(preferenceKernel, randomForTreePolicy), defaultPolicy, maxIterations, gamma, epsilon, tabooExhaustedNodes); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/PlackettLuceMCTSFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; import java.util.Random; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public class PlackettLuceMCTSFactory<N, A> extends MCTSFactory<N, A, PlackettLuceMCTSFactory<N, A>> { private IPreferenceKernel<N, A> preferenceKernel; public PlackettLuceMCTSFactory () { this.withTabooExhaustedNodes(true); } public IPreferenceKernel<N, A> getPreferenceKernel() { return this.preferenceKernel; } public PlackettLuceMCTSFactory<N, A> withPreferenceKernel(final IPreferenceKernel<N, A> preferenceKernel) { this.preferenceKernel = preferenceKernel; return this; } @Override public MCTS<N, A> getAlgorithm(final IMDP<N, A, Double> input) { if (this.preferenceKernel == null) { throw new IllegalStateException("Cannot build PL-MCTS since no preference kernel has been set."); } return new PlackettLuceMCTS<>(input, this.getDefaultPolicy(true), this.preferenceKernel, this.getMaxIterations(), this.getGamma(), this.getEpsilon(), new Random(this.getRandom().nextLong()), this.isTabooExhaustedNodes()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/PlackettLucePolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison; 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.Objects; import java.util.Random; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import org.aeonbits.owner.ConfigFactory; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.common.event.IRelaxedEventEmitter; import org.api4.java.datastructure.graph.ILabeledPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig; import ai.libs.jaicore.basic.MathExt; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.graph.LabeledGraph; import ai.libs.jaicore.graphvisualizer.events.graph.GraphEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodePropertyChangedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeRemovedEvent; import ai.libs.jaicore.math.probability.pl.PLInferenceProblem; import ai.libs.jaicore.math.probability.pl.PLInferenceProblemEncoder; import ai.libs.jaicore.math.probability.pl.PLMMAlgorithm; import ai.libs.jaicore.search.algorithms.mdp.mcts.ActionPredictionFailedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.IRolloutLimitDependentPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.preferencekernel.bootstrapping.BootstrappingPreferenceKernel; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleList; public class PlackettLucePolicy<N, A> implements IPathUpdatablePolicy<N, A, Double>, ILoggingCustomizable, IRelaxedEventEmitter, IRolloutLimitDependentPolicy { private boolean hasListeners = false; private final EventBus eventBus = new EventBus(); public static final String VAR_COMMITMENT = "commitment"; private Logger logger = LoggerFactory.getLogger(PlackettLucePolicy.class); private final IPreferenceKernel<N, A> preferenceKernel; private final Set<N> nodesForWhichAnActionHasBeenRequested = new HashSet<>(); private final LabeledGraph<N, A> activeTree = new LabeledGraph<>(); // maintain back pointers and actions for nodes relevant to the policy private final Map<N, Map<A, Double>> skillsForActions = new HashMap<>(); private final Map<N, Map<A, Integer>> numPulls = new HashMap<>(); private final Map<N, A> fixedDecisions = new HashMap<>(); private final Map<N, Pair<A, Integer>> sequentialCertaintyCounts = new HashMap<>(); private final Map<N, Double> deepestRelativeNodeDepthsOfNodes = new HashMap<>(); private final Map<N, Map<A, Double>> lastLocalProbabilityOfNode = new HashMap<>(); private final Map<N, Integer> depths = new HashMap<>(); private final Random random; private IOwnerBasedAlgorithmConfig config = ConfigFactory.create(IOwnerBasedAlgorithmConfig.class); private final Map<N, Integer> maxChildren = new HashMap<>(); private double avgDepth; private double avgTargetDepth; private double avgBranchingFactor = -1; private int numUpdates; private Function<Integer, Integer> rolloutsForGammaEquals1AsFunctionOfHeight = d -> 1000; /* configuration of gamma-shape. this depends on the branching factor. * Note that "per child" does not mean that each child needs so many visits but for k children, the parent needs k * p observations. */ private static final int GAMMA_LONG_MAX = 2; private static final int GAMMA_LONG_MIN_OBSERVATIONS_PER_CHILD_FOR_SUPPORT_INIT = 1; private static final int GAMMA_LONG_MIN_OBSERVATIONS_PER_CHILD_FOR_SUPPORT_ABS = 10; private static final int GAMMA_LONG_OBSERVATIONS_PER_CHILD_TO_REACH_ONE = 10; private static final double GAMMA_LONG_DERIVATIVE_EXP = 1; private static final double GOAL_COMMIT_DEPTH = 1.2; private static final int GOAL_TARGET_SIZE = (int) Math.pow(2, 5); private static final int MINIMUMNUMBERTOCOMMIT = 20; public PlackettLucePolicy(final IPreferenceKernel<N, A> preferenceKernel, final Random random) { super(); this.preferenceKernel = preferenceKernel; this.random = random; if (preferenceKernel instanceof IRelaxedEventEmitter) { ((IRelaxedEventEmitter) preferenceKernel).registerListener(new Object() { @Subscribe public void receiveEvent(final GraphEvent event) { PlackettLucePolicy.this.eventBus.post(event); } }); } } public IGammaFunction getGammaFunction(final N node, final Collection<A> actions) { int k = actions.size(); int depth = this.depths.get(node); int numberOfOpenDecisions = depth - this.fixedDecisions.size(); boolean isInDecisionMode = numberOfOpenDecisions < this.avgTargetDepth; int obsRequiredForOne = isInDecisionMode ? this.rolloutsForGammaEquals1AsFunctionOfHeight.apply(depth) : 1; if (isInDecisionMode && obsRequiredForOne < GAMMA_LONG_MIN_OBSERVATIONS_PER_CHILD_FOR_SUPPORT_INIT) { this.logger.warn("Cannot work on this problem with {} open decisions, because even the minimum required observations ({}) are higher than the number of observations required to reach one ({}). Setting value to minimum + 1 = {}", numberOfOpenDecisions, GAMMA_LONG_MIN_OBSERVATIONS_PER_CHILD_FOR_SUPPORT_INIT, obsRequiredForOne, GAMMA_LONG_MIN_OBSERVATIONS_PER_CHILD_FOR_SUPPORT_INIT + 1); } if (obsRequiredForOne < 0) { obsRequiredForOne = 100000; // large number } obsRequiredForOne = Math.max(GAMMA_LONG_OBSERVATIONS_PER_CHILD_TO_REACH_ONE * k, obsRequiredForOne); int minObservationsToSupportGamma = GAMMA_LONG_MIN_OBSERVATIONS_PER_CHILD_FOR_SUPPORT_INIT * k; minObservationsToSupportGamma = Math.max(minObservationsToSupportGamma, Math.max(minObservationsToSupportGamma * 2 / 3, obsRequiredForOne - 100)); return new CosLinGammaFunction(GAMMA_LONG_MAX, obsRequiredForOne, minObservationsToSupportGamma, k * GAMMA_LONG_MIN_OBSERVATIONS_PER_CHILD_FOR_SUPPORT_ABS); } public double getGammaValue(final N node, final Collection<A> actions) { Map<A, Integer> numPullsPerAction = this.numPulls.get(node); int visits = 0; for (int pulls : numPullsPerAction.values()) { visits += pulls; } IGammaFunction gammaFunction = this.getGammaFunction(node, actions); double relativeDepth = this.deepestRelativeNodeDepthsOfNodes.get(node); double nodeProbability = this.getProbabilityOfNode(node); return gammaFunction.getNodeGamma(visits, nodeProbability, relativeDepth); } @Override public A getAction(final N node, final Collection<A> actions) throws ActionPredictionFailedException { long start = System.currentTimeMillis(); Map<String, Object> nodeInfoMap = new HashMap<>(); if (!this.depths.containsKey(node)) { throw new IllegalArgumentException("No depth information for node " + node + ". The node has apparently not occured in any back-propagation!"); } int depth = this.depths.get(node); this.logger.info("Determining action for node in depth {}. {} actions available. Node info: {}", depth, actions.size(), node); if (!this.nodesForWhichAnActionHasBeenRequested.contains(node)) { /* memorize that this node has been relevant for decision */ this.logger.debug("Mark node {} as one for which an action has been requested!", node); this.nodesForWhichAnActionHasBeenRequested.add(node); /* inform kernel about this new node */ this.preferenceKernel.signalNodeActiveness(node); if (!this.maxChildren.containsKey(node)) { this.maxChildren.put(node, actions.size()); } } /* disable PL policy for nodes in which x times in a row the same action was recommended with a high probability (then always return that action) */ if (this.fixedDecisions.containsKey(node)) { this.logger.info("Choosing fixed action {}", this.fixedDecisions.get(node)); return this.fixedDecisions.get(node); } /* check whether we can produce a useful information */ if (!this.preferenceKernel.canProduceReliableRankings(node, actions)) { this.logger.info("The preference kernel tells us that it cannot produce reliable information yet. Choosing one that seems most useful to the preference kernel."); return this.preferenceKernel.getMostImportantActionToObtainApplicability(node, actions); } /* determine probability to proceed */ Map<A, Double> lastProbabilities = this.lastLocalProbabilityOfNode.computeIfAbsent(node, dummy -> new HashMap<>()); int k = actions.size(); double maxProb = lastProbabilities.isEmpty() ? 1.0 / k : lastProbabilities.values().stream().max(Double::compare).get(); double probabilityToDerivePLModel = k * (1.0 - maxProb) / (k - 1); this.logger.info("Probability to derive a new model is {}*(1-{}) / ({} - 1) = {}. Last probs were: {}", k, maxProb, k, probabilityToDerivePLModel, lastProbabilities); /* make sure that actions are sorted */ List<A> orderedActions = actions instanceof List ? (List<A>) actions : new ArrayList<>(actions); try { int numChildren = actions.size(); /* compute gamma for this decision */ IGammaFunction gammaFunction = this.getGammaFunction(node, actions); double relativeDepth = this.deepestRelativeNodeDepthsOfNodes.get(node); double nodeProbability = this.getProbabilityOfNode(node); double gammaValue = this.getGammaValue(node, actions); /* update node map (only if there are listeners for this) */ if (this.hasListeners) { if (gammaFunction instanceof CombinedGammaFunction) { double lgw = ((CombinedGammaFunction) gammaFunction).getLongTermWeightBasedOnProbability(nodeProbability); nodeInfoMap.put("longgammaweight", lgw); } nodeInfoMap.put("gamma", gammaValue); nodeInfoMap.put("prob", nodeProbability); } /* if the gamma value is 0, just return a random element */ if (gammaValue == 0) { this.logger.info("Gamma is 0, so all options have equal probability of being chosen. Just return a random element."); nodeInfoMap.put(VAR_COMMITMENT, 0); this.eventBus.post(new NodePropertyChangedEvent<N>(null, node, nodeInfoMap)); return SetUtil.getRandomElement(orderedActions, this.random); } /* check whether there is only one child */ if (numChildren <= 1) { if (numChildren < 1) { throw new UnsupportedOperationException("Cannot compute action for nodes without successors."); } if (orderedActions.size() != 1) { throw new IllegalStateException(); } nodeInfoMap.put(VAR_COMMITMENT, 1); this.eventBus.post(new NodePropertyChangedEvent<N>(null, node, nodeInfoMap)); return orderedActions.iterator().next(); } /* estimate PL-parameters */ Map<A, Double> skills; long skillEstimateStart = System.currentTimeMillis(); long mmRuntime = 0; if (this.random.nextDouble() <= probabilityToDerivePLModel) { this.logger.debug("Computing PL-Problem instance"); PLInferenceProblemEncoder encoder = new PLInferenceProblemEncoder(); PLInferenceProblem problem = encoder.encode(this.preferenceKernel.getRankingsForActions(node, orderedActions)); this.logger.debug("Start computation of skills for {}. Using {} rankings. Gamma value is {} based on node probability {} and depth {}", node, problem.getRankings().size(), gammaValue, nodeProbability, relativeDepth); skills = this.skillsForActions.get(node); long mmStart = System.currentTimeMillis(); PLMMAlgorithm plAlgorithm = new PLMMAlgorithm(problem, skills != null ? new DoubleArrayList(orderedActions.stream().map(skills::get).collect(Collectors.toList())) : null, this.config); plAlgorithm.setLoggerName(this.getLoggerName() + ".pl"); DoubleList skillVector = plAlgorithm.call(); mmRuntime = System.currentTimeMillis() - mmStart; if (skillVector.size() != problem.getNumObjects()) { throw new IllegalStateException("Have " + skills.size() + " skills (" + skills + ") for " + problem.getNumObjects() + " objects."); } if (skills == null) { skills = new HashMap<>(); this.skillsForActions.put(node, skills); } for (A action : orderedActions) { skills.put(action, skillVector.getDouble(encoder.getIndexOfObject(action))); } } else { skills = this.skillsForActions.get(node); this.logger.info("Reusing skill vetor of last iteration. Probability for reuse was {}. Skill map is: {}", 1 - probabilityToDerivePLModel, skills); } long skillEstimateRuntime = System.currentTimeMillis() - skillEstimateStart; Objects.requireNonNull(skills, "The skill map must not be null at this point."); /* adjust PL-parameters according to gamma */ long choiceStart = System.currentTimeMillis(); int n = skills.size(); double sum = 0; Map<A, Double> gammaAdjustedSkills = new HashMap<>(); for (Entry<A, Double> skillValue : skills.entrySet()) { double newVal = Math.pow(skillValue.getValue(), gammaValue); gammaAdjustedSkills.put(skillValue.getKey(), newVal); sum += newVal; } if (sum == 0) { throw new IllegalStateException(); } /* compute probability vector */ DoubleList pVector = new DoubleArrayList(); double curMaxProb = 0; for (A action : orderedActions) { double newProbOfAction = gammaAdjustedSkills.get(action) / sum; curMaxProb = Math.max(curMaxProb, newProbOfAction); if (Double.isNaN(newProbOfAction)) { this.logger.error("Probability of successor is NaN! Skill vector: {}", skills); } lastProbabilities.put(action, newProbOfAction); pVector.add(newProbOfAction); } double commitment = 1 - (k * (1.0 - curMaxProb) / (k - 1)); if (depth == 1) { for (Entry<A, DoubleList> entry : ((BootstrappingPreferenceKernel<N, A>) this.preferenceKernel).getObservations(node).entrySet()) { DescriptiveStatistics stats = new DescriptiveStatistics(); for (double v : entry.getValue()) { stats.addValue(v); } } } nodeInfoMap.put(VAR_COMMITMENT, commitment); this.eventBus.post(new NodePropertyChangedEvent<N>(null, node, nodeInfoMap)); /* draw random action */ A randomChoice = SetUtil.getRandomElement(orderedActions, this.random, pVector); int chosenIndex = orderedActions.indexOf(randomChoice); double probOfChosenAction = pVector.getDouble(chosenIndex); long choiceRuntime = System.currentTimeMillis() - choiceStart; long runtime = System.currentTimeMillis() - start; /* update sequence of sure actions */ long metaStart = System.currentTimeMillis(); if (gammaValue >= 1) { Pair<A, Integer> lastChosenAction = this.sequentialCertaintyCounts.get(node); if (lastChosenAction != null) { if (lastChosenAction.getX().equals(randomChoice) && probOfChosenAction >= .99 && (!this.activeTree.hasItem(node) || this.activeTree.getRoot() == node || this.fixedDecisions.containsKey(this.activeTree.getPredecessors(node).iterator().next()))) { this.logger.info("Incrementing number of sure choices for this action by 1."); int numberOfSuccessfulChoices = lastChosenAction.getY(); if (numberOfSuccessfulChoices >= MINIMUMNUMBERTOCOMMIT) { this.sequentialCertaintyCounts.remove(node); this.logger.warn("Definitely committing to action {} in node {} in depth {}. Freeing resources.", randomChoice, node, this.fixedDecisions.size()); this.fixedDecisions.put(node, randomChoice); this.preferenceKernel.clearKnowledge(node); List<N> irrelevantNodes = new ArrayList<>(); irrelevantNodes.addAll(this.activeTree.getSiblings(node)); List<N> descendants = new ArrayList<>(); irrelevantNodes.forEach(ni -> descendants.addAll(this.activeTree.getDescendants(ni))); irrelevantNodes.addAll(descendants); irrelevantNodes.forEach(in -> { this.preferenceKernel.clearKnowledge(in); this.activeTree.removeItem(in); this.eventBus.post(new NodeRemovedEvent<>(null, in)); }); } else { this.sequentialCertaintyCounts.put(node, new Pair<>(randomChoice, numberOfSuccessfulChoices + 1)); } } else { this.logger.info("Resetting certainty count for this node."); this.sequentialCertaintyCounts.put(node, null); } } else if (probOfChosenAction >= .99) { this.logger.info("Initializing number of sure choices for this action by 1."); this.sequentialCertaintyCounts.put(node, new Pair<>(randomChoice, 1)); } } /* log decision summary */ if (this.logger.isDebugEnabled()) { for (int i = 0; i < n; i++) { A action = orderedActions.get(i); this.logger.debug("Derived probability of {}-th action {} by {} -> {} -> {}", i, action, skills.get(action), gammaAdjustedSkills.get(action), pVector.getDouble(i)); } } long metaRuntime = System.currentTimeMillis() - metaStart; if (this.logger.isInfoEnabled()) { this.logger.info("Eventual choice after {}ms: {} (index {} with probability of {}%). Runtimes are as follows. PL: {}ms ({}ms for MM algorithm), Choice: {}ms, Meta: {}ms", runtime, randomChoice, chosenIndex, MathExt.round(100 * probOfChosenAction, 2), skillEstimateRuntime, mmRuntime, choiceRuntime, metaRuntime); } if (runtime > 10) { this.logger.warn("PL inference took {}ms for {} options, which is more than the allowed!", runtime, actions.size()); } return randomChoice; } catch (AlgorithmTimeoutedException | AlgorithmExecutionCanceledException | AlgorithmException e) { throw new ActionPredictionFailedException(e); } catch (InterruptedException e) { this.logger.info("Policy thread has been interrupted. Re-interrupting thread, because no InterruptedException can be thrown here."); Thread.currentThread().interrupt(); return null; } } public double getProbabilityOfNode(final N node) { N curNode = node; double prob = 1; N root = this.activeTree.getRoot(); while (root != null && curNode != root) { N parent = this.activeTree.getPredecessors(curNode).iterator().next(); A edge = this.activeTree.getEdgeLabel(parent, curNode); if (this.lastLocalProbabilityOfNode.containsKey(parent) && this.lastLocalProbabilityOfNode.get(parent).containsKey(edge)) { prob *= this.lastLocalProbabilityOfNode.get(parent).get(edge); } else { double uniform = 1.0 / this.activeTree.getSuccessors(parent).size(); this.logger.debug("No probability known for node {}. Assuming uniform probability {}.", curNode, uniform); prob *= uniform; } curNode = parent; } return prob; } @Override public void registerListener(final Object listener) { this.eventBus.register(listener); this.hasListeners = true; } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); if (this.preferenceKernel instanceof ILoggingCustomizable) { ((ILoggingCustomizable) this.preferenceKernel).setLoggerName(name + ".kernel"); } } @Override public void updatePath(final ILabeledPath<N, A> path, final List<Double> scores) { double playoutScore = SetUtil.sum(scores); // we neither discount nor care for the segmentation of the scores this.logger.info("Received a playout score of {}. Communicating this to the preference kernel.", playoutScore); this.preferenceKernel.signalNewScore(path, playoutScore); int depth = 0; List<N> nodes = path.getNodes(); List<A> arcs = path.getArcs(); int totalDepth = path.getNumberOfNodes(); int pathLength = path.getNumberOfNodes(); N lastNode = null; A lastAction = null; boolean isNextNodeRelevantForDecisions = true; // a node is relevant if its parent has been subject to decisions at least once while (isNextNodeRelevantForDecisions && depth < pathLength - 1) { N node = nodes.get(depth); A arc = arcs.get(depth); double relativeDepth = depth * 1.0 / totalDepth; if (lastNode != null) { this.activeTree.addEdge(lastNode, node, lastAction); } this.numPulls.computeIfAbsent(node, dummy -> new HashMap<>()).put(arc, this.numPulls.get(node).computeIfAbsent(arc, a -> 0) + 1); this.logger.debug("Updating action {} for node {} with score {} and incrementing its number of pulls.", arc, node, playoutScore); if (!this.deepestRelativeNodeDepthsOfNodes.containsKey(node) || this.deepestRelativeNodeDepthsOfNodes.get(node) < relativeDepth) { this.deepestRelativeNodeDepthsOfNodes.put(node, relativeDepth); } this.logger.debug("Setting depth of node {} to {}", node, depth); this.depths.put(node, depth); isNextNodeRelevantForDecisions = this.nodesForWhichAnActionHasBeenRequested.contains(node); if (!isNextNodeRelevantForDecisions) { this.logger.debug("Node {} has never been requested for an action, so disregarding upcoming observations.", node); } lastNode = node; lastAction = arc; depth++; } /* update avg depth */ if (!this.maxChildren.isEmpty()) { this.avgBranchingFactor = Math.max(2, this.maxChildren.values().stream().reduce((a, b) -> a + b).get() / (1.0 * this.maxChildren.size())); } this.avgDepth = (this.numUpdates * this.avgDepth + pathLength) / (this.numUpdates + 1.0); if (this.avgBranchingFactor > 0) { this.avgTargetDepth = this.avgDepth * GOAL_COMMIT_DEPTH + (Math.log(GOAL_TARGET_SIZE) / Math.log(this.avgBranchingFactor)); } else { this.avgTargetDepth = this.avgDepth; } this.numUpdates++; this.logger.info("Setting avg target depth to {}", this.avgTargetDepth); } @Override public void setEstimatedNumberOfRemainingRollouts(final int pNumRollouts) { if (pNumRollouts < 0) { this.logger.warn("Estimated number of remaining rollouts must not be negative but was {}! Setting it to 1.", pNumRollouts); } if (this.avgBranchingFactor > 0) { /* compute samples to be required in the root for gamma = 1 */ double sumTmp = 0; double hmax = this.avgTargetDepth - this.fixedDecisions.size(); for (int h = 0; h < hmax; h++) { double f = (1 - h / hmax); double innerSum = 0; for (int t = 0; t < h; t++) { innerSum += Math.pow(-1 / this.avgBranchingFactor, t); } sumTmp += innerSum * f; } final double x0 = sumTmp == 0 ? 0 : (pNumRollouts / sumTmp); final double a = x0 / hmax; this.rolloutsForGammaEquals1AsFunctionOfHeight = d -> Math.max((int) (x0 - a * (d - this.fixedDecisions.size())), GAMMA_LONG_MIN_OBSERVATIONS_PER_CHILD_FOR_SUPPORT_INIT + 1); } } public IPreferenceKernel<N, A> getPreferenceKernel() { return this.preferenceKernel; } public Set<N> getNodesForWhichAnActionHasBeenRequested() { return this.nodesForWhichAnActionHasBeenRequested; } public LabeledGraph<N, A> getActiveTree() { return this.activeTree; } public int getDepthOfActiveNode(final N node) { return this.depths.get(node); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/preferencekernel
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/preferencekernel/bootstrapping/BootstrappingPreferenceKernel.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.preferencekernel.bootstrapping; 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.Random; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.common.event.IRelaxedEventEmitter; import org.api4.java.datastructure.graph.ILabeledPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.graphvisualizer.events.graph.NodePropertyChangedEvent; import ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.IPreferenceKernel; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleList; public class BootstrappingPreferenceKernel<N, A> implements IPreferenceKernel<N, A>, ILoggingCustomizable, IRelaxedEventEmitter { private static final int MAXTIME_WARN_CREATERANKINGS = 1; private Logger logger = LoggerFactory.getLogger(BootstrappingPreferenceKernel.class); private final EventBus eventBus = new EventBus(); private boolean hasListeners = false; /* kernel state variables */ private final Set<N> activeNodes = new HashSet<>(); // the nodes for which we memorize the observations private final Map<N, Map<A, DoubleList>> observations = new HashMap<>(); private final Map<N, Map<A, Double>> bestObservationForAction = new HashMap<>(); /* configuration units */ private final IBootstrappingParameterComputer bootstrapParameterComputer; private final IBootstrapConfigurator bootstrapConfigurator; private final int maxNumSamplesInHistory; private final Random random; private final Map<N, List<List<A>>> rankingsForNodes = new HashMap<>(); private final int minSamplesToCreateRankings = 1; /* stats */ private int erasedObservationsInTotal = 0; public BootstrappingPreferenceKernel(final IBootstrappingParameterComputer bootstrapParameterComputer, final IBootstrapConfigurator bootstrapConfigurator, final Random random, final int minSamplesToCreateRankings, final int maxNumSamplesInHistory) { super(); this.bootstrapParameterComputer = bootstrapParameterComputer; this.bootstrapConfigurator = bootstrapConfigurator; this.random = random; this.maxNumSamplesInHistory = maxNumSamplesInHistory; } public BootstrappingPreferenceKernel(final IBootstrappingParameterComputer bootstrapParameterComputer, final IBootstrapConfigurator bootstrapConfigurator, final int minSamplesToCreateRankings) { this(bootstrapParameterComputer, bootstrapConfigurator, new Random(0), minSamplesToCreateRankings, 1000); } @Override public void signalNewScore(final ILabeledPath<N, A> path, final double newScore) { /* add the observation to all stats on the path */ List<N> nodes = path.getNodes(); List<A> arcs = path.getArcs(); int l = nodes.size(); for (int i = 0; i < l - 1; i++) { N node = nodes.get(i); A arc = arcs.get(i); DoubleList list = this.observations.computeIfAbsent(node, n -> new HashMap<>()).computeIfAbsent(arc, a -> new DoubleArrayList()); list.add(newScore); Map<A, Double> bestMap = this.bestObservationForAction.computeIfAbsent(node, n -> new HashMap<>()); bestMap.put(arc, Math.min(newScore, bestMap.computeIfAbsent(arc, a -> Double.MAX_VALUE))); if (list.size() > this.maxNumSamplesInHistory) { list.removeDouble(0); } this.logger.debug("Updated observations for action {} in node {}. New list of observations is: {}", arc, node, list); if (!this.activeNodes.contains(node)) { this.logger.info("The current node has not been marked active and hence, we abort the update procedure saving {} entries.", l - i); return; } } } /** * Computes new rankings from a fresh bootstrap * * @param node * @param parameterComputer * @return */ public List<List<A>> drawNewRankingsForActions(final N node, final Collection<A> actions, final IBootstrappingParameterComputer parameterComputer) { long start = System.currentTimeMillis(); for (A action : actions) { if (!this.observations.containsKey(node) || !this.observations.get(node).containsKey(action)) { throw new IllegalArgumentException("No observations available for action " + action + ", cannot draw ranking."); } } Map<A, DoubleList> observationsPerAction = this.observations.get(node); final int numBootstraps = this.bootstrapConfigurator.getNumBootstraps(observationsPerAction); final int numSamplesPerChildInEachBootstrap = this.bootstrapConfigurator.getBootstrapSizePerChild(observationsPerAction); this.logger.debug("Now creating {} bootstraps (rankings)", numBootstraps); int totalObservations = 0; List<List<A>> rankings = new ArrayList<>(numBootstraps); for (int bootstrap = 0; bootstrap < numBootstraps; bootstrap++) { Map<A, Double> scorePerAction = new HashMap<>(); totalObservations = 0; for (A action : actions) { DoubleList observedScoresForChild = observationsPerAction.get(action); totalObservations += observedScoresForChild.size(); double bestObservation = this.bestObservationForAction.get(node).get(action); DescriptiveStatistics statsForThisChild = new DescriptiveStatistics(); statsForThisChild.addValue(bestObservation); // always ensure that the best value is inside the bootstrap for (int sample = 0; sample < numSamplesPerChildInEachBootstrap - 1; sample++) { statsForThisChild.addValue(SetUtil.getRandomElement(observedScoresForChild, this.random)); } scorePerAction.put(action, parameterComputer.getParameter(statsForThisChild)); } List<A> ranking = actions.stream().sorted((a1, a2) -> Double.compare(scorePerAction.get(a1), scorePerAction.get(a2))).collect(Collectors.toList()); rankings.add(ranking); } long runtime = System.currentTimeMillis() - start; if (runtime > MAXTIME_WARN_CREATERANKINGS) { this.logger.warn("Creating the {} rankings took {}ms for {} options and {} total observations, which is more than the allowed {}ms!", numBootstraps, runtime, actions.size(), totalObservations, MAXTIME_WARN_CREATERANKINGS); } return rankings; } @Override public List<List<A>> getRankingsForActions(final N node, final Collection<A> actions) { this.rankingsForNodes.put(node, this.drawNewRankingsForActions(node, actions, this.bootstrapParameterComputer)); return this.rankingsForNodes.get(node); } @Override public boolean canProduceReliableRankings(final N node, final Collection<A> actions) { /* first check that there is any information about the node */ if (!this.observations.containsKey(node)) { if (this.hasListeners) { this.eventBus.post(new NodePropertyChangedEvent<>(null, node, "plkernelstatus", 0.0)); } this.logger.info("No observations for node yet, not allowing to produce rankings."); return false; } /* now check that the minimum number of samples per node is available */ Map<A, DoubleList> scoresPerAction = this.observations.get(node); for (A action : actions) { if (!scoresPerAction.containsKey(action) || scoresPerAction.get(action).size() < this.minSamplesToCreateRankings) { this.logger.info("Refusing production of rankings, because are less than {} observations for action {}.", this.minSamplesToCreateRankings, action); if (this.hasListeners) { this.eventBus.post(new NodePropertyChangedEvent<>(null, node, "plkernelstatus", 0.0)); } return false; } } this.logger.debug("Enough examples. Allowing the construction of rankings."); if (this.hasListeners) { this.eventBus.post(new NodePropertyChangedEvent<>(null, node, "plkernelstatus", 1.0)); } return true; } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); } @Override public void clearKnowledge(final N node) { if (!this.observations.containsKey(node) || this.observations.get(node).isEmpty()) { return; } if (this.logger.isInfoEnabled()) { this.logger.info("Removing {} observations.", this.observations.get(node).values().stream().map(l -> l.size()).reduce((a, b) -> a + b).get()); } this.erasedObservationsInTotal += this.observations.get(node).size(); this.observations.remove(node); if (this.logger.isInfoEnabled() && this.rankingsForNodes.containsKey(node)) { this.logger.info("Removing {} rankings.", this.rankingsForNodes.get(node).size()); } this.rankingsForNodes.remove(node); } public Map<A, DoubleList> getObservations(final N node) { return this.observations.get(node); } public Set<N> getActiveNodes() { return this.activeNodes; } @Override public void registerListener(final Object listener) { this.eventBus.register(listener); this.hasListeners = true; } @Override public void signalNodeActiveness(final N node) { this.activeNodes.add(node); } @Override public int getErasedObservationsInTotal() { return this.erasedObservationsInTotal; } /** * Returns the action that has least observations */ @Override public A getMostImportantActionToObtainApplicability(final N node, final Collection<A> actions) { Map<A, DoubleList> obsForNode = this.observations.get(node); A leastTriedAction = null; int minAttempts = Integer.MAX_VALUE; for (A action : actions) { int attempts = obsForNode.containsKey(action) ? obsForNode.get(action).size() : 0; if (attempts < minAttempts) { minAttempts = attempts; leastTriedAction = action; } } return leastTriedAction; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/preferencekernel
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/preferencekernel/bootstrapping/DefaultBootsrapConfigurator.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.preferencekernel.bootstrapping; import java.util.Map; import it.unimi.dsi.fastutil.doubles.DoubleList; public class DefaultBootsrapConfigurator implements IBootstrapConfigurator { private final int factor; private final int minNumberOfBootstraps; private final int maxNumberOfBootstraps; private final int size; public DefaultBootsrapConfigurator() { this(2, 100, 1000, 100); } public DefaultBootsrapConfigurator(final int factor, final int minNumberOfBootstraps, final int maxNumberOfBootstraps, final int size) { super(); this.factor = factor; this.minNumberOfBootstraps = minNumberOfBootstraps; this.maxNumberOfBootstraps = maxNumberOfBootstraps; this.size = size; } @Override public int getNumBootstraps(final Map<?, DoubleList> observationsPerAction) { return Math.min(this.maxNumberOfBootstraps, Math.max(this.minNumberOfBootstraps, this.factor * observationsPerAction.size())); } @Override public int getBootstrapSizePerChild(final Map<?, DoubleList> observationsPerAction) { return this.size; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/preferencekernel
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/preferencekernel/bootstrapping/IBootstrapConfigurator.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.preferencekernel.bootstrapping; import java.util.Map; import it.unimi.dsi.fastutil.doubles.DoubleList; public interface IBootstrapConfigurator { public int getNumBootstraps(Map<?, DoubleList> observationsPerAction); public int getBootstrapSizePerChild(Map<?, DoubleList> observationsPerAction); }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/preferencekernel
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/comparison/preferencekernel/bootstrapping/IBootstrappingParameterComputer.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.comparison.preferencekernel.bootstrapping; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; public interface IBootstrappingParameterComputer { public double getParameter(DescriptiveStatistics stats); }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/ensemble/EnsembleMCTS.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.ensemble; import java.util.Collection; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.probleminputs.IMDP; public class EnsembleMCTS<N, A> extends MCTS<N, A> { public EnsembleMCTS(final IMDP<N, A, Double> input, final IPolicy<N, A> defaultPolicy, final Collection<IPathUpdatablePolicy<N, A, Double>> treePolicies, final int maxIterations, final double gamma, final double epsilon, final boolean tabooExhaustedNodes) { super(input, new EnsembleTreePolicy<>(treePolicies), defaultPolicy, maxIterations, gamma, epsilon, tabooExhaustedNodes); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/ensemble/EnsembleMCTSFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.ensemble; import java.util.ArrayList; import java.util.Collection; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public class EnsembleMCTSFactory<N, A> extends MCTSFactory<N, A, EnsembleMCTSFactory<N, A>> { private Collection<IPathUpdatablePolicy<N, A, Double>> treePolicies = new ArrayList<>(); public Collection<IPathUpdatablePolicy<N, A, Double>> getTreePolicies() { return this.treePolicies; } public void setTreePolicies(final Collection<IPathUpdatablePolicy<N, A, Double>> treePolicies) { this.treePolicies = treePolicies; } @Override public EnsembleMCTS<N, A> getAlgorithm(final IMDP<N, A, Double> input) { return new EnsembleMCTS<>(input, this.getDefaultPolicy(true), this.treePolicies, this.getMaxIterations(), this.getGamma(), this.getEpsilon(), this.isTabooExhaustedNodes()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/ensemble/EnsembleTreePolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.ensemble; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.graph.LabeledGraph; import ai.libs.jaicore.search.algorithms.mdp.mcts.ActionPredictionFailedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IGraphDependentPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; public class EnsembleTreePolicy<N, A> implements IPathUpdatablePolicy<N, A, Double>, IGraphDependentPolicy<N, A> { private final List<IPathUpdatablePolicy<N, A, Double>> treePolicies; private final Random rand = new Random(0); private IPolicy<N, A> lastPolicy; private Map<IPolicy<N, A>, Double> meansOfObservations = new HashMap<>(); private Map<IPolicy<N, A>, Integer> numberOfTimesChosen = new HashMap<>(); private int calls; public EnsembleTreePolicy(final Collection<? extends IPathUpdatablePolicy<N, A, Double>> treePolicies) { super(); this.treePolicies = new ArrayList<>(treePolicies); } @Override public A getAction(final N node, final Collection<A> actions) throws ActionPredictionFailedException, InterruptedException { this.calls ++; if (this.rand.nextDouble() < 1.1) { this.lastPolicy = this.treePolicies.get(this.rand.nextInt(this.treePolicies.size())); return this.lastPolicy.getAction(node, actions); } else { double bestScore = Double.MAX_VALUE; IPolicy<N, A> bestPolicy = null; for (IPolicy<N, A> policy : this.treePolicies) { double score; if (!this.numberOfTimesChosen.containsKey(policy)) { score = 0; } else { double explorationTerm = -1 * Math.sqrt(2) * Math.sqrt(Math.log(this.calls) / this.numberOfTimesChosen.get(policy)); score = this.meansOfObservations.get(policy) + explorationTerm; } if (score < bestScore) { bestScore = score; bestPolicy = policy; } } Objects.requireNonNull(bestPolicy); this.lastPolicy = bestPolicy; return bestPolicy.getAction(node, actions); } } @Override public void updatePath(final ILabeledPath<N, A> path, final List<Double> scores) { for (IPathUpdatablePolicy<N, A, Double> policy : this.treePolicies) { policy.updatePath(path, scores); } int visits = this.numberOfTimesChosen.computeIfAbsent(this.lastPolicy, p -> 0); this.numberOfTimesChosen.put(this.lastPolicy, visits + 1); double playoutScore = scores.stream().reduce((a,b) -> a + b).get(); // we neither discount nor care for the segmentation of the scores this.meansOfObservations.put(this.lastPolicy, (this.meansOfObservations.computeIfAbsent(this.lastPolicy, p -> 0.0) * visits + playoutScore ) / (visits + 1)); } @Override public void setGraph(final LabeledGraph<N, A> graph) { for (IPathUpdatablePolicy<N, A, Double> policy : this.treePolicies) { if (policy instanceof IGraphDependentPolicy) { ((IGraphDependentPolicy<N, A>)policy).setGraph(graph); } } } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/spuct/SPUCBPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.spuct; import java.util.HashMap; import java.util.List; import java.util.Map; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.datastructure.graph.ILabeledPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.NodeLabel; import ai.libs.jaicore.search.algorithms.mdp.mcts.uct.UCBPolicy; public class SPUCBPolicy<N, A> extends UCBPolicy<N, A> implements ILoggingCustomizable { private String loggerName; private Logger logger = LoggerFactory.getLogger(SPUCBPolicy.class); private final double bigD; private Map<NodeLabel<A>, Double> squaredObservations = new HashMap<>(); public SPUCBPolicy(final double gamma, final double bigD) { this(gamma, true, bigD); } public SPUCBPolicy(final double gamma, final boolean maximize, final double bigD) { super(gamma, maximize); this.bigD = bigD; } @Override public String getLoggerName() { return this.loggerName; } @Override public void setLoggerName(final String name) { this.loggerName = name; super.setLoggerName(name + "._updating"); this.logger = LoggerFactory.getLogger(name); } @Override public void updatePath(final ILabeledPath<N, A> path, final List<Double> scores) { super.updatePath(path, scores); // careful! the visits stats has already been updated here! List<N> nodes = path.getNodes(); int l = nodes.size(); double accumulatedScores = 0; for (int i = l - 2; i >= 0; i--) { NodeLabel<A> nl = this.getLabelOfNode(nodes.get(i)); if (!Double.isNaN(accumulatedScores) && scores.get(i) != null) { accumulatedScores = scores.get(i) + this.getGamma() * accumulatedScores; } else if (!Double.isNaN(accumulatedScores)) { accumulatedScores = Double.NaN; } this.squaredObservations.put(nl, this.squaredObservations.computeIfAbsent(nl, label -> 0.0) + Math.pow(accumulatedScores, 2)); } } @Override public double getScore(final N node, final A action) { /* get ucb term */ double ucbMean = super.getEmpiricalMean(node, action); double ucbExploration = super.getEmpiricalMean(node, action); double ucb = ucbMean + ucbExploration; /* get single player term added */ NodeLabel<A> labelOfNode = this.getLabelOfNode(node); int visitsOfChild = labelOfNode.getNumPulls(action); // the t-parameter in the paper double squaredResults = this.squaredObservations.containsKey(labelOfNode) ? this.squaredObservations.get(labelOfNode) : 0.0; double expectedResults = visitsOfChild * Math.pow(ucbMean, 2); double spTerm = (this.isMaximize() ? 1 : -1) * Math.sqrt((squaredResults - expectedResults + this.bigD) / visitsOfChild); double score = ucb + spTerm; this.logger.debug("Computed score for action {}: {} = {} + {}", action, score, ucb, spTerm); return score; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/spuct/SPUCT.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.spuct; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.probleminputs.IMDP; public class SPUCT<N, A> extends MCTS<N, A> { public SPUCT(final IMDP<N, A, Double> input, final IPolicy<N, A> defaultPolicy, final double bigD, final int maxIterations, final double gamma, final double epsilon, final boolean tabooExhaustedNodes) { super(input, new SPUCBPolicy<>(gamma, bigD), defaultPolicy, maxIterations, gamma, epsilon, tabooExhaustedNodes); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/spuct/SPUCTFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.spuct; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public class SPUCTFactory<N, A> extends MCTSFactory<N, A, SPUCTFactory<N, A>> { private double bigD = 1000; public double getBigD() { return this.bigD; } public void setBigD(final double bigD) { this.bigD = bigD; } @Override public MCTS<N, A> getAlgorithm(final IMDP<N, A, Double> input) { return new SPUCT<>(input, this.getDefaultPolicy(true), this.bigD, this.getMaxIterations(), this.getGamma(), this.getEpsilon(), this.isTabooExhaustedNodes()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/tag/TAGMCTS.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.tag; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.probleminputs.IMDP; public class TAGMCTS<N, A> extends MCTS<N, A> { public TAGMCTS(final IMDP<N, A, Double> input, final IPolicy<N, A> defaultPolicy, final double c, final int s, final double delta, final double thresholdIncrement, final int maxIterations, final double gamma, final double epsilon, final boolean tabooExhaustedNodes) { super(input, new TAGPolicy<>(c, s, delta, thresholdIncrement, input.isMaximizing()), defaultPolicy, maxIterations, gamma, epsilon, tabooExhaustedNodes); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/tag/TAGMCTSFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.tag; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public class TAGMCTSFactory<N, A> extends MCTSFactory<N, A, TAGMCTSFactory<N, A>> { private double explorationConstant = Math.sqrt(2); private int s = 100; private double delta = 0.01; private double thresholdIncrement = 0.001; public double getExplorationConstant() { return this.explorationConstant; } public void setExplorationConstant(final double explorationConstant) { this.explorationConstant = explorationConstant; } public int getS() { return this.s; } public void setS(final int s) { this.s = s; } public double getDelta() { return this.delta; } public void setDelta(final double delta) { this.delta = delta; } /** * The DELTA in the Streeter paper * * @param thresholdIncrement */ public void setThresholdIncrement(final double thresholdIncrement) { this.thresholdIncrement = thresholdIncrement; } @Override public TAGMCTS<N, A> getAlgorithm(final IMDP<N, A, Double> input) { return new TAGMCTS<>(input, this.getDefaultPolicy(true), this.explorationConstant, this.s, this.delta, this.thresholdIncrement, this.getMaxIterations(), this.getGamma(), this.getEpsilon(), this.isTabooExhaustedNodes()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/tag/TAGPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.tag; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Queue; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.datastructure.graph.ILabeledPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.search.algorithms.mdp.mcts.ActionPredictionFailedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; public class TAGPolicy<T, A> implements IPathUpdatablePolicy<T, A, Double>, ILoggingCustomizable { private String loggerName; private Logger logger = LoggerFactory.getLogger(TAGPolicy.class); private double explorationConstant = Math.sqrt(2); private final int s; private final Map<T, Double> thresholdPerNode = new HashMap<>(); private final double delta; private final double thresholdIncrement; // the constant by which the threshold is incremented private final boolean isMaximize; private final Map<T, Map<A, PriorityQueue<Double>>> statsPerNode = new HashMap<>(); private final Map<T, Map<A, Integer>> pullsPerNodeAction = new HashMap<>(); private final Map<T, Integer> visitsPerNode = new HashMap<>(); public TAGPolicy() { this(false); } public TAGPolicy(final double explorationConstant, final int s, final double delta, final double thresholdIncrement, final boolean isMaximize) { super(); this.explorationConstant = explorationConstant; this.s = s; this.delta = delta; this.thresholdIncrement = thresholdIncrement; this.isMaximize = isMaximize; } public TAGPolicy(final boolean maximize) { this(Math.sqrt(2), 10, 1.0, 0.01, maximize); } @Override public A getAction(final T node, final Collection<A> actions) throws ActionPredictionFailedException { this.logger.info("Getting action for node {}", node); /* make sure that each successor has been visited at least once in this stats (by the default policy) */ Map<A, Integer> pullMap = this.pullsPerNodeAction.computeIfAbsent(node, n -> new HashMap<>()); actions.forEach(a -> pullMap.computeIfAbsent(a, action -> 1)); this.visitsPerNode.put(node, this.visitsPerNode.computeIfAbsent(node, n -> 0) + 1); this.logger.debug("Adjusting threshold."); this.adjustThreshold(node); // first adjust threshold of node this.logger.debug("Threshold adjusted. Is now {}", this.thresholdPerNode.get(node)); A choice = null; double best = (this.isMaximize ? -1 : 1) * Double.MAX_VALUE; int k = actions.size(); for (A action : actions) { double score = this.getUtilityOfAction(node, action, k); if (!Double.isNaN(score) && (this.isMaximize && score > best || !this.isMaximize && score < best)) { this.logger.trace("Updating best choice {} with {} since it is better than the current solution with performance {}", choice, action, best); best = score; choice = action; } else { this.logger.trace("Skipping current solution {} since its score {} is not better than the currently best {}.", action, score, best); } } /* if no choice appears reasonable, return a random one, but also give a warning, because this seems strange. */ if (choice == null) { this.logger.warn("All options have score NaN. Returning random element."); return SetUtil.getRandomElement(actions, 0); } /* augment pulls for this action by one */ pullMap.put(choice, pullMap.get(choice) + 1); return choice; } public void adjustThreshold(final T node) { Map<A, PriorityQueue<Double>> observations = this.statsPerNode.get(node); double t = this.thresholdPerNode.computeIfAbsent(node, n -> this.isMaximize ? 0.0 : 100.0); this.logger.debug("Initial value for threshold is {}. Observations are: {}", t, observations); if (observations == null) { return; } int sum; boolean first = true; do { if (!first) { t += this.thresholdIncrement * (this.isMaximize ? 1 : -1); } sum = 0; for (Entry<A, PriorityQueue<Double>> entry : observations.entrySet()) { final double localT = t; entry.getValue().removeIf(d -> this.isMaximize && d < localT || !this.isMaximize && d > localT); sum += entry.getValue().size(); } first = false; } while (sum != Double.NaN && sum > this.s); this.logger.debug("Setting threshold to {}", t); this.thresholdPerNode.put(node, t); } /** * This method computes the part (b) in the Streeter paper * * @param node * @param action * @return */ public double getUtilityOfAction(final T node, final A action, final int k) { if (!this.statsPerNode.containsKey(node) || !this.statsPerNode.get(node).containsKey(action)) { return Double.NaN; } /* compute nominator */ double alpha = Math.log(2 * this.visitsPerNode.get(node) * k / this.delta); Queue<Double> memorizedScoresForArm = this.statsPerNode.get(node).get(action); int sChild = memorizedScoresForArm.size(); if (alpha < 0) { throw new IllegalStateException("Alpha must not be negative. Check delta value (must be smaller than 1)"); } double nominator = sChild + alpha + Math.sqrt(2 * sChild * alpha + Math.pow(alpha, 2)); /* compute denominator (only child visits) */ int armPulls = this.pullsPerNodeAction.get(node).get(action); if (armPulls == 0) { throw new IllegalArgumentException("Cannot compute score for child with no visits!"); } double h = nominator / armPulls; this.logger.trace("Compute TAG score of {}", h); return h; } public double getExplorationConstant() { return this.explorationConstant; } public void setExplorationConstant(final double explorationConstant) { this.explorationConstant = explorationConstant; } @Override public void updatePath(final ILabeledPath<T, A> path, final List<Double> scores) { int l = path.getNumberOfNodes() - 1; List<T> nodes = path.getNodes(); List<A> arcs = path.getArcs(); double accumulatedScores = 0; for (int i = l - 1; i >= 0; i--) { T node = nodes.get(i); A action = arcs.get(i); /* update list of best observed scores */ Map<A, PriorityQueue<Double>> actionMap = this.statsPerNode.computeIfAbsent(node, n -> new HashMap<>()); PriorityQueue<Double> bestScores = actionMap.computeIfAbsent(action, a -> this.isMaximize ? new PriorityQueue<>((c1, c2) -> Double.compare(c2, c1)) : new PriorityQueue<>()); assert !bestScores.contains(Double.NaN); if (accumulatedScores != Double.NaN && scores.get(i) != null) { accumulatedScores += scores.get(i); // no discounting used here } else if (!Double.isNaN(accumulatedScores)) { accumulatedScores = Double.NaN; } if (Double.isNaN(accumulatedScores)) { return; } if (bestScores.size() < this.s) { bestScores.add(accumulatedScores); } else if (bestScores.peek() < accumulatedScores) { bestScores.poll(); bestScores.add(accumulatedScores); } assert !bestScores.contains(Double.NaN); } } @Override public String getLoggerName() { return this.loggerName; } @Override public void setLoggerName(final String name) { this.loggerName = name; this.logger = LoggerFactory.getLogger(name); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/thompson/DNGBeliefUpdateEvent.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.thompson; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; public class DNGBeliefUpdateEvent<N> extends AAlgorithmEvent { private final N node; private final double mu; private final double alpha; private final double beta; private final double lambda; public DNGBeliefUpdateEvent(final IAlgorithm<?, ?> algorithm, final N node, final double mu, final double alpha, final double beta, final double lambda) { super(algorithm); this.node = node; this.mu = mu; this.alpha = alpha; this.beta = beta; this.lambda = lambda; } public N getNode() { return this.node; } public double getMu() { return this.mu; } public double getAlpha() { return this.alpha; } public double getBeta() { return this.beta; } public double getLambda() { return this.lambda; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/thompson/DNGMCTS.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.thompson; import java.util.Random; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.algorithms.mdp.mcts.UniformRandomPolicy; import ai.libs.jaicore.search.probleminputs.IMDP; public class DNGMCTS<N, A> extends MCTS<N, A> { public DNGMCTS(final IMDP<N, A, Double> input, final double varianceFactor, final double initLambda, final int maxIterations, final double gamma, final double epsilon, final Random random, final boolean tabooExhaustedNodes, final boolean maximize) { this(input, new UniformRandomPolicy<>(random), varianceFactor, initLambda, maxIterations, gamma, epsilon, tabooExhaustedNodes, maximize); } public DNGMCTS(final IMDP<N, A, Double> input, final IPolicy<N, A> defaultPolicy, final double varianceFactor, final double initLambda, final int maxIterations, final double gamma, final double epsilon, final boolean tabooExhaustedNodes, final boolean maximize) { super(input, new DNGPolicy<>(gamma, t -> { try { return input.isTerminalState(t); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // re-interrupt! return false; } }, varianceFactor, initLambda, maximize), defaultPolicy, maxIterations, gamma, epsilon, tabooExhaustedNodes); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/thompson/DNGMCTSFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.thompson; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public class DNGMCTSFactory<N, A> extends MCTSFactory<N, A, DNGMCTSFactory<N, A>> { private double varianceFactor = 0; private double initLambda = 1.0; public double getVarianceFactor() { return this.varianceFactor; } public void setVarianceFactor(final double varianceFactor) { this.varianceFactor = varianceFactor; } public double getInitLambda() { return this.initLambda; } public void setInitLambda(final double initLambda) { this.initLambda = initLambda; } @Override public MCTS<N, A> getAlgorithm(final IMDP<N, A, Double> input) { return new DNGMCTS<>(input, this.varianceFactor, this.initLambda, this.getMaxIterations(), this.getGamma(), this.getEpsilon(), this.getRandom(), this.isTabooExhaustedNodes(), this.isMaximize()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/thompson/DNGPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.thompson; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Predicate; import org.apache.commons.math3.distribution.GammaDistribution; import org.apache.commons.math3.distribution.NormalDistribution; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.common.event.IRelaxedEventEmitter; import org.api4.java.datastructure.graph.ILabeledPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; import ai.libs.jaicore.basic.sets.Pair; import ai.libs.jaicore.search.algorithms.mdp.mcts.ActionPredictionFailedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; /** * This is the implementation of the DNG-algorithm (for MDPs) presented in * * @article{bai2018posterior, title={Posterior sampling for Monte Carlo planning under uncertainty}, author={Bai, Aijun and Wu, Feng and Chen, Xiaoping}, journal={Applied Intelligence}, volume={48}, number={12}, pages={4998--5018}, * year={2018}, publisher={Springer} } It does not consider rewards per step but only once for a complete roll-out * * Implementation details: - the time horizon H is irrelevant for the policy, because, if a horizon is used, the MCTS algorithm would not call the tree policy for cases of d >= H - we add another parameter for a * factor that will be multiplied to the sampled variance \tau * * * @author Felix Mohr * * @param <N> * @param <A> */ public class DNGPolicy<N, A> implements IPathUpdatablePolicy<N, A, Double>, ILoggingCustomizable, IRelaxedEventEmitter { private Logger logger = LoggerFactory.getLogger(DNGPolicy.class); private EventBus eventBus = new EventBus(); private final boolean maximize; /* initialization according to section 6.2 in the paper */ private final double initLambda; private static final double INIT_ALPHA = 1.0; private final double initBeta; private static final double INIT_MU = 0.5; // we set this to .5 since we already know that scores are in [0,1] /* DNG model parameters */ private final Map<N, Double> alpha = new HashMap<>(); private final Map<N, Double> beta = new HashMap<>(); private final Map<N, Double> mu = new HashMap<>(); private final Map<N, Double> lambda = new HashMap<>(); private final Map<N, Map<A, Map<N, Integer>>> rho = new HashMap<>(); /* MDP-related variables */ private final double gammaMDP; // the discount factor of the MDP private final Predicate<N> terminalStatePredicate; // this policy needs to know a bit of the MDP: it needs to know whether or not a state is terminal private final Map<N, Map<A, Double>> rewardsMDP = new HashMap<>(); // memorizes the rewards observed for an action in the MDP private final double varianceFactor; private boolean sampling = true; // can be deactivated after using the policy to only use the final model public DNGPolicy(final double gammaMDP, final Predicate<N> terminalStatePredicate, final double varianceFactor, final double lambda, final boolean maximize) { super(); this.gammaMDP = gammaMDP; this.terminalStatePredicate = terminalStatePredicate; this.varianceFactor = varianceFactor; this.initLambda = lambda; this.initBeta = 1 / this.initLambda; this.maximize = maximize; } public boolean isSampling() { return this.sampling; } public void setSampling(final boolean sampling) { this.sampling = sampling; } @Override /** * This is the first part of the ELSE branch in the MCTS algorithm of the paper (calling Thompson sampling to choose A). The "simulation" part is taken over by the general MCTS routine */ public A getAction(final N node, final Collection<A> actionsWithSuccessors) throws ActionPredictionFailedException, InterruptedException { return this.sampleWithThompson(node, actionsWithSuccessors); } /** * The ThompsonSampling procedure of the paper * * @param state * @param actions * @return * @throws InterruptedException * @throws ObjectEvaluationFailedException */ public A sampleWithThompson(final N state, final Collection<A> actions) throws InterruptedException { A bestAction = null; this.logger.info("Determining best action for state {}", state); double bestScore = (this.maximize ? -1 : 1) * Double.MAX_VALUE; for (A action : actions) { double score = this.getQValue(state, action); this.logger.debug("Score for action {} is {}", action, score); this.eventBus.post(new DNGQSampleEvent<N, A>(null, state, action, score)); if (bestAction == null || (score < bestScore || (this.maximize && score > bestScore))) { bestAction = action; bestScore = score; this.logger.debug("Considering this as the new best action."); } } Objects.requireNonNull(bestAction, "Best action cannot be null if there were " + actions.size() + " options!"); this.logger.info("Recommending action {}", bestAction); return bestAction; } /** * In the deterministic case (and when transitions are clear), without discounts, and inner rewards = 0, the QValue function in the paper degenerates to just returning the value of the successor state of the given state. * * @param state * This is not needed and may be null; is rather for documentation here. * @param successorState * @return * @throws InterruptedException * @throws ObjectEvaluationFailedException */ public double getQValue(final N state, final A action) throws InterruptedException { /* make sure that the rho-values are available to estimate the transition probabilities */ Map<N, Integer> rhoForThisPair = this.rho.get(state).get(action); if (rhoForThisPair == null) { throw new IllegalStateException("Have no rho vector for state/action pair " + state + "/" + action); } List<N> possibleSuccessors = new ArrayList<>(rhoForThisPair.keySet()); int numSuccessors = possibleSuccessors.size(); if (rhoForThisPair.size() < numSuccessors) { throw new IllegalStateException("The rho vector for state/action pair " + state + "/" + action + " is incomplete and only has " + rhoForThisPair.size() + " instead of " + numSuccessors + " entries."); } /* compute score */ double r = 0; this.logger.debug("Now determining q-value of action {}. Sampling: {}", action, this.sampling); if (this.sampling) { // draw weight vector from Dirichlet (we sample using sampling from a Gamma distribution) double[] gammaVector = new double[numSuccessors]; double totalGammas = 0; for (int i = 0; i < numSuccessors; i++) { N succ = possibleSuccessors.get(i); double gamma = new GammaDistribution(rhoForThisPair.get(succ), 1).sample(); gammaVector[i] = gamma; totalGammas += gamma; } if (totalGammas == 0) { throw new IllegalStateException("The gamma estimates must not sum up to 0!"); } for (int i = 0; i < numSuccessors; i++) { r += gammaVector[i] / totalGammas * this.getValue(possibleSuccessors.get(i)); // the first factor is the Dirichlet estimate } } else { double denominator = rhoForThisPair.values().stream().reduce((a, b) -> a + b).get(); for (N succ : possibleSuccessors) { r += rhoForThisPair.get(succ) / denominator; } } double reward = this.rewardsMDP.get(state).get(action); double totalReward = reward + this.gammaMDP * r; this.logger.debug("Considering a reward of {} + {} * {} = {}", reward, this.gammaMDP, r, totalReward); return totalReward; } public Pair<Double, Double> sampleWithNormalGamma(final N state) { double tau = new GammaDistribution(this.alpha.get(state), this.beta.get(state)).sample(); double std = 1 / (this.lambda.get(state) * tau); double muNew = std > 0 ? new NormalDistribution(this.mu.get(state), std).sample() : this.mu.get(state); return new Pair<>(muNew, tau); } /** * The Value procedure of the paper * * @return * @throws InterruptedException * @throws ObjectEvaluationFailedException */ public double getValue(final N state) throws InterruptedException { boolean isTerminal = this.terminalStatePredicate.test(state); if (Thread.interrupted()) { throw new InterruptedException(); } if (isTerminal) { // this assumes that terminal states are also goal states! this.logger.debug("Returning value of 0 for terminal state {}", state); return 0; } else if (this.sampling) { Pair<Double, Double> meanAndVariance = this.sampleWithNormalGamma(state); double val = meanAndVariance.getX() - this.varianceFactor * Math.sqrt(meanAndVariance.getY()); this.logger.debug("Returning sampled value of {}", val); return val; } else { double val = this.mu.get(state); this.logger.debug("Returning fixed value of {}", val); return val; } } @Override /** * This is the update section of the algorithm, which can be found in the ELSE-branch on the left of Fig. 1 (lines 21-25) */ public void updatePath(final ILabeledPath<N, A> path, final List<Double> scores) { List<N> nodes = path.getNodes(); List<A> actions = path.getArcs(); int l = path.getNumberOfNodes(); this.logger.info("Updating path with scores {}", scores); double accumulatedScores = 0; for (int i = l - 2; i >= 0; i --) { N node = nodes.get(i); A action = actions.get(i); double rewardOfThisAction = scores.get(i) != null ? scores.get(i) : Double.NaN; this.rewardsMDP.computeIfAbsent(node, n -> new HashMap<>()).putIfAbsent(action, rewardOfThisAction); accumulatedScores = rewardOfThisAction + this.gammaMDP * accumulatedScores; this.logger.debug("Updating statistics for {}-th node with accumulated score {}. State here is: {}", i, accumulatedScores, node); /* if we had no model for this node yet, create an empty one */ if (!this.lambda.containsKey(node)) { /* NormalGamma parameters */ this.lambda.put(node, this.initLambda); this.mu.put(node, INIT_MU); this.alpha.put(node, INIT_ALPHA); this.beta.put(node, this.initBeta); /* rho-parameter */ N succNode = nodes.get(i + 1); Map<N, Integer> rhoForNodeActionPair = new HashMap<>(); rhoForNodeActionPair.put(succNode, 1); Map<A, Map<N, Integer>> mapForAction = new HashMap<>(); mapForAction.put(action, rhoForNodeActionPair); this.rho.put(node, mapForAction); } else { /* update model parameters */ double lambdaOfN = this.lambda.get(node); double muOfN = this.mu.get(node); this.alpha.put(node, this.alpha.get(node) + 0.5); this.beta.put(node, this.beta.get(node) + (lambdaOfN * Math.pow(accumulatedScores - muOfN, 2) / (lambdaOfN + 1)) / 2); this.mu.put(node, (muOfN * lambdaOfN + accumulatedScores) / (lambdaOfN + 1)); this.lambda.put(node, lambdaOfN + 1); N succNode = nodes.get(i + 1); this.rho.get(node).computeIfAbsent(action, a -> new HashMap<>()).put(succNode, this.rho.get(node).get(action).computeIfAbsent(succNode, n -> 0) + 1); this.eventBus.post(new DNGBeliefUpdateEvent<N>(null, node, this.mu.get(node), this.alpha.get(node), this.beta.get(node), this.lambda.get(node))); } } } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); this.logger.info("Logger is now {}", name); } @Override public void registerListener(final Object listener) { this.eventBus.register(listener); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/thompson/DNGQSampleEvent.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.thompson; import org.api4.java.algorithm.IAlgorithm; import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent; public class DNGQSampleEvent<N, A> extends AAlgorithmEvent { private final N node; private final A action; private final double score; public DNGQSampleEvent(final IAlgorithm<?, ?> algorithm, final N node, final A action, final double score) { super(algorithm); this.node = node; this.action = action; this.score = score; } public N getNode() { return this.node; } public A getAction() { return this.action; } public double getScore() { return this.score; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uct/AUpdatingPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uct; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.datastructure.graph.ILabeledPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.search.algorithms.mdp.mcts.EBehaviorForNotFullyExploredStates; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.NodeLabel; public abstract class AUpdatingPolicy<N, A> implements IPathUpdatablePolicy<N, A, Double>, ILoggingCustomizable { private Logger logger = LoggerFactory.getLogger(AUpdatingPolicy.class); private final double gamma; // discount factor to consider when interpreting the scores private final boolean maximize; private EBehaviorForNotFullyExploredStates behaviorWhenActionForNotFullyExploredStateIsRequested; private final Map<N, NodeLabel<A>> labels = new HashMap<>(); public AUpdatingPolicy(final double gamma, final boolean maximize) { super(); this.gamma = gamma; this.maximize = maximize; } public NodeLabel<A> getLabelOfNode(final N node) { if (!this.labels.containsKey(node)) { throw new IllegalArgumentException("No label for node " + node); } return this.labels.get(node); } public abstract double getScore(N node, A action); public abstract A getActionBasedOnScores(Map<A, Double> scores); /** * Note that this is a transposition-based and hence, only partially path-dependent, update. The labels are associated to nodes of the original MDP (states) and not to nodes in the MCTS search tree (paths)! This means that, in fact, * several paths are (partially) updated simultanously. However, on all other paths crossing the nodes on the updated paths, only those situations are updated and not the situations in higher nodes of the search tree. * */ @Override public void updatePath(final ILabeledPath<N, A> path, final List<Double> scores) { this.logger.debug("Updating path {} with score {}", path, scores); if (path.isPoint()) { throw new IllegalArgumentException("Cannot update path consisting only of the root."); } List<N> nodes = path.getNodes(); List<A> arcs = path.getArcs(); int l = nodes.size(); double accumulatedDiscountedReward = 0; for (int i = l - 2; i >= 0; i--) { // update bottom up N node = nodes.get(i); A action = arcs.get(i); NodeLabel<A> label = this.labels.computeIfAbsent(node, n -> new NodeLabel<>()); double rewardForThisAction = scores.get(i) != null ? scores.get(i) : Double.NaN; accumulatedDiscountedReward = rewardForThisAction + this.gamma * accumulatedDiscountedReward; label.addRewardForAction(action, accumulatedDiscountedReward); label.addPull(action); label.addVisit(); this.logger.trace("Updated label of node {}. Visits now {}. Action pulls of {} now {}. Observed total rewards for this action: {}", node, label.getVisits(), action, label.getNumPulls(action), label.getAccumulatedRewardsOfAction(action)); } this.logger.debug("Path update completed."); } @Override public A getAction(final N node, final Collection<A> possibleActions) { this.logger.debug("Deriving action for node {}. The {} options are: {}", node, possibleActions.size(), possibleActions); /* if an applicable action has not been tried, play it to get some initial idea */ List<A> actionsThatHaveNotBeenTriedYet = possibleActions.stream().filter(a -> !this.labels.containsKey(node)).collect(Collectors.toList()); if (!actionsThatHaveNotBeenTriedYet.isEmpty()) { if (this.behaviorWhenActionForNotFullyExploredStateIsRequested == EBehaviorForNotFullyExploredStates.EXCEPTION) { throw new IllegalStateException("Tree policy should only be consulted for nodes for which each child has been used at least once."); } else if (this.behaviorWhenActionForNotFullyExploredStateIsRequested == EBehaviorForNotFullyExploredStates.BEST) { throw new UnsupportedOperationException("Can currently only work with RANDOM or EXCEPTION"); } A action = actionsThatHaveNotBeenTriedYet.get(0); this.logger.info("Dictating action {}, because this was never played before.", action); return action; } /* otherwise, play best action */ NodeLabel<A> labelOfNode = this.labels.get(node); this.logger.debug("All actions have been tried. Label is: {}", labelOfNode); Map<A, Double> scores = new HashMap<>(); for (A action : possibleActions) { assert labelOfNode.getVisits() != 0 : "Visits of action " + action + " cannot be 0 if we already used this action before!"; this.logger.trace("Considering action {}, which has {} visits and cummulative rewards {}.", action, labelOfNode.getNumPulls(action), labelOfNode.getAccumulatedRewardsOfAction(action)); Double score = this.getScore(node, action); if (!score.isNaN()) { scores.put(action, score); } } /* finalize the choice */ if (scores.isEmpty()) { this.logger.warn("All children have score NaN. Returning a random one."); return SetUtil.getRandomElement(possibleActions, 0); } A choice = this.getActionBasedOnScores(scores); Objects.requireNonNull(choice, "Would return null, but this must not be the case! Check the method that chooses an action given the scores."); this.logger.info("Recommending action {}.", choice); return choice; } public boolean isMaximize() { return this.maximize; } @Override public String getLoggerName() { return this.logger.getName(); } @Override public void setLoggerName(final String name) { this.logger = LoggerFactory.getLogger(name); this.logger.info("Set logger of {} to {}", this, name); } public double getGamma() { return this.gamma; } public EBehaviorForNotFullyExploredStates getBehaviorWhenActionForNotFullyExploredStateIsRequested() { return this.behaviorWhenActionForNotFullyExploredStateIsRequested; } public void setBehaviorWhenActionForNotFullyExploredStateIsRequested(final EBehaviorForNotFullyExploredStates behaviorWhenActionForNotFullyExploredStateIsRequested) { this.behaviorWhenActionForNotFullyExploredStateIsRequested = behaviorWhenActionForNotFullyExploredStateIsRequested; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uct/UCBPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uct; import java.util.Map; import java.util.Map.Entry; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.search.algorithms.mdp.mcts.NodeLabel; public class UCBPolicy<T, A> extends AUpdatingPolicy<T, A> implements ILoggingCustomizable { private String loggerName; private Logger logger = LoggerFactory.getLogger(UCBPolicy.class); private double explorationConstant; public UCBPolicy(final double gamma, final double explorationConstant, final boolean maximize) { super(gamma, maximize); this.explorationConstant = explorationConstant; } public UCBPolicy(final double gamma, final boolean maximize) { this(gamma, Math.sqrt(2), maximize); } @Override public String getLoggerName() { return this.loggerName; } @Override public void setLoggerName(final String name) { this.loggerName = name; super.setLoggerName(name + "._updating"); this.logger = LoggerFactory.getLogger(name); } public double getEmpiricalMean(final T node, final A action) { NodeLabel<A> nodeLabel = this.getLabelOfNode(node); if (nodeLabel == null || nodeLabel.getNumPulls(action) == 0) { return (this.isMaximize() ? -1 : 1) * Double.MAX_VALUE; } int timesThisActionHasBeenChosen = nodeLabel.getNumPulls(action); return nodeLabel.getAccumulatedRewardsOfAction(action) / timesThisActionHasBeenChosen; } public double getExplorationTerm(final T node, final A action) { NodeLabel<A> nodeLabel = this.getLabelOfNode(node); if (nodeLabel == null || nodeLabel.getNumPulls(action) == 0) { return (this.isMaximize() ? -1 : 1) * Double.MAX_VALUE; } int timesThisActionHasBeenChosen = nodeLabel.getNumPulls(action); return (this.isMaximize() ? 1 : -1) * this.explorationConstant * Math.sqrt(Math.log(nodeLabel.getVisits()) / timesThisActionHasBeenChosen); } @Override public double getScore(final T node, final A action) { NodeLabel<A> nodeLabel = this.getLabelOfNode(node); if (nodeLabel == null || nodeLabel.isVirgin(action)) { return (this.isMaximize() ? -1 : 1) * Double.MAX_VALUE; } int timesThisActionHasBeenChosen = nodeLabel.getNumPulls(action); double averageScoreForThisAction = nodeLabel.getAccumulatedRewardsOfAction(action) / timesThisActionHasBeenChosen; double explorationTerm = (this.isMaximize() ? 1 : -1) * this.explorationConstant * Math.sqrt(Math.log(nodeLabel.getVisits()) / timesThisActionHasBeenChosen); double score = averageScoreForThisAction + explorationTerm; this.logger.trace("Computed UCB score {} = {} + {} * {} * sqrt(log({})/{}). That is, exploration term is {}", score, averageScoreForThisAction, this.isMaximize() ? 1 : -1, this.explorationConstant, nodeLabel.getVisits(), timesThisActionHasBeenChosen, explorationTerm); return score; } public double getExplorationConstant() { return this.explorationConstant; } public void setExplorationConstant(final double explorationConstant) { this.explorationConstant = explorationConstant; } @Override public A getActionBasedOnScores(final Map<A, Double> scores) { A choice = null; if (scores.isEmpty()) { throw new IllegalArgumentException("An empty set of scored actions has been given to UCB to decide!"); } this.logger.debug("Getting action for scores {}", scores); double best = (this.isMaximize() ? (-1) : 1) * Double.MAX_VALUE; for (Entry<A, Double> entry : scores.entrySet()) { A action = entry.getKey(); double score = entry.getValue(); if (choice == null || (this.isMaximize() && (score > best) || !this.isMaximize() && (score < best))) { this.logger.trace("Updating best choice {} with {} since it is better than the current solution with performance {}", choice, action, best); best = score; choice = action; } else { this.logger.trace("Skipping current solution {} since its score {} is not better than the currently best {}.", action, score, best); } } if (choice == null) { throw new IllegalStateException("UCB would return NULL action, which must not be the case!"); } return choice; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uct/UCT.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uct; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.probleminputs.IMDP; public class UCT<N, A> extends MCTS<N, A> { public UCT(final IMDP<N, A, Double> input, final IPolicy<N, A> defaultPolicy, final int maxIterations, final double gamma, final double epsilon, final boolean tabooExhaustedNodes) { super(input, new UCBPolicy<>(gamma, input.isMaximizing()), defaultPolicy, maxIterations, gamma, epsilon, tabooExhaustedNodes); } @Override public UCBPolicy<N, A> getTreePolicy() { return (UCBPolicy<N, A>) super.getTreePolicy(); } @Override public UCBPolicy<N, A> call() throws AlgorithmTimeoutedException, InterruptedException, AlgorithmExecutionCanceledException, AlgorithmException { return (UCBPolicy<N, A>) super.call(); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uct/UCTFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uct; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public class UCTFactory<N, A> extends MCTSFactory<N, A, UCTFactory<N, A>> { @Override public MCTS<N, A> getAlgorithm(final IMDP<N, A, Double> input) { return new UCT<>(input, this.getDefaultPolicy(true), this.getMaxIterations(), this.getGamma(), this.getEpsilon(), this.isTabooExhaustedNodes()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uuct/IUCBUtilityFunction.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uuct; import it.unimi.dsi.fastutil.doubles.DoubleList; public interface IUCBUtilityFunction { public double getUtility(DoubleList observations); public double getQ(); public double getA(); public double getB(); }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uuct/UUCBPolicy.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uuct; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.api4.java.datastructure.graph.ILabeledPath; import ai.libs.jaicore.basic.sets.SetUtil; import ai.libs.jaicore.search.algorithms.mdp.mcts.ActionPredictionFailedException; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPathUpdatablePolicy; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleList; public class UUCBPolicy<N, A> implements IPathUpdatablePolicy<N, A, Double> { private static final double ALPHA = 3; private final IUCBUtilityFunction utilityFunction; private final double a; private final double b; private final double q; private final Map<N, Map<A, DoubleList>> observations = new HashMap<>(); private int t = 0; public UUCBPolicy(final IUCBUtilityFunction utilityFunction) { super(); this.utilityFunction = utilityFunction; this.a = utilityFunction.getA(); this.b = utilityFunction.getB(); this.q = utilityFunction.getQ(); } @Override public A getAction(final N node, final Collection<A> possibleActions) throws ActionPredictionFailedException { /* compute score of each successor (eq 16 in paper and 15 in extended) */ double bestScore = Double.MAX_VALUE * -1; A bestAction = null; Map<A, DoubleList> observationsForActions = this.observations.get(node); if (observationsForActions == null) { return SetUtil.getRandomElement(possibleActions, new Random().nextLong()); } for (A succ : possibleActions) { DoubleList observationsOfChild = observationsForActions.get(succ); if (observationsOfChild == null) { continue; } double utility = this.utilityFunction.getUtility(observationsOfChild); double phiInverse = this.phiInverse((ALPHA * Math.log(this.t)) / observationsOfChild.size()); double score = utility + phiInverse; if (score > bestScore) { bestScore = score; bestAction = succ; } } if (bestAction == null) { return SetUtil.getRandomElement(possibleActions, new Random().nextLong()); } return bestAction; } private double phiInverse(final double x) { return Math.max(2 * this.b * Math.sqrt(x / this.a), 2 * this.b * Math.pow(x / this.a, this.q / 2)); } @Override public void updatePath(final ILabeledPath<N, A> path, final List<Double> scores) { double playoutScore = SetUtil.sum(scores); // we neither discount nor care for the segmentation of the scores double s = playoutScore; path.getPathToParentOfHead().getNodes().forEach(n -> { DoubleList obs = this.observations.computeIfAbsent(n, node -> new HashMap<>()).computeIfAbsent(path.getOutArc(n), x -> new DoubleArrayList()); int size = obs.size(); if (size == 0) { obs.add(s); } else if (s <= obs.getDouble(0)) { obs.add(0, s); } else { double last = obs.getDouble(0); double next; for (int i = 1; i < size; i++) { next = obs.getDouble(i); if (playoutScore >= last && playoutScore <= next) { obs.add(i, s); return; } last = next; } } }); this.t++; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uuct/UUCT.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uuct; import ai.libs.jaicore.search.algorithms.mdp.mcts.IPolicy; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.probleminputs.IMDP; public class UUCT<N, A> extends MCTS<N, A> { public UUCT(final IMDP<N, A, Double> input, final IPolicy<N, A> defaultPolicy, final IUCBUtilityFunction utility, final int maxIterations, final double gamma, final double epsilon, final boolean tabooExhaustedNodes) { super(input, new UUCBPolicy<>(utility), defaultPolicy, maxIterations, gamma, epsilon, tabooExhaustedNodes); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uuct/UUCTFactory.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uuct; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTS; import ai.libs.jaicore.search.algorithms.mdp.mcts.MCTSFactory; import ai.libs.jaicore.search.probleminputs.IMDP; public class UUCTFactory<N, A> extends MCTSFactory<N, A, UUCTFactory<N, A>> { private IUCBUtilityFunction utility; public IUCBUtilityFunction getUtility() { return this.utility; } public void setUtility(final IUCBUtilityFunction utility) { this.utility = utility; } @Override public MCTS<N, A> getAlgorithm(final IMDP<N, A, Double> input) { return new UUCT<>(input, this.getDefaultPolicy(true), this.utility, this.getMaxIterations(), this.getGamma(), this.getEpsilon(), this.isTabooExhaustedNodes()); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uuct
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uuct/utility/CVaR.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uuct.utility; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import ai.libs.jaicore.search.algorithms.mdp.mcts.uuct.IUCBUtilityFunction; import it.unimi.dsi.fastutil.doubles.DoubleList; public class CVaR implements IUCBUtilityFunction { private final double alpha; private static final boolean MAXIMIZE = true; // true if we want to minimize the observations public CVaR(final double alpha) { super(); this.alpha = alpha; } @Override public double getUtility(final DoubleList observations) { List<Double> inverseList = observations.stream().map(o -> o * -1).collect(Collectors.toList()); Collections.sort(inverseList); int threshold = (int)Math.ceil(this.alpha * inverseList.size()); double sum = 0; if (MAXIMIZE) { for (int i = 0; i < threshold; i++) { sum += inverseList.get(i); } } else { for (int i = threshold; i < observations.size(); i++) { sum += inverseList.get(i); } } return sum / threshold; } @Override public double getQ() { return 2; } @Override public double getA() { return 1; } @Override public double getB() { return 1 / this.alpha * (1 + 3 / Math.min(this.alpha, 1 - this.alpha)); // according to Proposition 4 in the extended version of the paper, setting c* := 1 } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uuct
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/mdp/mcts/uuct/utility/VaR.java
package ai.libs.jaicore.search.algorithms.mdp.mcts.uuct.utility; import ai.libs.jaicore.search.algorithms.mdp.mcts.uuct.IUCBUtilityFunction; import it.unimi.dsi.fastutil.doubles.DoubleList; public class VaR implements IUCBUtilityFunction { private final double alpha; private final double b; public VaR(final double alpha, final double b) { super(); this.alpha = alpha; this.b = b; } @Override public double getUtility(final DoubleList observations) { if (observations.isEmpty()) { return Double.MAX_VALUE; } int threshold = Math.min(observations.size(), (int)Math.floor((1 - this.alpha) * observations.size())); return observations.getDouble(threshold) * -1; } @Override public double getQ() { return 1; } @Override public double getA() { return 1; } @Override public double getB() { return this.b; // return 1 / this.alpha * (1 + 3 / Math.min(this.alpha, 1 - this.alpha)); // according to Proposition 4 in the extended version of the paper, setting c* := 1 } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/astar/AStar.java
package ai.libs.jaicore.search.algorithms.standard.astar; import ai.libs.jaicore.search.algorithms.standard.bestfirst.BestFirst; import ai.libs.jaicore.search.probleminputs.GraphSearchWithNumberBasedAdditivePathEvaluation; /** * A* algorithm implementation that is nothing else than BestFirst with a * specific problem input. * * @author Felix Mohr */ public class AStar<N, A> extends BestFirst<GraphSearchWithNumberBasedAdditivePathEvaluation<N, A>, N, A, Double> { public AStar(GraphSearchWithNumberBasedAdditivePathEvaluation<N, A> problem) { super(problem); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/astar/AStarEdgeCost.java
package ai.libs.jaicore.search.algorithms.standard.astar; import ai.libs.jaicore.search.model.travesaltree.BackPointerPath; public interface AStarEdgeCost<T, A> { public double g(BackPointerPath<T, A, ?> from, BackPointerPath<T, A, ?> to); }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/astar/AStarFactory.java
package ai.libs.jaicore.search.algorithms.standard.astar; import ai.libs.jaicore.search.algorithms.standard.bestfirst.BestFirstFactory; import ai.libs.jaicore.search.probleminputs.GraphSearchWithNumberBasedAdditivePathEvaluation; public class AStarFactory<T, A> extends BestFirstFactory<GraphSearchWithNumberBasedAdditivePathEvaluation<T, A>, T, A, Double> { public AStarFactory() { super(); } public AStarFactory(final int timeoutForFInMS) { super(timeoutForFInMS); } @Override public AStar<T, A> getAlgorithm() { return this.getAlgorithm(this.getInput()); } @Override public AStar<T, A> getAlgorithm(final GraphSearchWithNumberBasedAdditivePathEvaluation<T, A> input) { AStar<T, A> search = new AStar<>(input); this.setupAlgorithm(search); return search; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/auxilliary
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/auxilliary/iteratingoptimizer/IteratingGraphSearchOptimizer.java
package ai.libs.jaicore.search.algorithms.standard.auxilliary.iteratingoptimizer; import org.api4.java.ai.graphsearch.problem.IPathSearch; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.algorithm.Timeout; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import org.api4.java.common.attributedobjects.ObjectEvaluationFailedException; import com.google.common.eventbus.Subscribe; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.GraphSearchSolutionCandidateFoundEvent; import ai.libs.jaicore.search.core.interfaces.AOptimalPathInORGraphSearch; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.model.other.SearchGraphPath; /** * This is a wrapper class to turn non-optimization algorithms into (uninformed working) optimizers. * The algorithm just iterates over all solutions, evaluates them with the given scoring function and eventually returns the best scored solution. * * @author fmohr * * @param <I> * @param <N> * @param <A> * @param <V> */ public class IteratingGraphSearchOptimizer<I extends IPathSearchWithPathEvaluationsInput<N, A, V>, N, A, V extends Comparable<V>> extends AOptimalPathInORGraphSearch<I, N, A, V> { private final IPathSearch<IPathSearchInput<N, A>, SearchGraphPath<N, A>, N, A> baseAlgorithm; public IteratingGraphSearchOptimizer(final I problem, final IPathSearch<IPathSearchInput<N, A>, SearchGraphPath<N, A>, N, A> baseAlgorithm) { super(problem); this.baseAlgorithm = baseAlgorithm; baseAlgorithm.registerListener(new Object() { @Subscribe public void receiveEvent(final IAlgorithmEvent e) { IteratingGraphSearchOptimizer.this.post(e); } }); } @Override public boolean hasNext() { return this.baseAlgorithm.hasNext(); } @Override public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { IAlgorithmEvent parentEvent = this.baseAlgorithm.nextWithException(); if (parentEvent instanceof GraphSearchSolutionCandidateFoundEvent) { try { SearchGraphPath<N, A> path = ((GraphSearchSolutionCandidateFoundEvent<N,A,?>) parentEvent).getSolutionCandidate(); V score = this.getInput().getPathEvaluator().evaluate(path); EvaluatedSearchGraphPath<N, A, V> evaluatedPath = new EvaluatedSearchGraphPath<>(path.getNodes(), path.getArcs(), score); this.updateBestSeenSolution(evaluatedPath); EvaluatedSearchSolutionCandidateFoundEvent<N,A,V> event = new EvaluatedSearchSolutionCandidateFoundEvent<>(this, evaluatedPath); this.post(event); return event; } catch (ObjectEvaluationFailedException e) { throw new AlgorithmException("Object evaluation failed", e); } } else { return parentEvent; } } public IPathSearch<IPathSearchInput<N, A>, SearchGraphPath<N, A>, N, A> getBaseAlgorithm() { return this.baseAlgorithm; } @Override public void setTimeout(final Timeout to) { this.baseAlgorithm.setTimeout(to); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/auxilliary
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/auxilliary/iteratingoptimizer/IteratingGraphSearchOptimizerFactory.java
package ai.libs.jaicore.search.algorithms.standard.auxilliary.iteratingoptimizer; import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearchFactory; import org.api4.java.ai.graphsearch.problem.IPathSearchFactory; import org.api4.java.ai.graphsearch.problem.IPathSearchInput; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import ai.libs.jaicore.search.core.interfaces.StandardORGraphSearchFactory; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.model.other.SearchGraphPath; public class IteratingGraphSearchOptimizerFactory<I extends IPathSearchWithPathEvaluationsInput<N, A, V>, N, A, V extends Comparable<V>> extends StandardORGraphSearchFactory<I, EvaluatedSearchGraphPath<N, A, V>, N, A, V, IteratingGraphSearchOptimizer<I, N, A, V>> implements IOptimalPathInORGraphSearchFactory<I, EvaluatedSearchGraphPath<N, A, V>, N, A, V, IteratingGraphSearchOptimizer<I, N, A, V>> { private IPathSearchFactory<IPathSearchInput<N, A>, SearchGraphPath<N, A>, N, A, ?> baseAlgorithmFactory; public IteratingGraphSearchOptimizerFactory() { super(); } public IteratingGraphSearchOptimizerFactory(final IPathSearchFactory<IPathSearchInput<N, A>, SearchGraphPath<N, A>, N, A, ?> baseAlgorithmFactory) { super(); this.baseAlgorithmFactory = baseAlgorithmFactory; } @Override public IteratingGraphSearchOptimizer<I, N, A, V> getAlgorithm() { if (this.getInput().getGraphGenerator() == null) { throw new IllegalStateException("Cannot produce " + IteratingGraphSearchOptimizer.class + " searches before the graph generator is set in the problem."); } return this.getAlgorithm(this.getInput()); } @Override public IteratingGraphSearchOptimizer<I, N, A, V> getAlgorithm(final I input) { if (this.baseAlgorithmFactory == null) { throw new IllegalStateException("Cannot produce " + IteratingGraphSearchOptimizer.class + " searches before the factory for the base search algorithm has been set."); } return new IteratingGraphSearchOptimizer<>(input, this.baseAlgorithmFactory.getAlgorithm(input)); } public IPathSearchFactory<IPathSearchInput<N, A>, SearchGraphPath<N, A>, N, A, ?> getBaseAlgorithmFactory() { return this.baseAlgorithmFactory; } public void setBaseAlgorithmFactory(final IPathSearchFactory<IPathSearchInput<N, A>, SearchGraphPath<N, A>, N, A, ?> baseAlgorithmFactory) { this.baseAlgorithmFactory = baseAlgorithmFactory; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/awastar/AWAStarFactory.java
package ai.libs.jaicore.search.algorithms.standard.awastar; import ai.libs.jaicore.search.core.interfaces.StandardORGraphSearchFactory; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; public class AWAStarFactory<I extends GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V extends Comparable<V>> extends StandardORGraphSearchFactory<I, EvaluatedSearchGraphPath<N, A, V>, N, A, V, AwaStarSearch<I, N, A, V>> { @Override public AwaStarSearch<I, N, A, V> getAlgorithm() { return this.getAlgorithm(this.getInput()); } @Override public AwaStarSearch<I, N, A, V> getAlgorithm(final I input) { return new AwaStarSearch<>(input); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/awastar/AwaStarSearch.java
package ai.libs.jaicore.search.algorithms.standard.awastar; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.ICancelablePathEvaluator; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallySolutionReportingPathEvaluator; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.PathEvaluationException; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; 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 com.google.common.eventbus.Subscribe; import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeTypeSwitchEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.GraphSearchSolutionCandidateFoundEvent; import ai.libs.jaicore.search.core.interfaces.AOptimalPathInORGraphSearch; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.model.travesaltree.BackPointerPath; import ai.libs.jaicore.search.model.travesaltree.DefaultNodeComparator; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; /** * This is a modified version of the AWA* algorithm for problems without admissible heuristic. * Important differences are: * - no early termination if a best-f-valued solution is found as f is not optimistic * * @inproceedings{ * title={AWA*-A Window Constrained Anytime Heuristic Search Algorithm.}, * author={Aine, Sandip and Chakrabarti, PP and Kumar, Rajeev}, * booktitle={IJCAI}, * pages={2250--2255}, * year={2007} * } * * @author lbrandt2 and fmohr * * @param <N> * @param <A> * @param <V> */ public class AwaStarSearch<I extends GraphSearchWithSubpathEvaluationsInput<N, A, V>, N, A, V extends Comparable<V>> extends AOptimalPathInORGraphSearch<I, N, A, V> { private Logger logger = LoggerFactory.getLogger(AwaStarSearch.class); private String loggerName; private final ISingleRootGenerator<N> rootNodeGenerator; private final ISuccessorGenerator<N, A> successorGenerator; private final IPathGoalTester<N, A> goalTester; private final IPathEvaluator<N, A, V> nodeEvaluator; private final Queue<BackPointerPath<N, A, V>> closedList; private final Queue<BackPointerPath<N, A, V>> suspendList; private final Queue<BackPointerPath<N, A, V>> openList; private int currentLevel = -1; private int windowSize; private final List<EvaluatedSearchGraphPath<N, A, V>> unconfirmedSolutions = new ArrayList<>(); // these are solutions emitted on the basis of the node evaluator but whose solutions have not been found in the original graph yet private final List<EvaluatedSearchSolutionCandidateFoundEvent<N, A, V>> unreturnedSolutionEvents = new ArrayList<>(); @SuppressWarnings("rawtypes") public AwaStarSearch(final I problem) { super(problem); this.rootNodeGenerator = (ISingleRootGenerator<N>) problem.getGraphGenerator().getRootGenerator(); this.successorGenerator = problem.getGraphGenerator().getSuccessorGenerator(); this.goalTester = problem.getGoalTester(); this.nodeEvaluator = problem.getPathEvaluator(); this.closedList = new PriorityQueue<>(new DefaultNodeComparator<>()); this.suspendList = new PriorityQueue<>(new DefaultNodeComparator<>()); this.openList = new PriorityQueue<>(new DefaultNodeComparator<>()); this.windowSize = 0; if (this.nodeEvaluator instanceof IPotentiallySolutionReportingPathEvaluator) { ((IPotentiallySolutionReportingPathEvaluator) this.nodeEvaluator).registerSolutionListener(this); } } private void windowAStar() throws AlgorithmTimeoutedException, AlgorithmExecutionCanceledException, InterruptedException, AlgorithmException, PathEvaluationException { while (!this.openList.isEmpty()) { this.checkAndConductTermination(); if (!this.unreturnedSolutionEvents.isEmpty()) { this.logger.info("Not doing anything because there are still unreturned solutions."); return; } BackPointerPath<N, A, V> n = this.openList.peek(); this.openList.remove(n); this.closedList.add(n); if (!n.isGoal()) { this.post(new NodeTypeSwitchEvent<>(this, n, "or_closed")); } /* check whether this node is outside the window and suspend it */ int nLevel = n.getNodes().size() - 1; if (nLevel <= (this.currentLevel - this.windowSize)) { this.closedList.remove(n); this.suspendList.add(n); this.logger.info("Suspending node {} with level {}, which is lower than {}", n, nLevel, this.currentLevel - this.windowSize); this.post(new NodeTypeSwitchEvent<>(this, n, "or_suspended")); continue; } /* if the level should even be increased, do this now */ if (nLevel > this.currentLevel) { this.logger.info("Switching level from {} to {}", this.currentLevel, nLevel); this.currentLevel = nLevel; } this.checkAndConductTermination(); /* compute successors of the expanded node */ this.logger.debug("Expanding {}. Starting successor generation.", n.getHead()); Collection<INewNodeDescription<N, A>> successors = this.computeTimeoutAware(() -> this.successorGenerator.generateSuccessors(n.getHead()), "Successor generation timeouted" , true); this.logger.debug("Successor generation finished. Identified {} successors.", successors.size()); for (INewNodeDescription<N, A> expansionDescription : successors) { this.checkAndConductTermination(); BackPointerPath<N, A, V> nPrime = new BackPointerPath<>(n, expansionDescription.getTo(), expansionDescription.getArcLabel()); nPrime.setGoal(this.goalTester.isGoal(nPrime)); V nPrimeScore = this.nodeEvaluator.evaluate(nPrime); /* ignore nodes whose value cannot be determined */ if (nPrimeScore == null) { this.logger.debug("Discarding node {} for which no f-value could be computed.", nPrime); continue; } /* determine whether this is a goal node */ if (nPrime.isGoal()) { EvaluatedSearchGraphPath<N, A, V> solution = new EvaluatedSearchGraphPath<>(nPrime, nPrimeScore); this.registerNewSolutionCandidate(solution); } if (!this.openList.contains(nPrime) && !this.closedList.contains(nPrime) && !this.suspendList.contains(nPrime)) { nPrime.setParent(n); nPrime.setScore(nPrimeScore); if (!nPrime.isGoal()) { this.openList.add(nPrime); } this.post(new NodeAddedEvent<>(this, n, nPrime, nPrime.isGoal() ? "or_solution" : "or_open")); } else if (this.openList.contains(nPrime) || this.suspendList.contains(nPrime)) { V oldScore = nPrime.getScore(); if (oldScore != null && oldScore.compareTo(nPrimeScore) > 0) { nPrime.setParent(n); nPrime.setScore(nPrimeScore); } } else if (this.closedList.contains(nPrime)) { V oldScore = nPrime.getScore(); if (oldScore != null && oldScore.compareTo(nPrimeScore) > 0) { nPrime.setParent(n); nPrime.setScore(nPrimeScore); } if (!nPrime.isGoal()) { this.openList.add(nPrime); } } } } } @Subscribe public void receiveSolutionEvent(final EvaluatedSearchSolutionCandidateFoundEvent<N, A, V> solutionEvent) { this.registerNewSolutionCandidate(solutionEvent.getSolutionCandidate()); this.unconfirmedSolutions.add(solutionEvent.getSolutionCandidate()); } public EvaluatedSearchSolutionCandidateFoundEvent<N, A, V> registerNewSolutionCandidate(final EvaluatedSearchGraphPath<N, A, V> solution) { EvaluatedSearchSolutionCandidateFoundEvent<N, A, V> event = this.registerSolution(solution); this.unreturnedSolutionEvents.add(event); return event; } @Override public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException{ try { this.registerActiveThread(); this.logger.debug("Next step in {}. State is {}", this.getId(), this.getState()); this.checkAndConductTermination(); switch (this.getState()) { case CREATED: N externalRootNode = this.rootNodeGenerator.getRoot(); BackPointerPath<N, A, V> rootNode = new BackPointerPath<>(null, externalRootNode, null); this.logger.info("Initializing graph and OPEN with {}.", rootNode); this.openList.add(rootNode); this.post(new GraphInitializedEvent<>(this, rootNode)); rootNode.setScore(this.nodeEvaluator.evaluate(rootNode)); return this.activate(); case ACTIVE: IAlgorithmEvent event; this.logger.info("Searching for next solution."); /* return pending solutions if there are any */ while (this.unreturnedSolutionEvents.isEmpty()) { this.checkAndConductTermination(); /* if the current graph has been exhausted, add all suspended nodes to OPEN and increase window size */ if (this.openList.isEmpty()) { if (this.suspendList.isEmpty()) { this.logger.info("The whole graph has been exhausted. No more solutions can be found!"); return this.terminate(); } else { this.logger.info("Search with window size {} is exhausted. Reactivating {} suspended nodes and incrementing window size.", this.windowSize, this.suspendList.size()); this.openList.addAll(this.suspendList); this.suspendList.clear(); this.windowSize++; this.currentLevel = -1; } } this.logger.info("Running core algorithm with window size {} and current level {}. {} items are in OPEN", this.windowSize, this.currentLevel, this.openList.size()); this.windowAStar(); } /* if we reached this point, there is at least one item in the result list. We return it */ event = this.unreturnedSolutionEvents.get(0); this.unreturnedSolutionEvents.remove(0); if (!(event instanceof GraphSearchSolutionCandidateFoundEvent)) { // solution events are sent directly over the event bus this.post(event); } return event; default: throw new IllegalStateException("Cannot do anything in state " + this.getState()); } } catch (PathEvaluationException e) { throw new AlgorithmException("Algorithm failed due to path evaluation exception.", e); } finally { this.unregisterActiveThread(); } } @Override protected void shutdown() { if (this.isShutdownInitialized()) { return; } /* set state to inactive*/ this.logger.info("Invoking shutdown routine ..."); super.shutdown(); /* cancel node evaluator */ if (this.nodeEvaluator instanceof ICancelablePathEvaluator) { this.logger.info("Canceling node evaluator."); ((ICancelablePathEvaluator) this.nodeEvaluator).cancelActiveTasks(); } } @Override public void setNumCPUs(final int numberOfCPUs) { this.logger.warn("Currently no support for parallelization"); } @Override public int getNumCPUs() { return 1; } @Override public IGraphGenerator<N, A> getGraphGenerator() { return this.getInput().getGraphGenerator(); } @Override public void setLoggerName(final String name) { this.logger.info("Switching logger to {}", name); this.loggerName = name; this.logger = LoggerFactory.getLogger(name); this.logger.info("Switched to logger {}", name); super.setLoggerName(this.loggerName + "._orgraphsearch"); } @Override public String getLoggerName() { return this.loggerName; } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/BestFirst.java
package ai.libs.jaicore.search.algorithms.standard.bestfirst; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import org.aeonbits.owner.ConfigFactory; import org.api4.java.ai.graphsearch.problem.IPathSearchWithPathEvaluationsInput; import org.api4.java.ai.graphsearch.problem.implicit.graphgenerator.IPathGoalTester; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.ICancelablePathEvaluator; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallyGraphDependentPathEvaluator; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallySolutionReportingPathEvaluator; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPotentiallyUncertaintyAnnotatingPathEvaluator; import org.api4.java.algorithm.events.IAlgorithmEvent; import org.api4.java.algorithm.events.result.ISolutionCandidateFoundEvent; import org.api4.java.algorithm.exceptions.AlgorithmException; import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException; import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException; import org.api4.java.common.control.ILoggingCustomizable; import org.api4.java.datastructure.graph.implicit.IGraphGenerator; import org.api4.java.datastructure.graph.implicit.INewNodeDescription; import org.api4.java.datastructure.graph.implicit.IRootGenerator; import org.api4.java.datastructure.graph.implicit.ISuccessorGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; import ai.libs.jaicore.basic.algorithm.AlgorithmInitializedEvent; import ai.libs.jaicore.concurrent.GlobalTimer; import ai.libs.jaicore.graphvisualizer.events.graph.GraphInitializedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeAddedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeInfoAlteredEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeParentSwitchEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeRemovedEvent; import ai.libs.jaicore.graphvisualizer.events.graph.NodeTypeSwitchEvent; import ai.libs.jaicore.interrupt.InterruptionTimerTask; import ai.libs.jaicore.logging.LoggerUtil; import ai.libs.jaicore.logging.ToJSONStringUtil; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.EvaluatedSearchSolutionCandidateFoundEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.FValueEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.NodeAnnotationEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.NodeExpansionCompletedEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.NodeExpansionJobSubmittedEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RemovedGoalNodeFromOpenEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.RolloutEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.SolutionAnnotationEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.events.SuccessorComputationCompletedEvent; import ai.libs.jaicore.search.algorithms.standard.bestfirst.nodeevaluation.DecoratingNodeEvaluator; import ai.libs.jaicore.search.core.interfaces.AOptimalPathInORGraphSearch; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.model.travesaltree.BackPointerPath; /** * * @author fmohr, wever * * @param <I> * @param <N> * @param <A> * @param <V> */ public class BestFirst<I extends IPathSearchWithPathEvaluationsInput<N, A, V>, N, A, V extends Comparable<V>> extends AOptimalPathInORGraphSearch<I, N, A, V> { private Logger bfLogger = LoggerFactory.getLogger(BestFirst.class); private String loggerName; private static final String SPACER = "\n\t\t"; public enum ParentDiscarding { NONE, OPEN, ALL } /* problem definition */ protected final IGraphGenerator<N, A> graphGenerator; protected final IRootGenerator<N> rootGenerator; protected final ISuccessorGenerator<N, A> successorGenerator; protected final IPathGoalTester<N, A> pathGoalTester; protected final IPathEvaluator<N, A, V> nodeEvaluator; /* algorithm configuration */ private int timeoutForComputationOfF; private IPathEvaluator<N, A, V> timeoutNodeEvaluator; /* solutions bounds. If node evaluator is optimistic and we have lower bounds, the algorithm will use the maximum over them to assign an f-score */ private final boolean considerNodeEvaluationOptimistic; // if this is set to true, then every node with a score worst than the currently best will be pruned (B&B) private final IPathEvaluator<N, A, V> lowerBoundEvaluator; // if this is set, it is used to compute lower bounds prior to truly evaluating the node and to possible prune the node. /* automatically derived auxiliary variables */ private final boolean solutionReportingNodeEvaluator; private final boolean cancelableNodeEvaluator; /* general algorithm state and statistics */ private int createdCounter; private int expandedCounter; private boolean initialized = false; private final List<INewNodeDescription<N, A>> lastExpansion = new ArrayList<>(); protected final Queue<EvaluatedSearchGraphPath<N, A, V>> solutions = new LinkedBlockingQueue<>(); protected final Queue<EvaluatedSearchSolutionCandidateFoundEvent<N, A, V>> pendingSolutionFoundEvents = new LinkedBlockingQueue<>(); private boolean shutdownComplete = false; /* communication */ protected final Map<N, BackPointerPath<N, A, V>> ext2int = new ConcurrentHashMap<>(); /* search graph model */ protected Queue<BackPointerPath<N, A, V>> open = new PriorityQueue<>((n1, n2) -> n1.getScore().compareTo(n2.getScore())); private BackPointerPath<N, A, V> nodeSelectedForExpansion; // the node that will be expanded next private final Map<N, Thread> expanding = new HashMap<>(); // EXPANDING contains the nodes being expanded and the threads doing this job private final Set<N> closed = new HashSet<>(); // CLOSED contains only node but not paths /* parallelization */ protected int additionalThreadsForNodeAttachment = 0; private ExecutorService pool; private Collection<Thread> threadsOfPool = new ArrayList<>(); // the worker threads of the pool protected final AtomicInteger activeJobs = new AtomicInteger(0); // this is the number of jobs for which a worker is currently running in the pool private final Lock activeJobsCounterLock = new ReentrantLock(); // lock that has to be locked before accessing the open queue private final Lock openLock = new ReentrantLock(); // lock that has to be locked before accessing the open queue private final Lock nodeSelectionLock = new ReentrantLock(true); private final Condition numberOfActiveJobsHasChanged = this.activeJobsCounterLock.newCondition(); // condition that is signaled whenever a node is added to the open queue public BestFirst(final I problem) { this(problem, null); } public BestFirst(final I problem, final IPathEvaluator<N, A, V> lowerBoundEvaluator) { this(ConfigFactory.create(IBestFirstConfig.class), problem, lowerBoundEvaluator); } public BestFirst(final IBestFirstConfig config, final I problem) { this(config, problem, null); } public BestFirst(final IBestFirstConfig config, final I problem, final IPathEvaluator<N, A, V> lowerBoundEvaluator) { super(config, problem); this.graphGenerator = problem.getGraphGenerator(); this.rootGenerator = this.graphGenerator.getRootGenerator(); this.successorGenerator = this.graphGenerator.getSuccessorGenerator(); this.pathGoalTester = problem.getGoalTester(); this.considerNodeEvaluationOptimistic = config.optimisticHeuristic(); this.lowerBoundEvaluator = lowerBoundEvaluator; /* if the node evaluator is graph dependent, communicate the generator to it */ this.nodeEvaluator = problem.getPathEvaluator(); if (this.nodeEvaluator == null) { throw new IllegalArgumentException("Cannot work with node evaulator that is null"); } else if (this.nodeEvaluator instanceof DecoratingNodeEvaluator<?, ?, ?>) { DecoratingNodeEvaluator<N, A, V> castedEvaluator = (DecoratingNodeEvaluator<N, A, V>) this.nodeEvaluator; if (castedEvaluator.requiresGraphGenerator()) { this.bfLogger.info("{} is a graph dependent node evaluator. Setting its graph generator now ...", castedEvaluator); castedEvaluator.setGenerator(this.graphGenerator, this.pathGoalTester); } if (castedEvaluator.reportsSolutions()) { this.bfLogger.info("{} is a solution reporter. Register the search algo in its event bus", castedEvaluator); castedEvaluator.registerSolutionListener(this); this.solutionReportingNodeEvaluator = true; } else { this.solutionReportingNodeEvaluator = false; } } else { if (this.nodeEvaluator instanceof IPotentiallyGraphDependentPathEvaluator) { this.bfLogger.info("{} is a graph dependent node evaluator. Setting its graph generator now ...", this.nodeEvaluator); ((IPotentiallyGraphDependentPathEvaluator<N, A, V>) this.nodeEvaluator).setGenerator(this.graphGenerator, this.pathGoalTester); } /* if the node evaluator is a solution reporter, register in his event bus */ if (this.nodeEvaluator instanceof IPotentiallySolutionReportingPathEvaluator) { this.bfLogger.info("{} is a solution reporter. Register the search algo in its event bus", this.nodeEvaluator); ((IPotentiallySolutionReportingPathEvaluator<N, A, V>) this.nodeEvaluator).registerSolutionListener(this); this.solutionReportingNodeEvaluator = true; } else { this.solutionReportingNodeEvaluator = false; } } this.cancelableNodeEvaluator = this.nodeEvaluator instanceof ICancelablePathEvaluator; /* * add shutdown hook so as to cancel the search once the overall program is * shutdown */ Runtime.getRuntime().addShutdownHook(new Thread(() -> BestFirst.this.cancel(), "Shutdown hook thread for " + BestFirst.this)); } /** BLOCK A: Internal behavior of the algorithm **/ private enum ENodeType { OR_PRUNED("or_pruned"), OR_TIMEDOUT("or_timedout"), OR_OPEN("or_open"), OR_SOLUTION("or_solution"), OR_CREATED("or_created"), OR_CLOSED("or_closed"); private String name; private ENodeType(final String name) { this.name = name; } @Override public String toString() { return this.name; } } private class NodeBuilder implements Runnable { private final Collection<N> todoList; private final BackPointerPath<N, A, V> expandedNodeInternal; private final INewNodeDescription<N, A> successorDescription; public NodeBuilder(final Collection<N> todoList, final BackPointerPath<N, A, V> expandedNodeInternal, final INewNodeDescription<N, A> successorDescription) { super(); this.todoList = todoList; this.expandedNodeInternal = expandedNodeInternal; this.successorDescription = successorDescription; } private void communicateJobFinished() { synchronized (this.todoList) { this.todoList.remove(this.successorDescription.getTo()); if (this.todoList.isEmpty()) { BestFirst.this.post(new NodeExpansionCompletedEvent<>(BestFirst.this, this.expandedNodeInternal)); } } } @Override public void run() { BestFirst.this.bfLogger.debug("Start node creation."); long start = System.currentTimeMillis(); try { if (BestFirst.this.isStopCriterionSatisfied()) { this.communicateJobFinished(); return; } BestFirst.this.lastExpansion.add(this.successorDescription); /* create node */ BackPointerPath<N, A, V> newNode = BestFirst.this.newNode(this.expandedNodeInternal, this.successorDescription.getTo(), this.successorDescription.getArcLabel()); /* check whether the node can be pruned based on a lower bound */ final V lowerBound = (BestFirst.this.lowerBoundEvaluator != null) ? BestFirst.this.lowerBoundEvaluator.evaluate(newNode) : null; if (lowerBound != null) { V currentUpperBound = BestFirst.this.getBestScoreKnownToExist(); if (currentUpperBound != null && lowerBound.compareTo(currentUpperBound) >= 0) { BestFirst.this.bfLogger.debug("Pruning node due to lower bound {} >= {}", lowerBound, currentUpperBound); BestFirst.this.post(new NodeTypeSwitchEvent<>(BestFirst.this, newNode, ENodeType.OR_PRUNED.toString())); return; } } /* update creation counter */ BestFirst.this.createdCounter++; /* compute node label */ try { BestFirst.this.labelNode(newNode); if (newNode.getScore() == null) { BestFirst.this.post(new NodeTypeSwitchEvent<>(BestFirst.this, newNode, ENodeType.OR_PRUNED.toString())); return; } else { BestFirst.this.post(new NodeInfoAlteredEvent<>(BestFirst.this, newNode)); } if (BestFirst.this.isStopCriterionSatisfied()) { this.communicateJobFinished(); return; } } catch (InterruptedException e) { if (!BestFirst.this.isShutdownInitialized()) { BestFirst.this.bfLogger.warn("Leaving node building routine due to interrupt. This leaves the search inconsistent; the node should be attached again!"); } BestFirst.this.bfLogger.debug("Worker has been interrupted, exiting."); BestFirst.this.post(new NodeAnnotationEvent<>(BestFirst.this, newNode, ENodeAnnotation.F_ERROR.toString(), e)); BestFirst.this.post(new NodeTypeSwitchEvent<>(BestFirst.this, newNode, ENodeType.OR_PRUNED.toString())); BestFirst.this.post(new NodeInfoAlteredEvent<>(BestFirst.this, newNode)); Thread.currentThread().interrupt(); return; } catch (TimeoutException e) { BestFirst.this.bfLogger.debug("Node evaluation of {} has timed out.", newNode.hashCode()); newNode.setAnnotation(ENodeAnnotation.F_ERROR.toString(), e); BestFirst.this.post(new NodeAnnotationEvent<>(BestFirst.this, newNode, ENodeAnnotation.F_ERROR.toString(), e)); BestFirst.this.post(new NodeTypeSwitchEvent<>(BestFirst.this, newNode, ENodeType.OR_TIMEDOUT.toString())); BestFirst.this.post(new NodeInfoAlteredEvent<>(BestFirst.this, newNode)); return; } catch (Exception e) { BestFirst.this.bfLogger.debug("Observed an exception during computation of f:\n{}", LoggerUtil.getExceptionInfo(e)); newNode.setAnnotation(ENodeAnnotation.F_ERROR.toString(), e); BestFirst.this.post(new NodeAnnotationEvent<>(BestFirst.this, newNode, ENodeAnnotation.F_ERROR.toString(), e)); BestFirst.this.post(new NodeTypeSwitchEvent<>(BestFirst.this, newNode, ENodeType.OR_PRUNED.toString())); BestFirst.this.post(new NodeInfoAlteredEvent<>(BestFirst.this, newNode)); return; } /* if the node labeling is optimistic and worse than the best currently known solution, then we prune the node */ V bestKnownAchievableScore = BestFirst.this.getBestScoreKnownToExist(); if (BestFirst.this.considerNodeEvaluationOptimistic && bestKnownAchievableScore != null && bestKnownAchievableScore.compareTo(newNode.getScore()) <= 0) { BestFirst.this.bfLogger.info("Pruning newly generated node, since its optimistic estimate is {} and hence not better than the best already known solution score {}.", newNode.getScore(), bestKnownAchievableScore); BestFirst.this.post(new NodeTypeSwitchEvent<>(BestFirst.this, newNode, ENodeType.OR_PRUNED.toString())); return; } /* depending on the algorithm setup, now decide how to proceed with the node */ /* if we discard (either only on OPEN or on both OPEN and CLOSED) */ boolean nodeProcessed = false; if (BestFirst.this.getConfig().parentDiscarding() != ParentDiscarding.NONE) { BestFirst.this.openLock.lockInterruptibly(); try { /* determine whether we already have the node AND it is worse than the one we want to insert */ Optional<BackPointerPath<N, A, V>> existingIdenticalNodeOnOpen = BestFirst.this.open.stream().filter(n -> n.getHead().equals(newNode.getHead())).findFirst(); if (existingIdenticalNodeOnOpen.isPresent()) { BackPointerPath<N, A, V> existingNode = existingIdenticalNodeOnOpen.get(); if (newNode.getScore().compareTo(existingNode.getScore()) < 0) { BestFirst.this.post(new NodeTypeSwitchEvent<>(BestFirst.this, newNode, (newNode.isGoal() ? ENodeType.OR_SOLUTION.toString() : ENodeType.OR_OPEN.toString()))); BestFirst.this.post(new NodeRemovedEvent<>(BestFirst.this, existingNode)); BestFirst.this.open.remove(existingNode); if (newNode.getScore() == null) { throw new IllegalArgumentException("Cannot insert nodes with value NULL into OPEN!"); } BestFirst.this.open.add(newNode); } else { BestFirst.this.post(new NodeRemovedEvent<>(BestFirst.this, newNode)); } nodeProcessed = true; } /* * if parent discarding is not only for OPEN but also for CLOSE (and the node * was not on OPEN), check the list of expanded nodes */ else if (BestFirst.this.getConfig().parentDiscarding() == ParentDiscarding.ALL) { /* reopening, if the node is already on CLOSED */ Optional<N> existingIdenticalNodeOnClosed = BestFirst.this.closed.stream().filter(n -> n.equals(newNode.getHead())).findFirst(); if (existingIdenticalNodeOnClosed.isPresent()) { BackPointerPath<N, A, V> node = BestFirst.this.ext2int.get(existingIdenticalNodeOnClosed.get()); if (newNode.getScore().compareTo(node.getScore()) < 0) { node.setParent(newNode.getParent()); node.setScore(newNode.getScore()); BestFirst.this.closed.remove(node.getHead()); BestFirst.this.open.add(node); BestFirst.this.post(new NodeParentSwitchEvent<BackPointerPath<N, A, V>>(BestFirst.this, node, node.getParent(), newNode.getParent())); } BestFirst.this.post(new NodeRemovedEvent<BackPointerPath<N, A, V>>(BestFirst.this, newNode)); nodeProcessed = true; } } } finally { BestFirst.this.openLock.unlock(); } } /* * if parent discarding is turned off OR if the node was node processed by a * parent discarding rule, just insert it on OPEN */ if (!nodeProcessed) { if (!newNode.isGoal()) { BestFirst.this.openLock.lockInterruptibly(); synchronized (BestFirst.this.expanding) { try { assert !BestFirst.this.closed.contains(newNode.getHead()) : "Currently only tree search is supported. But now we add a node to OPEN whose point has already been expanded before."; BestFirst.this.expanding.keySet().forEach(node -> { assert !node.equals(newNode.getHead()) : Thread.currentThread() + " cannot add node to OPEN that is currently being expanded by " + BestFirst.this.expanding.get(node) + ".\n\tFrom: " + newNode.getParent().getHead() + "\n\tTo: " + node; }); if (newNode.getScore() == null) { throw new IllegalArgumentException("Cannot insert nodes with value NULL into OPEN!"); } BestFirst.this.bfLogger.debug("Inserting successor {} of {} to OPEN. F-Value is {}", newNode.hashCode(), this.expandedNodeInternal.hashCode(), newNode.getScore()); BestFirst.this.open.add(newNode); } finally { BestFirst.this.openLock.unlock(); } } } BestFirst.this.post(new NodeTypeSwitchEvent<>(BestFirst.this, newNode, (newNode.isGoal() ? ENodeType.OR_SOLUTION.toString() : ENodeType.OR_OPEN.toString()))); BestFirst.this.createdCounter++; } /* Recognize solution in cache together with annotation */ if (newNode.isGoal()) { EvaluatedSearchGraphPath<N, A, V> solution = new EvaluatedSearchGraphPath<>(newNode, newNode.getScore()); /* * if the node evaluator has not reported the solution already anyway, register * the solution */ if (!BestFirst.this.solutionReportingNodeEvaluator) { BestFirst.this.registerSolution(solution); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); // interrupt myself. This is for the case that the main thread executes this part BestFirst.this.bfLogger.info("Node builder has been interrupted, finishing execution."); } catch (Exception e) { BestFirst.this.bfLogger.error("An unexpected exception occurred while building nodes", e); } finally { /* free resources if this is computed by helper threads and notify the listeners */ assert !Thread.holdsLock(BestFirst.this.openLock) : "Node Builder must not hold a lock on OPEN when locking the active jobs counter"; BestFirst.this.bfLogger.debug("Trying to decrement active jobs by one."); BestFirst.this.bfLogger.trace("Waiting for activeJobsCounterlock to become free."); BestFirst.this.activeJobsCounterLock.lock(); // cannot be interruptible without opening more cases BestFirst.this.bfLogger.trace("Acquired activeJobsCounterLock for decrement."); try { if (BestFirst.this.pool != null) { BestFirst.this.activeJobs.decrementAndGet(); BestFirst.this.bfLogger.trace("Decremented job counter."); } } finally { BestFirst.this.numberOfActiveJobsHasChanged.signalAll(); BestFirst.this.activeJobsCounterLock.unlock(); BestFirst.this.bfLogger.trace("Released activeJobsCounterLock after decrement."); } this.communicateJobFinished(); BestFirst.this.bfLogger.debug("Builder exits. Build process took {}ms. Interrupt-flag is {}", System.currentTimeMillis() - start, Thread.currentThread().isInterrupted()); } } } protected BackPointerPath<N, A, V> newNode(final BackPointerPath<N, A, V> parent, final N t2, final A arc) throws InterruptedException { return this.newNode(parent, t2, arc, null); } protected BackPointerPath<N, A, V> newNode(final BackPointerPath<N, A, V> parent, final N t2, final A arc, final V evaluation) throws InterruptedException { this.openLock.lockInterruptibly(); try { assert !this.open.contains(parent) : "Parent node " + parent + " is still on OPEN, which must not be the case! OPEN class: " + this.open.getClass().getName() + ". OPEN size: " + this.open.size(); } finally { this.openLock.unlock(); } /* create new node and check whether it is a goal */ BackPointerPath<N, A, V> newNode = new BackPointerPath<>(parent, t2, arc); if (evaluation != null) { newNode.setScore(evaluation); } /* check loop */ assert parent == null || !parent.getNodes().contains(t2) : "There is a loop in the underlying graph. The following path contains the last node twice: " + newNode.getNodes().stream().map(N::toString).reduce("", (s, t) -> s + SPACER + t); /* currently, we only support tree search */ assert !this.ext2int.containsKey(t2) : "Reached node " + t2 + " for the second time.\nt\tFirst path:" + this.ext2int.get(t2).getNodes().stream().map(n -> n + "").reduce("", (s, t) -> s + SPACER + t) + "\n\tSecond Path:" + newNode.getNodes().stream().map(N::toString).reduce("", (s, t) -> s + SPACER + t); /* register node in map and create annotation object */ this.ext2int.put(t2, newNode); /* detect whether node is solution */ if (this.pathGoalTester.isGoal(newNode)) { newNode.setGoal(true); } /* send events for this new node */ if (parent == null) { this.post(new GraphInitializedEvent<BackPointerPath<N, A, V>>(this, newNode)); } else { this.post(new NodeAddedEvent<BackPointerPath<N, A, V>>(this, parent, newNode, (newNode.isGoal() ? ENodeType.OR_SOLUTION.toString() : ENodeType.OR_CREATED.toString()))); this.bfLogger.debug("Sent message for creation of node {} as a successor of {}", newNode.hashCode(), parent.hashCode()); } return newNode; } protected void labelNode(final BackPointerPath<N, A, V> node) throws AlgorithmTimeoutedException, AlgorithmExecutionCanceledException, InterruptedException, AlgorithmException { /* define timeouter for label computation */ this.bfLogger.debug("Computing node label for node with hash code {}", node.hashCode()); if (this.isStopCriterionSatisfied()) { this.bfLogger.debug("Found stop criterion to be true. Returning control."); return; } InterruptionTimerTask interruptionTask = null; AtomicBoolean timedout = new AtomicBoolean(false); if (BestFirst.this.timeoutForComputationOfF > 0) { interruptionTask = new InterruptionTimerTask("Timeout for Node-Labeling in " + BestFirst.this, Thread.currentThread(), () -> timedout.set(true)); this.bfLogger.debug("Scheduling timeout for f-value computation. Allowed time: {}ms", this.timeoutForComputationOfF); GlobalTimer.getInstance().schedule(interruptionTask, this.timeoutForComputationOfF); } /* compute f */ V label = null; boolean computationTimedout = false; long startComputation = System.currentTimeMillis(); try { this.bfLogger.trace("Calling f-function of node evaluator for {}", node.hashCode()); label = this.computeTimeoutAware(() -> BestFirst.this.nodeEvaluator.evaluate(node), "Node Labeling with " + BestFirst.this.nodeEvaluator, !this.threadsOfPool.contains(Thread.currentThread())); // shutdown algorithm on exception // iff // this is not a worker thread this.bfLogger.trace("Determined f-value of {}", label); if (this.isStopCriterionSatisfied()) { return; } /* check whether the required time exceeded the timeout */ long fTime = System.currentTimeMillis() - startComputation; if (BestFirst.this.timeoutForComputationOfF > 0 && fTime > BestFirst.this.timeoutForComputationOfF + 1000) { BestFirst.this.bfLogger.warn("Computation of f for node {} took {}ms, which is more than the allowed {}ms", node, fTime, BestFirst.this.timeoutForComputationOfF); } } catch (InterruptedException e) { this.bfLogger.info("Thread {} received interrupt in node evaluation. Timeout flag is {}", Thread.currentThread(), timedout.get()); if (timedout.get()) { BestFirst.this.bfLogger.debug("Received interrupt during computation of f."); this.post(new NodeTypeSwitchEvent<>(this, node, ENodeType.OR_TIMEDOUT.toString())); node.setAnnotation(ENodeAnnotation.F_ERROR.toString(), "Timeout"); computationTimedout = true; Thread.interrupted(); // set interrupt state of thread to FALSE, because interrupt try { label = BestFirst.this.timeoutNodeEvaluator != null ? BestFirst.this.timeoutNodeEvaluator.evaluate(node) : null; } catch (Exception e2) { this.bfLogger.error("An unexpected exception occurred while labeling node {}", node, e2); } } else { /* maybe, this interrupt occurred during the shutdown/cancellation process. In that case, the InterruptedException needs to be "converted" into another one */ this.checkAndConductTermination(); /* if we came here, this was really a particular interruption */ this.bfLogger.info("Received external interrupt. Forwarding this interrupt."); throw e; } } if (interruptionTask != null) { interruptionTask.cancel(); } /* register time required to compute this node label */ long fTime = System.currentTimeMillis() - startComputation; node.setAnnotation(ENodeAnnotation.F_TIME.toString(), fTime); this.bfLogger.debug("Computed label {} for {} in {}ms", label, node.hashCode(), fTime); /* if no label was computed, prune the node and cancel the computation */ if (label == null) { if (!computationTimedout) { BestFirst.this.bfLogger.debug("Not inserting node {} since its label is missing!", node.hashCode()); } else { BestFirst.this.bfLogger.debug("Not inserting node {} because computation of f-value timed out.", node.hashCode()); } if (!node.getAnnotations().containsKey(ENodeAnnotation.F_ERROR.toString())) { node.setAnnotation(ENodeAnnotation.F_ERROR.toString(), "f-computer returned NULL"); } return; } /* check whether an uncertainty-value is present if the node evaluator is an uncertainty-measuring evaluator */ assert !(this.nodeEvaluator instanceof IPotentiallyUncertaintyAnnotatingPathEvaluator) || !((IPotentiallyUncertaintyAnnotatingPathEvaluator<?, ?, ?>) this.nodeEvaluator).annotatesUncertainty() || node.getAnnotation(ENodeAnnotation.F_UNCERTAINTY.name()) != null : "Uncertainty-based node evaluator (" + this.nodeEvaluator.getClass().getName() + ") claims to annotate uncertainty but has not assigned any uncertainty to " + node.getHead() + " with label " + label; /* eventually set the label */ node.setScore(label); assert node.getScore() != null : "Node label must not be NULL"; this.post(new NodeInfoAlteredEvent<BackPointerPath<N, A, V>>(this, node)); } /** * This method setups the graph by inserting the root nodes. * * @throws InterruptedException * @throws AlgorithmExecutionCanceledException * @throws TimeoutException * @throws AlgorithmException */ protected void initGraph() throws AlgorithmTimeoutedException, AlgorithmExecutionCanceledException, InterruptedException, AlgorithmException { if (!this.initialized) { this.bfLogger.info("Start graph initialization."); this.initialized = true; this.bfLogger.debug("Compute labels of root node(s)"); for (N n0 : this.rootGenerator.getRoots()) { BackPointerPath<N, A, V> root = this.newNode(null, n0, null); if (root == null) { throw new IllegalArgumentException("Root cannot be null. Cannot add NULL as a node to OPEN"); } try { this.labelNode(root); } catch (AlgorithmException e) { throw new AlgorithmException("Graph initialization failed: Could not compute the label for the root node due to an exception.", e); } this.bfLogger.debug("Labeled root with {}", root.getScore()); this.checkAndConductTermination(); if (root.getScore() == null) { throw new IllegalArgumentException("The node evaluator has assigned NULL to the root node, which impedes an initialization of the search graph. Node evaluator: " + this.nodeEvaluator); } this.openLock.lockInterruptibly(); try { this.open.add(root); } finally { this.openLock.unlock(); } } this.bfLogger.info("Finished graph initialization."); } } protected void selectNodeForNextExpansion(final BackPointerPath<N, A, V> node) throws InterruptedException { assert node != null : "Cannot select node NULL for expansion!"; this.nodeSelectionLock.lockInterruptibly(); try { this.openLock.lockInterruptibly(); try { assert !this.open.contains(null) : "OPEN contains NULL"; assert this.open.stream().noneMatch(n -> n.getScore() == null) : "OPEN contains an element with value NULL"; int openSizeBefore = this.open.size(); assert this.nodeSelectedForExpansion == null : "Node selected for expansion must be NULL when setting it!"; this.nodeSelectedForExpansion = node; assert this.open.contains(node) : "OPEN must contain the node to be expanded.\n\tOPEN size: " + this.open.size() + "\n\tNode to be expanded: " + node + ".\n\tOPEN: " + this.open.stream().map(n -> SPACER + n).collect(Collectors.joining()); this.open.remove(this.nodeSelectedForExpansion); int openSizeAfter = this.open.size(); assert this.ext2int.containsKey(this.nodeSelectedForExpansion.getHead()) : "A node chosen for expansion has no entry in the ext2int map!"; assert openSizeAfter == openSizeBefore - 1 : "OPEN size must descrease by one when selecting node for expansion"; } finally { this.openLock.unlock(); } } finally { this.nodeSelectionLock.unlock(); } } /** * This method conducts the expansion of the next node. Unless the next node has been selected from outside, it selects the first node on OPEN (if OPEN is empty but active jobs are running, it waits until those terminate) * * @return * @throws InterruptedException * @throws AlgorithmExecutionCanceledException * @throws TimeoutException * @throws AlgorithmException */ protected IAlgorithmEvent expandNextNode() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { /* Preliminarily check that the active jobs are less than the additional threads */ assert this.additionalThreadsForNodeAttachment == 0 || this.activeJobs.get() < this.additionalThreadsForNodeAttachment : "Cannot expand nodes if number of active jobs (" + this.activeJobs.get() + " is at least as high as the threads available for node attachment (" + this.additionalThreadsForNodeAttachment + ")"; /* * Step 1: determine node that will be expanded next. Either it already has been set * or it will be the first of OPEN. If necessary, we wait for potential incoming nodes */ long startTimeOfExpansion = System.currentTimeMillis(); final BackPointerPath<N, A, V> actualNodeSelectedForExpansion; BackPointerPath<N, A, V> tmpNodeSelectedForExpansion = null; // necessary workaround as setting final variables in a try-block is not reasonably possible this.nodeSelectionLock.lockInterruptibly(); try { if (this.nodeSelectedForExpansion == null) { this.activeJobsCounterLock.lockInterruptibly(); this.bfLogger.trace("Acquired activeJobsCounterLock for read."); boolean stopCriterionSatisfied = this.isStopCriterionSatisfied(); try { this.bfLogger.debug("No next node has been selected. Choosing the first from OPEN."); while (this.open.isEmpty() && this.activeJobs.get() > 0 && !stopCriterionSatisfied) { this.bfLogger.trace("Await condition as open queue is empty and active jobs is {} ...", this.activeJobs.get()); this.numberOfActiveJobsHasChanged.await(); this.bfLogger.trace("Got signaled"); stopCriterionSatisfied = this.isStopCriterionSatisfied(); } if (!stopCriterionSatisfied) { this.openLock.lock(); try { if (this.open.isEmpty()) { return null; } this.selectNodeForNextExpansion(this.open.peek()); } finally { this.openLock.unlock(); } } } finally { this.activeJobsCounterLock.unlock(); this.bfLogger.trace("Released activeJobsCounterLock after read. Now checking termination."); this.checkAndConductTermination(); } } assert this.nodeSelectedForExpansion != null : "We have not selected any node for expansion, but this must be the case at this point."; tmpNodeSelectedForExpansion = this.nodeSelectedForExpansion; this.nodeSelectedForExpansion = null; } finally { this.nodeSelectionLock.unlock(); } assert this.nodeSelectedForExpansion == null : "The object variable for the next selected node must be NULL at the end of the select step."; actualNodeSelectedForExpansion = tmpNodeSelectedForExpansion; synchronized (this.expanding) { this.expanding.put(actualNodeSelectedForExpansion.getHead(), Thread.currentThread()); assert this.expanding.keySet().contains(tmpNodeSelectedForExpansion.getHead()) : "The node selected for expansion should be in the EXPANDING map by now."; } assert !this.open.contains(actualNodeSelectedForExpansion) : "Node selected for expansion is still on OPEN"; assert actualNodeSelectedForExpansion != null : "We have not selected any node for expansion, but this must be the case at this point."; this.checkTerminationAndUnregisterFromExpand(actualNodeSelectedForExpansion); /* steps 2 and 3 only for non-goal nodes */ IAlgorithmEvent expansionEvent; if (!actualNodeSelectedForExpansion.isGoal()) { /* Step 2: compute the successors in the underlying graph */ this.beforeExpansion(actualNodeSelectedForExpansion); this.post(new NodeTypeSwitchEvent<BackPointerPath<N, A, V>>(this, actualNodeSelectedForExpansion, "or_expanding")); this.bfLogger.debug("Expanding node {} with f-value {}", actualNodeSelectedForExpansion.hashCode(), actualNodeSelectedForExpansion.getScore()); this.bfLogger.debug("Start computation of successors"); final List<INewNodeDescription<N, A>> successorDescriptions; List<INewNodeDescription<N, A>> tmpSuccessorDescriptions = null; assert !actualNodeSelectedForExpansion.isGoal() : "Goal nodes must not be expanded!"; tmpSuccessorDescriptions = this.computeTimeoutAware(() -> { this.bfLogger.trace("Invoking getSuccessors"); return BestFirst.this.successorGenerator.generateSuccessors(actualNodeSelectedForExpansion.getHead()); }, "Successor generation", !this.threadsOfPool.contains(Thread.currentThread())); // shutdown algorithm on exception iff this is not one of the worker threads assert tmpSuccessorDescriptions != null : "Successor descriptions must never be null!"; if (this.bfLogger.isTraceEnabled()) { this.bfLogger.trace("Received {} successor descriptions for node with hash code {}. The first 1000 of these are \n\t{}", tmpSuccessorDescriptions.size(), actualNodeSelectedForExpansion.getHead(), tmpSuccessorDescriptions.stream().limit(1000).map(s -> s.getTo().toString()).collect(Collectors.joining("\n\t"))); } successorDescriptions = tmpSuccessorDescriptions; this.checkTerminationAndUnregisterFromExpand(actualNodeSelectedForExpansion); this.bfLogger.debug("Finished computation of successors. Sending SuccessorComputationCompletedEvent with {} successors for {}", successorDescriptions.size(), actualNodeSelectedForExpansion.hashCode()); this.post(new SuccessorComputationCompletedEvent<>(this, actualNodeSelectedForExpansion, successorDescriptions)); /* * step 3: trigger node builders that compute node details and decide whether * and how to integrate the successors into the search */ List<N> todoList = successorDescriptions.stream().map(INewNodeDescription::getTo).collect(Collectors.toList()); long lastTerminationCheck = System.currentTimeMillis(); for (INewNodeDescription<N, A> successorDescription : successorDescriptions) { NodeBuilder nb = new NodeBuilder(todoList, actualNodeSelectedForExpansion, successorDescription); this.bfLogger.trace("Number of additional threads for node attachment is {}", this.additionalThreadsForNodeAttachment); if (this.additionalThreadsForNodeAttachment < 1) { nb.run(); } else { this.lockConditionSafeleyWhileExpandingNode(this.activeJobsCounterLock, actualNodeSelectedForExpansion); // acquires the lock and shuts down properly when being interrupted this.bfLogger.trace("Acquired activeJobsCounterLock for increment"); try { this.activeJobs.incrementAndGet(); } finally { this.numberOfActiveJobsHasChanged.signalAll(); this.activeJobsCounterLock.unlock(); this.bfLogger.trace("Released activeJobsCounterLock after increment"); } if (this.isShutdownInitialized()) { break; } this.pool.submit(nb); } /* frequently check termination conditions */ if (System.currentTimeMillis() - lastTerminationCheck > 50) { if (this.expanding.containsKey(actualNodeSelectedForExpansion)) { this.checkTerminationAndUnregisterFromExpand(actualNodeSelectedForExpansion); } else { // maybe the node has been removed from the expansion list during a timeout or a cancel this.checkAndConductTermination(); } lastTerminationCheck = System.currentTimeMillis(); } } this.bfLogger.debug("Finished expansion of node {} after {}ms. Size of OPEN is now {}. Number of active jobs is {}", actualNodeSelectedForExpansion.hashCode(), System.currentTimeMillis() - startTimeOfExpansion, this.open.size(), this.activeJobs.get()); this.checkTerminationAndUnregisterFromExpand(actualNodeSelectedForExpansion); expansionEvent = new NodeExpansionJobSubmittedEvent<>(this, actualNodeSelectedForExpansion, successorDescriptions); } else { expansionEvent = new RemovedGoalNodeFromOpenEvent<>(this, actualNodeSelectedForExpansion); } /* * step 4: update statistics, send closed notifications, and possibly return a * solution */ this.expandedCounter++; synchronized (this.expanding) { this.expanding.remove(actualNodeSelectedForExpansion.getHead()); assert !this.expanding.containsKey(actualNodeSelectedForExpansion.getHead()) : actualNodeSelectedForExpansion + " was expanded and it was not removed from EXPANDING!"; } this.closed.add(actualNodeSelectedForExpansion.getHead()); assert this.closed.contains(actualNodeSelectedForExpansion.getHead()) : "Expanded node " + actualNodeSelectedForExpansion + " was not inserted into CLOSED!"; this.post(new NodeTypeSwitchEvent<BackPointerPath<N, A, V>>(this, actualNodeSelectedForExpansion, ENodeType.OR_CLOSED.toString())); this.afterExpansion(actualNodeSelectedForExpansion); this.checkAndConductTermination(); this.openLock.lockInterruptibly(); try { this.bfLogger.debug("Step ends. Size of OPEN now {}", this.open.size()); } finally { this.openLock.unlock(); } return expansionEvent; } @Override protected EvaluatedSearchSolutionCandidateFoundEvent<N, A, V> registerSolution(final EvaluatedSearchGraphPath<N, A, V> solutionPath) { EvaluatedSearchSolutionCandidateFoundEvent<N, A, V> solutionEvent = super.registerSolution(solutionPath); // this emits an event on the event bus this.bfLogger.debug("Successfully registered solution on parent level, now adding the solution to the local queue."); assert !this.solutions.contains(solutionEvent.getSolutionCandidate()) : "Registering solution " + solutionEvent.getSolutionCandidate() + " for the second time!"; this.solutions.add(solutionEvent.getSolutionCandidate()); synchronized (this.pendingSolutionFoundEvents) { this.pendingSolutionFoundEvents.add(solutionEvent); } return solutionEvent; } private void lockConditionSafeleyWhileExpandingNode(final Lock l, final BackPointerPath<N, A, V> node) throws AlgorithmTimeoutedException, AlgorithmExecutionCanceledException, InterruptedException { try { l.lockInterruptibly(); } catch (InterruptedException e) { // if we are interrupted during a wait, we must still conduct a controlled shutdown this.bfLogger.debug("Received an interrupt while waiting for {} to become available.", l); Thread.currentThread().interrupt(); this.checkTerminationAndUnregisterFromExpand(node); } } private void unregisterFromExpand(final BackPointerPath<N, A, V> node) { assert this.expanding.containsKey(node.getHead()) : "Cannot unregister a node that is not being expanded currently"; assert this.expanding.get(node.getHead()) == Thread.currentThread() : "Thread " + Thread.currentThread() + " cannot unregister other thread " + this.expanding.get(node.getHead()) + " from expansion map!"; this.bfLogger.debug("Removing {} from EXPANDING.", node.hashCode()); this.expanding.remove(node.getHead()); } /** * This is a small extension of the checkTermination method that makes sure that the current thread is not counted as a worker for an expanding node. This is important to make sure that the thread does not interrupt itself on a shutdown * * @throws TimeoutException * @throws AlgorithmExecutionCanceledException * @throws InterruptedException */ private void checkTerminationAndUnregisterFromExpand(final BackPointerPath<N, A, V> node) throws AlgorithmTimeoutedException, AlgorithmExecutionCanceledException, InterruptedException { if (this.isStopCriterionSatisfied()) { assert this.shutdownComplete || this.expanding.containsKey(node.getHead()) : "Expanded node " + this.nodeSelectedForExpansion + " is not contained EXPANDING currently! That cannot be the case. The " + this.expanding.size() + " nodes currently in EXPANDING are: " + this.expanding.keySet().stream().map(n -> "\n\t" + n).collect(Collectors.joining()); synchronized (this.expanding) { if (this.expanding.containsKey(node.getHead())) { this.unregisterFromExpand(node); assert !this.expanding.containsKey(node.getHead()) : "Expanded node " + this.nodeSelectedForExpansion + " was not removed from EXPANDING!"; } else { this.bfLogger.debug("Node {} is already unregistered from expansion.", node.getHead().hashCode()); } } } super.checkAndConductTermination(); } @Override protected void shutdown() { /* check that the shutdown is not invoked by one of the workers or an interrupted thread */ if (this.threadsOfPool.contains(Thread.currentThread())) { this.bfLogger.error("Worker thread {} must not shutdown the algorithm!", Thread.currentThread()); } assert !Thread.currentThread().isInterrupted() : "The thread should not be interrupted when shutdown is called."; if (this.isShutdownInitialized()) { return; } /* set state to inactive */ this.bfLogger.info("Invoking shutdown routine ..."); this.bfLogger.debug("First conducting general algorithm shutdown routine ..."); super.shutdown(); this.bfLogger.debug("General algorithm shutdown routine completed. Now conducting BestFirst-specific shutdown activities."); /* interrupt the expanding threads */ synchronized (this.expanding) { int interruptedThreads = 0; for (Entry<N, Thread> entry : this.expanding.entrySet()) { Thread t = entry.getValue(); if (!t.equals(Thread.currentThread())) { this.expanding.remove(entry.getKey()); this.bfLogger.debug("Removing node {} with thread {} from expansion map, since this thread is realizing the shutdown.", entry.getKey(), t); } else { if (!this.hasThreadBeenInterruptedDuringShutdown(t)) { this.interruptThreadAsPartOfShutdown(t); interruptedThreads++; } else { this.bfLogger.debug("Not interrupting thread {} again, since it already has been interrupted during shutdown.", t); } } } this.bfLogger.debug("Interrupted {} active expansion threads.", interruptedThreads); } /* cancel ongoing work */ if (this.additionalThreadsForNodeAttachment > 0) { this.bfLogger.debug("Shutting down worker pool."); if (this.pool != null) { this.bfLogger.info("Triggering shutdown of builder thread pool with interrupt"); this.pool.shutdownNow(); } try { this.bfLogger.debug("Waiting 3 days for pool shutdown."); if (this.pool != null) { this.pool.awaitTermination(3, TimeUnit.DAYS); } else { this.bfLogger.error("Apparently, the pool was unexpectedly not set and thus null."); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); this.bfLogger.warn("Got interrupted during shutdown!", e); } if (this.pool != null) { assert this.pool.isTerminated() : "The worker pool has not been shutdown correctly!"; if (!this.pool.isTerminated()) { this.bfLogger.error("Worker pool has not been shutdown correctly!"); } else { this.bfLogger.info("Worker pool has been shut down."); } } this.bfLogger.info("Setting number of active jobs to 0."); this.bfLogger.trace("Waiting for activeJobsCounterLock."); this.activeJobsCounterLock.lock(); try { this.bfLogger.trace("Acquired activeJobsCounterLock for setting it to 0"); this.activeJobs.set(0); this.numberOfActiveJobsHasChanged.signalAll(); } finally { this.activeJobsCounterLock.unlock(); this.bfLogger.trace("Released activeJobsCounterLock after reset"); } this.bfLogger.debug("Pool shutdown completed."); } else { this.bfLogger.debug("No additional threads for node attachment have been admitted, so there is no pool to close down."); } /* cancel node evaluator */ if (this.cancelableNodeEvaluator) { this.bfLogger.info("Canceling node evaluator."); ((ICancelablePathEvaluator) this.nodeEvaluator).cancelActiveTasks(); } assert this.pool == null || this.pool.isShutdown() : "The pool has not been shutdown correctly at the end of the routine."; this.shutdownComplete = true; this.bfLogger.info("Shutdown completed"); } @Subscribe public void receiveSolutionCandidateEvent(final EvaluatedSearchSolutionCandidateFoundEvent<N, A, V> solutionEvent) { try { this.bfLogger.info("Received solution with f-value {} and annotations {}", solutionEvent.getSolutionCandidate().getScore(), solutionEvent.getSolutionCandidate().getAnnotations()); this.registerSolution(solutionEvent.getSolutionCandidate()); // unpack this solution and plug it into the registration process } catch (Exception e) { this.bfLogger.error("An unexpected exception occurred while receiving EvaluatedSearchSolutionCandidateFoundEvent.", e); } } @Subscribe public void receiveRolloutEvent(final RolloutEvent<N, V> event) { try { this.bfLogger.debug("Received rollout event: {}", event); this.post(event); } catch (Exception e) { this.bfLogger.error("An unexpected exception occurred while receiving RolloutEvent", e); } } @Subscribe public void receiveSolutionCandidateAnnotationEvent(final SolutionAnnotationEvent<N, A, V> event) { try { this.bfLogger.debug("Received solution annotation: {}", event); this.post(event); } catch (Exception e) { this.bfLogger.error("An unexpected exception occurred receiveSolutionCandidateAnnotationEvent.", e); } } @Subscribe public void receiveNodeAnnotationEvent(final NodeAnnotationEvent<N> event) { try { N nodeExt = event.getNode(); this.bfLogger.debug("Received annotation {} with value {} for node {}", event.getAnnotationName(), event.getAnnotationValue(), event.getNode()); if (!this.ext2int.containsKey(nodeExt)) { throw new IllegalArgumentException("Received annotation for a node I don't know!"); } BackPointerPath<N, A, V> nodeInt = this.ext2int.get(nodeExt); nodeInt.setAnnotation(event.getAnnotationName(), event.getAnnotationValue()); } catch (Exception e) { this.bfLogger.error("An unexpected exception occurred while receiving node annotation event ", e); } } protected void insertNodeIntoLocalGraph(final BackPointerPath<N, A, V> node) throws InterruptedException { BackPointerPath<N, A, V> localVersionOfParent = null; List<BackPointerPath<N, A, V>> path = node.path(); BackPointerPath<N, A, V> leaf = path.get(path.size() - 1); for (BackPointerPath<N, A, V> nodeOnPath : path) { if (!this.ext2int.containsKey(nodeOnPath.getHead())) { assert nodeOnPath.getParent() != null : "Want to insert a new node that has no parent. That must not be the case! Affected node is: " + nodeOnPath.getHead(); assert this.ext2int.containsKey(nodeOnPath.getParent().getHead()) : "Want to insert a node whose parent is unknown locally"; BackPointerPath<N, A, V> newNode = this.newNode(localVersionOfParent, nodeOnPath.getHead(), nodeOnPath.getEdgeLabelToParent(), nodeOnPath.getScore()); if (!newNode.isGoal() && !newNode.getHead().equals(leaf.getHead())) { this.post(new NodeTypeSwitchEvent<BackPointerPath<N, A, V>>(this, newNode, "or_closed")); } localVersionOfParent = newNode; } else { localVersionOfParent = this.getLocalVersionOfNode(nodeOnPath); } } } /** * This is relevant if we work with several copies of a node (usually if we need to copy the search space somewhere). * * @param node * @return */ protected BackPointerPath<N, A, V> getLocalVersionOfNode(final BackPointerPath<N, A, V> node) { return this.ext2int.get(node.getHead()); } /** BLOCK B: Controlling the algorithm from the outside **/ /** * This method can be used to create an initial graph different from just root nodes. This can be interesting if the search is distributed and we want to search only an excerpt of the original one. * * @param initialNodes */ public void bootstrap(final Collection<BackPointerPath<N, A, V>> initialNodes) throws InterruptedException { if (this.initialized) { throw new UnsupportedOperationException("Bootstrapping is only supported if the search has already been initialized."); } /* now initialize the graph */ try { this.initGraph(); } catch (InterruptedException e) { throw e; } catch (Exception e) { this.bfLogger.error("An unexpected exception occurred while the graph should be initialized.", e); return; } this.openLock.lockInterruptibly(); try { /* remove previous roots from open */ this.open.clear(); /* now insert new nodes, and the leaf ones in open */ for (BackPointerPath<N, A, V> node : initialNodes) { this.insertNodeIntoLocalGraph(node); if (node == null) { throw new IllegalArgumentException("Cannot add NULL as a node to OPEN"); } if (node.getScore() == null) { throw new IllegalArgumentException("Cannot insert node with label NULL"); } this.open.add(this.getLocalVersionOfNode(node)); } } finally { this.openLock.unlock(); } } @Override public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException { try { this.registerActiveThread(); switch (this.getState()) { case CREATED: AlgorithmInitializedEvent initEvent = this.activate(); this.bfLogger.info( "Initializing BestFirst search {} with the following configuration:\n\tCPUs: {}\n\tTimeout: {}ms\n\tGraph Generator: {}\n\tNode Evaluator: {}\n\tConsidering node evaluator optimistic: {}\n\tListening to solutions delivered by node evaluator: {}\n\tInitial score upper bound: {}", this, this.getConfig().cpus(), this.getConfig().timeout(), this.graphGenerator.getClass(), this.nodeEvaluator, this.considerNodeEvaluationOptimistic, this.solutionReportingNodeEvaluator, this.getBestScoreKnownToExist()); int additionalCPUs = this.getConfig().cpus() - 1; if (additionalCPUs > 0) { this.parallelizeNodeExpansion(additionalCPUs); } this.initGraph(); this.bfLogger.info("Search initialized, returning activation event."); return initEvent; case ACTIVE: synchronized (this.pendingSolutionFoundEvents) { if (!this.pendingSolutionFoundEvents.isEmpty()) { return this.pendingSolutionFoundEvents.poll(); // these already have been posted over the event bus but are now returned to the controller for respective handling } } IAlgorithmEvent event; /* if worker threads are used for expansion, make sure that there is at least one that is not busy */ if (this.additionalThreadsForNodeAttachment > 0) { boolean poolSlotFree = false; boolean haveLock = false; do { this.checkAndConductTermination(); try { this.activeJobsCounterLock.lockInterruptibly(); haveLock = true; this.bfLogger.trace("Acquired activeJobsCounterLock for read"); this.bfLogger.debug("The pool is currently busy with {}/{} jobs.", this.activeJobs.get(), this.additionalThreadsForNodeAttachment); if (this.additionalThreadsForNodeAttachment > this.activeJobs.get()) { poolSlotFree = true; } this.bfLogger.trace("Number of active jobs is now {}", this.activeJobs.get()); if (!poolSlotFree) { this.bfLogger.trace("Releasing activeJobsCounterLock for a wait."); try { haveLock = false; this.numberOfActiveJobsHasChanged.await(); haveLock = true; } catch (InterruptedException e) { // if we are interrupted during a wait, we must still conduct a controlled shutdown this.bfLogger.debug("Received an interrupt while waiting for number of active jobs to change."); this.activeJobsCounterLock.unlock(); Thread.currentThread().interrupt(); this.checkAndConductTermination(); } this.bfLogger.trace("Re-acquired activeJobsCounterLock after a wait."); this.bfLogger.debug("Number of active jobs has changed. Let's see whether we can enter now ..."); } } finally { if (haveLock) { this.bfLogger.trace("Trying to unlock activeJobsCounterLock"); this.activeJobsCounterLock.unlock(); haveLock = false; this.bfLogger.trace("Released activeJobsCounterLock after read."); } else { this.bfLogger.trace("Don't need to give lock free, because we came to the finally-block via an exception."); } } } while (!poolSlotFree); } /* expand next node */ this.checkAndConductTermination(); event = this.expandNextNode(); /* if no event has occurred, still check whether a solution has arrived in the meantime prior to setting the algorithm state to inactive */ if (event == null) { synchronized (this.pendingSolutionFoundEvents) { if (!this.pendingSolutionFoundEvents.isEmpty()) { event = this.pendingSolutionFoundEvents.poll(); } else { this.bfLogger.info("No event was returned and there are no pending solutions. Number of active jobs: {}. Setting state to inactive.", this.activeJobs.get()); return this.terminate(); } } } if (!(event instanceof ISolutionCandidateFoundEvent)) { this.post(event); } return event; default: throw new IllegalStateException("BestFirst search is in state " + this.getState() + " in which next must not be called!"); } } finally { this.unregisterActiveThread(); } } public void selectNodeForNextExpansion(final N node) throws InterruptedException { this.selectNodeForNextExpansion(this.ext2int.get(node)); } @SuppressWarnings("unchecked") public NodeExpansionJobSubmittedEvent<N, A, V> nextNodeExpansion() { while (this.hasNext()) { IAlgorithmEvent e = this.next(); if (e instanceof NodeExpansionJobSubmittedEvent) { return (NodeExpansionJobSubmittedEvent<N, A, V>) e; } } return null; } public EvaluatedSearchGraphPath<N, A, V> nextSolutionThatDominatesOpen() throws InterruptedException, AlgorithmExecutionCanceledException, TimeoutException, AlgorithmException { EvaluatedSearchGraphPath<N, A, V> currentlyBestSolution = null; V currentlyBestScore = null; boolean loopCondition = true; while (loopCondition) { EvaluatedSearchGraphPath<N, A, V> solution = this.nextSolutionCandidate(); V scoreOfSolution = solution.getScore(); if (currentlyBestScore == null || scoreOfSolution.compareTo(currentlyBestScore) < 0) { currentlyBestScore = scoreOfSolution; currentlyBestSolution = solution; } this.openLock.lockInterruptibly(); try { loopCondition = this.open.peek().getScore().compareTo(currentlyBestScore) < 0; } finally { this.openLock.unlock(); } } return currentlyBestSolution; } /** BLOCK C: Hooks **/ protected void afterInitialization() { /* intentionally left blank */ } protected boolean beforeSelection() { return true; } protected void afterSelection(final BackPointerPath<N, A, V> node) { /* intentionally left blank */ } protected void beforeExpansion(final BackPointerPath<N, A, V> node) { /* intentionally left blank */ } protected void afterExpansion(final BackPointerPath<N, A, V> node) { /* intentionally left blank */ } /** BLOCK D: Getters and Setters **/ public List<N> getCurrentPathToNode(final N node) { return this.ext2int.get(node).getNodes(); } public IPathEvaluator<N, A, V> getNodeEvaluator() { return this.nodeEvaluator; } public int getAdditionalThreadsForExpansion() { return this.additionalThreadsForNodeAttachment; } private void parallelizeNodeExpansion(final int threadsForExpansion) { if (this.pool != null) { throw new UnsupportedOperationException("The number of additional threads can be only set once per search!"); } if (threadsForExpansion < 1) { throw new IllegalArgumentException("Number of threads should be at least 1 for " + this.getClass().getName()); } int threadsForAlgorithm = (this.getConfig().threads() >= 0) ? this.getConfig().threads() : this.getConfig().cpus(); this.additionalThreadsForNodeAttachment = threadsForExpansion; if (this.additionalThreadsForNodeAttachment > threadsForAlgorithm - 2) { // timer and main thread must not add up here this.additionalThreadsForNodeAttachment = Math.min(this.additionalThreadsForNodeAttachment, threadsForAlgorithm - 2); } if (this.additionalThreadsForNodeAttachment < 1) { this.bfLogger.info("Effectively not parallelizing, since only {} threads are allowed by configuration, and 2 are needed for control and maintenance.", threadsForAlgorithm); this.additionalThreadsForNodeAttachment = 0; return; } AtomicInteger counter = new AtomicInteger(0); this.pool = Executors.newFixedThreadPool(this.additionalThreadsForNodeAttachment, r -> { Thread t = new Thread(r); t.setName("ORGraphSearch-worker-" + counter.incrementAndGet()); this.threadsOfPool.add(t); return t; }); } public int getTimeoutForComputationOfF() { return this.timeoutForComputationOfF; } public void setTimeoutForComputationOfF(final int timeoutInMS, final IPathEvaluator<N, A, V> timeoutEvaluator) { this.timeoutForComputationOfF = timeoutInMS; this.timeoutNodeEvaluator = timeoutEvaluator; } /** * @return the openCollection */ public List<BackPointerPath<N, A, V>> getOpen() { return Collections.unmodifiableList(new ArrayList<>(this.open)); } public BackPointerPath<N, A, V> getInternalRepresentationOf(final N node) { return this.ext2int.get(node); } /** * @param open * the openCollection to set */ public void setOpen(final Queue<BackPointerPath<N, A, V>> collection) { this.openLock.lock(); try { collection.clear(); collection.addAll(this.open); this.open = collection; } finally { this.openLock.unlock(); } } @Override public String getLoggerName() { return this.loggerName; } @Override public void setLoggerName(final String name) { this.bfLogger.info("Switching logger from {} to {}", this.bfLogger.getName(), name); this.loggerName = name; this.bfLogger = LoggerFactory.getLogger(name); this.bfLogger.info("Activated logger {} with name {}", name, this.bfLogger.getName()); if (this.graphGenerator instanceof ILoggingCustomizable) { this.bfLogger.info("Setting logger of graph generator to {}.gg", name); ((ILoggingCustomizable) this.graphGenerator).setLoggerName(this.loggerName + ".gg"); } if (this.nodeEvaluator instanceof ILoggingCustomizable) { this.bfLogger.info("Setting logger of node evaluator {} to {}.nodeevaluator", this.nodeEvaluator, name); ((ILoggingCustomizable) this.nodeEvaluator).setLoggerName(name + ".nodeevaluator"); } else { this.bfLogger.info("Node evaluator {} does not implement ILoggingCustomizable, so its logger won't be customized.", this.nodeEvaluator); } super.setLoggerName(this.loggerName + "._orgraphsearch"); } public Queue<EvaluatedSearchGraphPath<N, A, V>> getSolutionQueue() { return this.solutions; } public boolean isShutdownComplete() { return this.shutdownComplete; } /** * Check how many times a node was expanded. * * @return A counter of how many times a node was expanded. */ public int getExpandedCounter() { return this.expandedCounter; } public int getCreatedCounter() { return this.createdCounter; } public V getFValue(final N node) { return this.getFValue(this.ext2int.get(node)); } public V getFValue(final BackPointerPath<N, A, V> node) { return node.getScore(); } public Map<String, Object> getNodeAnnotations(final N node) { BackPointerPath<N, A, V> intNode = this.ext2int.get(node); return intNode.getAnnotations(); } public Object getNodeAnnotation(final N node, final String annotation) { BackPointerPath<N, A, V> intNode = this.ext2int.get(node); return intNode.getAnnotation(annotation); } @Subscribe public void onFValueReceivedEvent(final FValueEvent<V> event) { this.post(event); } @Override public IBestFirstConfig getConfig() { return (IBestFirstConfig) super.getConfig(); } public String toDetailedString() { Map<String, Object> fields = new HashMap<>(); fields.put("graphGenerator", this.graphGenerator); fields.put("nodeEvaluator", this.nodeEvaluator); return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields); } @Override public String toString() { return this.getId(); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/BestFirstEpsilon.java
package ai.libs.jaicore.search.algorithms.standard.bestfirst; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.PriorityQueue; import java.util.stream.Collectors; import org.api4.java.ai.graphsearch.problem.pathsearch.pathevaluation.IPathEvaluator; import org.api4.java.common.control.ILoggingCustomizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.search.model.travesaltree.BackPointerPath; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; /** * A* algorithm implementation using the method design pattern. * * @author Felix Mohr */ public class BestFirstEpsilon<T, A, W extends Comparable<W>> extends StandardBestFirst<T, A, Double> { private Logger logger = LoggerFactory.getLogger(BestFirstEpsilon.class); private String loggerName; private final IPathEvaluator<T, A, W> secondaryNodeEvaluator; private final Map<BackPointerPath<T, A, Double>, W> secondaryCache = new HashMap<>(); private final OpenList focalBasedOpenList = new OpenList(); private final boolean absolute; private final double epsilon; @SuppressWarnings("serial") private class OpenList extends PriorityQueue<BackPointerPath<T, A, Double>> { @Override public BackPointerPath<T, A, Double> peek() { if (BestFirstEpsilon.this.epsilon <= 0 || BestFirstEpsilon.this.open.isEmpty()) { return super.peek(); } /* build focal list and compute secondary f values for the elements in the list */ double best = super.peek().getScore(); double threshold = (BestFirstEpsilon.this.absolute ? (best >= 0 ? best + BestFirstEpsilon.this.epsilon : best - BestFirstEpsilon.this.epsilon) : best * (best >= 0 ? 1 + BestFirstEpsilon.this.epsilon : 1 - BestFirstEpsilon.this.epsilon)); Collection<BackPointerPath<T, A, Double>> focal = super.stream().filter(n -> n.getScore() <= threshold).collect(Collectors.toList()); focal.stream().filter(n -> !BestFirstEpsilon.this.secondaryCache.containsKey(n)).forEach(n -> { try { BestFirstEpsilon.this.secondaryCache.put(n, BestFirstEpsilon.this.secondaryNodeEvaluator.evaluate(n)); } catch (Exception e) { BestFirstEpsilon.this.logger.error("Observed exception during computation of f: {}", e); } }); Optional<BackPointerPath<T, A, Double>> choice = focal.stream().min((p1, p2) -> BestFirstEpsilon.this.secondaryCache.get(p1).compareTo(BestFirstEpsilon.this.secondaryCache.get(p2))); if (!choice.isPresent()) { throw new IllegalStateException("No choice found!"); } BestFirstEpsilon.this.logger.info("Best score is {}. Threshold for focal is {}. Choose node with f1 {} and best f2 {}. Size of focal was {}.", best, threshold, choice.get().getScore(), BestFirstEpsilon.this.secondaryCache.get(choice.get()), focal.size()); return choice.get(); } } public BestFirstEpsilon(final GraphSearchWithSubpathEvaluationsInput<T, A, Double> problem, final IPathEvaluator<T, A, W> pSecondaryNodeEvaluator, final int epsilon) { this(problem, pSecondaryNodeEvaluator, epsilon, true); } public BestFirstEpsilon(final GraphSearchWithSubpathEvaluationsInput<T, A, Double> problem, final IPathEvaluator<T, A, W> pSecondaryNodeEvaluator, final double epsilon, final boolean absolute) { super(problem); this.secondaryNodeEvaluator = pSecondaryNodeEvaluator; this.epsilon = epsilon; this.absolute = absolute; /* overwrite node selector */ this.setOpen(this.focalBasedOpenList); } public boolean isAbsolute() { return this.absolute; } public double getEpsilon() { return this.epsilon; } @Override public String getLoggerName() { return this.loggerName; } @Override public void setLoggerName(final String name) { this.logger.info("Switching logger from {} to {}", this.logger.getName(), name); this.logger = LoggerFactory.getLogger(name); this.logger.info("Activated logger {} with name {}", name, this.logger.getName()); if (this.secondaryNodeEvaluator instanceof ILoggingCustomizable) { ((ILoggingCustomizable) this.secondaryNodeEvaluator).setLoggerName(name + ".secnodeeval"); } super.setLoggerName(this.loggerName + "._bestfirst"); } }
0
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard
java-sources/ai/libs/jaicore-search/0.2.7/ai/libs/jaicore/search/algorithms/standard/bestfirst/BestFirstFactory.java
package ai.libs.jaicore.search.algorithms.standard.bestfirst; import java.util.Objects; import org.api4.java.ai.graphsearch.problem.IOptimalPathInORGraphSearchFactory; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.basic.algorithm.reduction.AlgorithmicProblemReduction; import ai.libs.jaicore.search.core.interfaces.StandardORGraphSearchFactory; import ai.libs.jaicore.search.model.other.EvaluatedSearchGraphPath; import ai.libs.jaicore.search.probleminputs.GraphSearchWithSubpathEvaluationsInput; public class BestFirstFactory<P extends IPathSearchWithPathEvaluationsInput<N, A, V>, N, A, V extends Comparable<V>> extends StandardORGraphSearchFactory<P, EvaluatedSearchGraphPath<N, A, V>, N, A, V, BestFirst<P, N, A, V>> implements IOptimalPathInORGraphSearchFactory<P, EvaluatedSearchGraphPath<N, A, V>, N, A, V, BestFirst<P, N, A, V>> { private int timeoutForFInMS; private IPathEvaluator<N, A, V> timeoutEvaluator; private Logger logger = LoggerFactory.getLogger(BestFirstFactory.class); private AlgorithmicProblemReduction<IPathSearchInput<N, A>, EvaluatedSearchGraphPath<N, A, V>, GraphSearchWithSubpathEvaluationsInput<N, A, V>, EvaluatedSearchGraphPath<N, A, V>> reduction; public BestFirstFactory() { super(); } public BestFirstFactory(final int timeoutForFInMS) { this(); if (timeoutForFInMS > 0) { this.timeoutForFInMS = timeoutForFInMS; } } @Override public BestFirst<P, N, A, V> getAlgorithm() { if (this.getInput().getGraphGenerator() == null) { throw new IllegalStateException("Cannot produce BestFirst searches before the graph generator is set in the problem."); } if (this.getInput().getPathEvaluator() == null) { throw new IllegalStateException("Cannot produce BestFirst searches before the node evaluator is set."); } return this.getAlgorithm(this.getInput()); } public void setTimeoutForFComputation(final int timeoutInMS, final IPathEvaluator<N, A, V> timeoutEvaluator) { this.timeoutForFInMS = timeoutInMS; this.timeoutEvaluator = timeoutEvaluator; } public int getTimeoutForFInMS() { return this.timeoutForFInMS; } public IPathEvaluator<N, A, V> getTimeoutEvaluator() { return this.timeoutEvaluator; } public String getLoggerName() { return this.logger.getName(); } public void setLoggerName(final String loggerName) { this.logger = LoggerFactory.getLogger(loggerName); } public AlgorithmicProblemReduction<IPathSearchInput<N, A>, EvaluatedSearchGraphPath<N, A, V>, GraphSearchWithSubpathEvaluationsInput<N, A, V>, EvaluatedSearchGraphPath<N, A, V>> getReduction() { return this.reduction; } public void setReduction(final AlgorithmicProblemReduction<IPathSearchInput<N, A>, EvaluatedSearchGraphPath<N, A, V>, GraphSearchWithSubpathEvaluationsInput<N, A, V>, EvaluatedSearchGraphPath<N, A, V>> reduction) { this.reduction = reduction; } @Override public BestFirst<P, N, A, V> getAlgorithm(final P problem) { P acceptedProblem = problem; if (!(problem instanceof GraphSearchWithSubpathEvaluationsInput)) { if (this.reduction == null) { throw new IllegalStateException("No reduction provided for inputs of type " + problem.getClass().getName() + "."); } Objects.requireNonNull(this.reduction); this.logger.info("Reducing the original problem {} using reduction {}", problem, this.reduction); acceptedProblem = (P) this.reduction.encodeProblem(problem); } if (problem.getPathEvaluator() == null) { throw new IllegalArgumentException("Cannot create BestFirst algorithm for node evaluator NULL"); } BestFirst<P, N, A, V> search = new BestFirst<>(acceptedProblem); this.setupAlgorithm(search); return search; } protected void setupAlgorithm(final BestFirst<P, N, A, V> algorithm) { algorithm.setTimeoutForComputationOfF(this.timeoutForFInMS, this.timeoutEvaluator); } }