file_path
stringlengths
20
202
content
stringlengths
9
3.85M
size
int64
9
3.85M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
8
993
alphanum_fraction
float64
0.26
0.93
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_information.h
#ifndef PDBS_PATTERN_INFORMATION_H #define PDBS_PATTERN_INFORMATION_H #include "types.h" #include "../task_proxy.h" #include <memory> namespace pdbs { /* This class is a wrapper for a pair of a pattern and the corresponding PDB. It always contains a pattern and can contain the computed PDB. If the latter is not set, it is computed on demand. Ownership of the information is shared between the creators of this class (usually PatternGenerators), the class itself, and its users (consumers of patterns like heuristics). TODO: consider using this class not for shared ownership but for actual ownership transfer, from the generator to the user. */ class PatternInformation { TaskProxy task_proxy; Pattern pattern; std::shared_ptr<PatternDatabase> pdb; void create_pdb_if_missing(); bool information_is_valid() const; public: PatternInformation(const TaskProxy &task_proxy, Pattern pattern); void set_pdb(const std::shared_ptr<PatternDatabase> &pdb); TaskProxy get_task_proxy() const { return task_proxy; } const Pattern &get_pattern() const; std::shared_ptr<PatternDatabase> get_pdb(); }; } #endif
1,176
C
25.155555
78
0.72619
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_combo.h
#ifndef PDBS_PATTERN_COLLECTION_GENERATOR_COMBO_H #define PDBS_PATTERN_COLLECTION_GENERATOR_COMBO_H #include "pattern_generator.h" namespace pdbs { /* Take one large pattern and then single-variable patterns for all goal variables that are not in the large pattern. */ class PatternCollectionGeneratorCombo : public PatternCollectionGenerator { int max_states; public: explicit PatternCollectionGeneratorCombo(const options::Options &opts); virtual ~PatternCollectionGeneratorCombo() = default; virtual PatternCollectionInformation generate( const std::shared_ptr<AbstractTask> &task) override; }; } #endif
638
C
29.42857
75
0.778997
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/zero_one_pdbs_heuristic.cc
#include "zero_one_pdbs_heuristic.h" #include "pattern_generator.h" #include "../option_parser.h" #include "../plugin.h" #include <limits> using namespace std; namespace pdbs { ZeroOnePDBs get_zero_one_pdbs_from_options( const shared_ptr<AbstractTask> &task, const Options &opts) { shared_ptr<PatternCollectionGenerator> pattern_generator = opts.get<shared_ptr<PatternCollectionGenerator>>("patterns"); PatternCollectionInformation pattern_collection_info = pattern_generator->generate(task); shared_ptr<PatternCollection> patterns = pattern_collection_info.get_patterns(); TaskProxy task_proxy(*task); return ZeroOnePDBs(task_proxy, *patterns); } ZeroOnePDBsHeuristic::ZeroOnePDBsHeuristic( const options::Options &opts) : Heuristic(opts), zero_one_pdbs(get_zero_one_pdbs_from_options(task, opts)) { } int ZeroOnePDBsHeuristic::compute_heuristic(const State &ancestor_state) { State state = convert_ancestor_state(ancestor_state); int h = zero_one_pdbs.get_value(state); if (h == numeric_limits<int>::max()) return DEAD_END; return h; } static shared_ptr<Heuristic> _parse(OptionParser &parser) { parser.document_synopsis( "Zero-One PDB", "The zero/one pattern database heuristic is simply the sum of the " "heuristic values of all patterns in the pattern collection. In contrast " "to the canonical pattern database heuristic, there is no need to check " "for additive subsets, because the additivity of the patterns is " "guaranteed by action cost partitioning. This heuristic uses the most " "simple form of action cost partitioning, i.e. if an operator affects " "more than one pattern in the collection, its costs are entirely taken " "into account for one pattern (the first one which it affects) and set " "to zero for all other affected patterns."); parser.document_language_support("action costs", "supported"); parser.document_language_support("conditional effects", "not supported"); parser.document_language_support("axioms", "not supported"); parser.document_property("admissible", "yes"); parser.document_property("consistent", "yes"); parser.document_property("safe", "yes"); parser.document_property("preferred operators", "no"); parser.add_option<shared_ptr<PatternCollectionGenerator>>( "patterns", "pattern generation method", "systematic(1)"); Heuristic::add_options_to_parser(parser); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<ZeroOnePDBsHeuristic>(opts); } static Plugin<Evaluator> _plugin("zopdbs", _parse, "heuristics_pdb"); }
2,760
C++
36.31081
82
0.698551
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/zero_one_pdbs.h
#ifndef PDBS_ZERO_ONE_PDBS_H #define PDBS_ZERO_ONE_PDBS_H #include "types.h" class State; class TaskProxy; namespace pdbs { class ZeroOnePDBs { PDBCollection pattern_databases; public: ZeroOnePDBs(const TaskProxy &task_proxy, const PatternCollection &patterns); ~ZeroOnePDBs() = default; int get_value(const State &state) const; /* Returns the sum of all mean finite h-values of every PDB. This is an approximation of the real mean finite h-value of the Heuristic, because dead-ends are ignored for the computation of the mean finite h-values for a PDB. As a consequence, if different PDBs have different states which are dead-end, we do not calculate the real mean h-value for these states. */ double compute_approx_mean_finite_h() const; void dump() const; }; } #endif
844
C
26.258064
80
0.707346
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_database.h
#ifndef PDBS_PATTERN_DATABASE_H #define PDBS_PATTERN_DATABASE_H #include "types.h" #include "../task_proxy.h" #include <utility> #include <vector> namespace utils { class RandomNumberGenerator; } namespace pdbs { class AbstractOperator { /* This class represents an abstract operator how it is needed for the regression search performed during the PDB-construction. As all abstract states are represented as a number, abstract operators don't have "usual" effects but "hash effects", i.e. the change (as number) the abstract operator implies on a given abstract state. */ int concrete_op_id; int cost; /* Preconditions for the regression search, corresponds to normal effects and prevail of concrete operators. */ std::vector<FactPair> regression_preconditions; /* Effect of the operator during regression search on a given abstract state number. */ int hash_effect; public: /* Abstract operators are built from concrete operators. The parameters follow the usual name convention of SAS+ operators, meaning prevail, preconditions and effects are all related to progression search. */ AbstractOperator(const std::vector<FactPair> &prevail, const std::vector<FactPair> &preconditions, const std::vector<FactPair> &effects, int cost, const std::vector<int> &hash_multipliers, int concrete_op_id); ~AbstractOperator(); /* Returns variable value pairs which represent the preconditions of the abstract operator in a regression search */ const std::vector<FactPair> &get_regression_preconditions() const { return regression_preconditions; } /* Returns the effect of the abstract operator in form of a value change (+ or -) to an abstract state index */ int get_hash_effect() const {return hash_effect;} int get_concrete_op_id() const { return concrete_op_id; } /* Returns the cost of the abstract operator (same as the cost of the original concrete operator) */ int get_cost() const {return cost;} void dump(const Pattern &pattern, const VariablesProxy &variables) const; }; // Implements a single pattern database class PatternDatabase { Pattern pattern; // size of the PDB int num_states; /* final h-values for abstract-states. dead-ends are represented by numeric_limits<int>::max() */ std::vector<int> distances; std::vector<int> generating_op_ids; std::vector<std::vector<OperatorID>> wildcard_plan; // multipliers for each variable for perfect hash function std::vector<int> hash_multipliers; /* Recursive method; called by build_abstract_operators. In the case of a precondition with value = -1 in the concrete operator, all multiplied out abstract operators are computed, i.e. for all possible values of the variable (with precondition = -1), one abstract operator with a concrete value (!= -1) is computed. */ void multiply_out( int pos, int cost, std::vector<FactPair> &prev_pairs, std::vector<FactPair> &pre_pairs, std::vector<FactPair> &eff_pairs, const std::vector<FactPair> &effects_without_pre, const VariablesProxy &variables, int concrete_op_id, std::vector<AbstractOperator> &operators); /* Computes all abstract operators for a given concrete operator (by its global operator number). Initializes data structures for initial call to recursive method multiply_out. variable_to_index maps variables in the task to their index in the pattern or -1. */ void build_abstract_operators( const OperatorProxy &op, int cost, const std::vector<int> &variable_to_index, const VariablesProxy &variables, std::vector<AbstractOperator> &operators); /* Computes all abstract operators, builds the match tree (successor generator) and then does a Dijkstra regression search to compute all final h-values (stored in distances). operator_costs can specify individual operator costs for each operator for action cost partitioning. If left empty, default operator costs are used. */ void create_pdb( const TaskProxy &task_proxy, const std::vector<int> &operator_costs, bool compute_plan, const std::shared_ptr<utils::RandomNumberGenerator> &rng, bool compute_wildcard_plan); /* For a given abstract state (given as index), the according values for each variable in the state are computed and compared with the given pairs of goal variables and values. Returns true iff the state is a goal state. */ bool is_goal_state( int state_index, const std::vector<FactPair> &abstract_goals, const VariablesProxy &variables) const; /* The given concrete state is used to calculate the index of the according abstract state. This is only used for table lookup (distances) during search. */ int hash_index(const std::vector<int> &state) const; public: /* Important: It is assumed that the pattern (passed via Options) is sorted, contains no duplicates and is small enough so that the number of abstract states is below numeric_limits<int>::max() Parameters: dump: If set to true, prints the construction time. operator_costs: Can specify individual operator costs for each operator. This is useful for action cost partitioning. If left empty, default operator costs are used. compute_plan: if true, compute an optimal plan when computing distances of the PDB. This requires a RNG object passed via rng. compute_wildcard_plan: when computing a plan (see compute_plan), compute a wildcard plan, i.e., a sequence of parallel operators inducing an optimal plan. Otherwise, compute a simple plan (a sequence of operators). */ PatternDatabase( const TaskProxy &task_proxy, const Pattern &pattern, bool dump = false, const std::vector<int> &operator_costs = std::vector<int>(), bool compute_plan = false, const std::shared_ptr<utils::RandomNumberGenerator> &rng = nullptr, bool compute_wildcard_plan = false); ~PatternDatabase() = default; int get_value(const std::vector<int> &state) const; // Returns the pattern (i.e. all variables used) of the PDB const Pattern &get_pattern() const { return pattern; } // Returns the size (number of abstract states) of the PDB int get_size() const { return num_states; } std::vector<std::vector<OperatorID>> && extract_wildcard_plan() { return std::move(wildcard_plan); }; /* Returns the average h-value over all states, where dead-ends are ignored (they neither increase the sum of all h-values nor the number of entries for the mean value calculation). If all states are dead-ends, infinity is returned. Note: This is only calculated when called; avoid repeated calls to this method! */ double compute_mean_finite_h() const; // Returns true iff op has an effect on a variable in the pattern. bool is_operator_relevant(const OperatorProxy &op) const; }; } #endif
7,550
C
33.479452
80
0.664503
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/canonical_pdbs.h
#ifndef PDBS_CANONICAL_PDBS_H #define PDBS_CANONICAL_PDBS_H #include "types.h" #include <memory> class State; namespace pdbs { class CanonicalPDBs { std::shared_ptr<PDBCollection> pdbs; std::shared_ptr<std::vector<PatternClique>> pattern_cliques; public: CanonicalPDBs( const std::shared_ptr<PDBCollection> &pdbs, const std::shared_ptr<std::vector<PatternClique>> &pattern_cliques); ~CanonicalPDBs() = default; int get_value(const State &state) const; }; } #endif
507
C
18.538461
76
0.698225
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/zero_one_pdbs_heuristic.h
#ifndef PDBS_ZERO_ONE_PDBS_HEURISTIC_H #define PDBS_ZERO_ONE_PDBS_HEURISTIC_H #include "zero_one_pdbs.h" #include "../heuristic.h" namespace pdbs { class PatternDatabase; class ZeroOnePDBsHeuristic : public Heuristic { ZeroOnePDBs zero_one_pdbs; protected: virtual int compute_heuristic(const State &ancestor_state) override; public: ZeroOnePDBsHeuristic(const options::Options &opts); virtual ~ZeroOnePDBsHeuristic() = default; }; } #endif
462
C
20.045454
72
0.751082
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_combo.cc
#include "pattern_collection_generator_combo.h" #include "pattern_generator_greedy.h" #include "utils.h" #include "validation.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../utils/logging.h" #include "../utils/timer.h" #include <iostream> #include <memory> #include <set> using namespace std; namespace pdbs { PatternCollectionGeneratorCombo::PatternCollectionGeneratorCombo(const Options &opts) : max_states(opts.get<int>("max_states")) { } PatternCollectionInformation PatternCollectionGeneratorCombo::generate( const shared_ptr<AbstractTask> &task) { utils::Timer timer; utils::g_log << "Generating patterns using the combo generator..." << endl; TaskProxy task_proxy(*task); shared_ptr<PatternCollection> patterns = make_shared<PatternCollection>(); PatternGeneratorGreedy large_pattern_generator(max_states); const Pattern &large_pattern = large_pattern_generator.generate(task).get_pattern(); patterns->push_back(large_pattern); set<int> used_vars(large_pattern.begin(), large_pattern.end()); for (FactProxy goal : task_proxy.get_goals()) { int goal_var_id = goal.get_variable().get_id(); if (!used_vars.count(goal_var_id)) patterns->emplace_back(1, goal_var_id); } PatternCollectionInformation pci(task_proxy, patterns); dump_pattern_collection_generation_statistics( "Combo generator", timer(), pci); return pci; } static shared_ptr<PatternCollectionGenerator> _parse(OptionParser &parser) { parser.add_option<int>( "max_states", "maximum abstraction size for combo strategy", "1000000", Bounds("1", "infinity")); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<PatternCollectionGeneratorCombo>(opts); } static Plugin<PatternCollectionGenerator> _plugin("combo", _parse); }
1,936
C++
28.8
88
0.695764
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_information.cc
#include "pattern_information.h" #include "pattern_database.h" #include "validation.h" #include <cassert> using namespace std; namespace pdbs { PatternInformation::PatternInformation( const TaskProxy &task_proxy, Pattern pattern) : task_proxy(task_proxy), pattern(move(pattern)), pdb(nullptr) { validate_and_normalize_pattern(task_proxy, this->pattern); } bool PatternInformation::information_is_valid() const { return !pdb || pdb->get_pattern() == pattern; } void PatternInformation::create_pdb_if_missing() { if (!pdb) { pdb = make_shared<PatternDatabase>(task_proxy, pattern); } } void PatternInformation::set_pdb(const shared_ptr<PatternDatabase> &pdb_) { pdb = pdb_; assert(information_is_valid()); } const Pattern &PatternInformation::get_pattern() const { return pattern; } shared_ptr<PatternDatabase> PatternInformation::get_pdb() { create_pdb_if_missing(); return pdb; } }
959
C++
20.818181
75
0.691345
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_hillclimbing.cc
#include "pattern_collection_generator_hillclimbing.h" #include "canonical_pdbs_heuristic.h" #include "incremental_canonical_pdbs.h" #include "pattern_database.h" #include "utils.h" #include "validation.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_utils/causal_graph.h" #include "../task_utils/sampling.h" #include "../task_utils/task_properties.h" #include "../utils/collections.h" #include "../utils/countdown_timer.h" #include "../utils/logging.h" #include "../utils/markup.h" #include "../utils/math.h" #include "../utils/memory.h" #include "../utils/rng.h" #include "../utils/rng_options.h" #include "../utils/timer.h" #include <algorithm> #include <cassert> #include <iostream> #include <limits> using namespace std; namespace pdbs { /* Since this exception class is only used for control flow and thus has no need for an error message, we use a standalone class instead of inheriting from utils::Exception. */ class HillClimbingTimeout { }; static vector<int> get_goal_variables(const TaskProxy &task_proxy) { vector<int> goal_vars; GoalsProxy goals = task_proxy.get_goals(); goal_vars.reserve(goals.size()); for (FactProxy goal : goals) { goal_vars.push_back(goal.get_variable().get_id()); } assert(utils::is_sorted_unique(goal_vars)); return goal_vars; } /* When growing a pattern, we only want to consider successor patterns that are *interesting*. A pattern is interesting if the subgraph of the causal graph induced by the pattern satisfies the following two properties: A. it is weakly connected (considering all kinds of arcs) B. from every variable in the pattern, a goal variable is reachable by a path that only uses pre->eff arcs We can use the assumption that the pattern we want to extend is already interesting, so the question is how an interesting pattern can be obtained from an interesting pattern by adding one variable. There are two ways to do this: 1. Add a *predecessor* of an existing variable along a pre->eff arc. 2. Add any *goal variable* that is a weakly connected neighbour of an existing variable (using any kind of arc). Note that in the iPDB paper, the second case was missed. Adding it significantly helps with performance in our experiments (see issue743, msg6595). In our implementation, for efficiency we replace condition 2. by only considering causal graph *successors* (along either pre->eff or eff--eff arcs), because these can be obtained directly, and the missing case (predecessors along pre->eff arcs) is already covered by the first condition anyway. This method precomputes all variables which satisfy conditions 1. or 2. for a given neighbour variable already in the pattern. */ static vector<vector<int>> compute_relevant_neighbours(const TaskProxy &task_proxy) { const causal_graph::CausalGraph &causal_graph = task_proxy.get_causal_graph(); const vector<int> goal_vars = get_goal_variables(task_proxy); vector<vector<int>> connected_vars_by_variable; VariablesProxy variables = task_proxy.get_variables(); connected_vars_by_variable.reserve(variables.size()); for (VariableProxy var : variables) { int var_id = var.get_id(); // Consider variables connected backwards via pre->eff arcs. const vector<int> &pre_to_eff_predecessors = causal_graph.get_eff_to_pre(var_id); // Consider goal variables connected (forwards) via eff--eff and pre->eff arcs. const vector<int> &causal_graph_successors = causal_graph.get_successors(var_id); vector<int> goal_variable_successors; set_intersection( causal_graph_successors.begin(), causal_graph_successors.end(), goal_vars.begin(), goal_vars.end(), back_inserter(goal_variable_successors)); // Combine relevant goal and non-goal variables. vector<int> relevant_neighbours; set_union( pre_to_eff_predecessors.begin(), pre_to_eff_predecessors.end(), goal_variable_successors.begin(), goal_variable_successors.end(), back_inserter(relevant_neighbours)); connected_vars_by_variable.push_back(move(relevant_neighbours)); } return connected_vars_by_variable; } PatternCollectionGeneratorHillclimbing::PatternCollectionGeneratorHillclimbing(const Options &opts) : pdb_max_size(opts.get<int>("pdb_max_size")), collection_max_size(opts.get<int>("collection_max_size")), num_samples(opts.get<int>("num_samples")), min_improvement(opts.get<int>("min_improvement")), max_time(opts.get<double>("max_time")), rng(utils::parse_rng_from_options(opts)), num_rejected(0), hill_climbing_timer(0) { } int PatternCollectionGeneratorHillclimbing::generate_candidate_pdbs( const TaskProxy &task_proxy, const vector<vector<int>> &relevant_neighbours, const PatternDatabase &pdb, set<Pattern> &generated_patterns, PDBCollection &candidate_pdbs) { const Pattern &pattern = pdb.get_pattern(); int pdb_size = pdb.get_size(); int max_pdb_size = 0; for (int pattern_var : pattern) { assert(utils::in_bounds(pattern_var, relevant_neighbours)); const vector<int> &connected_vars = relevant_neighbours[pattern_var]; // Only use variables which are not already in the pattern. vector<int> relevant_vars; set_difference( connected_vars.begin(), connected_vars.end(), pattern.begin(), pattern.end(), back_inserter(relevant_vars)); for (int rel_var_id : relevant_vars) { VariableProxy rel_var = task_proxy.get_variables()[rel_var_id]; int rel_var_size = rel_var.get_domain_size(); if (utils::is_product_within_limit(pdb_size, rel_var_size, pdb_max_size)) { Pattern new_pattern(pattern); new_pattern.push_back(rel_var_id); sort(new_pattern.begin(), new_pattern.end()); if (!generated_patterns.count(new_pattern)) { /* If we haven't seen this pattern before, generate a PDB for it and add it to candidate_pdbs if its size does not surpass the size limit. */ generated_patterns.insert(new_pattern); candidate_pdbs.push_back( make_shared<PatternDatabase>(task_proxy, new_pattern)); max_pdb_size = max(max_pdb_size, candidate_pdbs.back()->get_size()); } } else { ++num_rejected; } } } return max_pdb_size; } void PatternCollectionGeneratorHillclimbing::sample_states( const sampling::RandomWalkSampler &sampler, int init_h, vector<State> &samples) { assert(samples.empty()); samples.reserve(num_samples); for (int i = 0; i < num_samples; ++i) { samples.push_back(sampler.sample_state( init_h, [this](const State &state) { return current_pdbs->is_dead_end(state); })); if (hill_climbing_timer->is_expired()) { throw HillClimbingTimeout(); } } } pair<int, int> PatternCollectionGeneratorHillclimbing::find_best_improving_pdb( const vector<State> &samples, const vector<int> &samples_h_values, PDBCollection &candidate_pdbs) { /* TODO: The original implementation by Haslum et al. uses A* to compute h values for the sample states only instead of generating all PDBs. improvement: best improvement (= highest count) for a pattern so far. We require that a pattern must have an improvement of at least one in order to be taken into account. */ int improvement = 0; int best_pdb_index = -1; // Iterate over all candidates and search for the best improving pattern/pdb for (size_t i = 0; i < candidate_pdbs.size(); ++i) { if (hill_climbing_timer->is_expired()) throw HillClimbingTimeout(); const shared_ptr<PatternDatabase> &pdb = candidate_pdbs[i]; if (!pdb) { /* candidate pattern is too large or has already been added to the canonical heuristic. */ continue; } /* If a candidate's size added to the current collection's size exceeds the maximum collection size, then forget the pdb. */ int combined_size = current_pdbs->get_size() + pdb->get_size(); if (combined_size > collection_max_size) { candidate_pdbs[i] = nullptr; continue; } /* Calculate the "counting approximation" for all sample states: count the number of samples for which the current pattern collection heuristic would be improved if the new pattern was included into it. */ /* TODO: The original implementation by Haslum et al. uses m/t as a statistical confidence interval to stop the A*-search (which they use, see above) earlier. */ int count = 0; vector<PatternClique> pattern_cliques = current_pdbs->get_pattern_cliques(pdb->get_pattern()); for (int sample_id = 0; sample_id < num_samples; ++sample_id) { const State &sample = samples[sample_id]; assert(utils::in_bounds(sample_id, samples_h_values)); int h_collection = samples_h_values[sample_id]; if (is_heuristic_improved( *pdb, sample, h_collection, *current_pdbs->get_pattern_databases(), pattern_cliques)) { ++count; } } if (count > improvement) { improvement = count; best_pdb_index = i; } if (count > 0) { utils::g_log << "pattern: " << candidate_pdbs[i]->get_pattern() << " - improvement: " << count << endl; } } return make_pair(improvement, best_pdb_index); } bool PatternCollectionGeneratorHillclimbing::is_heuristic_improved( const PatternDatabase &pdb, const State &sample, int h_collection, const PDBCollection &pdbs, const vector<PatternClique> &pattern_cliques) { const vector<int> &sample_data = sample.get_unpacked_values(); // h_pattern: h-value of the new pattern int h_pattern = pdb.get_value(sample_data); if (h_pattern == numeric_limits<int>::max()) { return true; } // h_collection: h-value of the current collection heuristic if (h_collection == numeric_limits<int>::max()) return false; vector<int> h_values; h_values.reserve(pdbs.size()); for (const shared_ptr<PatternDatabase> &p : pdbs) { int h = p->get_value(sample_data); if (h == numeric_limits<int>::max()) return false; h_values.push_back(h); } for (const PatternClique &clilque : pattern_cliques) { int h_clique = 0; for (PatternID pattern_id : clilque) { h_clique += h_values[pattern_id]; } if (h_pattern + h_clique > h_collection) { /* return true if a pattern clique is found for which the condition is met */ return true; } } return false; } void PatternCollectionGeneratorHillclimbing::hill_climbing( const TaskProxy &task_proxy) { hill_climbing_timer = new utils::CountdownTimer(max_time); utils::g_log << "Average operator cost: " << task_properties::get_average_operator_cost(task_proxy) << endl; const vector<vector<int>> relevant_neighbours = compute_relevant_neighbours(task_proxy); // Candidate patterns generated so far (used to avoid duplicates). set<Pattern> generated_patterns; // The PDBs for the patterns in generated_patterns that satisfy the size // limit to avoid recomputation. PDBCollection candidate_pdbs; // The maximum size over all PDBs in candidate_pdbs. int max_pdb_size = 0; for (const shared_ptr<PatternDatabase> &current_pdb : *(current_pdbs->get_pattern_databases())) { int new_max_pdb_size = generate_candidate_pdbs( task_proxy, relevant_neighbours, *current_pdb, generated_patterns, candidate_pdbs); max_pdb_size = max(max_pdb_size, new_max_pdb_size); } /* NOTE: The initial set of candidate patterns (in generated_patterns) is guaranteed to be "normalized" in the sense that there are no duplicates and patterns are sorted. */ utils::g_log << "Done calculating initial candidate PDBs" << endl; int num_iterations = 0; State initial_state = task_proxy.get_initial_state(); sampling::RandomWalkSampler sampler(task_proxy, *rng); vector<State> samples; vector<int> samples_h_values; try { while (true) { ++num_iterations; int init_h = current_pdbs->get_value(initial_state); utils::g_log << "current collection size is " << current_pdbs->get_size() << endl; utils::g_log << "current initial h value: "; if (current_pdbs->is_dead_end(initial_state)) { utils::g_log << "infinite => stopping hill climbing" << endl; break; } else { utils::g_log << init_h << endl; } samples.clear(); samples_h_values.clear(); sample_states(sampler, init_h, samples); for (const State &sample : samples) { samples_h_values.push_back(current_pdbs->get_value(sample)); } pair<int, int> improvement_and_index = find_best_improving_pdb(samples, samples_h_values, candidate_pdbs); int improvement = improvement_and_index.first; int best_pdb_index = improvement_and_index.second; if (improvement < min_improvement) { utils::g_log << "Improvement below threshold. Stop hill climbing." << endl; break; } // Add the best PDB to the CanonicalPDBsHeuristic. assert(best_pdb_index != -1); const shared_ptr<PatternDatabase> &best_pdb = candidate_pdbs[best_pdb_index]; const Pattern &best_pattern = best_pdb->get_pattern(); utils::g_log << "found a better pattern with improvement " << improvement << endl; utils::g_log << "pattern: " << best_pattern << endl; current_pdbs->add_pdb(best_pdb); // Generate candidate patterns and PDBs for next iteration. int new_max_pdb_size = generate_candidate_pdbs( task_proxy, relevant_neighbours, *best_pdb, generated_patterns, candidate_pdbs); max_pdb_size = max(max_pdb_size, new_max_pdb_size); // Remove the added PDB from candidate_pdbs. candidate_pdbs[best_pdb_index] = nullptr; utils::g_log << "Hill climbing time so far: " << hill_climbing_timer->get_elapsed_time() << endl; } } catch (HillClimbingTimeout &) { utils::g_log << "Time limit reached. Abort hill climbing." << endl; } utils::g_log << "Hill climbing iterations: " << num_iterations << endl; utils::g_log << "Hill climbing generated patterns: " << generated_patterns.size() << endl; utils::g_log << "Hill climbing rejected patterns: " << num_rejected << endl; utils::g_log << "Hill climbing maximum PDB size: " << max_pdb_size << endl; utils::g_log << "Hill climbing time: " << hill_climbing_timer->get_elapsed_time() << endl; delete hill_climbing_timer; hill_climbing_timer = nullptr; } PatternCollectionInformation PatternCollectionGeneratorHillclimbing::generate( const shared_ptr<AbstractTask> &task) { TaskProxy task_proxy(*task); utils::Timer timer; utils::g_log << "Generating patterns using the hill climbing generator..." << endl; // Generate initial collection: a pattern for each goal variable. PatternCollection initial_pattern_collection; for (FactProxy goal : task_proxy.get_goals()) { int goal_var_id = goal.get_variable().get_id(); initial_pattern_collection.emplace_back(1, goal_var_id); } current_pdbs = utils::make_unique_ptr<IncrementalCanonicalPDBs>( task_proxy, initial_pattern_collection); utils::g_log << "Done calculating initial pattern collection: " << timer << endl; State initial_state = task_proxy.get_initial_state(); if (!current_pdbs->is_dead_end(initial_state) && max_time > 0) { hill_climbing(task_proxy); } PatternCollectionInformation pci = current_pdbs->get_pattern_collection_information(); dump_pattern_collection_generation_statistics( "Hill climbing generator", timer(), pci); return pci; } void add_hillclimbing_options(OptionParser &parser) { parser.add_option<int>( "pdb_max_size", "maximal number of states per pattern database ", "2000000", Bounds("1", "infinity")); parser.add_option<int>( "collection_max_size", "maximal number of states in the pattern collection", "20000000", Bounds("1", "infinity")); parser.add_option<int>( "num_samples", "number of samples (random states) on which to evaluate each " "candidate pattern collection", "1000", Bounds("1", "infinity")); parser.add_option<int>( "min_improvement", "minimum number of samples on which a candidate pattern " "collection must improve on the current one to be considered " "as the next pattern collection ", "10", Bounds("1", "infinity")); parser.add_option<double>( "max_time", "maximum time in seconds for improving the initial pattern " "collection via hill climbing. If set to 0, no hill climbing " "is performed at all. Note that this limit only affects hill " "climbing. Use max_time_dominance_pruning to limit the time " "spent for pruning dominated patterns.", "infinity", Bounds("0.0", "infinity")); utils::add_rng_options(parser); } void check_hillclimbing_options( OptionParser &parser, const Options &opts) { if (opts.get<int>("min_improvement") > opts.get<int>("num_samples")) parser.error("minimum improvement must not be higher than number of " "samples"); } static shared_ptr<PatternCollectionGenerator> _parse(OptionParser &parser) { add_hillclimbing_options(parser); Options opts = parser.parse(); if (parser.help_mode()) return nullptr; check_hillclimbing_options(parser, opts); if (parser.dry_run()) return nullptr; return make_shared<PatternCollectionGeneratorHillclimbing>(opts); } static shared_ptr<Heuristic> _parse_ipdb(OptionParser &parser) { parser.document_synopsis( "iPDB", "This pattern generation method is an adaption of the algorithm " "described in the following paper:" + utils::format_conference_reference( {"Patrik Haslum", "Adi Botea", "Malte Helmert", "Blai Bonet", "Sven Koenig"}, "Domain-Independent Construction of Pattern Database Heuristics for" " Cost-Optimal Planning", "http://www.informatik.uni-freiburg.de/~ki/papers/haslum-etal-aaai07.pdf", "Proceedings of the 22nd AAAI Conference on Artificial" " Intelligence (AAAI 2007)", "1007-1012", "AAAI Press", "2007") + "For implementation notes, see:" + utils::format_conference_reference( {"Silvan Sievers", "Manuela Ortlieb", "Malte Helmert"}, "Efficient Implementation of Pattern Database Heuristics for" " Classical Planning", "https://ai.dmi.unibas.ch/papers/sievers-et-al-socs2012.pdf", "Proceedings of the Fifth Annual Symposium on Combinatorial" " Search (SoCS 2012)", "105-111", "AAAI Press", "2012")); parser.document_note( "Note", "The pattern collection created by the algorithm will always contain " "all patterns consisting of a single goal variable, even if this " "violates the pdb_max_size or collection_max_size limits."); parser.document_language_support("action costs", "supported"); parser.document_language_support("conditional effects", "not supported"); parser.document_language_support("axioms", "not supported"); parser.document_property("admissible", "yes"); parser.document_property("consistent", "yes"); parser.document_property("safe", "yes"); parser.document_property("preferred operators", "no"); parser.document_note( "Note", "This pattern generation method uses the canonical pattern collection " "heuristic."); parser.document_note( "Implementation Notes", "The following will very briefly describe the algorithm and explain " "the differences between the original implementation from 2007 and the " "new one in Fast Downward.\n\n" "The aim of the algorithm is to output a pattern collection for which " "the Evaluator#Canonical_PDB yields the best heuristic estimates.\n\n" "The algorithm is basically a local search (hill climbing) which " "searches the \"pattern neighbourhood\" (starting initially with a " "pattern for each goal variable) for improving the pattern collection. " "This is done as described in the section \"pattern construction as " "search\" in the paper, except for the corrected search " "neighbourhood discussed below. For evaluating the " "neighbourhood, the \"counting approximation\" as introduced in the " "paper was implemented. An important difference however consists in " "the fact that this implementation computes all pattern databases for " "each candidate pattern rather than using A* search to compute the " "heuristic values only for the sample states for each pattern.\n\n" "Also the logic for sampling the search space differs a bit from the " "original implementation. The original implementation uses a random " "walk of a length which is binomially distributed with the mean at the " "estimated solution depth (estimation is done with the current pattern " "collection heuristic). In the Fast Downward implementation, also a " "random walk is used, where the length is the estimation of the number " "of solution steps, which is calculated by dividing the current " "heuristic estimate for the initial state by the average operator " "costs of the planning task (calculated only once and not updated " "during sampling!) to take non-unit cost problems into account. This " "yields a random walk of an expected lenght of np = 2 * estimated " "number of solution steps. If the random walk gets stuck, it is being " "restarted from the initial state, exactly as described in the " "original paper.\n\n" "The section \"avoiding redundant evaluations\" describes how the " "search neighbourhood of patterns can be restricted to variables that " "are relevant to the variables already included in the pattern by " "analyzing causal graphs. There is a mistake in the paper that leads " "to some relevant neighbouring patterns being ignored. See the [errata " "https://ai.dmi.unibas.ch/research/publications.html] for details. This " "mistake has been addressed in this implementation. " "The second approach described in the paper (statistical confidence " "interval) is not applicable to this implementation, as it doesn't use " "A* search but constructs the entire pattern databases for all " "candidate patterns anyway.\n" "The search is ended if there is no more improvement (or the " "improvement is smaller than the minimal improvement which can be set " "as an option), however there is no limit of iterations of the local " "search. This is similar to the techniques used in the original " "implementation as described in the paper.", true); add_hillclimbing_options(parser); /* Add, possibly among others, the options for dominance pruning. Note that using dominance pruning during hill climbing could lead to fewer discovered patterns and pattern collections. A dominated pattern (or pattern collection) might no longer be dominated after more patterns are added. We thus only use dominance pruning on the resulting collection. */ add_canonical_pdbs_options_to_parser(parser); Heuristic::add_options_to_parser(parser); Options opts = parser.parse(); if (parser.help_mode()) return nullptr; check_hillclimbing_options(parser, opts); if (parser.dry_run()) return nullptr; shared_ptr<PatternCollectionGeneratorHillclimbing> pgh = make_shared<PatternCollectionGeneratorHillclimbing>(opts); Options heuristic_opts; heuristic_opts.set<shared_ptr<AbstractTask>>( "transform", opts.get<shared_ptr<AbstractTask>>("transform")); heuristic_opts.set<bool>( "cache_estimates", opts.get<bool>("cache_estimates")); heuristic_opts.set<shared_ptr<PatternCollectionGenerator>>( "patterns", pgh); heuristic_opts.set<double>( "max_time_dominance_pruning", opts.get<double>("max_time_dominance_pruning")); return make_shared<CanonicalPDBsHeuristic>(heuristic_opts); } static Plugin<Evaluator> _plugin_ipdb("ipdb", _parse_ipdb, "heuristics_pdb"); static Plugin<PatternCollectionGenerator> _plugin("hillclimbing", _parse); }
26,383
C++
41.012739
99
0.634803
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/plugin_group.cc
#include "../plugin.h" namespace pdbs { static PluginGroupPlugin _plugin( "heuristics_pdb", "Pattern Database Heuristics"); }
135
C++
15.999998
35
0.696296
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_systematic.h
#ifndef PDBS_PATTERN_COLLECTION_GENERATOR_SYSTEMATIC_H #define PDBS_PATTERN_COLLECTION_GENERATOR_SYSTEMATIC_H #include "pattern_generator.h" #include "types.h" #include "../utils/hash.h" #include <cstdlib> #include <memory> #include <unordered_set> #include <vector> class TaskProxy; namespace causal_graph { class CausalGraph; } namespace options { class Options; } namespace pdbs { class CanonicalPDBsHeuristic; // Invariant: patterns are always sorted. class PatternCollectionGeneratorSystematic : public PatternCollectionGenerator { using PatternSet = utils::HashSet<Pattern>; const size_t max_pattern_size; const bool only_interesting_patterns; std::shared_ptr<PatternCollection> patterns; PatternSet pattern_set; // Cleared after pattern computation. void enqueue_pattern_if_new(const Pattern &pattern); void compute_eff_pre_neighbors(const causal_graph::CausalGraph &cg, const Pattern &pattern, std::vector<int> &result) const; void compute_connection_points(const causal_graph::CausalGraph &cg, const Pattern &pattern, std::vector<int> &result) const; void build_sga_patterns(const TaskProxy &task_proxy, const causal_graph::CausalGraph &cg); void build_patterns(const TaskProxy &task_proxy); void build_patterns_naive(const TaskProxy &task_proxy); public: explicit PatternCollectionGeneratorSystematic(const options::Options &opts); virtual PatternCollectionInformation generate( const std::shared_ptr<AbstractTask> &task) override; }; } #endif
1,668
C
28.803571
94
0.697242
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/incremental_canonical_pdbs.cc
#include "incremental_canonical_pdbs.h" #include "canonical_pdbs.h" #include "pattern_database.h" #include <limits> using namespace std; namespace pdbs { IncrementalCanonicalPDBs::IncrementalCanonicalPDBs( const TaskProxy &task_proxy, const PatternCollection &intitial_patterns) : task_proxy(task_proxy), patterns(make_shared<PatternCollection>(intitial_patterns.begin(), intitial_patterns.end())), pattern_databases(make_shared<PDBCollection>()), pattern_cliques(nullptr), size(0) { pattern_databases->reserve(patterns->size()); for (const Pattern &pattern : *patterns) add_pdb_for_pattern(pattern); are_additive = compute_additive_vars(task_proxy); recompute_pattern_cliques(); } void IncrementalCanonicalPDBs::add_pdb_for_pattern(const Pattern &pattern) { pattern_databases->push_back(make_shared<PatternDatabase>(task_proxy, pattern)); size += pattern_databases->back()->get_size(); } void IncrementalCanonicalPDBs::add_pdb(const shared_ptr<PatternDatabase> &pdb) { patterns->push_back(pdb->get_pattern()); pattern_databases->push_back(pdb); size += pattern_databases->back()->get_size(); recompute_pattern_cliques(); } void IncrementalCanonicalPDBs::recompute_pattern_cliques() { pattern_cliques = compute_pattern_cliques(*patterns, are_additive); } vector<PatternClique> IncrementalCanonicalPDBs::get_pattern_cliques( const Pattern &new_pattern) { return pdbs::compute_pattern_cliques_with_pattern( *patterns, *pattern_cliques, new_pattern, are_additive); } int IncrementalCanonicalPDBs::get_value(const State &state) const { CanonicalPDBs canonical_pdbs(pattern_databases, pattern_cliques); return canonical_pdbs.get_value(state); } bool IncrementalCanonicalPDBs::is_dead_end(const State &state) const { state.unpack(); for (const shared_ptr<PatternDatabase> &pdb : *pattern_databases) if (pdb->get_value(state.get_unpacked_values()) == numeric_limits<int>::max()) return true; return false; } PatternCollectionInformation IncrementalCanonicalPDBs::get_pattern_collection_information() const { PatternCollectionInformation result(task_proxy, patterns); result.set_pdbs(pattern_databases); result.set_pattern_cliques(pattern_cliques); return result; } }
2,419
C++
33.571428
86
0.70153
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/dominance_pruning.h
#ifndef PDBS_DOMINANCE_PRUNING_H #define PDBS_DOMINANCE_PRUNING_H #include "types.h" namespace pdbs { /* Clique superset dominates clique subset iff for every pattern p_subset in subset there is a pattern p_superset in superset where p_superset is a superset of p_subset. */ extern void prune_dominated_cliques( PatternCollection &patterns, PDBCollection &pdbs, std::vector<PatternClique> &pattern_cliques, int num_variables, double max_time); } #endif
482
C
21.999999
68
0.742739
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/zero_one_pdbs.cc
#include "zero_one_pdbs.h" #include "pattern_database.h" #include "../task_proxy.h" #include "../utils/logging.h" #include <iostream> #include <limits> #include <memory> #include <vector> using namespace std; namespace pdbs { ZeroOnePDBs::ZeroOnePDBs( const TaskProxy &task_proxy, const PatternCollection &patterns) { vector<int> remaining_operator_costs; OperatorsProxy operators = task_proxy.get_operators(); remaining_operator_costs.reserve(operators.size()); for (OperatorProxy op : operators) remaining_operator_costs.push_back(op.get_cost()); pattern_databases.reserve(patterns.size()); for (const Pattern &pattern : patterns) { shared_ptr<PatternDatabase> pdb = make_shared<PatternDatabase>( task_proxy, pattern, false, remaining_operator_costs); /* Set cost of relevant operators to 0 for further iterations (action cost partitioning). */ for (OperatorProxy op : operators) { if (pdb->is_operator_relevant(op)) remaining_operator_costs[op.get_id()] = 0; } pattern_databases.push_back(pdb); } } int ZeroOnePDBs::get_value(const State &state) const { /* Because we use cost partitioning, we can simply add up all heuristic values of all patterns in the pattern collection. */ state.unpack(); int h_val = 0; for (const shared_ptr<PatternDatabase> &pdb : pattern_databases) { int pdb_value = pdb->get_value(state.get_unpacked_values()); if (pdb_value == numeric_limits<int>::max()) return numeric_limits<int>::max(); h_val += pdb_value; } return h_val; } double ZeroOnePDBs::compute_approx_mean_finite_h() const { double approx_mean_finite_h = 0; for (const shared_ptr<PatternDatabase> &pdb : pattern_databases) { approx_mean_finite_h += pdb->compute_mean_finite_h(); } return approx_mean_finite_h; } void ZeroOnePDBs::dump() const { for (const shared_ptr<PatternDatabase> &pdb : pattern_databases) { utils::g_log << pdb->get_pattern() << endl; } } }
2,115
C++
28.388888
71
0.649173
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/match_tree.h
#ifndef PDBS_MATCH_TREE_H #define PDBS_MATCH_TREE_H #include "types.h" #include "../task_proxy.h" #include <cstddef> #include <vector> namespace pdbs { /* Successor Generator for abstract operators. NOTE: MatchTree keeps a reference to the task proxy passed to the constructor. Therefore, users of the class must ensure that the task lives at least as long as the match tree. */ class MatchTree { TaskProxy task_proxy; struct Node; // See PatternDatabase for documentation on pattern and hash_multipliers. Pattern pattern; std::vector<int> hash_multipliers; Node *root; void insert_recursive(int op_id, const std::vector<FactPair> &regression_preconditions, int pre_index, Node **edge_from_parent); void get_applicable_operator_ids_recursive( Node *node, int state_index, std::vector<int> &operator_ids) const; void dump_recursive(Node *node) const; public: // Initialize an empty match tree. MatchTree(const TaskProxy &task_proxy, const Pattern &pattern, const std::vector<int> &hash_multipliers); ~MatchTree(); /* Insert an abstract operator into the match tree, creating or enlarging it. */ void insert(int op_id, const std::vector<FactPair> &regression_preconditions); /* Extracts all IDs of applicable abstract operators for the abstract state given by state_index (the index is converted back to variable/values pairs). */ void get_applicable_operator_ids( int state_index, std::vector<int> &operator_ids) const; void dump() const; }; } #endif
1,685
C
29.107142
82
0.661128
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_manual.cc
#include "pattern_collection_generator_manual.h" #include "validation.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../utils/logging.h" #include <iostream> using namespace std; namespace pdbs { PatternCollectionGeneratorManual::PatternCollectionGeneratorManual(const Options &opts) : patterns(make_shared<PatternCollection>(opts.get_list<Pattern>("patterns"))) { } PatternCollectionInformation PatternCollectionGeneratorManual::generate( const shared_ptr<AbstractTask> &task) { utils::g_log << "Manual pattern collection: " << *patterns << endl; TaskProxy task_proxy(*task); return PatternCollectionInformation(task_proxy, patterns); } static shared_ptr<PatternCollectionGenerator> _parse(OptionParser &parser) { parser.add_list_option<Pattern>( "patterns", "list of patterns (which are lists of variable numbers of the planning " "task)."); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<PatternCollectionGeneratorManual>(opts); } static Plugin<PatternCollectionGenerator> _plugin("manual_patterns", _parse); }
1,179
C++
27.095237
87
0.723494
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_generator_greedy.cc
#include "pattern_generator_greedy.h" #include "pattern_information.h" #include "utils.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../task_utils/variable_order_finder.h" #include "../utils/logging.h" #include "../utils/math.h" #include "../utils/timer.h" #include <iostream> using namespace std; namespace pdbs { PatternGeneratorGreedy::PatternGeneratorGreedy(const Options &opts) : PatternGeneratorGreedy(opts.get<int>("max_states")) { } PatternGeneratorGreedy::PatternGeneratorGreedy(int max_states) : max_states(max_states) { } PatternInformation PatternGeneratorGreedy::generate(const shared_ptr<AbstractTask> &task) { utils::Timer timer; utils::g_log << "Generating a pattern using the greedy generator..." << endl; TaskProxy task_proxy(*task); Pattern pattern; variable_order_finder::VariableOrderFinder order(task_proxy, variable_order_finder::GOAL_CG_LEVEL); VariablesProxy variables = task_proxy.get_variables(); int size = 1; while (true) { if (order.done()) break; int next_var_id = order.next(); VariableProxy next_var = variables[next_var_id]; int next_var_size = next_var.get_domain_size(); if (!utils::is_product_within_limit(size, next_var_size, max_states)) break; pattern.push_back(next_var_id); size *= next_var_size; } PatternInformation pattern_info(task_proxy, move(pattern)); dump_pattern_generation_statistics( "Greedy generator", timer(), pattern_info); return pattern_info; } static shared_ptr<PatternGenerator> _parse(OptionParser &parser) { parser.add_option<int>( "max_states", "maximal number of abstract states in the pattern database.", "1000000", Bounds("1", "infinity")); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<PatternGeneratorGreedy>(opts); } static Plugin<PatternGenerator> _plugin("greedy", _parse); }
2,053
C++
27.136986
103
0.670726
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_generator_manual.cc
#include "pattern_generator_manual.h" #include "pattern_information.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../utils/logging.h" #include <iostream> using namespace std; namespace pdbs { PatternGeneratorManual::PatternGeneratorManual(const Options &opts) : pattern(opts.get_list<int>("pattern")) { } PatternInformation PatternGeneratorManual::generate( const shared_ptr<AbstractTask> &task) { PatternInformation pattern_info(TaskProxy(*task), move(pattern)); utils::g_log << "Manual pattern: " << pattern_info.get_pattern() << endl; return pattern_info; } static shared_ptr<PatternGenerator> _parse(OptionParser &parser) { parser.add_list_option<int>( "pattern", "list of variable numbers of the planning task that should be used as " "pattern."); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<PatternGeneratorManual>(opts); } static Plugin<PatternGenerator> _plugin("manual_pattern", _parse); }
1,069
C++
24.47619
79
0.695978
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pdb_heuristic.h
#ifndef PDBS_PDB_HEURISTIC_H #define PDBS_PDB_HEURISTIC_H #include "../heuristic.h" namespace options { class Options; } namespace pdbs { class PatternDatabase; // Implements a heuristic for a single PDB. class PDBHeuristic : public Heuristic { std::shared_ptr<PatternDatabase> pdb; protected: virtual int compute_heuristic(const State &ancestor_state) override; public: /* Important: It is assumed that the pattern (passed via Options) is sorted, contains no duplicates and is small enough so that the number of abstract states is below numeric_limits<int>::max() Parameters: operator_costs: Can specify individual operator costs for each operator. This is useful for action cost partitioning. If left empty, default operator costs are used. */ PDBHeuristic(const options::Options &opts); virtual ~PDBHeuristic() override = default; }; } #endif
920
C
26.088235
72
0.719565
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_information.h
#ifndef PDBS_PATTERN_COLLECTION_INFORMATION_H #define PDBS_PATTERN_COLLECTION_INFORMATION_H #include "types.h" #include "../task_proxy.h" #include <memory> namespace pdbs { /* This class contains everything we know about a pattern collection. It will always contain patterns, but can also contain the computed PDBs and maximal additive subsets of the PDBs. If one of the latter is not available, then this information is created when it is requested. Ownership of the information is shared between the creators of this class (usually PatternCollectionGenerators), the class itself, and its users (consumers of pattern collections like heuristics). TODO: this should probably re-use PatternInformation and it could also act as an interface for ownership transfer rather than sharing it. */ class PatternCollectionInformation { TaskProxy task_proxy; std::shared_ptr<PatternCollection> patterns; std::shared_ptr<PDBCollection> pdbs; std::shared_ptr<std::vector<PatternClique>> pattern_cliques; void create_pdbs_if_missing(); void create_pattern_cliques_if_missing(); bool information_is_valid() const; public: PatternCollectionInformation( const TaskProxy &task_proxy, const std::shared_ptr<PatternCollection> &patterns); ~PatternCollectionInformation() = default; void set_pdbs(const std::shared_ptr<PDBCollection> &pdbs); void set_pattern_cliques( const std::shared_ptr<std::vector<PatternClique>> &pattern_cliques); TaskProxy get_task_proxy() const { return task_proxy; } std::shared_ptr<PatternCollection> get_patterns() const; std::shared_ptr<PDBCollection> get_pdbs(); std::shared_ptr<std::vector<PatternClique>> get_pattern_cliques(); }; } #endif
1,776
C
31.907407
77
0.738176
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_genetic.cc
#include "pattern_collection_generator_genetic.h" #include "utils.h" #include "validation.h" #include "zero_one_pdbs.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../task_utils/causal_graph.h" #include "../utils/logging.h" #include "../utils/markup.h" #include "../utils/math.h" #include "../utils/rng.h" #include "../utils/rng_options.h" #include "../utils/timer.h" #include <algorithm> #include <cassert> #include <iostream> #include <unordered_set> #include <vector> using namespace std; namespace pdbs { PatternCollectionGeneratorGenetic::PatternCollectionGeneratorGenetic( const Options &opts) : pdb_max_size(opts.get<int>("pdb_max_size")), num_collections(opts.get<int>("num_collections")), num_episodes(opts.get<int>("num_episodes")), mutation_probability(opts.get<double>("mutation_probability")), disjoint_patterns(opts.get<bool>("disjoint")), rng(utils::parse_rng_from_options(opts)) { } void PatternCollectionGeneratorGenetic::select( const vector<double> &fitness_values) { vector<double> cumulative_fitness; cumulative_fitness.reserve(fitness_values.size()); double total_so_far = 0; for (double fitness_value : fitness_values) { total_so_far += fitness_value; cumulative_fitness.push_back(total_so_far); } // total_so_far is now sum over all fitness values. vector<vector<vector<bool>>> new_pattern_collections; new_pattern_collections.reserve(num_collections); for (int i = 0; i < num_collections; ++i) { int selected; if (total_so_far == 0) { // All fitness values are 0 => choose uniformly. selected = (*rng)(fitness_values.size()); } else { // [0..total_so_far) double random = (*rng)() * total_so_far; // Find first entry which is strictly greater than random. selected = upper_bound(cumulative_fitness.begin(), cumulative_fitness.end(), random) - cumulative_fitness.begin(); } new_pattern_collections.push_back(pattern_collections[selected]); } pattern_collections.swap(new_pattern_collections); } void PatternCollectionGeneratorGenetic::mutate() { for (auto &collection : pattern_collections) { for (vector<bool> &pattern : collection) { for (size_t k = 0; k < pattern.size(); ++k) { double random = (*rng)(); // [0..1) if (random < mutation_probability) { pattern[k].flip(); } } } } } Pattern PatternCollectionGeneratorGenetic::transform_to_pattern_normal_form( const vector<bool> &bitvector) const { Pattern pattern; for (size_t i = 0; i < bitvector.size(); ++i) { if (bitvector[i]) pattern.push_back(i); } return pattern; } void PatternCollectionGeneratorGenetic::remove_irrelevant_variables( Pattern &pattern) const { TaskProxy task_proxy(*task); unordered_set<int> in_original_pattern(pattern.begin(), pattern.end()); unordered_set<int> in_pruned_pattern; vector<int> vars_to_check; for (FactProxy goal : task_proxy.get_goals()) { int var_id = goal.get_variable().get_id(); if (in_original_pattern.count(var_id)) { // Goals are causally relevant. vars_to_check.push_back(var_id); in_pruned_pattern.insert(var_id); } } while (!vars_to_check.empty()) { int var = vars_to_check.back(); vars_to_check.pop_back(); /* A variable is relevant to the pattern if it is a goal variable or if there is a pre->eff arc from the variable to a relevant variable. Note that there is no point in considering eff->eff arcs here. */ const causal_graph::CausalGraph &cg = task_proxy.get_causal_graph(); const vector<int> &rel = cg.get_eff_to_pre(var); for (size_t i = 0; i < rel.size(); ++i) { int var_no = rel[i]; if (in_original_pattern.count(var_no) && !in_pruned_pattern.count(var_no)) { // Parents of relevant variables are causally relevant. vars_to_check.push_back(var_no); in_pruned_pattern.insert(var_no); } } } pattern.assign(in_pruned_pattern.begin(), in_pruned_pattern.end()); sort(pattern.begin(), pattern.end()); } bool PatternCollectionGeneratorGenetic::is_pattern_too_large( const Pattern &pattern) const { // Test if the pattern respects the memory limit. TaskProxy task_proxy(*task); VariablesProxy variables = task_proxy.get_variables(); int mem = 1; for (size_t i = 0; i < pattern.size(); ++i) { VariableProxy var = variables[pattern[i]]; int domain_size = var.get_domain_size(); if (!utils::is_product_within_limit(mem, domain_size, pdb_max_size)) return true; mem *= domain_size; } return false; } bool PatternCollectionGeneratorGenetic::mark_used_variables( const Pattern &pattern, vector<bool> &variables_used) const { for (size_t i = 0; i < pattern.size(); ++i) { int var_id = pattern[i]; if (variables_used[var_id]) return true; variables_used[var_id] = true; } return false; } void PatternCollectionGeneratorGenetic::evaluate(vector<double> &fitness_values) { TaskProxy task_proxy(*task); for (const auto &collection : pattern_collections) { //utils::g_log << "evaluate pattern collection " << (i + 1) << " of " // << pattern_collections.size() << endl; double fitness = 0; bool pattern_valid = true; vector<bool> variables_used(task_proxy.get_variables().size(), false); shared_ptr<PatternCollection> pattern_collection = make_shared<PatternCollection>(); pattern_collection->reserve(collection.size()); for (const vector<bool> &bitvector : collection) { Pattern pattern = transform_to_pattern_normal_form(bitvector); if (is_pattern_too_large(pattern)) { utils::g_log << "pattern exceeds the memory limit!" << endl; pattern_valid = false; break; } if (disjoint_patterns) { if (mark_used_variables(pattern, variables_used)) { utils::g_log << "patterns are not disjoint anymore!" << endl; pattern_valid = false; break; } } remove_irrelevant_variables(pattern); pattern_collection->push_back(pattern); } if (!pattern_valid) { /* Set fitness to a very small value to cover cases in which all patterns are invalid. */ fitness = 0.001; } else { /* Generate the pattern collection heuristic and get its fitness value. */ ZeroOnePDBs zero_one_pdbs(task_proxy, *pattern_collection); fitness = zero_one_pdbs.compute_approx_mean_finite_h(); // Update the best heuristic found so far. if (fitness > best_fitness) { best_fitness = fitness; utils::g_log << "best_fitness = " << best_fitness << endl; best_patterns = pattern_collection; } } fitness_values.push_back(fitness); } } void PatternCollectionGeneratorGenetic::bin_packing() { TaskProxy task_proxy(*task); VariablesProxy variables = task_proxy.get_variables(); vector<int> variable_ids; variable_ids.reserve(variables.size()); for (size_t i = 0; i < variables.size(); ++i) { variable_ids.push_back(i); } for (int i = 0; i < num_collections; ++i) { // Use random variable ordering for all pattern collections. rng->shuffle(variable_ids); vector<vector<bool>> pattern_collection; vector<bool> pattern(variables.size(), false); int current_size = 1; for (size_t j = 0; j < variable_ids.size(); ++j) { int var_id = variable_ids[j]; int next_var_size = variables[var_id].get_domain_size(); if (next_var_size > pdb_max_size) // var never fits into a bin. continue; if (!utils::is_product_within_limit(current_size, next_var_size, pdb_max_size)) { // Open a new bin for var. pattern_collection.push_back(pattern); pattern.clear(); pattern.resize(variables.size(), false); current_size = 1; } current_size *= next_var_size; pattern[var_id] = true; } /* The last bin has not bin inserted into pattern_collection, do so now. We test current_size against 1 because this is cheaper than testing if pattern is an all-zero bitvector. current_size can only be 1 if *all* variables have a domain larger than pdb_max_size. */ if (current_size > 1) { pattern_collection.push_back(pattern); } pattern_collections.push_back(pattern_collection); } } void PatternCollectionGeneratorGenetic::genetic_algorithm() { best_fitness = -1; best_patterns = nullptr; bin_packing(); vector<double> initial_fitness_values; evaluate(initial_fitness_values); for (int i = 0; i < num_episodes; ++i) { utils::g_log << endl; utils::g_log << "--------- episode no " << (i + 1) << " ---------" << endl; mutate(); vector<double> fitness_values; evaluate(fitness_values); // We allow to select invalid pattern collections. select(fitness_values); } } PatternCollectionInformation PatternCollectionGeneratorGenetic::generate( const shared_ptr<AbstractTask> &task_) { utils::Timer timer; utils::g_log << "Generating patterns using the genetic generator..." << endl; task = task_; genetic_algorithm(); TaskProxy task_proxy(*task); assert(best_patterns); PatternCollectionInformation pci(task_proxy, best_patterns); dump_pattern_collection_generation_statistics( "Genetic generator", timer(), pci); return pci; } static shared_ptr<PatternCollectionGenerator> _parse(OptionParser &parser) { parser.document_synopsis( "Genetic Algorithm Patterns", "The following paper describes the automated creation of pattern " "databases with a genetic algorithm. Pattern collections are initially " "created with a bin-packing algorithm. The genetic algorithm is used " "to optimize the pattern collections with an objective function that " "estimates the mean heuristic value of the the pattern collections. " "Pattern collections with higher mean heuristic estimates are more " "likely selected for the next generation." + utils::format_conference_reference( {"Stefan Edelkamp"}, "Automated Creation of Pattern Database Search Heuristics", "http://www.springerlink.com/content/20613345434608x1/", "Proceedings of the 4th Workshop on Model Checking and Artificial" " Intelligence (!MoChArt 2006)", "35-50", "AAAI Press", "2007")); parser.document_language_support("action costs", "supported"); parser.document_language_support("conditional effects", "not supported"); parser.document_language_support("axioms", "not supported"); parser.document_note( "Note", "This pattern generation method uses the " "zero/one pattern database heuristic."); parser.document_note( "Implementation Notes", "The standard genetic algorithm procedure as described in the paper is " "implemented in Fast Downward. The implementation is close to the " "paper.\n\n" "+ Initialization<<BR>>" "In Fast Downward bin-packing with the next-fit strategy is used. A " "bin corresponds to a pattern which contains variables up to " "``pdb_max_size``. With this method each variable occurs exactly in " "one pattern of a collection. There are ``num_collections`` " "collections created.\n" "+ Mutation<<BR>>" "With probability ``mutation_probability`` a bit is flipped meaning " "that either a variable is added to a pattern or deleted from a " "pattern.\n" "+ Recombination<<BR>>" "Recombination isn't implemented in Fast Downward. In the paper " "recombination is described but not used.\n" "+ Evaluation<<BR>>" "For each pattern collection the mean heuristic value is computed. For " "a single pattern database the mean heuristic value is the sum of all " "pattern database entries divided through the number of entries. " "Entries with infinite heuristic values are ignored in this " "calculation. The sum of these individual mean heuristic values yield " "the mean heuristic value of the collection.\n" "+ Selection<<BR>>" "The higher the mean heuristic value of a pattern collection is, the " "more likely this pattern collection should be selected for the next " "generation. Therefore the mean heuristic values are normalized and " "converted into probabilities and Roulette Wheel Selection is used.\n" "+\n\n", true); parser.add_option<int>( "pdb_max_size", "maximal number of states per pattern database ", "50000", Bounds("1", "infinity")); parser.add_option<int>( "num_collections", "number of pattern collections to maintain in the genetic " "algorithm (population size)", "5", Bounds("1", "infinity")); parser.add_option<int>( "num_episodes", "number of episodes for the genetic algorithm", "30", Bounds("0", "infinity")); parser.add_option<double>( "mutation_probability", "probability for flipping a bit in the genetic algorithm", "0.01", Bounds("0.0", "1.0")); parser.add_option<bool>( "disjoint", "consider a pattern collection invalid (giving it very low " "fitness) if its patterns are not disjoint", "false"); utils::add_rng_options(parser); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<PatternCollectionGeneratorGenetic>(opts); } static Plugin<PatternCollectionGenerator> _plugin("genetic", _parse); }
14,833
C++
37.430052
92
0.606216
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/canonical_pdbs_heuristic.h
#ifndef PDBS_CANONICAL_PDBS_HEURISTIC_H #define PDBS_CANONICAL_PDBS_HEURISTIC_H #include "canonical_pdbs.h" #include "../heuristic.h" namespace options { class OptionParser; } namespace pdbs { // Implements the canonical heuristic function. class CanonicalPDBsHeuristic : public Heuristic { CanonicalPDBs canonical_pdbs; protected: virtual int compute_heuristic(const State &ancestor_state) override; public: explicit CanonicalPDBsHeuristic(const options::Options &opts); virtual ~CanonicalPDBsHeuristic() = default; }; void add_canonical_pdbs_options_to_parser(options::OptionParser &parser); } #endif
627
C
20.655172
73
0.770335
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_generator_manual.h
#ifndef PDBS_PATTERN_GENERATOR_MANUAL_H #define PDBS_PATTERN_GENERATOR_MANUAL_H #include "pattern_generator.h" #include "types.h" namespace options { class Options; } namespace pdbs { class PatternGeneratorManual : public PatternGenerator { Pattern pattern; public: explicit PatternGeneratorManual(const options::Options &opts); virtual ~PatternGeneratorManual() = default; virtual PatternInformation generate(const std::shared_ptr<AbstractTask> &task) override; }; } #endif
496
C
20.608695
92
0.768145
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/incremental_canonical_pdbs.h
#ifndef PDBS_INCREMENTAL_CANONICAL_PDBS_H #define PDBS_INCREMENTAL_CANONICAL_PDBS_H #include "pattern_cliques.h" #include "pattern_collection_information.h" #include "types.h" #include "../task_proxy.h" #include <memory> namespace pdbs { class IncrementalCanonicalPDBs { TaskProxy task_proxy; std::shared_ptr<PatternCollection> patterns; std::shared_ptr<PDBCollection> pattern_databases; std::shared_ptr<std::vector<PatternClique>> pattern_cliques; // A pair of variables is additive if no operator has an effect on both. VariableAdditivity are_additive; // The sum of all abstract state sizes of all pdbs in the collection. int size; // Adds a PDB for pattern but does not recompute pattern_cliques. void add_pdb_for_pattern(const Pattern &pattern); void recompute_pattern_cliques(); public: IncrementalCanonicalPDBs(const TaskProxy &task_proxy, const PatternCollection &intitial_patterns); virtual ~IncrementalCanonicalPDBs() = default; // Adds a new PDB to the collection and recomputes pattern_cliques. void add_pdb(const std::shared_ptr<PatternDatabase> &pdb); /* Returns a list of pattern cliques that would be additive to the new pattern. Detailed documentation in max_additive_pdb_sets.h */ std::vector<PatternClique> get_pattern_cliques(const Pattern &new_pattern); int get_value(const State &state) const; /* The following method offers a quick dead-end check for the sampling procedure of iPDB-hillclimbing. This exists because we can much more efficiently test if the canonical heuristic is infinite than computing the exact heuristic value. */ bool is_dead_end(const State &state) const; PatternCollectionInformation get_pattern_collection_information() const; std::shared_ptr<PDBCollection> get_pattern_databases() const { return pattern_databases; } int get_size() const { return size; } }; } #endif
2,012
C
29.96923
79
0.713221
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_database.cc
#include "pattern_database.h" #include "match_tree.h" #include "../algorithms/priority_queues.h" #include "../task_utils/task_properties.h" #include "../utils/collections.h" #include "../utils/logging.h" #include "../utils/math.h" #include "../utils/rng.h" #include "../utils/timer.h" #include <algorithm> #include <cassert> #include <cstdlib> #include <iostream> #include <limits> #include <string> #include <vector> using namespace std; namespace pdbs { AbstractOperator::AbstractOperator(const vector<FactPair> &prev_pairs, const vector<FactPair> &pre_pairs, const vector<FactPair> &eff_pairs, int cost, const vector<int> &hash_multipliers, int concrete_op_id) : concrete_op_id(concrete_op_id), cost(cost), regression_preconditions(prev_pairs) { regression_preconditions.insert(regression_preconditions.end(), eff_pairs.begin(), eff_pairs.end()); // Sort preconditions for MatchTree construction. sort(regression_preconditions.begin(), regression_preconditions.end()); for (size_t i = 1; i < regression_preconditions.size(); ++i) { assert(regression_preconditions[i].var != regression_preconditions[i - 1].var); } hash_effect = 0; assert(pre_pairs.size() == eff_pairs.size()); for (size_t i = 0; i < pre_pairs.size(); ++i) { int var = pre_pairs[i].var; assert(var == eff_pairs[i].var); int old_val = eff_pairs[i].value; int new_val = pre_pairs[i].value; assert(new_val != -1); int effect = (new_val - old_val) * hash_multipliers[var]; hash_effect += effect; } } AbstractOperator::~AbstractOperator() { } void AbstractOperator::dump(const Pattern &pattern, const VariablesProxy &variables) const { utils::g_log << "AbstractOperator:" << endl; utils::g_log << "Regression preconditions:" << endl; for (size_t i = 0; i < regression_preconditions.size(); ++i) { int var_id = regression_preconditions[i].var; int val = regression_preconditions[i].value; utils::g_log << "Variable: " << var_id << " (True name: " << variables[pattern[var_id]].get_name() << ", Index: " << i << ") Value: " << val << endl; } utils::g_log << "Hash effect:" << hash_effect << endl; } PatternDatabase::PatternDatabase( const TaskProxy &task_proxy, const Pattern &pattern, bool dump, const vector<int> &operator_costs, bool compute_plan, const shared_ptr<utils::RandomNumberGenerator> &rng, bool compute_wildcard_plan) : pattern(pattern) { task_properties::verify_no_axioms(task_proxy); task_properties::verify_no_conditional_effects(task_proxy); assert(operator_costs.empty() || operator_costs.size() == task_proxy.get_operators().size()); assert(utils::is_sorted_unique(pattern)); utils::Timer timer; hash_multipliers.reserve(pattern.size()); num_states = 1; for (int pattern_var_id : pattern) { hash_multipliers.push_back(num_states); VariableProxy var = task_proxy.get_variables()[pattern_var_id]; if (utils::is_product_within_limit(num_states, var.get_domain_size(), numeric_limits<int>::max())) { num_states *= var.get_domain_size(); } else { cerr << "Given pattern is too large! (Overflow occured): " << endl; cerr << pattern << endl; utils::exit_with(utils::ExitCode::SEARCH_CRITICAL_ERROR); } } create_pdb(task_proxy, operator_costs, compute_plan, rng, compute_wildcard_plan); if (dump) utils::g_log << "PDB construction time: " << timer << endl; } void PatternDatabase::multiply_out( int pos, int cost, vector<FactPair> &prev_pairs, vector<FactPair> &pre_pairs, vector<FactPair> &eff_pairs, const vector<FactPair> &effects_without_pre, const VariablesProxy &variables, int concrete_op_id, vector<AbstractOperator> &operators) { if (pos == static_cast<int>(effects_without_pre.size())) { // All effects without precondition have been checked: insert op. if (!eff_pairs.empty()) { operators.push_back( AbstractOperator(prev_pairs, pre_pairs, eff_pairs, cost, hash_multipliers, concrete_op_id)); } } else { // For each possible value for the current variable, build an // abstract operator. int var_id = effects_without_pre[pos].var; int eff = effects_without_pre[pos].value; VariableProxy var = variables[pattern[var_id]]; for (int i = 0; i < var.get_domain_size(); ++i) { if (i != eff) { pre_pairs.emplace_back(var_id, i); eff_pairs.emplace_back(var_id, eff); } else { prev_pairs.emplace_back(var_id, i); } multiply_out(pos + 1, cost, prev_pairs, pre_pairs, eff_pairs, effects_without_pre, variables, concrete_op_id, operators); if (i != eff) { pre_pairs.pop_back(); eff_pairs.pop_back(); } else { prev_pairs.pop_back(); } } } } void PatternDatabase::build_abstract_operators( const OperatorProxy &op, int cost, const vector<int> &variable_to_index, const VariablesProxy &variables, vector<AbstractOperator> &operators) { // All variable value pairs that are a prevail condition vector<FactPair> prev_pairs; // All variable value pairs that are a precondition (value != -1) vector<FactPair> pre_pairs; // All variable value pairs that are an effect vector<FactPair> eff_pairs; // All variable value pairs that are a precondition (value = -1) vector<FactPair> effects_without_pre; size_t num_vars = variables.size(); vector<bool> has_precond_and_effect_on_var(num_vars, false); vector<bool> has_precondition_on_var(num_vars, false); for (FactProxy pre : op.get_preconditions()) has_precondition_on_var[pre.get_variable().get_id()] = true; for (EffectProxy eff : op.get_effects()) { int var_id = eff.get_fact().get_variable().get_id(); int pattern_var_id = variable_to_index[var_id]; int val = eff.get_fact().get_value(); if (pattern_var_id != -1) { if (has_precondition_on_var[var_id]) { has_precond_and_effect_on_var[var_id] = true; eff_pairs.emplace_back(pattern_var_id, val); } else { effects_without_pre.emplace_back(pattern_var_id, val); } } } for (FactProxy pre : op.get_preconditions()) { int var_id = pre.get_variable().get_id(); int pattern_var_id = variable_to_index[var_id]; int val = pre.get_value(); if (pattern_var_id != -1) { // variable occurs in pattern if (has_precond_and_effect_on_var[var_id]) { pre_pairs.emplace_back(pattern_var_id, val); } else { prev_pairs.emplace_back(pattern_var_id, val); } } } multiply_out(0, cost, prev_pairs, pre_pairs, eff_pairs, effects_without_pre, variables, op.get_id(), operators); } void PatternDatabase::create_pdb( const TaskProxy &task_proxy, const vector<int> &operator_costs, bool compute_plan, const shared_ptr<utils::RandomNumberGenerator> &rng, bool compute_wildcard_plan) { VariablesProxy variables = task_proxy.get_variables(); vector<int> variable_to_index(variables.size(), -1); for (size_t i = 0; i < pattern.size(); ++i) { variable_to_index[pattern[i]] = i; } // compute all abstract operators vector<AbstractOperator> operators; for (OperatorProxy op : task_proxy.get_operators()) { int op_cost; if (operator_costs.empty()) { op_cost = op.get_cost(); } else { op_cost = operator_costs[op.get_id()]; } build_abstract_operators( op, op_cost, variable_to_index, variables, operators); } // build the match tree MatchTree match_tree(task_proxy, pattern, hash_multipliers); for (size_t op_id = 0; op_id < operators.size(); ++op_id) { const AbstractOperator &op = operators[op_id]; match_tree.insert(op_id, op.get_regression_preconditions()); } // compute abstract goal var-val pairs vector<FactPair> abstract_goals; for (FactProxy goal : task_proxy.get_goals()) { int var_id = goal.get_variable().get_id(); int val = goal.get_value(); if (variable_to_index[var_id] != -1) { abstract_goals.emplace_back(variable_to_index[var_id], val); } } distances.reserve(num_states); // first implicit entry: priority, second entry: index for an abstract state priority_queues::AdaptiveQueue<int> pq; // initialize queue for (int state_index = 0; state_index < num_states; ++state_index) { if (is_goal_state(state_index, abstract_goals, variables)) { pq.push(0, state_index); distances.push_back(0); } else { distances.push_back(numeric_limits<int>::max()); } } if (compute_plan) { /* If computing a plan during Dijkstra, we store, for each state, an operator leading from that state to another state on a strongly optimal plan of the PDB. We store the first operator encountered during Dijkstra and only update it if the goal distance of the state was updated. Note that in the presence of zero-cost operators, this does not guarantee that we compute a strongly optimal plan because we do not minimize the number of used zero-cost operators. */ generating_op_ids.resize(num_states); } // Dijkstra loop while (!pq.empty()) { pair<int, int> node = pq.pop(); int distance = node.first; int state_index = node.second; if (distance > distances[state_index]) { continue; } // regress abstract_state vector<int> applicable_operator_ids; match_tree.get_applicable_operator_ids(state_index, applicable_operator_ids); for (int op_id : applicable_operator_ids) { const AbstractOperator &op = operators[op_id]; int predecessor = state_index + op.get_hash_effect(); int alternative_cost = distances[state_index] + op.get_cost(); if (alternative_cost < distances[predecessor]) { distances[predecessor] = alternative_cost; pq.push(alternative_cost, predecessor); if (compute_plan) { generating_op_ids[predecessor] = op_id; } } } } // Compute abstract plan if (compute_plan) { /* Using the generating operators computed during Dijkstra, we start from the initial state and follow the generating operator to the next state. Then we compute all operators of the same cost inducing the same abstract transition and randomly pick one of them to set for the next state. We iterate until reaching a goal state. Note that this kind of plan extraction does not uniformly at random consider all successor of a state but rather uses the arbitrarily chosen generating operator to settle on one successor state, which is biased by the number of operators leading to the same successor from the given state. */ State initial_state = task_proxy.get_initial_state(); initial_state.unpack(); int current_state = hash_index(initial_state.get_unpacked_values()); if (distances[current_state] != numeric_limits<int>::max()) { while (!is_goal_state(current_state, abstract_goals, variables)) { int op_id = generating_op_ids[current_state]; assert(op_id != -1); const AbstractOperator &op = operators[op_id]; int successor_state = current_state - op.get_hash_effect(); // Compute equivalent ops vector<OperatorID> cheapest_operators; vector<int> applicable_operator_ids; match_tree.get_applicable_operator_ids(successor_state, applicable_operator_ids); for (int applicable_op_id : applicable_operator_ids) { const AbstractOperator &applicable_op = operators[applicable_op_id]; int predecessor = successor_state + applicable_op.get_hash_effect(); if (predecessor == current_state && op.get_cost() == applicable_op.get_cost()) { cheapest_operators.emplace_back(applicable_op.get_concrete_op_id()); } } if (compute_wildcard_plan) { rng->shuffle(cheapest_operators); wildcard_plan.push_back(move(cheapest_operators)); } else { OperatorID random_op_id = *rng->choose(cheapest_operators); wildcard_plan.emplace_back(); wildcard_plan.back().push_back(random_op_id); } current_state = successor_state; } } utils::release_vector_memory(generating_op_ids); } } bool PatternDatabase::is_goal_state( int state_index, const vector<FactPair> &abstract_goals, const VariablesProxy &variables) const { for (const FactPair &abstract_goal : abstract_goals) { int pattern_var_id = abstract_goal.var; int var_id = pattern[pattern_var_id]; VariableProxy var = variables[var_id]; int temp = state_index / hash_multipliers[pattern_var_id]; int val = temp % var.get_domain_size(); if (val != abstract_goal.value) { return false; } } return true; } int PatternDatabase::hash_index(const vector<int> &state) const { int index = 0; for (size_t i = 0; i < pattern.size(); ++i) { index += hash_multipliers[i] * state[pattern[i]]; } return index; } int PatternDatabase::get_value(const vector<int> &state) const { return distances[hash_index(state)]; } double PatternDatabase::compute_mean_finite_h() const { double sum = 0; int size = 0; for (size_t i = 0; i < distances.size(); ++i) { if (distances[i] != numeric_limits<int>::max()) { sum += distances[i]; ++size; } } if (size == 0) { // All states are dead ends. return numeric_limits<double>::infinity(); } else { return sum / size; } } bool PatternDatabase::is_operator_relevant(const OperatorProxy &op) const { for (EffectProxy effect : op.get_effects()) { int var_id = effect.get_fact().get_variable().get_id(); if (binary_search(pattern.begin(), pattern.end(), var_id)) { return true; } } return false; } }
15,465
C++
37.859296
100
0.584222
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/utils.cc
#include "utils.h" #include "pattern_collection_information.h" #include "pattern_database.h" #include "pattern_information.h" #include "../task_proxy.h" #include "../task_utils/task_properties.h" #include "../utils/logging.h" #include "../utils/math.h" #include "../utils/rng.h" #include <limits> using namespace std; namespace pdbs { int compute_pdb_size(const TaskProxy &task_proxy, const Pattern &pattern) { int size = 1; for (int var : pattern) { int domain_size = task_proxy.get_variables()[var].get_domain_size(); if (utils::is_product_within_limit(size, domain_size, numeric_limits<int>::max())) { size *= domain_size; } else { cerr << "Given pattern is too large! (Overflow occured): " << endl; cerr << pattern << endl; utils::exit_with(utils::ExitCode::SEARCH_CRITICAL_ERROR); } } return size; } int compute_total_pdb_size( const TaskProxy &task_proxy, const PatternCollection &pattern_collection) { int size = 0; for (const Pattern &pattern : pattern_collection) { size += compute_pdb_size(task_proxy, pattern); } return size; } vector<FactPair> get_goals_in_random_order( const TaskProxy &task_proxy, utils::RandomNumberGenerator &rng) { vector<FactPair> goals = task_properties::get_fact_pairs(task_proxy.get_goals()); rng.shuffle(goals); return goals; } vector<int> get_non_goal_variables(const TaskProxy &task_proxy) { size_t num_vars = task_proxy.get_variables().size(); GoalsProxy goals = task_proxy.get_goals(); vector<bool> is_goal(num_vars, false); for (FactProxy goal : goals) { is_goal[goal.get_variable().get_id()] = true; } vector<int> non_goal_variables; non_goal_variables.reserve(num_vars - goals.size()); for (int var_id = 0; var_id < static_cast<int>(num_vars); ++var_id) { if (!is_goal[var_id]) { non_goal_variables.push_back(var_id); } } return non_goal_variables; } void dump_pattern_generation_statistics( const string &identifier, utils::Duration runtime, const PatternInformation &pattern_info) { const Pattern &pattern = pattern_info.get_pattern(); utils::g_log << identifier << " pattern: " << pattern << endl; utils::g_log << identifier << " number of variables: " << pattern.size() << endl; utils::g_log << identifier << " PDB size: " << compute_pdb_size(pattern_info.get_task_proxy(), pattern) << endl; utils::g_log << identifier << " computation time: " << runtime << endl; } void dump_pattern_collection_generation_statistics( const string &identifier, utils::Duration runtime, const PatternCollectionInformation &pci) { const PatternCollection &pattern_collection = *pci.get_patterns(); utils::g_log << identifier << " number of patterns: " << pattern_collection.size() << endl; utils::g_log << identifier << " total PDB size: "; utils::g_log << compute_total_pdb_size( pci.get_task_proxy(), pattern_collection) << endl; utils::g_log << identifier << " computation time: " << runtime << endl; } }
3,217
C++
32.873684
86
0.627603
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_generator.cc
#include "pattern_generator.h" #include "../plugin.h" namespace pdbs { static PluginTypePlugin<PatternCollectionGenerator> _type_plugin_collection( "PatternCollectionGenerator", "Factory for pattern collections"); static PluginTypePlugin<PatternGenerator> _type_plugin_single( "PatternGenerator", "Factory for single patterns"); }
350
C++
24.071427
76
0.762857
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/utils.h
#ifndef PDBS_UTILS_H #define PDBS_UTILS_H #include "types.h" #include "../task_proxy.h" #include "../utils/timer.h" #include <memory> #include <string> namespace utils { class RandomNumberGenerator; } namespace pdbs { class PatternCollectionInformation; class PatternInformation; extern int compute_pdb_size(const TaskProxy &task_proxy, const Pattern &pattern); extern int compute_total_pdb_size( const TaskProxy &task_proxy, const PatternCollection &pattern_collection); extern std::vector<FactPair> get_goals_in_random_order( const TaskProxy &task_proxy, utils::RandomNumberGenerator &rng); extern std::vector<int> get_non_goal_variables(const TaskProxy &task_proxy); /* Dump the given pattern, the number of variables contained, the size of the corresponding PDB, and the runtime used for computing it. All output is prepended with the given string identifier. */ extern void dump_pattern_generation_statistics( const std::string &identifier, utils::Duration runtime, const PatternInformation &pattern_info); /* Compute and dump the number of patterns, the total size of the corresponding PDBs, and the runtime used for computing the collection. All output is prepended with the given string identifier. */ extern void dump_pattern_collection_generation_statistics( const std::string &identifier, utils::Duration runtime, const PatternCollectionInformation &pci); } #endif
1,431
C
27.078431
81
0.763802
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_systematic.cc
#include "pattern_collection_generator_systematic.h" #include "utils.h" #include "validation.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../task_utils/causal_graph.h" #include "../utils/logging.h" #include "../utils/markup.h" #include "../utils/timer.h" #include <algorithm> #include <cassert> #include <iostream> using namespace std; namespace pdbs { static bool patterns_are_disjoint( const Pattern &pattern1, const Pattern &pattern2) { size_t i = 0; size_t j = 0; for (;;) { if (i == pattern1.size() || j == pattern2.size()) return true; int val1 = pattern1[i]; int val2 = pattern2[j]; if (val1 == val2) return false; else if (val1 < val2) ++i; else ++j; } } static void compute_union_pattern( const Pattern &pattern1, const Pattern &pattern2, Pattern &result) { result.clear(); result.reserve(pattern1.size() + pattern2.size()); set_union(pattern1.begin(), pattern1.end(), pattern2.begin(), pattern2.end(), back_inserter(result)); } PatternCollectionGeneratorSystematic::PatternCollectionGeneratorSystematic( const Options &opts) : max_pattern_size(opts.get<int>("pattern_max_size")), only_interesting_patterns(opts.get<bool>("only_interesting_patterns")) { } void PatternCollectionGeneratorSystematic::compute_eff_pre_neighbors( const causal_graph::CausalGraph &cg, const Pattern &pattern, vector<int> &result) const { /* Compute all variables that are reachable from pattern by an (eff, pre) arc and are not already contained in the pattern. */ unordered_set<int> candidates; // Compute neighbors. for (int var : pattern) { const vector<int> &neighbors = cg.get_eff_to_pre(var); candidates.insert(neighbors.begin(), neighbors.end()); } // Remove elements of pattern. for (int var : pattern) { candidates.erase(var); } result.assign(candidates.begin(), candidates.end()); } void PatternCollectionGeneratorSystematic::compute_connection_points( const causal_graph::CausalGraph &cg, const Pattern &pattern, vector<int> &result) const { /* The "connection points" of a pattern are those variables of which one must be contained in an SGA pattern that can be attached to this pattern to form a larger interesting pattern. (Interesting patterns are disjoint unions of SGA patterns.) A variable is a connection point if it satisfies the following criteria: 1. We can get from the pattern to the connection point via a (pre, eff) or (eff, eff) arc in the causal graph. 2. It is not part of pattern. 3. We *cannot* get from the pattern to the connection point via an (eff, pre) arc. Condition 1. is the important one. The other conditions are optimizations that help reduce the number of candidates to consider. */ unordered_set<int> candidates; // Handle rule 1. for (int var : pattern) { const vector<int> &succ = cg.get_successors(var); candidates.insert(succ.begin(), succ.end()); } // Handle rules 2 and 3. for (int var : pattern) { // Rule 2: candidates.erase(var); // Rule 3: const vector<int> &eff_pre = cg.get_eff_to_pre(var); for (int pre_var : eff_pre) candidates.erase(pre_var); } result.assign(candidates.begin(), candidates.end()); } void PatternCollectionGeneratorSystematic::enqueue_pattern_if_new( const Pattern &pattern) { if (pattern_set.insert(pattern).second) patterns->push_back(pattern); } void PatternCollectionGeneratorSystematic::build_sga_patterns( const TaskProxy &task_proxy, const causal_graph::CausalGraph &cg) { assert(max_pattern_size >= 1); assert(pattern_set.empty()); assert(patterns && patterns->empty()); /* SGA patterns are "single-goal ancestor" patterns, i.e., those patterns which can be generated by following eff/pre arcs from a single goal variable. This method must generate all SGA patterns up to size "max_pattern_size". They must be generated in order of increasing size, and they must be placed in "patterns". The overall structure of this is a similar processing queue as in the main pattern generation method below, and we reuse "patterns" and "pattern_set" between the two methods. */ // Build goal patterns. for (FactProxy goal : task_proxy.get_goals()) { int var_id = goal.get_variable().get_id(); Pattern goal_pattern; goal_pattern.push_back(var_id); enqueue_pattern_if_new(goal_pattern); } /* Grow SGA patterns untill all patterns are processed. Note that the patterns vectors grows during the computation. */ for (size_t pattern_no = 0; pattern_no < patterns->size(); ++pattern_no) { // We must copy the pattern because references to patterns can be invalidated. Pattern pattern = (*patterns)[pattern_no]; if (pattern.size() == max_pattern_size) break; vector<int> neighbors; compute_eff_pre_neighbors(cg, pattern, neighbors); for (int neighbor_var_id : neighbors) { Pattern new_pattern(pattern); new_pattern.push_back(neighbor_var_id); sort(new_pattern.begin(), new_pattern.end()); enqueue_pattern_if_new(new_pattern); } } pattern_set.clear(); } void PatternCollectionGeneratorSystematic::build_patterns( const TaskProxy &task_proxy) { int num_variables = task_proxy.get_variables().size(); const causal_graph::CausalGraph &cg = task_proxy.get_causal_graph(); // Generate SGA (single-goal-ancestor) patterns. // They are generated into the patterns variable, // so we swap them from there. build_sga_patterns(task_proxy, cg); PatternCollection sga_patterns; patterns->swap(sga_patterns); /* Index the SGA patterns by variable. Important: sga_patterns_by_var[var] must be sorted by size. This is guaranteed because build_sga_patterns generates patterns ordered by size. */ vector<vector<const Pattern *>> sga_patterns_by_var(num_variables); for (const Pattern &pattern : sga_patterns) { for (int var : pattern) { sga_patterns_by_var[var].push_back(&pattern); } } // Enqueue the SGA patterns. for (const Pattern &pattern : sga_patterns) enqueue_pattern_if_new(pattern); utils::g_log << "Found " << sga_patterns.size() << " SGA patterns." << endl; /* Combine patterns in the queue with SGA patterns until all patterns are processed. Note that the patterns vectors grows during the computation. */ for (size_t pattern_no = 0; pattern_no < patterns->size(); ++pattern_no) { // We must copy the pattern because references to patterns can be invalidated. Pattern pattern1 = (*patterns)[pattern_no]; vector<int> neighbors; compute_connection_points(cg, pattern1, neighbors); for (int neighbor_var : neighbors) { const auto &candidates = sga_patterns_by_var[neighbor_var]; for (const Pattern *p_pattern2 : candidates) { const Pattern &pattern2 = *p_pattern2; if (pattern1.size() + pattern2.size() > max_pattern_size) break; // All remaining candidates are too large. if (patterns_are_disjoint(pattern1, pattern2)) { Pattern new_pattern; compute_union_pattern(pattern1, pattern2, new_pattern); enqueue_pattern_if_new(new_pattern); } } } } pattern_set.clear(); utils::g_log << "Found " << patterns->size() << " interesting patterns." << endl; } void PatternCollectionGeneratorSystematic::build_patterns_naive( const TaskProxy &task_proxy) { int num_variables = task_proxy.get_variables().size(); PatternCollection current_patterns(1); PatternCollection next_patterns; for (size_t i = 0; i < max_pattern_size; ++i) { for (const Pattern &current_pattern : current_patterns) { int max_var = -1; if (i > 0) max_var = current_pattern.back(); for (int var = max_var + 1; var < num_variables; ++var) { Pattern pattern = current_pattern; pattern.push_back(var); next_patterns.push_back(pattern); patterns->push_back(pattern); } } next_patterns.swap(current_patterns); next_patterns.clear(); } utils::g_log << "Found " << patterns->size() << " patterns." << endl; } PatternCollectionInformation PatternCollectionGeneratorSystematic::generate( const shared_ptr<AbstractTask> &task) { utils::Timer timer; utils::g_log << "Generating patterns using the systematic generator..." << endl; TaskProxy task_proxy(*task); patterns = make_shared<PatternCollection>(); pattern_set.clear(); if (only_interesting_patterns) { build_patterns(task_proxy); } else { build_patterns_naive(task_proxy); } PatternCollectionInformation pci(task_proxy, patterns); /* Do not dump the collection since it can be very large for pattern_max_size >= 3. */ dump_pattern_collection_generation_statistics( "Systematic generator", timer(), pci); return pci; } static shared_ptr<PatternCollectionGenerator> _parse(OptionParser &parser) { parser.document_synopsis( "Systematically generated patterns", "Generates all (interesting) patterns with up to pattern_max_size " "variables. " "For details, see" + utils::format_conference_reference( {"Florian Pommerening", "Gabriele Roeger", "Malte Helmert"}, "Getting the Most Out of Pattern Databases for Classical Planning", "https://ai.dmi.unibas.ch/papers/pommerening-et-al-ijcai2013.pdf", "Proceedings of the Twenty-Third International Joint" " Conference on Artificial Intelligence (IJCAI 2013)", "2357-2364", "AAAI Press", "2013")); parser.add_option<int>( "pattern_max_size", "max number of variables per pattern", "1", Bounds("1", "infinity")); parser.add_option<bool>( "only_interesting_patterns", "Only consider the union of two disjoint patterns if the union has " "more information than the individual patterns.", "true"); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<PatternCollectionGeneratorSystematic>(opts); } static Plugin<PatternCollectionGenerator> _plugin("systematic", _parse); }
11,016
C++
33.53605
93
0.632262
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/dominance_pruning.cc
#include "dominance_pruning.h" #include "pattern_database.h" #include "../utils/countdown_timer.h" #include "../utils/hash.h" #include "../utils/logging.h" #include <cassert> #include <unordered_map> #include <vector> using namespace std; namespace pdbs { class Pruner { /* Algorithm for pruning dominated patterns. "patterns" is the vector of patterns used. Each pattern is a vector of variable IDs. "pattern_cliques" is the vector of pattern cliques. The algorithm works by setting a "current pattern collection" against which other patterns and collections can be tested for dominance efficiently. "variable_to_pattern_id" encodes the relevant information about the current clique. For every variable v, variable_to_pattern_id[v] is the id of the pattern containing v in the current clique, or -1 if the variable is not contained in the current clique. (Note that patterns in a pattern clique must be disjoint, which is verified by an assertion in debug mode.) To test if a given pattern v_1, ..., v_k is dominated by the current clique, we check that all entries variable_to_pattern_id[v_i] are equal and different from -1. "dominated_patterns" is a vector<bool> that can be used to quickly test whether a given pattern is dominated by the current clique. This is precomputed for every pattern whenever the current clique is set. */ const PatternCollection &patterns; const vector<PatternClique> &pattern_cliques; const int num_variables; vector<int> variable_to_pattern_id; vector<bool> dominated_patterns; void set_current_clique(int clique_id) { /* Set the current pattern collection to be used for is_pattern_dominated() or is_collection_dominated(). Compute dominated_patterns based on the current pattern collection. */ variable_to_pattern_id.assign(num_variables, -1); assert(variable_to_pattern_id == vector<int>(num_variables, -1)); for (PatternID pattern_id : pattern_cliques[clique_id]) { for (int variable : patterns[pattern_id]) { assert(variable_to_pattern_id[variable] == -1); variable_to_pattern_id[variable] = pattern_id; } } dominated_patterns.clear(); dominated_patterns.reserve(patterns.size()); for (size_t i = 0; i < patterns.size(); ++i) { dominated_patterns.push_back(is_pattern_dominated(i)); } } bool is_pattern_dominated(int pattern_id) const { /* Check if the pattern with the given pattern_id is dominated by the current pattern clique. */ const Pattern &pattern = patterns[pattern_id]; assert(!pattern.empty()); PatternID clique_pattern_id = variable_to_pattern_id[pattern[0]]; if (clique_pattern_id == -1) { return false; } int pattern_size = pattern.size(); for (int i = 1; i < pattern_size; ++i) { if (variable_to_pattern_id[pattern[i]] != clique_pattern_id) { return false; } } return true; } bool is_clique_dominated(int clique_id) const { /* Check if the collection with the given collection_id is dominated by the current pattern collection. */ for (PatternID pattern_id : pattern_cliques[clique_id]) { if (!dominated_patterns[pattern_id]) { return false; } } return true; } public: Pruner( const PatternCollection &patterns, const vector<PatternClique> &pattern_cliques, int num_variables) : patterns(patterns), pattern_cliques(pattern_cliques), num_variables(num_variables) { } vector<bool> get_pruned_cliques(const utils::CountdownTimer &timer) { int num_cliques = pattern_cliques.size(); vector<bool> pruned(num_cliques, false); /* Already pruned cliques are not used to prune other cliques. This makes things faster and helps handle duplicate cliques in the correct way: the first copy will survive and prune all duplicates. */ for (int c1 = 0; c1 < num_cliques; ++c1) { if (!pruned[c1]) { set_current_clique(c1); for (int c2 = 0; c2 < num_cliques; ++c2) { if (c1 != c2 && !pruned[c2] && is_clique_dominated(c2)) pruned[c2] = true; } } if (timer.is_expired()) { /* Since after each iteration, we determined if a given clique is pruned or not, we can just break the computation here if reaching the time limit and use all information we collected so far. */ utils::g_log << "Time limit reached. Abort dominance pruning." << endl; break; } } return pruned; } }; void prune_dominated_cliques( PatternCollection &patterns, PDBCollection &pdbs, vector<PatternClique> &pattern_cliques, int num_variables, double max_time) { utils::g_log << "Running dominance pruning..." << endl; utils::CountdownTimer timer(max_time); int num_patterns = patterns.size(); int num_cliques = pattern_cliques.size(); vector<bool> pruned = Pruner( patterns, pattern_cliques, num_variables).get_pruned_cliques(timer); vector<PatternClique> remaining_pattern_cliques; vector<bool> is_remaining_pattern(num_patterns, false); int num_remaining_patterns = 0; for (size_t i = 0; i < pattern_cliques.size(); ++i) { if (!pruned[i]) { PatternClique &clique = pattern_cliques[i]; for (PatternID pattern_id : clique) { if (!is_remaining_pattern[pattern_id]) { is_remaining_pattern[pattern_id] = true; ++num_remaining_patterns; } } remaining_pattern_cliques.push_back(move(clique)); } } PatternCollection remaining_patterns; PDBCollection remaining_pdbs; remaining_patterns.reserve(num_remaining_patterns); remaining_pdbs.reserve(num_remaining_patterns); vector<PatternID> old_to_new_pattern_id(num_patterns, -1); for (PatternID old_pattern_id = 0; old_pattern_id < num_patterns; ++old_pattern_id) { if (is_remaining_pattern[old_pattern_id]) { PatternID new_pattern_id = remaining_patterns.size(); old_to_new_pattern_id[old_pattern_id] = new_pattern_id; remaining_patterns.push_back(move(patterns[old_pattern_id])); remaining_pdbs.push_back(move(pdbs[old_pattern_id])); } } for (PatternClique &clique : remaining_pattern_cliques) { for (size_t i = 0; i < clique.size(); ++i) { PatternID old_pattern_id = clique[i]; PatternID new_pattern_id = old_to_new_pattern_id[old_pattern_id]; assert(new_pattern_id != -1); clique[i] = new_pattern_id; } } int num_pruned_collections = num_cliques - remaining_pattern_cliques.size(); utils::g_log << "Pruned " << num_pruned_collections << " of " << num_cliques << " pattern cliques" << endl; int num_pruned_patterns = num_patterns - num_remaining_patterns; utils::g_log << "Pruned " << num_pruned_patterns << " of " << num_patterns << " PDBs" << endl; patterns.swap(remaining_patterns); pdbs.swap(remaining_pdbs); pattern_cliques.swap(remaining_pattern_cliques); utils::g_log << "Dominance pruning took " << timer.get_elapsed_time() << endl; } }
7,918
C++
34.832579
89
0.598636
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/validation.h
#ifndef PDBS_VALIDATION_H #define PDBS_VALIDATION_H #include "types.h" class TaskProxy; namespace pdbs { extern void validate_and_normalize_pattern( const TaskProxy &task_proxy, Pattern &pattern); extern void validate_and_normalize_patterns( const TaskProxy &task_proxy, PatternCollection &patterns); } #endif
322
C
19.187499
62
0.767081
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pdb_heuristic.cc
#include "pdb_heuristic.h" #include "pattern_database.h" #include "pattern_generator.h" #include "../option_parser.h" #include "../plugin.h" #include <limits> #include <memory> using namespace std; namespace pdbs { shared_ptr<PatternDatabase> get_pdb_from_options(const shared_ptr<AbstractTask> &task, const Options &opts) { shared_ptr<PatternGenerator> pattern_generator = opts.get<shared_ptr<PatternGenerator>>("pattern"); PatternInformation pattern_info = pattern_generator->generate(task); return pattern_info.get_pdb(); } PDBHeuristic::PDBHeuristic(const Options &opts) : Heuristic(opts), pdb(get_pdb_from_options(task, opts)) { } int PDBHeuristic::compute_heuristic(const State &ancestor_state) { State state = convert_ancestor_state(ancestor_state); int h = pdb->get_value(state.get_unpacked_values()); if (h == numeric_limits<int>::max()) return DEAD_END; return h; } static shared_ptr<Heuristic> _parse(OptionParser &parser) { parser.document_synopsis("Pattern database heuristic", "TODO"); parser.document_language_support("action costs", "supported"); parser.document_language_support("conditional effects", "not supported"); parser.document_language_support("axioms", "not supported"); parser.document_property("admissible", "yes"); parser.document_property("consistent", "yes"); parser.document_property("safe", "yes"); parser.document_property("preferred operators", "no"); parser.add_option<shared_ptr<PatternGenerator>>( "pattern", "pattern generation method", "greedy()"); Heuristic::add_options_to_parser(parser); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<PDBHeuristic>(opts); } static Plugin<Evaluator> _plugin("pdb", _parse, "heuristics_pdb"); }
1,911
C++
30.344262
86
0.676086
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_manual.h
#ifndef PDBS_PATTERN_COLLECTION_GENERATOR_MANUAL_H #define PDBS_PATTERN_COLLECTION_GENERATOR_MANUAL_H #include "pattern_generator.h" #include "types.h" #include <memory> namespace options { class Options; } namespace pdbs { class PatternCollectionGeneratorManual : public PatternCollectionGenerator { std::shared_ptr<PatternCollection> patterns; public: explicit PatternCollectionGeneratorManual(const options::Options &opts); virtual ~PatternCollectionGeneratorManual() = default; virtual PatternCollectionInformation generate( const std::shared_ptr<AbstractTask> &task) override; }; } #endif
624
C
23.038461
76
0.780449
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_single_cegar.h
#ifndef PDBS_PATTERN_COLLECTION_GENERATOR_SINGLE_CEGAR_H #define PDBS_PATTERN_COLLECTION_GENERATOR_SINGLE_CEGAR_H #include "pattern_generator.h" namespace utils { class RandomNumberGenerator; enum class Verbosity; } namespace pdbs { /* This pattern collection generator uses the CEGAR algorithm to compute a disjoint pattern collection for the given task. See cegar.h for more details. */ class PatternCollectionGeneratorSingleCegar : public PatternCollectionGenerator { const int max_pdb_size; const int max_collection_size; const bool use_wildcard_plans; const double max_time; const utils::Verbosity verbosity; std::shared_ptr<utils::RandomNumberGenerator> rng; public: explicit PatternCollectionGeneratorSingleCegar(const options::Options &opts); virtual PatternCollectionInformation generate( const std::shared_ptr<AbstractTask> &task) override; }; } #endif
912
C
27.531249
81
0.775219
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_generator_greedy.h
#ifndef PDBS_PATTERN_GENERATOR_GREEDY_H #define PDBS_PATTERN_GENERATOR_GREEDY_H #include "pattern_generator.h" namespace options { class Options; } namespace pdbs { class PatternGeneratorGreedy : public PatternGenerator { int max_states; public: explicit PatternGeneratorGreedy(const options::Options &opts); explicit PatternGeneratorGreedy(int max_states); virtual ~PatternGeneratorGreedy() = default; virtual PatternInformation generate(const std::shared_ptr<AbstractTask> &task) override; }; } #endif
529
C
22.043477
92
0.771267
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/types.h
#ifndef PDBS_TYPES_H #define PDBS_TYPES_H #include <memory> #include <vector> namespace pdbs { class PatternDatabase; using Pattern = std::vector<int>; using PatternCollection = std::vector<Pattern>; using PDBCollection = std::vector<std::shared_ptr<PatternDatabase>>; using PatternID = int; /* NOTE: pattern cliques are often called maximal additive pattern subsets in the literature. A pattern clique is an additive set of patterns, represented by their IDs (indices) in a pattern collection. */ using PatternClique = std::vector<PatternID>; } #endif
562
C
27.149999
74
0.761566
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/canonical_pdbs_heuristic.cc
#include "canonical_pdbs_heuristic.h" #include "dominance_pruning.h" #include "pattern_generator.h" #include "utils.h" #include "../option_parser.h" #include "../plugin.h" #include "../utils/logging.h" #include "../utils/timer.h" #include <iostream> #include <limits> #include <memory> using namespace std; namespace pdbs { CanonicalPDBs get_canonical_pdbs_from_options( const shared_ptr<AbstractTask> &task, const Options &opts) { shared_ptr<PatternCollectionGenerator> pattern_generator = opts.get<shared_ptr<PatternCollectionGenerator>>("patterns"); utils::Timer timer; utils::g_log << "Initializing canonical PDB heuristic..." << endl; PatternCollectionInformation pattern_collection_info = pattern_generator->generate(task); shared_ptr<PatternCollection> patterns = pattern_collection_info.get_patterns(); /* We compute PDBs and pattern cliques here (if they have not been computed before) so that their computation is not taken into account for dominance pruning time. */ shared_ptr<PDBCollection> pdbs = pattern_collection_info.get_pdbs(); shared_ptr<vector<PatternClique>> pattern_cliques = pattern_collection_info.get_pattern_cliques(); double max_time_dominance_pruning = opts.get<double>("max_time_dominance_pruning"); if (max_time_dominance_pruning > 0.0) { int num_variables = TaskProxy(*task).get_variables().size(); /* NOTE: Dominance pruning could also be computed without having access to the PDBs, but since we want to delete patterns, we also want to update the list of corresponding PDBs so they are synchronized. In the long term, we plan to have patterns and their PDBs live together, in which case we would only need to pass their container and the pattern cliques. */ prune_dominated_cliques( *patterns, *pdbs, *pattern_cliques, num_variables, max_time_dominance_pruning); } // Do not dump pattern collections for size reasons. dump_pattern_collection_generation_statistics( "Canonical PDB heuristic", timer(), pattern_collection_info); return CanonicalPDBs(pdbs, pattern_cliques); } CanonicalPDBsHeuristic::CanonicalPDBsHeuristic(const Options &opts) : Heuristic(opts), canonical_pdbs(get_canonical_pdbs_from_options(task, opts)) { } int CanonicalPDBsHeuristic::compute_heuristic(const State &ancestor_state) { State state = convert_ancestor_state(ancestor_state); int h = canonical_pdbs.get_value(state); if (h == numeric_limits<int>::max()) { return DEAD_END; } else { return h; } } void add_canonical_pdbs_options_to_parser(options::OptionParser &parser) { parser.add_option<double>( "max_time_dominance_pruning", "The maximum time in seconds spent on dominance pruning. Using 0.0 " "turns off dominance pruning. Dominance pruning excludes patterns " "and additive subsets that will never contribute to the heuristic " "value because there are dominating subsets in the collection.", "infinity", Bounds("0.0", "infinity")); } static shared_ptr<Heuristic> _parse(OptionParser &parser) { parser.document_synopsis( "Canonical PDB", "The canonical pattern database heuristic is calculated as follows. " "For a given pattern collection C, the value of the " "canonical heuristic function is the maximum over all " "maximal additive subsets A in C, where the value for one subset " "S in A is the sum of the heuristic values for all patterns in S " "for a given state."); parser.document_language_support("action costs", "supported"); parser.document_language_support("conditional effects", "not supported"); parser.document_language_support("axioms", "not supported"); parser.document_property("admissible", "yes"); parser.document_property("consistent", "yes"); parser.document_property("safe", "yes"); parser.document_property("preferred operators", "no"); parser.add_option<shared_ptr<PatternCollectionGenerator>>( "patterns", "pattern generation method", "systematic(1)"); add_canonical_pdbs_options_to_parser(parser); Heuristic::add_options_to_parser(parser); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<CanonicalPDBsHeuristic>(opts); } static Plugin<Evaluator> _plugin("cpdbs", _parse, "heuristics_pdb"); }
4,623
C++
35.698412
87
0.679862
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_cliques.h
#ifndef PDBS_PATTERN_CLIQUES_H #define PDBS_PATTERN_CLIQUES_H #include "types.h" #include <memory> #include <vector> class TaskProxy; namespace pdbs { using VariableAdditivity = std::vector<std::vector<bool>>; extern VariableAdditivity compute_additive_vars(const TaskProxy &task_proxy); /* Returns true iff the two patterns are additive i.e. there is no operator which affects variables in pattern one as well as in pattern two. */ extern bool are_patterns_additive(const Pattern &pattern1, const Pattern &pattern2, const VariableAdditivity &are_additive); /* Computes pattern cliques of the given patterns. */ extern std::shared_ptr<std::vector<PatternClique>> compute_pattern_cliques( const PatternCollection &patterns, const VariableAdditivity &are_additive); /* We compute pattern cliques S with the property that we could add the new pattern P to S and still have a pattern clique. Ideally, we would like to return all *maximal* cliques S with this property (w.r.t. set inclusion), but we don't currently guarantee this. (What we guarantee is that all maximal such cliques are *included* in the result, but the result could contain duplicates or cliques that are subcliques of other cliques in the result.) We currently implement this as follows: * Consider all pattern cliques of the current collection. * For each clique S, take the subclique S' that contains those patterns that are additive with the new pattern P. * Include the subclique S' in the result. As an optimization, we actually only include S' in the result if it is non-empty. However, this is wrong if *all* subcliques we get are empty, so we correct for this case at the end. This may include dominated elements and duplicates in the result. To avoid this, we could instead use the following algorithm: * Let N (= neighbours) be the set of patterns in our current collection that are additive with the new pattern P. * Let G_N be the compatibility graph of the current collection restricted to set N (i.e. drop all non-neighbours and their incident edges.) * Return the maximal cliques of G_N. One nice thing about this alternative algorithm is that we could also use it to incrementally compute the new set of pattern cliques after adding the new pattern P: G_N_cliques = max_cliques(G_N) // as above new_max_cliques = (old_max_cliques \setminus G_N_cliques) \union { clique \union {P} | clique in G_N_cliques} That is, the new set of maximal cliques is exactly the set of those "old" cliques that we cannot extend by P (old_max_cliques \setminus G_N_cliques) and all "new" cliques including P. */ extern std::vector<PatternClique> compute_pattern_cliques_with_pattern( const PatternCollection &patterns, const std::vector<PatternClique> &known_pattern_cliques, const Pattern &new_pattern, const VariableAdditivity &are_additive); } #endif
3,024
C
36.345679
79
0.727513
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/validation.cc
#include "validation.h" #include "../task_proxy.h" #include "../utils/logging.h" #include "../utils/system.h" #include <algorithm> #include <iostream> using namespace std; using utils::ExitCode; namespace pdbs { void validate_and_normalize_pattern(const TaskProxy &task_proxy, Pattern &pattern) { /* - Sort by variable number and remove duplicate variables. - Warn if duplicate variables exist. - Error if patterns contain out-of-range variable numbers. */ sort(pattern.begin(), pattern.end()); auto it = unique(pattern.begin(), pattern.end()); if (it != pattern.end()) { pattern.erase(it, pattern.end()); utils::g_log << "Warning: duplicate variables in pattern have been removed" << endl; } if (!pattern.empty()) { if (pattern.front() < 0) { cerr << "Variable number too low in pattern" << endl; utils::exit_with(ExitCode::SEARCH_CRITICAL_ERROR); } int num_variables = task_proxy.get_variables().size(); if (pattern.back() >= num_variables) { cerr << "Variable number too high in pattern" << endl; utils::exit_with(ExitCode::SEARCH_CRITICAL_ERROR); } } } void validate_and_normalize_patterns(const TaskProxy &task_proxy, PatternCollection &patterns) { /* - Validate and normalize each pattern (see there). - Warn if duplicate patterns exist. */ for (Pattern &pattern : patterns) validate_and_normalize_pattern(task_proxy, pattern); PatternCollection sorted_patterns(patterns); sort(sorted_patterns.begin(), sorted_patterns.end()); auto it = unique(sorted_patterns.begin(), sorted_patterns.end()); if (it != sorted_patterns.end()) { utils::g_log << "Warning: duplicate patterns have been detected" << endl; } } }
1,928
C++
32.25862
83
0.606328
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_genetic.h
#ifndef PDBS_PATTERN_COLLECTION_GENERATOR_GENETIC_H #define PDBS_PATTERN_COLLECTION_GENERATOR_GENETIC_H #include "pattern_generator.h" #include "types.h" #include <memory> #include <vector> class AbstractTask; namespace options { class Options; } namespace utils { class RandomNumberGenerator; } namespace pdbs { /* Implementation of the pattern generation algorithm by Edelkamp. See: Stefan Edelkamp, Automated Creation of Pattern Database Search Heuristics. Proceedings of the 4th Workshop on Model Checking and Artificial Intelligence (MoChArt 2006), pp. 35-50, 2007. */ class PatternCollectionGeneratorGenetic : public PatternCollectionGenerator { // Maximum number of states for each pdb const int pdb_max_size; const int num_collections; const int num_episodes; const double mutation_probability; /* Specifies whether patterns in each pattern collection need to be disjoint or not. */ const bool disjoint_patterns; std::shared_ptr<utils::RandomNumberGenerator> rng; std::shared_ptr<AbstractTask> task; // All current pattern collections. std::vector<std::vector<std::vector<bool>>> pattern_collections; // Store best pattern collection over all episodes and its fitness value. std::shared_ptr<PatternCollection> best_patterns; double best_fitness; /* The fitness values (from evaluate) are used as probabilities. Then num_collections many pattern collections are chosen from the vector of all pattern collections according to their probabilities. If all fitness values are 0, we select uniformly randomly. Note that the set of pattern collection where we select from is only changed by mutate, NOT by evaluate. All changes there (i.e. transformation and removal of irrelevant variables) are just temporary for improved PDB computation. */ void select(const std::vector<double> &fitness_values); /* Iterate over all patterns and flip every variable (set 0 if 1 or 1 if 0) with the given probability from options. This method does not check for pdb_max_size or disjoint patterns. */ void mutate(); /* Transforms a bit vector (internal pattern representation in this class, mainly for easy mutation) to the "normal" pattern form vector<int>, which we need for ZeroOnePDBsHeuristic. */ Pattern transform_to_pattern_normal_form( const std::vector<bool> &bitvector) const; /* Calculates the mean h-value (fitness value) for each pattern collection. For each pattern collection, we iterate over all patterns, first checking whether they respect the size limit, then modifying them in a way that only causally relevant variables remain in the patterns. Then the zero one partitioning pattern collection heuristic is constructed and its fitness ( = summed up mean h-values (dead ends are ignored) of all PDBs in the collection) computed. The overall best heuristic is eventually updated and saved for further episodes. */ void evaluate(std::vector<double> &fitness_values); bool is_pattern_too_large(const Pattern &pattern) const; /* Mark used variables in variables_used and return true iff anything was already used (in which case we do not mark the remaining variables). */ bool mark_used_variables(const Pattern &pattern, std::vector<bool> &variables_used) const; void remove_irrelevant_variables(Pattern &pattern) const; /* Calculates the initial pattern collections with a next-fit bin packing algorithm. Variables are shuffled to obtain a different random ordering for every pattern collection. Then, variables are inserted into a pattern as long as pdb_max_sizes allows. If the "bin" is full, a new one is opened. This is repeated until all variables have been treated. Every initial pattern collection contains every variable exactly once and all initial patterns of each pattern collection are disjoint (regardless of the disjoint_patterns flag). */ void bin_packing(); /* Main genetic algorithm loop. All pattern collections are initialized with bin packing. In each iteration (or episode), all patterns are first mutated, then evaluated and finally some patterns in each collection are selected to be part of the next episode. Note that we do not do any kind of recombination. */ void genetic_algorithm(); public: explicit PatternCollectionGeneratorGenetic(const options::Options &opts); virtual PatternCollectionInformation generate( const std::shared_ptr<AbstractTask> &task) override; }; } #endif
4,765
C
37.435484
80
0.72235
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/cegar.cc
#include "cegar.h" #include "types.h" #include "utils.h" #include "../option_parser.h" #include "../task_utils/task_properties.h" #include "../utils/countdown_timer.h" #include "../utils/rng.h" #include <limits> using namespace std; namespace pdbs { CEGAR::CEGAR( int max_pdb_size, int max_collection_size, bool use_wildcard_plans, double max_time, utils::Verbosity verbosity, const shared_ptr<utils::RandomNumberGenerator> &rng, const shared_ptr<AbstractTask> &task, vector<FactPair> &&goals, unordered_set<int> &&blacklisted_variables) : max_pdb_size(max_pdb_size), max_collection_size(max_collection_size), use_wildcard_plans(use_wildcard_plans), max_time(max_time), verbosity(verbosity), rng(rng), task(task), task_proxy(*task), goals(move(goals)), blacklisted_variables(move(blacklisted_variables)), collection_size(0) { #ifndef NDEBUG for (const FactPair &goal : goals) { bool is_goal = false; for (FactProxy task_goal : task_proxy.get_goals()) { if (goal == task_goal.get_pair()) { is_goal = true; break; } } if (!is_goal) { cerr << "given goal is not a goal of the task." << endl; utils::exit_with(utils::ExitCode::SEARCH_INPUT_ERROR); } } #endif if (verbosity >= utils::Verbosity::NORMAL) { utils::g_log << "options of the CEGAR algorithm for computing a pattern collection: " << endl; utils::g_log << "max pdb size: " << max_pdb_size << endl; utils::g_log << "max collection size: " << max_collection_size << endl; utils::g_log << "wildcard plans: " << use_wildcard_plans << endl; utils::g_log << "Verbosity: "; switch (verbosity) { case utils::Verbosity::SILENT: utils::g_log << "silent"; break; case utils::Verbosity::NORMAL: utils::g_log << "normal"; break; case utils::Verbosity::VERBOSE: utils::g_log << "verbose"; break; case utils::Verbosity::DEBUG: utils::g_log << "debug"; break; } utils::g_log << endl; utils::g_log << "max time: " << max_time << endl; utils::g_log << "goal variables: "; for (const FactPair &goal : this->goals) { utils::g_log << goal.var << ", "; } utils::g_log << endl; utils::g_log << "blacklisted variables: "; if (this->blacklisted_variables.empty()) { utils::g_log << "none"; } else { for (int var : this->blacklisted_variables) { utils::g_log << var << ", "; } } utils::g_log << endl; } } void CEGAR::print_collection() const { utils::g_log << "["; for (size_t i = 0; i < pattern_collection.size(); ++i) { const unique_ptr<PatternInfo> &pattern_info = pattern_collection[i]; if (pattern_info) { utils::g_log << pattern_info->get_pattern(); if (i != pattern_collection.size() - 1) { utils::g_log << ", "; } } } utils::g_log << "]" << endl; } bool CEGAR::time_limit_reached( const utils::CountdownTimer &timer) const { if (timer.is_expired()) { if (verbosity >= utils::Verbosity::NORMAL) { utils::g_log << "time limit reached." << endl; } return true; } return false; } unique_ptr<PatternInfo> CEGAR::compute_pattern_info(Pattern &&pattern) const { bool dump = false; vector<int> op_cost; bool compute_plan = true; shared_ptr<PatternDatabase> pdb = make_shared<PatternDatabase>(task_proxy, pattern, dump, op_cost, compute_plan, rng, use_wildcard_plans); vector<vector<OperatorID>> plan = pdb->extract_wildcard_plan(); bool unsolvable = false; State initial_state = task_proxy.get_initial_state(); initial_state.unpack(); if (pdb->get_value(initial_state.get_unpacked_values()) == numeric_limits<int>::max()) { unsolvable = true; if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "Projection onto pattern " << pdb->get_pattern() << " is unsolvable" << endl; } } else { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "##### Plan for pattern " << pdb->get_pattern() << " #####" << endl; int step = 1; for (const vector<OperatorID> &equivalent_ops : plan) { utils::g_log << "step #" << step << endl; for (OperatorID op_id : equivalent_ops) { OperatorProxy op = task_proxy.get_operators()[op_id]; utils::g_log << op.get_name() << " " << op.get_cost() << endl; } ++step; } utils::g_log << "##### End of plan #####" << endl; } } return utils::make_unique_ptr<PatternInfo>(move(pdb), move(plan), unsolvable); } void CEGAR::compute_initial_collection() { assert(!goals.empty()); for (const FactPair &goal : goals) { add_pattern_for_var(goal.var); } if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "initial collection: "; print_collection(); utils::g_log << endl; } } /* Apply the operator to the given state, ignoring that the operator is potentially not applicable in the state, and expecting that the operator has not conditional effects. */ void apply_op_to_state(vector<int> &state, const OperatorProxy &op) { assert(!op.is_axiom()); for (EffectProxy effect : op.get_effects()) { assert(effect.get_conditions().empty()); FactPair effect_fact = effect.get_fact().get_pair(); state[effect_fact.var] = effect_fact.value; } } FlawList CEGAR::get_violated_preconditions( int collection_index, const OperatorProxy &op, const vector<int> &current_state) const { FlawList flaws; for (FactProxy precondition : op.get_preconditions()) { int var_id = precondition.get_variable().get_id(); // Ignore blacklisted variables. if (blacklisted_variables.count(var_id)) { continue; } if (current_state[var_id] != precondition.get_value()) { flaws.emplace_back(collection_index, var_id); } } return flaws; } FlawList CEGAR::apply_plan(int collection_index, vector<int> &current_state) const { PatternInfo &pattern_info = *pattern_collection[collection_index]; const vector<vector<OperatorID>> &plan = pattern_info.get_plan(); if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "executing plan for pattern " << pattern_info.get_pattern() << ": "; } for (const vector<OperatorID> &equivalent_ops : plan) { FlawList step_flaws; for (OperatorID op_id : equivalent_ops) { OperatorProxy op = task_proxy.get_operators()[op_id]; FlawList operator_flaws = get_violated_preconditions(collection_index, op, current_state); /* If the operator is applicable, clear step_flaws, update the state to the successor state and proceed with the next plan step in the next iteration. Otherwise, move the flaws of the operator to step_flaws. */ if (operator_flaws.empty()) { step_flaws.clear(); apply_op_to_state(current_state, op); break; } else { step_flaws.insert(step_flaws.end(), make_move_iterator(operator_flaws.begin()), make_move_iterator(operator_flaws.end())); } } /* If all equivalent operators are inapplicable, return the collected flaws of this plan step. */ if (!step_flaws.empty()) { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "failure." << endl; } return step_flaws; } } if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "success." << endl; } return {}; } bool CEGAR::get_flaws_for_pattern( int collection_index, const State &concrete_init, FlawList &flaws) { PatternInfo &pattern_info = *pattern_collection[collection_index]; if (pattern_info.is_unsolvable()) { utils::g_log << "task is unsolvable." << endl; utils::exit_with(utils::ExitCode::SEARCH_UNSOLVABLE); } vector<int> current_state = concrete_init.get_unpacked_values(); FlawList new_flaws = apply_plan(collection_index, current_state); if (new_flaws.empty()) { State final_state(*task, move(current_state)); if (task_properties::is_goal_state(task_proxy, final_state)) { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "plan led to a concrete goal state: "; } if (blacklisted_variables.empty()) { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "there are no blacklisted variables, " "task solved." << endl; } return true; } else { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "there are blacklisted variables, " "marking pattern as solved." << endl; } pattern_info.mark_as_solved(); } } else { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "plan did not lead to a goal state: "; } bool raise_goal_flaw = false; for (const FactPair &goal : goals) { int goal_var_id = goal.var; if (final_state[goal_var_id].get_value() != goal.value && !blacklisted_variables.count(goal_var_id)) { flaws.emplace_back(collection_index, goal_var_id); raise_goal_flaw = true; } } if (raise_goal_flaw) { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "raising goal violation flaw(s)." << endl; } } else { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "there are no non-blacklisted goal variables " "left, marking pattern as solved." << endl; } pattern_info.mark_as_solved(); } } } else { flaws.insert(flaws.end(), make_move_iterator(new_flaws.begin()), make_move_iterator(new_flaws.end())); } return false; } int CEGAR::get_flaws(const State &concrete_init, FlawList &flaws) { assert(flaws.empty()); for (size_t collection_index = 0; collection_index < pattern_collection.size(); ++collection_index) { if (pattern_collection[collection_index] && !pattern_collection[collection_index]->is_solved()) { bool solved = get_flaws_for_pattern(collection_index, concrete_init, flaws); if (solved) { return collection_index; } } } return -1; } void CEGAR::add_pattern_for_var(int var) { pattern_collection.push_back(compute_pattern_info({var})); variable_to_collection_index[var] = pattern_collection.size() - 1; collection_size += pattern_collection.back()->get_pdb()->get_size(); } bool CEGAR::can_merge_patterns(int index1, int index2) const { int pdb_size1 = pattern_collection[index1]->get_pdb()->get_size(); int pdb_size2 = pattern_collection[index2]->get_pdb()->get_size(); if (!utils::is_product_within_limit(pdb_size1, pdb_size2, max_pdb_size)) { return false; } int added_size = pdb_size1 * pdb_size2 - pdb_size1 - pdb_size2; return collection_size + added_size <= max_collection_size; } void CEGAR::merge_patterns(int index1, int index2) { // Merge pattern at index2 into pattern at index2. PatternInfo &pattern_info1 = *pattern_collection[index1]; PatternInfo &pattern_info2 = *pattern_collection[index2]; const Pattern &pattern2 = pattern_info2.get_pattern(); for (int var : pattern2) { variable_to_collection_index[var] = index1; } // Compute merged_pattern_info pattern. Pattern new_pattern = pattern_info1.get_pattern(); new_pattern.insert(new_pattern.end(), pattern2.begin(), pattern2.end()); sort(new_pattern.begin(), new_pattern.end()); // Store old PDB sizes. int pdb_size1 = pattern_collection[index1]->get_pdb()->get_size(); int pdb_size2 = pattern_collection[index2]->get_pdb()->get_size(); // Compute merged_pattern_info pattern. unique_ptr<PatternInfo> merged_pattern_info = compute_pattern_info(move(new_pattern)); // Update collection size. collection_size -= pdb_size1; collection_size -= pdb_size2; collection_size += merged_pattern_info->get_pdb()->get_size(); // Clean up. pattern_collection[index1] = move(merged_pattern_info); pattern_collection[index2] = nullptr; } bool CEGAR::can_add_variable_to_pattern(int index, int var) const { int pdb_size = pattern_collection[index]->get_pdb()->get_size(); int domain_size = task_proxy.get_variables()[var].get_domain_size(); if (!utils::is_product_within_limit(pdb_size, domain_size, max_pdb_size)) { return false; } int added_size = pdb_size * domain_size - pdb_size; return collection_size + added_size <= max_collection_size; } void CEGAR::add_variable_to_pattern(int collection_index, int var) { const PatternInfo &pattern_info = *pattern_collection[collection_index]; Pattern new_pattern(pattern_info.get_pattern()); new_pattern.push_back(var); sort(new_pattern.begin(), new_pattern.end()); unique_ptr<PatternInfo> new_pattern_info = compute_pattern_info(move(new_pattern)); collection_size -= pattern_info.get_pdb()->get_size(); collection_size += new_pattern_info->get_pdb()->get_size(); variable_to_collection_index[var] = collection_index; pattern_collection[collection_index] = move(new_pattern_info); } void CEGAR::refine(const FlawList &flaws) { assert(!flaws.empty()); const Flaw &flaw = *(rng->choose(flaws)); if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "chosen flaw: pattern " << pattern_collection[flaw.collection_index]->get_pattern() << " with a flaw on " << flaw.variable << endl; } int collection_index = flaw.collection_index; int var = flaw.variable; bool added_var = false; auto it = variable_to_collection_index.find(var); if (it != variable_to_collection_index.end()) { // Variable is contained in another pattern of the collection. int other_index = it->second; assert(other_index != collection_index); assert(pattern_collection[other_index] != nullptr); if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "var" << var << " is already in pattern " << pattern_collection[other_index]->get_pattern() << endl; } if (can_merge_patterns(collection_index, other_index)) { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "merge the two patterns" << endl; } merge_patterns(collection_index, other_index); added_var = true; } } else { // Variable is not yet in the collection. if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "var" << var << " is not in the collection yet" << endl; } if (can_add_variable_to_pattern(collection_index, var)) { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "add it to the pattern" << endl; } add_variable_to_pattern(collection_index, var); added_var = true; } } if (!added_var) { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "could not add var/merge patterns due to size " "limits. Blacklisting." << endl; } blacklisted_variables.insert(var); } } PatternCollectionInformation CEGAR::compute_pattern_collection() { utils::CountdownTimer timer(max_time); compute_initial_collection(); int iteration = 1; State concrete_init = task_proxy.get_initial_state(); concrete_init.unpack(); int concrete_solution_index = -1; while (!time_limit_reached(timer)) { if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "iteration #" << iteration << endl; } FlawList flaws; concrete_solution_index = get_flaws(concrete_init, flaws); if (concrete_solution_index != -1) { if (verbosity >= utils::Verbosity::NORMAL) { utils::g_log << "task solved during computation of abstraction" << endl; } break; } if (flaws.empty()) { if (verbosity >= utils::Verbosity::NORMAL) { utils::g_log << "flaw list empty. No further refinements possible" << endl; } break; } refine(flaws); ++iteration; if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << "current collection size: " << collection_size << endl; utils::g_log << "current collection: "; print_collection(); utils::g_log << endl; } } if (verbosity >= utils::Verbosity::VERBOSE) { utils::g_log << endl; } shared_ptr<PatternCollection> patterns = make_shared<PatternCollection>(); shared_ptr<PDBCollection> pdbs = make_shared<PDBCollection>(); if (concrete_solution_index != -1) { const shared_ptr<PatternDatabase> &pdb = pattern_collection[concrete_solution_index]->get_pdb(); patterns->push_back(pdb->get_pattern()); pdbs->push_back(pdb); } else { for (const unique_ptr<PatternInfo> &pattern_info : pattern_collection) { if (pattern_info) { const shared_ptr<PatternDatabase> &pdb = pattern_info->get_pdb(); patterns->push_back(pdb->get_pattern()); pdbs->push_back(pdb); } } } PatternCollectionInformation pattern_collection_information( task_proxy, patterns); pattern_collection_information.set_pdbs(pdbs); if (verbosity >= utils::Verbosity::NORMAL) { utils::g_log << "CEGAR number of iterations: " << iteration << endl; dump_pattern_collection_generation_statistics( "CEGAR", timer.get_elapsed_time(), pattern_collection_information); } return pattern_collection_information; } void add_implementation_notes_to_parser(options::OptionParser &parser) { parser.document_note( "Implementation Notes", "The following describes differences of the implementation to " "the original implementation used and described in the paper.\n\n" "Conceptually, there is one larger difference which concerns the " "computation of (regular or wildcard) plans for PDBs. The original " "implementation used an enforced hill-climbing (EHC) search with the " "PDB as the perfect heuristic, which ensured finding strongly optimal " "plans, i.e., optimal plans with a minimum number of zero-cost " "operators, in domains with zero-cost operators. The original " "implementation also slightly modified EHC to search for a best-" "improving successor, chosen uniformly at random among all best-" "improving successors.\n\n" "In contrast, the current implementation computes a plan alongside the " "computation of the PDB itself. A modification to Dijkstra's algorithm " "for computing the PDB values stores, for each state, the operator " "leading to that state (in a regression search). This generating " "operator is updated only if the algorithm found a cheaper path to " "the state. After Dijkstra finishes, the plan computation starts at the " "initial state and iteratively follows the generating operator, computes " "all operators of the same cost inducing the same transition, until " "reaching a goal. This constitutes a wildcard plan. It is turned into a " "regular one by randomly picking a single operator for each transition. " "\n\n" "Note that this kind of plan extraction does not consider all successors " "of a state uniformly at random but rather uses the previously deterministically " "chosen generating operator to settle on one successor state, which is " "biased by the number of operators leading to the same successor from " "the given state. Further note that in the presence of zero-cost " "operators, this procedure does not guarantee that the computed plan is " "strongly optimal because it does not minimize the number of used " "zero-cost operators leading to the state when choosing a generating " "operator. Experiments have shown (issue1007) that this speeds up the " "computation significantly while not having a strongly negative effect " "on heuristic quality due to potentially computing worse plans.\n\n" "Two further changes fix bugs of the original implementation to match " "the description in the paper. The first concerns the single CEGAR " "algorithm: raise a flaw for all goal variables of the task if the " "plan for a PDB can be executed on the concrete task but does not lead " "to a goal state. Previously, such flaws would not have been raised " "because all goal variables are part of the collection from the start " "on and therefore not considered. This means that the original " "implementation accidentally disallowed merging patterns due to goal " "violation flaws. The second bug fix is to actually randomize the " "order of parallel operators in wildcard plan steps.", true); } void add_cegar_options_to_parser(options::OptionParser &parser) { parser.add_option<int>( "max_pdb_size", "maximum number of states per pattern database (ignored for the " "initial collection consisting of singleton patterns for each goal " "variable)", "2000000", Bounds("1", "infinity")); parser.add_option<int>( "max_collection_size", "maximum number of states in the pattern collection (ignored for the " "initial collection consisting of singleton patterns for each goal " "variable)", "20000000", Bounds("1", "infinity")); parser.add_option<bool>( "use_wildcard_plans", "if true, compute wildcard plans which are sequences of sets of " "operators that induce the same transition; otherwise compute regular " "plans which are sequences of single operators", "true"); parser.add_option<double>( "max_time", "maximum time in seconds for the CEGAR algorithm (ignored for" "computing initial collection)", "infinity", Bounds("0.0", "infinity")); } }
23,852
C++
38.231908
112
0.588043
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/cegar.h
#ifndef PDBS_CEGAR_H #define PDBS_CEGAR_H #include "pattern_collection_information.h" #include "pattern_database.h" #include "../task_proxy.h" #include "../utils/logging.h" #include <memory> #include <unordered_set> #include <vector> namespace options { class OptionParser; } namespace utils { class CountdownTimer; class RandomNumberGenerator; } namespace pdbs { /* This is used as a "collection entry" in the CEGAR algorithm. It stores the PDB (and with that, the pattern) and an optimal plan (in the wildcard format) for that PDB if it exists or unsolvable is true otherwise. It can be marked as "solved" to ignore it in further iterations of the CEGAR algorithm. */ class PatternInfo { std::shared_ptr<PatternDatabase> pdb; std::vector<std::vector<OperatorID>> plan; bool unsolvable; bool solved; public: PatternInfo( const std::shared_ptr<PatternDatabase> &&pdb, const std::vector<std::vector<OperatorID>> &&plan, bool unsolvable) : pdb(move(pdb)), plan(move(plan)), unsolvable(unsolvable), solved(false) {} const std::shared_ptr<PatternDatabase> &get_pdb() const { return pdb; } const Pattern &get_pattern() const { return pdb->get_pattern(); } const std::vector<std::vector<OperatorID>> &get_plan() const { return plan; } bool is_unsolvable() const { return unsolvable; } void mark_as_solved() { solved = true; } bool is_solved() { return solved; } }; struct Flaw { int collection_index; int variable; Flaw(int collection_index, int variable) : collection_index(collection_index), variable(variable) { } }; using FlawList = std::vector<Flaw>; /* This class implements the CEGAR algorithm for computing pattern collections. In a nutshell, it receives a concrete task plus a (sub)set of its goals in a randomized order. Starting from the pattern collection consisting of a singleton pattern for each goal variable, it repeatedly attempts to execute an optimal plan of each pattern in the concrete task, collects reasons why this is not possible (so-called flaws) and refines the pattern in question by adding a variable to it. Further parameters allow blacklisting a (sub)set of the non-goal variables which are then never added to the collection, limiting PDB and collection size, setting a time limit and switching between computing regular or wildcard plans, where the latter are sequences of parallel operators inducing the same abstract transition. */ class CEGAR { const int max_pdb_size; const int max_collection_size; const bool use_wildcard_plans; const double max_time; const utils::Verbosity verbosity; std::shared_ptr<utils::RandomNumberGenerator> rng; const std::shared_ptr<AbstractTask> &task; const TaskProxy task_proxy; const std::vector<FactPair> goals; std::unordered_set<int> blacklisted_variables; std::vector<std::unique_ptr<PatternInfo>> pattern_collection; /* Map each variable of the task which is contained in the collection to the collection index at which the pattern containing the variable is stored. */ std::unordered_map<int, int> variable_to_collection_index; int collection_size; void print_collection() const; bool time_limit_reached(const utils::CountdownTimer &timer) const; std::unique_ptr<PatternInfo> compute_pattern_info(Pattern &&pattern) const; void compute_initial_collection(); /* Check if operator op is applicable in state, ignoring blacklisted variables. If it is, return an empty (flaw) list. Otherwise, return the violated preconditions. */ FlawList get_violated_preconditions( int collection_index, const OperatorProxy &op, const std::vector<int> &current_state) const; /* Try to apply the plan of the pattern at the given index in the concrete task starting at the given state. During application, blacklisted variables are ignored. If plan application succeeds, return an empty flaw list. Otherwise, return all precondition variables of all operators of the failing plan step. When the method returns, current is the last state reached when executing the plan. */ FlawList apply_plan(int collection_index, std::vector<int> &current_state) const; /* Use apply_plan to generate flaws. Return true if there are no flaws and no blacklisted variables, in which case the concrete task is solved. Return false in all other cases. Append new flaws to the passed-in flaws. */ bool get_flaws_for_pattern( int collection_index, const State &concrete_init, FlawList &flaws); /* Use get_flaws_for_pattern for all patterns of the collection. Append new flaws to the passed-in flaws. If the task is solved by the plan of any pattern, return the collection index of that pattern. Otherwise, return -1. */ int get_flaws(const State &concrete_init, FlawList &flaws); // Methods related to refining. void add_pattern_for_var(int var); bool can_merge_patterns(int index1, int index2) const; void merge_patterns(int index1, int index2); bool can_add_variable_to_pattern(int index, int var) const; void add_variable_to_pattern(int collection_index, int var); void refine(const FlawList &flaws); public: CEGAR( int max_pdb_size, int max_collection_size, bool use_wildcard_plans, double max_time, utils::Verbosity verbosity, const std::shared_ptr<utils::RandomNumberGenerator> &rng, const std::shared_ptr<AbstractTask> &task, std::vector<FactPair> &&goals, std::unordered_set<int> &&blacklisted_variables = std::unordered_set<int>()); PatternCollectionInformation compute_pattern_collection(); }; extern void add_implementation_notes_to_parser(options::OptionParser &parser); extern void add_cegar_options_to_parser(options::OptionParser &parser); } #endif
6,136
C
31.994623
85
0.695567
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/canonical_pdbs.cc
#include "canonical_pdbs.h" #include "pattern_database.h" #include <algorithm> #include <cassert> #include <iostream> #include <limits> using namespace std; namespace pdbs { CanonicalPDBs::CanonicalPDBs( const shared_ptr<PDBCollection> &pdbs, const shared_ptr<vector<PatternClique>> &pattern_cliques) : pdbs(pdbs), pattern_cliques(pattern_cliques) { assert(pdbs); assert(pattern_cliques); } int CanonicalPDBs::get_value(const State &state) const { // If we have an empty collection, then pattern_cliques = { \emptyset }. assert(!pattern_cliques->empty()); int max_h = 0; vector<int> h_values; h_values.reserve(pdbs->size()); state.unpack(); for (const shared_ptr<PatternDatabase> &pdb : *pdbs) { int h = pdb->get_value(state.get_unpacked_values()); if (h == numeric_limits<int>::max()) { return numeric_limits<int>::max(); } h_values.push_back(h); } for (const PatternClique &clique : *pattern_cliques) { int clique_h = 0; for (PatternID pdb_index : clique) { clique_h += h_values[pdb_index]; } max_h = max(max_h, clique_h); } return max_h; } }
1,202
C++
25.733333
76
0.620632
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/match_tree.cc
#include "match_tree.h" #include "../utils/logging.h" #include <cassert> #include <iostream> #include <utility> using namespace std; namespace pdbs { struct MatchTree::Node { static const int LEAF_NODE = -1; Node(); ~Node(); vector<int> applicable_operator_ids; // The variable which this node represents. int var_id; int var_domain_size; /* Each node has one outgoing edge for each possible value of the variable and one "star-edge" that is used when the value of the variable is undefined. */ Node **successors; Node *star_successor; void initialize(int var_id, int var_domain_size); bool is_leaf_node() const; }; MatchTree::Node::Node() : var_id(LEAF_NODE), var_domain_size(0), successors(nullptr), star_successor(nullptr) { } MatchTree::Node::~Node() { if (successors) { for (int i = 0; i < var_domain_size; ++i) { delete successors[i]; } delete[] successors; } delete star_successor; } void MatchTree::Node::initialize(int var_id_, int var_domain_size_) { assert(is_leaf_node()); assert(var_id_ >= 0); var_id = var_id_; var_domain_size = var_domain_size_; if (var_domain_size > 0) { successors = new Node *[var_domain_size]; for (int val = 0; val < var_domain_size; ++val) { successors[val] = nullptr; } } } bool MatchTree::Node::is_leaf_node() const { return var_id == LEAF_NODE; } MatchTree::MatchTree(const TaskProxy &task_proxy, const Pattern &pattern, const vector<int> &hash_multipliers) : task_proxy(task_proxy), pattern(pattern), hash_multipliers(hash_multipliers), root(nullptr) { } MatchTree::~MatchTree() { delete root; } void MatchTree::insert_recursive( int op_id, const vector<FactPair> &regression_preconditions, int pre_index, Node **edge_from_parent) { if (*edge_from_parent == 0) { // We don't exist yet: create a new node. *edge_from_parent = new Node(); } Node *node = *edge_from_parent; if (pre_index == static_cast<int>(regression_preconditions.size())) { // All preconditions have been checked, insert operator ID. node->applicable_operator_ids.push_back(op_id); } else { const FactPair &fact = regression_preconditions[pre_index]; int pattern_var_id = fact.var; int var_id = pattern[pattern_var_id]; VariableProxy var = task_proxy.get_variables()[var_id]; int var_domain_size = var.get_domain_size(); // Set up node correctly or insert a new node if necessary. if (node->is_leaf_node()) { node->initialize(pattern_var_id, var_domain_size); } else if (node->var_id > pattern_var_id) { /* The variable to test has been left out: must insert new node and treat it as the "node". */ Node *new_node = new Node(); new_node->initialize(pattern_var_id, var_domain_size); // The new node gets the left out variable as its variable. *edge_from_parent = new_node; new_node->star_successor = node; // The new node is now the node of interest. node = new_node; } /* Set up edge to the correct child (for which we want to call this function recursively). */ Node **edge_to_child = 0; if (node->var_id == fact.var) { // Operator has a precondition on the variable tested by node. edge_to_child = &node->successors[fact.value]; ++pre_index; } else { // Operator doesn't have a precondition on the variable tested by // node: follow/create the star-edge. assert(node->var_id < fact.var); edge_to_child = &node->star_successor; } insert_recursive(op_id, regression_preconditions, pre_index, edge_to_child); } } void MatchTree::insert(int op_id, const vector<FactPair> &regression_preconditions) { insert_recursive(op_id, regression_preconditions, 0, &root); } void MatchTree::get_applicable_operator_ids_recursive( Node *node, int state_index, vector<int> &operator_ids) const { /* Note: different from the code that builds the match tree, we do the test if node == 0 *before* calling traverse rather than *at the start* of traverse since this turned out to be faster in some informal experiments. */ operator_ids.insert(operator_ids.end(), node->applicable_operator_ids.begin(), node->applicable_operator_ids.end()); if (node->is_leaf_node()) return; int temp = state_index / hash_multipliers[node->var_id]; int val = temp % node->var_domain_size; if (node->successors[val]) { // Follow the correct successor edge, if it exists. get_applicable_operator_ids_recursive( node->successors[val], state_index, operator_ids); } if (node->star_successor) { // Always follow the star edge, if it exists. get_applicable_operator_ids_recursive( node->star_successor, state_index, operator_ids); } } void MatchTree::get_applicable_operator_ids( int state_index, vector<int> &operator_ids) const { if (root) get_applicable_operator_ids_recursive(root, state_index, operator_ids); } void MatchTree::dump_recursive(Node *node) const { if (!node) { // Node is the root node. utils::g_log << "Empty MatchTree" << endl; return; } utils::g_log << endl; utils::g_log << "node->var_id = " << node->var_id << endl; utils::g_log << "Number of applicable operators at this node: " << node->applicable_operator_ids.size() << endl; for (int op_id : node->applicable_operator_ids) { utils::g_log << "AbstractOperator #" << op_id << endl; } if (node->is_leaf_node()) { utils::g_log << "leaf node." << endl; assert(!node->successors); assert(!node->star_successor); } else { for (int val = 0; val < node->var_domain_size; ++val) { if (node->successors[val]) { utils::g_log << "recursive call for child with value " << val << endl; dump_recursive(node->successors[val]); utils::g_log << "back from recursive call (for successors[" << val << "]) to node with var_id = " << node->var_id << endl; } else { utils::g_log << "no child for value " << val << endl; } } if (node->star_successor) { utils::g_log << "recursive call for star_successor" << endl; dump_recursive(node->star_successor); utils::g_log << "back from recursive call (for star_successor) " << "to node with var_id = " << node->var_id << endl; } else { utils::g_log << "no star_successor" << endl; } } } void MatchTree::dump() const { dump_recursive(root); } }
7,193
C++
32.305555
86
0.577923
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_generator_hillclimbing.h
#ifndef PDBS_PATTERN_COLLECTION_GENERATOR_HILLCLIMBING_H #define PDBS_PATTERN_COLLECTION_GENERATOR_HILLCLIMBING_H #include "pattern_generator.h" #include "types.h" #include "../task_proxy.h" #include <cstdlib> #include <memory> #include <set> #include <vector> namespace options { class Options; } namespace utils { class CountdownTimer; class RandomNumberGenerator; } namespace sampling { class RandomWalkSampler; } namespace pdbs { class CanonicalPDBsHeuristic; class IncrementalCanonicalPDBs; class PatternDatabase; // Implementation of the pattern generation algorithm by Haslum et al. class PatternCollectionGeneratorHillclimbing : public PatternCollectionGenerator { // maximum number of states for each pdb const int pdb_max_size; // maximum added size of all pdbs const int collection_max_size; const int num_samples; // minimal improvement required for hill climbing to continue search const int min_improvement; const double max_time; std::shared_ptr<utils::RandomNumberGenerator> rng; std::unique_ptr<IncrementalCanonicalPDBs> current_pdbs; // for stats only int num_rejected; utils::CountdownTimer *hill_climbing_timer; /* For the given PDB, all possible extensions of its pattern by one relevant variable are considered as candidate patterns. If the candidate pattern has not been previously considered (not contained in generated_patterns) and if building a PDB for it does not surpass the size limit, then the PDB is built and added to candidate_pdbs. The method returns the size of the largest PDB added to candidate_pdbs. */ int generate_candidate_pdbs( const TaskProxy &task_proxy, const std::vector<std::vector<int>> &relevant_neighbours, const PatternDatabase &pdb, std::set<Pattern> &generated_patterns, PDBCollection &candidate_pdbs); /* Performs num_samples random walks with a length (different for each random walk) chosen according to a binomial distribution with n = 4 * solution depth estimate and p = 0.5, starting from the initial state. In each step of a random walk, a random operator is taken and applied to the current state. If a dead end is reached or no more operators are applicable, the walk starts over again from the initial state. At the end of each random walk, the last state visited is taken as a sample state, thus totalling exactly num_samples of sample states. */ void sample_states( const sampling::RandomWalkSampler &sampler, int init_h, std::vector<State> &samples); /* Searches for the best improving pdb in candidate_pdbs according to the counting approximation and the given samples. Returns the improvement and the index of the best pdb in candidate_pdbs. */ std::pair<int, int> find_best_improving_pdb( const std::vector<State> &samples, const std::vector<int> &samples_h_values, PDBCollection &candidate_pdbs); /* Returns true iff the h-value of the new pattern (from pdb) plus the h-value of all pattern cliques from the current pattern collection heuristic if the new pattern was added to it is greater than the h-value of the current pattern collection. */ bool is_heuristic_improved( const PatternDatabase &pdb, const State &sample, int h_collection, const PDBCollection &pdbs, const std::vector<PatternClique> &pattern_cliques); /* This is the core algorithm of this class. The initial PDB collection consists of one PDB for each goal variable. For each PDB of this initial collection, the set of candidate PDBs are added (see generate_candidate_pdbs) to the set of initial candidate PDBs. The main loop of the search computes a set of sample states (see sample_states) and uses this set to evaluate the set of all candidate PDBs (see find_best_improving_pdb, using the "counting approximation"). If the improvement obtained through adding the best PDB to the current heuristic is smaller than the minimal required improvement, the search is stopped. Otherwise, the best PDB is added to the heuristic and the candidate PDBs for this best PDB are computed (see generate_candidate_pdbs) and used for the next iteration. This method uses a set to store all patterns that are generated as candidate patterns in their "normal form" for duplicate detection. Futhermore, a vector stores the PDBs corresponding to the candidate patterns if its size does not surpass the user-specified size limit. Storing the PDBs has the only purpose to avoid re-computation of the same PDBs. This is quite a large time gain, but may use a lot of memory. */ void hill_climbing(const TaskProxy &task_proxy); public: explicit PatternCollectionGeneratorHillclimbing(const options::Options &opts); virtual ~PatternCollectionGeneratorHillclimbing() = default; /* Runs the hill climbing algorithm. Note that the initial pattern collection (consisting of exactly one PDB for each goal variable) may break the maximum collection size limit, if the latter is set too small or if there are many goal variables with a large domain. */ virtual PatternCollectionInformation generate( const std::shared_ptr<AbstractTask> &task) override; }; } #endif
5,521
C
37.347222
82
0.718348
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/pdbs/pattern_collection_information.cc
#include "pattern_collection_information.h" #include "pattern_database.h" #include "pattern_cliques.h" #include "validation.h" #include "../utils/logging.h" #include "../utils/timer.h" #include <algorithm> #include <cassert> #include <unordered_set> #include <utility> using namespace std; namespace pdbs { PatternCollectionInformation::PatternCollectionInformation( const TaskProxy &task_proxy, const shared_ptr<PatternCollection> &patterns) : task_proxy(task_proxy), patterns(patterns), pdbs(nullptr), pattern_cliques(nullptr) { assert(patterns); validate_and_normalize_patterns(task_proxy, *patterns); } bool PatternCollectionInformation::information_is_valid() const { if (!patterns) { return false; } int num_patterns = patterns->size(); if (pdbs) { if (patterns->size() != pdbs->size()) { return false; } for (int i = 0; i < num_patterns; ++i) { if ((*patterns)[i] != (*pdbs)[i]->get_pattern()) { return false; } } } if (pattern_cliques) { for (const PatternClique &clique : *pattern_cliques) { for (PatternID pattern_id : clique) { if (!utils::in_bounds(pattern_id, *patterns)) { return false; } } } } return true; } void PatternCollectionInformation::create_pdbs_if_missing() { assert(patterns); if (!pdbs) { utils::Timer timer; utils::g_log << "Computing PDBs for pattern collection..." << endl; pdbs = make_shared<PDBCollection>(); for (const Pattern &pattern : *patterns) { shared_ptr<PatternDatabase> pdb = make_shared<PatternDatabase>(task_proxy, pattern); pdbs->push_back(pdb); } utils::g_log << "Done computing PDBs for pattern collection: " << timer << endl; } } void PatternCollectionInformation::create_pattern_cliques_if_missing() { if (!pattern_cliques) { utils::Timer timer; utils::g_log << "Computing pattern cliques for pattern collection..." << endl; VariableAdditivity are_additive = compute_additive_vars(task_proxy); pattern_cliques = compute_pattern_cliques(*patterns, are_additive); utils::g_log << "Done computing pattern cliques for pattern collection: " << timer << endl; } } void PatternCollectionInformation::set_pdbs(const shared_ptr<PDBCollection> &pdbs_) { pdbs = pdbs_; assert(information_is_valid()); } void PatternCollectionInformation::set_pattern_cliques( const shared_ptr<vector<PatternClique>> &pattern_cliques_) { pattern_cliques = pattern_cliques_; assert(information_is_valid()); } shared_ptr<PatternCollection> PatternCollectionInformation::get_patterns() const { assert(patterns); return patterns; } shared_ptr<PDBCollection> PatternCollectionInformation::get_pdbs() { create_pdbs_if_missing(); return pdbs; } shared_ptr<vector<PatternClique>> PatternCollectionInformation::get_pattern_cliques() { create_pattern_cliques_if_missing(); return pattern_cliques; } }
3,192
C++
28.564815
88
0.631579
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/single_potential_heuristics.cc
#include "potential_function.h" #include "potential_heuristic.h" #include "potential_optimizer.h" #include "util.h" #include "../option_parser.h" #include "../plugin.h" #include "../utils/system.h" using namespace std; namespace potentials { enum class OptimizeFor { INITIAL_STATE, ALL_STATES, }; static unique_ptr<PotentialFunction> create_potential_function( const Options &opts, OptimizeFor opt_func) { PotentialOptimizer optimizer(opts); const AbstractTask &task = *opts.get<shared_ptr<AbstractTask>>("transform"); TaskProxy task_proxy(task); switch (opt_func) { case OptimizeFor::INITIAL_STATE: optimizer.optimize_for_state(task_proxy.get_initial_state()); break; case OptimizeFor::ALL_STATES: optimizer.optimize_for_all_states(); break; default: ABORT("Unkown optimization function"); } return optimizer.get_potential_function(); } static shared_ptr<Heuristic> _parse(OptionParser &parser, OptimizeFor opt_func) { prepare_parser_for_admissible_potentials(parser); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<PotentialHeuristic>( opts, create_potential_function(opts, opt_func)); } static shared_ptr<Heuristic> _parse_initial_state_potential(OptionParser &parser) { parser.document_synopsis( "Potential heuristic optimized for initial state", get_admissible_potentials_reference()); return _parse(parser, OptimizeFor::INITIAL_STATE); } static shared_ptr<Heuristic> _parse_all_states_potential(OptionParser &parser) { parser.document_synopsis( "Potential heuristic optimized for all states", get_admissible_potentials_reference()); return _parse(parser, OptimizeFor::ALL_STATES); } static Plugin<Evaluator> _plugin_initial_state( "initial_state_potential", _parse_initial_state_potential, "heuristics_potentials"); static Plugin<Evaluator> _plugin_all_states( "all_states_potential", _parse_all_states_potential, "heuristics_potentials"); }
2,075
C++
30.454545
88
0.710361
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/potential_max_heuristic.h
#ifndef POTENTIALS_POTENTIAL_MAX_HEURISTIC_H #define POTENTIALS_POTENTIAL_MAX_HEURISTIC_H #include "../heuristic.h" #include <memory> #include <vector> namespace potentials { class PotentialFunction; /* Maximize over multiple potential functions. */ class PotentialMaxHeuristic : public Heuristic { std::vector<std::unique_ptr<PotentialFunction>> functions; protected: virtual int compute_heuristic(const State &ancestor_state) override; public: explicit PotentialMaxHeuristic( const options::Options &opts, std::vector<std::unique_ptr<PotentialFunction>> &&functions); ~PotentialMaxHeuristic() = default; }; } #endif
659
C
20.999999
72
0.743551
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/diverse_potential_heuristics.cc
#include "diverse_potential_heuristics.h" #include "potential_function.h" #include "potential_max_heuristic.h" #include "util.h" #include "../option_parser.h" #include "../plugin.h" #include "../utils/logging.h" #include "../utils/rng.h" #include "../utils/rng_options.h" #include "../utils/timer.h" #include <unordered_set> using namespace std; namespace potentials { DiversePotentialHeuristics::DiversePotentialHeuristics(const Options &opts) : optimizer(opts), max_num_heuristics(opts.get<int>("max_num_heuristics")), num_samples(opts.get<int>("num_samples")), rng(utils::parse_rng_from_options(opts)) { } SamplesToFunctionsMap DiversePotentialHeuristics::filter_samples_and_compute_functions( const vector<State> &samples) { utils::Timer filtering_timer; utils::HashSet<State> dead_ends; int num_duplicates = 0; int num_dead_ends = 0; SamplesToFunctionsMap samples_to_functions; for (const State &sample : samples) { // Skipping duplicates is not necessary, but saves LP evaluations. if (samples_to_functions.count(sample) || dead_ends.count(sample)) { ++num_duplicates; continue; } optimizer.optimize_for_state(sample); if (optimizer.has_optimal_solution()) { samples_to_functions[sample] = optimizer.get_potential_function(); } else { dead_ends.insert(sample); ++num_dead_ends; } } utils::g_log << "Time for filtering dead ends: " << filtering_timer << endl; utils::g_log << "Duplicate samples: " << num_duplicates << endl; utils::g_log << "Dead end samples: " << num_dead_ends << endl; utils::g_log << "Unique non-dead-end samples: " << samples_to_functions.size() << endl; assert(num_duplicates + num_dead_ends + samples_to_functions.size() == samples.size()); return samples_to_functions; } void DiversePotentialHeuristics::remove_covered_samples( const PotentialFunction &chosen_function, SamplesToFunctionsMap &samples_to_functions) const { for (auto it = samples_to_functions.begin(); it != samples_to_functions.end();) { const State &sample = it->first; const PotentialFunction &sample_function = *it->second; int max_h = sample_function.get_value(sample); int h = chosen_function.get_value(sample); assert(h <= max_h); // TODO: Count as covered if max_h <= 0. if (h == max_h) { it = samples_to_functions.erase(it); } else { ++it; } } } unique_ptr<PotentialFunction> DiversePotentialHeuristics::find_function_and_remove_covered_samples( SamplesToFunctionsMap &samples_to_functions) { vector<State> uncovered_samples; for (auto &sample_and_function : samples_to_functions) { const State &state = sample_and_function.first; uncovered_samples.push_back(state); } optimizer.optimize_for_samples(uncovered_samples); unique_ptr<PotentialFunction> function = optimizer.get_potential_function(); size_t last_num_samples = samples_to_functions.size(); remove_covered_samples(*function, samples_to_functions); if (samples_to_functions.size() == last_num_samples) { utils::g_log << "No sample removed -> Use arbitrary precomputed function." << endl; function = move(samples_to_functions.begin()->second); // The move operation invalidated the entry, remove it. samples_to_functions.erase(samples_to_functions.begin()); remove_covered_samples(*function, samples_to_functions); } utils::g_log << "Removed " << last_num_samples - samples_to_functions.size() << " samples. " << samples_to_functions.size() << " remaining." << endl; return function; } void DiversePotentialHeuristics::cover_samples( SamplesToFunctionsMap &samples_to_functions) { utils::Timer covering_timer; while (!samples_to_functions.empty() && static_cast<int>(diverse_functions.size()) < max_num_heuristics) { utils::g_log << "Find heuristic #" << diverse_functions.size() + 1 << endl; diverse_functions.push_back( find_function_and_remove_covered_samples(samples_to_functions)); } utils::g_log << "Time for covering samples: " << covering_timer << endl; } vector<unique_ptr<PotentialFunction>> DiversePotentialHeuristics::find_functions() { assert(diverse_functions.empty()); utils::Timer init_timer; // Sample states. vector<State> samples = sample_without_dead_end_detection( optimizer, num_samples, *rng); // Filter dead end samples. SamplesToFunctionsMap samples_to_functions = filter_samples_and_compute_functions(samples); // Iteratively cover samples. cover_samples(samples_to_functions); utils::g_log << "Potential heuristics: " << diverse_functions.size() << endl; utils::g_log << "Initialization of potential heuristics: " << init_timer << endl; return move(diverse_functions); } static shared_ptr<Heuristic> _parse(OptionParser &parser) { parser.document_synopsis( "Diverse potential heuristics", get_admissible_potentials_reference()); parser.add_option<int>( "num_samples", "Number of states to sample", "1000", Bounds("0", "infinity")); parser.add_option<int>( "max_num_heuristics", "maximum number of potential heuristics", "infinity", Bounds("0", "infinity")); prepare_parser_for_admissible_potentials(parser); utils::add_rng_options(parser); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; DiversePotentialHeuristics factory(opts); return make_shared<PotentialMaxHeuristic>(opts, factory.find_functions()); } static Plugin<Evaluator> _plugin( "diverse_potentials", _parse, "heuristics_potentials"); }
5,950
C++
35.509202
91
0.652437
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/potential_optimizer.cc
#include "potential_optimizer.h" #include "potential_function.h" #include "../option_parser.h" #include "../task_utils/task_properties.h" #include "../utils/collections.h" #include "../utils/memory.h" #include "../utils/system.h" #include <limits> #include <unordered_map> using namespace std; using utils::ExitCode; namespace potentials { static int get_undefined_value(VariableProxy var) { return var.get_domain_size(); } PotentialOptimizer::PotentialOptimizer(const Options &opts) : task(opts.get<shared_ptr<AbstractTask>>("transform")), task_proxy(*task), lp_solver(opts.get<lp::LPSolverType>("lpsolver")), max_potential(opts.get<double>("max_potential")), num_lp_vars(0) { task_properties::verify_no_axioms(task_proxy); task_properties::verify_no_conditional_effects(task_proxy); initialize(); } void PotentialOptimizer::initialize() { VariablesProxy vars = task_proxy.get_variables(); lp_var_ids.resize(vars.size()); fact_potentials.resize(vars.size()); for (VariableProxy var : vars) { // Add LP variable for "undefined" value. lp_var_ids[var.get_id()].resize(var.get_domain_size() + 1); for (int val = 0; val < var.get_domain_size() + 1; ++val) { lp_var_ids[var.get_id()][val] = num_lp_vars++; } fact_potentials[var.get_id()].resize(var.get_domain_size()); } construct_lp(); } bool PotentialOptimizer::has_optimal_solution() const { return lp_solver.has_optimal_solution(); } void PotentialOptimizer::optimize_for_state(const State &state) { optimize_for_samples({state} ); } int PotentialOptimizer::get_lp_var_id(const FactProxy &fact) const { int var_id = fact.get_variable().get_id(); int value = fact.get_value(); assert(utils::in_bounds(var_id, lp_var_ids)); assert(utils::in_bounds(value, lp_var_ids[var_id])); return lp_var_ids[var_id][value]; } void PotentialOptimizer::optimize_for_all_states() { if (!potentials_are_bounded()) { cerr << "Potentials must be bounded for all-states LP." << endl; utils::exit_with(ExitCode::SEARCH_INPUT_ERROR); } vector<double> coefficients(num_lp_vars, 0.0); for (FactProxy fact : task_proxy.get_variables().get_facts()) { coefficients[get_lp_var_id(fact)] = 1.0 / fact.get_variable().get_domain_size(); } lp_solver.set_objective_coefficients(coefficients); solve_and_extract(); if (!has_optimal_solution()) { ABORT("all-states LP unbounded even though potentials are bounded."); } } void PotentialOptimizer::optimize_for_samples(const vector<State> &samples) { vector<double> coefficients(num_lp_vars, 0.0); for (const State &state : samples) { for (FactProxy fact : state) { coefficients[get_lp_var_id(fact)] += 1.0; } } lp_solver.set_objective_coefficients(coefficients); solve_and_extract(); } const shared_ptr<AbstractTask> PotentialOptimizer::get_task() const { return task; } bool PotentialOptimizer::potentials_are_bounded() const { return max_potential != numeric_limits<double>::infinity(); } void PotentialOptimizer::construct_lp() { double upper_bound = (potentials_are_bounded() ? max_potential : lp_solver.get_infinity()); named_vector::NamedVector<lp::LPVariable> lp_variables; lp_variables.reserve(num_lp_vars); for (int lp_var_id = 0; lp_var_id < num_lp_vars; ++lp_var_id) { // Use dummy coefficient for now. Adapt coefficient later. lp_variables.emplace_back(-lp_solver.get_infinity(), upper_bound, 1.0); } named_vector::NamedVector<lp::LPConstraint> lp_constraints; for (OperatorProxy op : task_proxy.get_operators()) { // Create constraint: // Sum_{V in vars(eff(o))} (P_{V=pre(o)[V]} - P_{V=eff(o)[V]}) <= cost(o) unordered_map<int, int> var_to_precondition; for (FactProxy pre : op.get_preconditions()) { var_to_precondition[pre.get_variable().get_id()] = pre.get_value(); } lp::LPConstraint constraint(-lp_solver.get_infinity(), op.get_cost()); vector<pair<int, int>> coefficients; for (EffectProxy effect : op.get_effects()) { VariableProxy var = effect.get_fact().get_variable(); int var_id = var.get_id(); // Set pre to pre(op) if defined, otherwise to u = |dom(var)|. int pre = -1; auto it = var_to_precondition.find(var_id); if (it == var_to_precondition.end()) { pre = get_undefined_value(var); } else { pre = it->second; } int post = effect.get_fact().get_value(); int pre_lp = lp_var_ids[var_id][pre]; int post_lp = lp_var_ids[var_id][post]; assert(pre_lp != post_lp); coefficients.emplace_back(pre_lp, 1); coefficients.emplace_back(post_lp, -1); } sort(coefficients.begin(), coefficients.end()); for (const auto &coeff : coefficients) constraint.insert(coeff.first, coeff.second); lp_constraints.push_back(constraint); } /* Create full goal state. Use value |dom(V)| as "undefined" value for variables V undefined in the goal. */ vector<int> goal(task_proxy.get_variables().size(), -1); for (FactProxy fact : task_proxy.get_goals()) { goal[fact.get_variable().get_id()] = fact.get_value(); } for (VariableProxy var : task_proxy.get_variables()) { if (goal[var.get_id()] == -1) goal[var.get_id()] = get_undefined_value(var); } for (VariableProxy var : task_proxy.get_variables()) { /* Create constraint (using variable bounds): P_{V=goal[V]} = 0 When each variable has a goal value (including the "undefined" value), this is equivalent to the goal-awareness constraint \sum_{fact in goal} P_fact <= 0. We can't set the potential of one goal fact to +2 and another to -2, but if all variables have goal values, this is not beneficial anyway. */ int var_id = var.get_id(); lp::LPVariable &lp_var = lp_variables[lp_var_ids[var_id][goal[var_id]]]; lp_var.lower_bound = 0; lp_var.upper_bound = 0; int undef_val_lp = lp_var_ids[var_id][get_undefined_value(var)]; for (int val = 0; val < var.get_domain_size(); ++val) { int val_lp = lp_var_ids[var_id][val]; // Create constraint: P_{V=v} <= P_{V=u} // Note that we could eliminate variables P_{V=u} if V is // undefined in the goal. lp::LPConstraint constraint(-lp_solver.get_infinity(), 0); constraint.insert(val_lp, 1); constraint.insert(undef_val_lp, -1); lp_constraints.push_back(constraint); } } lp_solver.load_problem(lp::LinearProgram(lp::LPObjectiveSense::MAXIMIZE, move(lp_variables), move(lp_constraints))); } void PotentialOptimizer::solve_and_extract() { lp_solver.solve(); if (has_optimal_solution()) { extract_lp_solution(); } } void PotentialOptimizer::extract_lp_solution() { assert(has_optimal_solution()); const vector<double> solution = lp_solver.extract_solution(); for (FactProxy fact : task_proxy.get_variables().get_facts()) { fact_potentials[fact.get_variable().get_id()][fact.get_value()] = solution[get_lp_var_id(fact)]; } } unique_ptr<PotentialFunction> PotentialOptimizer::get_potential_function() const { assert(has_optimal_solution()); return utils::make_unique_ptr<PotentialFunction>(fact_potentials); } }
7,751
C++
35.914286
120
0.615921
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/util.cc
#include "util.h" #include "potential_function.h" #include "potential_optimizer.h" #include "../heuristic.h" #include "../option_parser.h" #include "../task_utils/sampling.h" #include "../utils/markup.h" #include <limits> using namespace std; namespace potentials { vector<State> sample_without_dead_end_detection( PotentialOptimizer &optimizer, int num_samples, utils::RandomNumberGenerator &rng) { const shared_ptr<AbstractTask> task = optimizer.get_task(); const TaskProxy task_proxy(*task); State initial_state = task_proxy.get_initial_state(); optimizer.optimize_for_state(initial_state); int init_h = optimizer.get_potential_function()->get_value(initial_state); sampling::RandomWalkSampler sampler(task_proxy, rng); vector<State> samples; samples.reserve(num_samples); for (int i = 0; i < num_samples; ++i) { samples.push_back(sampler.sample_state(init_h)); } return samples; } string get_admissible_potentials_reference() { return "The algorithm is based on" + utils::format_conference_reference( {"Jendrik Seipp", "Florian Pommerening", "Malte Helmert"}, "New Optimization Functions for Potential Heuristics", "https://ai.dmi.unibas.ch/papers/seipp-et-al-icaps2015.pdf", "Proceedings of the 25th International Conference on" " Automated Planning and Scheduling (ICAPS 2015)", "193-201", "AAAI Press", "2015"); } void prepare_parser_for_admissible_potentials(OptionParser &parser) { parser.document_language_support("action costs", "supported"); parser.document_language_support("conditional effects", "not supported"); parser.document_language_support("axioms", "not supported"); parser.document_property("admissible", "yes"); parser.document_property("consistent", "yes"); parser.document_property("safe", "yes"); parser.document_property("preferred operators", "no"); parser.add_option<double>( "max_potential", "Bound potentials by this number. Using the bound {{{infinity}}} " "disables the bounds. In some domains this makes the computation of " "weights unbounded in which case no weights can be extracted. Using " "very high weights can cause numerical instability in the LP solver, " "while using very low weights limits the choice of potential " "heuristics. For details, see the ICAPS paper cited above.", "1e8", Bounds("0.0", "infinity")); lp::add_lp_solver_option_to_parser(parser); Heuristic::add_options_to_parser(parser); } }
2,602
C++
36.724637
78
0.684089
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/plugin_group.cc
#include "../plugin.h" namespace potentials { static PluginGroupPlugin _plugin( "heuristics_potentials", "Potential Heuristics"); }
141
C++
16.749998
33
0.716312
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/potential_heuristic.h
#ifndef POTENTIALS_POTENTIAL_HEURISTIC_H #define POTENTIALS_POTENTIAL_HEURISTIC_H #include "../heuristic.h" #include <memory> namespace potentials { class PotentialFunction; /* Use an internal potential function to evaluate a given state. */ class PotentialHeuristic : public Heuristic { std::unique_ptr<PotentialFunction> function; protected: virtual int compute_heuristic(const State &ancestor_state) override; public: explicit PotentialHeuristic( const options::Options &opts, std::unique_ptr<PotentialFunction> function); // Define in .cc file to avoid include in header. ~PotentialHeuristic(); }; } #endif
648
C
21.37931
83
0.746914
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/potential_function.cc
#include "potential_function.h" #include "../task_proxy.h" #include "../utils/collections.h" #include <cmath> using namespace std; namespace potentials { PotentialFunction::PotentialFunction( const vector<vector<double>> &fact_potentials) : fact_potentials(fact_potentials) { } int PotentialFunction::get_value(const State &state) const { double heuristic_value = 0.0; for (FactProxy fact : state) { int var_id = fact.get_variable().get_id(); int value = fact.get_value(); assert(utils::in_bounds(var_id, fact_potentials)); assert(utils::in_bounds(value, fact_potentials[var_id])); heuristic_value += fact_potentials[var_id][value]; } const double epsilon = 0.01; return static_cast<int>(ceil(heuristic_value - epsilon)); } }
800
C++
25.699999
65
0.67
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/sample_based_potential_heuristics.cc
#include "potential_function.h" #include "potential_max_heuristic.h" #include "potential_optimizer.h" #include "util.h" #include "../option_parser.h" #include "../plugin.h" #include "../utils/rng.h" #include "../utils/rng_options.h" #include <memory> #include <vector> using namespace std; namespace potentials { static void filter_dead_ends(PotentialOptimizer &optimizer, vector<State> &samples) { assert(!optimizer.potentials_are_bounded()); vector<State> non_dead_end_samples; for (const State &sample : samples) { optimizer.optimize_for_state(sample); if (optimizer.has_optimal_solution()) non_dead_end_samples.push_back(sample); } swap(samples, non_dead_end_samples); } static void optimize_for_samples( PotentialOptimizer &optimizer, int num_samples, utils::RandomNumberGenerator &rng) { vector<State> samples = sample_without_dead_end_detection( optimizer, num_samples, rng); if (!optimizer.potentials_are_bounded()) { filter_dead_ends(optimizer, samples); } optimizer.optimize_for_samples(samples); } /* Compute multiple potential functions that are optimized for different sets of samples. */ static vector<unique_ptr<PotentialFunction>> create_sample_based_potential_functions( const Options &opts) { vector<unique_ptr<PotentialFunction>> functions; PotentialOptimizer optimizer(opts); shared_ptr<utils::RandomNumberGenerator> rng(utils::parse_rng_from_options(opts)); for (int i = 0; i < opts.get<int>("num_heuristics"); ++i) { optimize_for_samples(optimizer, opts.get<int>("num_samples"), *rng); functions.push_back(optimizer.get_potential_function()); } return functions; } static shared_ptr<Heuristic> _parse(OptionParser &parser) { parser.document_synopsis( "Sample-based potential heuristics", "Maximum over multiple potential heuristics optimized for samples. " + get_admissible_potentials_reference()); parser.add_option<int>( "num_heuristics", "number of potential heuristics", "1", Bounds("0", "infinity")); parser.add_option<int>( "num_samples", "Number of states to sample", "1000", Bounds("0", "infinity")); prepare_parser_for_admissible_potentials(parser); utils::add_rng_options(parser); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; return make_shared<PotentialMaxHeuristic>( opts, create_sample_based_potential_functions(opts)); } static Plugin<Evaluator> _plugin( "sample_based_potentials", _parse, "heuristics_potentials"); }
2,668
C++
30.4
86
0.678036
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/potential_heuristic.cc
#include "potential_heuristic.h" #include "potential_function.h" #include "../option_parser.h" using namespace std; namespace potentials { PotentialHeuristic::PotentialHeuristic( const Options &opts, unique_ptr<PotentialFunction> function) : Heuristic(opts), function(move(function)) { } PotentialHeuristic::~PotentialHeuristic() { } int PotentialHeuristic::compute_heuristic(const State &ancestor_state) { State state = convert_ancestor_state(ancestor_state); return max(0, function->get_value(state)); } }
536
C++
21.374999
72
0.738806
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/potential_max_heuristic.cc
#include "potential_max_heuristic.h" #include "potential_function.h" #include "../option_parser.h" using namespace std; namespace potentials { PotentialMaxHeuristic::PotentialMaxHeuristic( const Options &opts, vector<unique_ptr<PotentialFunction>> &&functions) : Heuristic(opts), functions(move(functions)) { } int PotentialMaxHeuristic::compute_heuristic(const State &ancestor_state) { State state = convert_ancestor_state(ancestor_state); int value = 0; for (auto &function : functions) { value = max(value, function->get_value(state)); } return value; } }
610
C++
22.499999
75
0.701639
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/potential_optimizer.h
#ifndef POTENTIALS_POTENTIAL_OPTIMIZER_H #define POTENTIALS_POTENTIAL_OPTIMIZER_H #include "../task_proxy.h" #include "../lp/lp_solver.h" #include <memory> #include <vector> namespace options { class Options; } namespace potentials { class PotentialFunction; /* Add admissible potential constraints to LP and allow optimizing for different objectives. The implementation is based on transforming the task into transition normal form (TNF) (Pommerening and Helmert, ICAPS 2015). We add an undefined value u to each variable's domain, but do not create forgetting operators or change existing operators explicitly. Instead, we ensure that all fact potentials of a variable V are less than or equal to the potential of V=u and implicitly set pre(op) to V=u for operators op where pre(op) is undefined. Similarly, we set s_\star(V) = u for variables V without a goal value. For more information we refer to the paper introducing potential heuristics Florian Pommerening, Malte Helmert, Gabriele Roeger and Jendrik Seipp. From Non-Negative to General Operator Cost Partitioning. AAAI 2015. and the paper comparing various optimization functions Jendrik Seipp, Florian Pommerening and Malte Helmert. New Optimization Functions for Potential Heuristics. ICAPS 2015. */ class PotentialOptimizer { std::shared_ptr<AbstractTask> task; TaskProxy task_proxy; lp::LPSolver lp_solver; const double max_potential; int num_lp_vars; std::vector<std::vector<int>> lp_var_ids; std::vector<std::vector<double>> fact_potentials; int get_lp_var_id(const FactProxy &fact) const; void initialize(); void construct_lp(); void solve_and_extract(); void extract_lp_solution(); public: explicit PotentialOptimizer(const options::Options &opts); ~PotentialOptimizer() = default; const std::shared_ptr<AbstractTask> get_task() const; bool potentials_are_bounded() const; void optimize_for_state(const State &state); void optimize_for_all_states(); void optimize_for_samples(const std::vector<State> &samples); bool has_optimal_solution() const; std::unique_ptr<PotentialFunction> get_potential_function() const; }; } #endif
2,234
C
28.025974
72
0.738585
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/diverse_potential_heuristics.h
#ifndef POTENTIALS_DIVERSE_POTENTIAL_HEURISTICS_H #define POTENTIALS_DIVERSE_POTENTIAL_HEURISTICS_H #include "potential_optimizer.h" #include <memory> #include <unordered_map> #include <vector> namespace utils { class RandomNumberGenerator; } namespace potentials { using SamplesToFunctionsMap = utils::HashMap<State, std::unique_ptr<PotentialFunction>>; /* Factory class that finds diverse potential functions. */ class DiversePotentialHeuristics { PotentialOptimizer optimizer; // TODO: Remove max_num_heuristics and control number of heuristics // with num_samples parameter? const int max_num_heuristics; const int num_samples; std::shared_ptr<utils::RandomNumberGenerator> rng; std::vector<std::unique_ptr<PotentialFunction>> diverse_functions; /* Filter dead end samples and duplicates. Store potential heuristics for remaining samples. */ SamplesToFunctionsMap filter_samples_and_compute_functions( const std::vector<State> &samples); // Remove all samples for which the function achieves maximal values. void remove_covered_samples( const PotentialFunction &chosen_function, SamplesToFunctionsMap &samples_to_functions) const; /* Return potential function optimized for remaining samples or a precomputed heuristic if the former does not cover additional samples. */ std::unique_ptr<PotentialFunction> find_function_and_remove_covered_samples( SamplesToFunctionsMap &samples_to_functions); /* Iteratively try to find potential functions that achieve maximal values for as many samples as possible. */ void cover_samples(SamplesToFunctionsMap &samples_to_functions); public: explicit DiversePotentialHeuristics(const options::Options &opts); ~DiversePotentialHeuristics() = default; // Sample states, then cover them. std::vector<std::unique_ptr<PotentialFunction>> find_functions(); }; } #endif
1,949
C
32.620689
80
0.748076
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/potential_function.h
#ifndef POTENTIALS_POTENTIAL_FUNCTION_H #define POTENTIALS_POTENTIAL_FUNCTION_H #include <vector> class State; namespace potentials { /* A potential function calculates the sum of potentials in a given state. We decouple potential functions from potential heuristics to avoid the overhead that is induced by evaluating heuristics whenever possible. */ class PotentialFunction { const std::vector<std::vector<double>> fact_potentials; public: explicit PotentialFunction( const std::vector<std::vector<double>> &fact_potentials); ~PotentialFunction() = default; int get_value(const State &state) const; }; } #endif
650
C
22.249999
73
0.750769
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/potentials/util.h
#ifndef POTENTIALS_UTIL_H #define POTENTIALS_UTIL_H #include <memory> #include <string> #include <vector> class State; namespace options { class OptionParser; } namespace utils { class RandomNumberGenerator; } namespace potentials { class PotentialOptimizer; std::vector<State> sample_without_dead_end_detection( PotentialOptimizer &optimizer, int num_samples, utils::RandomNumberGenerator &rng); std::string get_admissible_potentials_reference(); void prepare_parser_for_admissible_potentials(options::OptionParser &parser); } #endif
555
C
16.935483
77
0.772973
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_h_m.cc
#include "landmark_factory_h_m.h" #include "exploration.h" #include "../abstract_task.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_utils/task_properties.h" #include "../utils/collections.h" #include "../utils/logging.h" #include "../utils/system.h" using namespace std; using utils::ExitCode; namespace landmarks { // alist = alist \cup other template<typename T> void union_with(list<T> &alist, const list<T> &other) { typename list<T>::iterator it1 = alist.begin(); typename list<T>::const_iterator it2 = other.begin(); while ((it1 != alist.end()) && (it2 != other.end())) { if (*it1 < *it2) { ++it1; } else if (*it1 > *it2) { alist.insert(it1, *it2); ++it2; } else { ++it1; ++it2; } } alist.insert(it1, it2, other.end()); } // alist = alist \cap other template<typename T> void intersect_with(list<T> &alist, const list<T> &other) { typename list<T>::iterator it1 = alist.begin(), tmp; typename list<T>::const_iterator it2 = other.begin(); while ((it1 != alist.end()) && (it2 != other.end())) { if (*it1 < *it2) { tmp = it1; ++tmp; alist.erase(it1); it1 = tmp; } else if (*it1 > *it2) { ++it2; } else { ++it1; ++it2; } } alist.erase(it1, alist.end()); } // alist = alist \setminus other template<typename T> void set_minus(list<T> &alist, const list<T> &other) { typename list<T>::iterator it1 = alist.begin(), tmp; typename list<T>::const_iterator it2 = other.begin(); while ((it1 != alist.end()) && (it2 != other.end())) { if (*it1 < *it2) { ++it1; } else if (*it1 > *it2) { ++it2; } else { tmp = it1; ++tmp; alist.erase(it1); it1 = tmp; ++it2; } } } // alist = alist \cup {val} template<typename T> void insert_into(list<T> &alist, const T &val) { typename list<T>::iterator it1 = alist.begin(); while (it1 != alist.end()) { if (*it1 > val) { alist.insert(it1, val); return; } else if (*it1 < val) { ++it1; } else { return; } } alist.insert(it1, val); } template<typename T> static bool contains(list<T> &alist, const T &val) { return find(alist.begin(), alist.end(), val) != alist.end(); } // find partial variable assignments with size m or less // (look at all the variables in the problem) void LandmarkFactoryHM::get_m_sets_(const VariablesProxy &variables, int m, int num_included, int current_var, FluentSet &current, vector<FluentSet> &subsets) { int num_variables = variables.size(); if (num_included == m) { subsets.push_back(current); return; } if (current_var == num_variables) { if (num_included != 0) { subsets.push_back(current); } return; } // include a value of current_var in the set for (int i = 0; i < variables[current_var].get_domain_size(); ++i) { bool use_var = true; FactPair current_var_fact(current_var, i); for (const FactPair &current_fact : current) { if (!interesting(variables, current_var_fact, current_fact)) { use_var = false; break; } } if (use_var) { current.push_back(current_var_fact); get_m_sets_(variables, m, num_included + 1, current_var + 1, current, subsets); current.pop_back(); } } // don't include a value of current_var in the set get_m_sets_(variables, m, num_included, current_var + 1, current, subsets); } // find all size m or less subsets of superset void LandmarkFactoryHM::get_m_sets_of_set(const VariablesProxy &variables, int m, int num_included, int current_var_index, FluentSet &current, vector<FluentSet> &subsets, const FluentSet &superset) { if (num_included == m) { subsets.push_back(current); return; } if (current_var_index == static_cast<int>(superset.size())) { if (num_included != 0) { subsets.push_back(current); } return; } bool use_var = true; for (const FactPair &fluent : current) { if (!interesting(variables, superset[current_var_index], fluent)) { use_var = false; break; } } if (use_var) { // include current fluent in the set current.push_back(superset[current_var_index]); get_m_sets_of_set(variables, m, num_included + 1, current_var_index + 1, current, subsets, superset); current.pop_back(); } // don't include current fluent in set get_m_sets_of_set(variables, m, num_included, current_var_index + 1, current, subsets, superset); } // get subsets of superset1 \cup superset2 with size m or less, // such that they have >= 1 elements from each set. void LandmarkFactoryHM::get_split_m_sets( const VariablesProxy &variables, int m, int ss1_num_included, int ss2_num_included, int ss1_var_index, int ss2_var_index, FluentSet &current, vector<FluentSet> &subsets, const FluentSet &superset1, const FluentSet &superset2) { /* if( ((ss1_var_index == superset1.size()) && (ss1_num_included == 0)) || ((ss2_var_index == superset2.size()) && (ss2_num_included == 0)) ) { return; } */ int sup1_size = superset1.size(); int sup2_size = superset2.size(); if (ss1_num_included + ss2_num_included == m || (ss1_var_index == sup1_size && ss2_var_index == sup2_size)) { // if set is empty, don't have to include from it if ((ss1_num_included > 0 || sup1_size == 0) && (ss2_num_included > 0 || sup2_size == 0)) { subsets.push_back(current); } return; } bool use_var = true; if (ss1_var_index != sup1_size && (ss2_var_index == sup2_size || superset1[ss1_var_index] < superset2[ss2_var_index])) { for (const FactPair &fluent : current) { if (!interesting(variables, superset1[ss1_var_index], fluent)) { use_var = false; break; } } if (use_var) { // include current.push_back(superset1[ss1_var_index]); get_split_m_sets(variables, m, ss1_num_included + 1, ss2_num_included, ss1_var_index + 1, ss2_var_index, current, subsets, superset1, superset2); current.pop_back(); } // don't include get_split_m_sets(variables, m, ss1_num_included, ss2_num_included, ss1_var_index + 1, ss2_var_index, current, subsets, superset1, superset2); } else { for (const FactPair &fluent : current) { if (!interesting(variables, superset2[ss2_var_index], fluent)) { use_var = false; break; } } if (use_var) { // include current.push_back(superset2[ss2_var_index]); get_split_m_sets(variables, m, ss1_num_included, ss2_num_included + 1, ss1_var_index, ss2_var_index + 1, current, subsets, superset1, superset2); current.pop_back(); } // don't include get_split_m_sets(variables, m, ss1_num_included, ss2_num_included, ss1_var_index, ss2_var_index + 1, current, subsets, superset1, superset2); } } // use together is method that determines whether the two variables are interesting together, // e.g. we don't want to represent (truck1-loc x, truck2-loc y) type stuff // get partial assignments of size <= m in the problem void LandmarkFactoryHM::get_m_sets(const VariablesProxy &variables, int m, vector<FluentSet> &subsets) { FluentSet c; get_m_sets_(variables, m, 0, 0, c, subsets); } // get subsets of superset with size <= m void LandmarkFactoryHM::get_m_sets(const VariablesProxy &variables, int m, vector<FluentSet> &subsets, const FluentSet &superset) { FluentSet c; get_m_sets_of_set(variables, m, 0, 0, c, subsets, superset); } // second function to get subsets of size at most m that // have at least one element in ss1 and same in ss2 // assume disjoint void LandmarkFactoryHM::get_split_m_sets( const VariablesProxy &variables, int m, vector<FluentSet> &subsets, const FluentSet &superset1, const FluentSet &superset2) { FluentSet c; get_split_m_sets(variables, m, 0, 0, 0, 0, c, subsets, superset1, superset2); } // get subsets of state with size <= m void LandmarkFactoryHM::get_m_sets(const VariablesProxy &variables, int m, vector<FluentSet> &subsets, const State &state) { FluentSet state_fluents; for (FactProxy fact : state) { state_fluents.push_back(fact.get_pair()); } get_m_sets(variables, m, subsets, state_fluents); } void LandmarkFactoryHM::print_proposition(const VariablesProxy &variables, const FactPair &fluent) const { VariableProxy var = variables[fluent.var]; FactProxy fact = var.get_fact(fluent.value); utils::g_log << fact.get_name() << " (" << var.get_name() << "(" << fact.get_variable().get_id() << ")" << "->" << fact.get_value() << ")"; } static FluentSet get_operator_precondition(const OperatorProxy &op) { FluentSet preconditions = task_properties::get_fact_pairs(op.get_preconditions()); sort(preconditions.begin(), preconditions.end()); return preconditions; } // get facts that are always true after the operator application // (effects plus prevail conditions) static FluentSet get_operator_postcondition(int num_vars, const OperatorProxy &op) { FluentSet postconditions; EffectsProxy effects = op.get_effects(); vector<bool> has_effect_on_var(num_vars, false); for (EffectProxy effect : effects) { FactProxy effect_fact = effect.get_fact(); postconditions.push_back(effect_fact.get_pair()); has_effect_on_var[effect_fact.get_variable().get_id()] = true; } for (FactProxy precondition : op.get_preconditions()) { if (!has_effect_on_var[precondition.get_variable().get_id()]) postconditions.push_back(precondition.get_pair()); } sort(postconditions.begin(), postconditions.end()); return postconditions; } void LandmarkFactoryHM::print_pm_op(const VariablesProxy &variables, const PMOp &op) { set<FactPair> pcs, effs, cond_pc, cond_eff; vector<pair<set<FactPair>, set<FactPair>>> conds; for (int pc : op.pc) { for (const FactPair &fluent : h_m_table_[pc].fluents) { pcs.insert(fluent); } } for (int eff : op.eff) { for (const FactPair &fluent : h_m_table_[eff].fluents) { effs.insert(fluent); } } for (size_t i = 0; i < op.cond_noops.size(); ++i) { cond_pc.clear(); cond_eff.clear(); int pm_fluent; size_t j; utils::g_log << "PC:" << endl; for (j = 0; (pm_fluent = op.cond_noops[i][j]) != -1; ++j) { print_fluentset(variables, h_m_table_[pm_fluent].fluents); utils::g_log << endl; for (size_t k = 0; k < h_m_table_[pm_fluent].fluents.size(); ++k) { cond_pc.insert(h_m_table_[pm_fluent].fluents[k]); } } // advance to effects section utils::g_log << endl; ++j; utils::g_log << "EFF:" << endl; for (; j < op.cond_noops[i].size(); ++j) { int pm_fluent = op.cond_noops[i][j]; print_fluentset(variables, h_m_table_[pm_fluent].fluents); utils::g_log << endl; for (size_t k = 0; k < h_m_table_[pm_fluent].fluents.size(); ++k) { cond_eff.insert(h_m_table_[pm_fluent].fluents[k]); } } conds.emplace_back(cond_pc, cond_eff); utils::g_log << endl << endl << endl; } utils::g_log << "Action " << op.index << endl; utils::g_log << "Precondition: "; for (const FactPair &pc : pcs) { print_proposition(variables, pc); utils::g_log << " "; } utils::g_log << endl << "Effect: "; for (const FactPair &eff : effs) { print_proposition(variables, eff); utils::g_log << " "; } utils::g_log << endl << "Conditionals: " << endl; int i = 0; for (const auto &cond : conds) { utils::g_log << "Cond PC #" << i++ << ":" << endl << "\t"; for (const FactPair &pc : cond.first) { print_proposition(variables, pc); utils::g_log << " "; } utils::g_log << endl << "Cond Effect #" << i << ":" << endl << "\t"; for (const FactPair &eff : cond.second) { print_proposition(variables, eff); utils::g_log << " "; } utils::g_log << endl << endl; } } void LandmarkFactoryHM::print_fluentset(const VariablesProxy &variables, const FluentSet &fs) { utils::g_log << "( "; for (const FactPair &fact : fs) { print_proposition(variables, fact); utils::g_log << " "; } utils::g_log << ")"; } // check whether fs2 is a possible noop set for action with fs1 as effect // sets cannot be 1) defined on same variable, 2) otherwise mutex bool LandmarkFactoryHM::possible_noop_set(const VariablesProxy &variables, const FluentSet &fs1, const FluentSet &fs2) { FluentSet::const_iterator fs1it = fs1.begin(), fs2it = fs2.begin(); while (fs1it != fs1.end() && fs2it != fs2.end()) { if (fs1it->var == fs2it->var) { return false; } else if (fs1it->var < fs2it->var) { ++fs1it; } else { ++fs2it; } } for (const FactPair &fluent1 : fs1) { FactProxy fact1 = variables[fluent1.var].get_fact(fluent1.value); for (const FactPair &fluent2 : fs2) { if (fact1.is_mutex( variables[fluent2.var].get_fact(fluent2.value))) return false; } } return true; } // make the operators of the P_m problem void LandmarkFactoryHM::build_pm_ops(const TaskProxy &task_proxy) { FluentSet pc, eff; vector<FluentSet> pc_subsets, eff_subsets, noop_pc_subsets, noop_eff_subsets; static int op_count = 0; int set_index, noop_index; OperatorsProxy operators = task_proxy.get_operators(); pm_ops_.resize(operators.size()); // set unsatisfied precondition counts, used in fixpoint calculation unsat_pc_count_.resize(operators.size()); VariablesProxy variables = task_proxy.get_variables(); // transfer ops from original problem // represent noops as "conditional" effects for (OperatorProxy op : operators) { PMOp &pm_op = pm_ops_[op.get_id()]; pm_op.index = op_count++; pc_subsets.clear(); eff_subsets.clear(); // preconditions of P_m op are all subsets of original pc pc = get_operator_precondition(op); get_m_sets(variables, m_, pc_subsets, pc); pm_op.pc.reserve(pc_subsets.size()); // set unsatisfied pc count for op unsat_pc_count_[op.get_id()].first = pc_subsets.size(); for (const FluentSet &pc_subset : pc_subsets) { assert(set_indices_.find(pc_subset) != set_indices_.end()); set_index = set_indices_[pc_subset]; pm_op.pc.push_back(set_index); h_m_table_[set_index].pc_for.emplace_back(op.get_id(), -1); } // same for effects eff = get_operator_postcondition(variables.size(), op); get_m_sets(variables, m_, eff_subsets, eff); pm_op.eff.reserve(eff_subsets.size()); for (const FluentSet &eff_subset : eff_subsets) { assert(set_indices_.find(eff_subset) != set_indices_.end()); set_index = set_indices_[eff_subset]; pm_op.eff.push_back(set_index); } noop_index = 0; // For all subsets used in the problem with size *<* m, check whether // they conflict with the effect of the operator (no need to check pc // because mvvs appearing in pc also appear in effect FluentSetToIntMap::const_iterator it = set_indices_.begin(); while (static_cast<int>(it->first.size()) < m_ && it != set_indices_.end()) { if (possible_noop_set(variables, eff, it->first)) { // for each such set, add a "conditional effect" to the operator pm_op.cond_noops.resize(pm_op.cond_noops.size() + 1); vector<int> &this_cond_noop = pm_op.cond_noops.back(); noop_pc_subsets.clear(); noop_eff_subsets.clear(); // get the subsets that have >= 1 element in the pc (unless pc is empty) // and >= 1 element in the other set get_split_m_sets(variables, m_, noop_pc_subsets, pc, it->first); get_split_m_sets(variables, m_, noop_eff_subsets, eff, it->first); this_cond_noop.reserve(noop_pc_subsets.size() + noop_eff_subsets.size() + 1); unsat_pc_count_[op.get_id()].second.push_back(noop_pc_subsets.size()); // push back all noop preconditions for (size_t j = 0; j < noop_pc_subsets.size(); ++j) { assert(static_cast<int>(noop_pc_subsets[j].size()) <= m_); assert(set_indices_.find(noop_pc_subsets[j]) != set_indices_.end()); set_index = set_indices_[noop_pc_subsets[j]]; this_cond_noop.push_back(set_index); // these facts are "conditional pcs" for this action h_m_table_[set_index].pc_for.emplace_back(op.get_id(), noop_index); } // separator this_cond_noop.push_back(-1); // and the noop effects for (size_t j = 0; j < noop_eff_subsets.size(); ++j) { assert(static_cast<int>(noop_eff_subsets[j].size()) <= m_); assert(set_indices_.find(noop_eff_subsets[j]) != set_indices_.end()); set_index = set_indices_[noop_eff_subsets[j]]; this_cond_noop.push_back(set_index); } ++noop_index; } ++it; } // print_pm_op(pm_ops_[i]); } } bool LandmarkFactoryHM::interesting(const VariablesProxy &variables, const FactPair &fact1, const FactPair &fact2) const { // mutexes can always be safely pruned return !variables[fact1.var].get_fact(fact1.value).is_mutex( variables[fact2.var].get_fact(fact2.value)); } LandmarkFactoryHM::LandmarkFactoryHM(const options::Options &opts) : m_(opts.get<int>("m")), conjunctive_landmarks(opts.get<bool>("conjunctive_landmarks")), use_orders(opts.get<bool>("use_orders")) { } void LandmarkFactoryHM::initialize(const TaskProxy &task_proxy) { utils::g_log << "h^m landmarks m=" << m_ << endl; if (!task_proxy.get_axioms().empty()) { cerr << "h^m landmarks don't support axioms" << endl; utils::exit_with(ExitCode::SEARCH_UNSUPPORTED); } // Get all the m or less size subsets in the domain. vector<vector<FactPair>> msets; get_m_sets(task_proxy.get_variables(), m_, msets); // map each set to an integer for (size_t i = 0; i < msets.size(); ++i) { h_m_table_.emplace_back(); set_indices_[msets[i]] = i; h_m_table_[i].fluents = msets[i]; } utils::g_log << "Using " << h_m_table_.size() << " P^m fluents." << endl; build_pm_ops(task_proxy); } void LandmarkFactoryHM::postprocess(const TaskProxy &task_proxy) { if (!conjunctive_landmarks) discard_conjunctive_landmarks(); lm_graph->set_landmark_ids(); if (!use_orders) discard_all_orderings(); mk_acyclic_graph(); calc_achievers(task_proxy); } void LandmarkFactoryHM::discard_conjunctive_landmarks() { if (lm_graph->get_num_conjunctive_landmarks() > 0) { utils::g_log << "Discarding " << lm_graph->get_num_conjunctive_landmarks() << " conjunctive landmarks" << endl; lm_graph->remove_node_if( [](const LandmarkNode &node) {return node.conjunctive;}); } } void LandmarkFactoryHM::calc_achievers(const TaskProxy &task_proxy) { utils::g_log << "Calculating achievers." << endl; OperatorsProxy operators = task_proxy.get_operators(); VariablesProxy variables = task_proxy.get_variables(); // first_achievers are already filled in by compute_h_m_landmarks // here only have to do possible_achievers for (auto &lmn : lm_graph->get_nodes()) { set<int> candidates; // put all possible adders in candidates set for (const FactPair &lm_fact : lmn->facts) { const vector<int> &ops = get_operators_including_eff(lm_fact); candidates.insert(ops.begin(), ops.end()); } for (int op_id : candidates) { FluentSet post = get_operator_postcondition(variables.size(), operators[op_id]); FluentSet pre = get_operator_precondition(operators[op_id]); size_t j; for (j = 0; j < lmn->facts.size(); ++j) { const FactPair &lm_fact = lmn->facts[j]; // action adds this element of lm as well if (find(post.begin(), post.end(), lm_fact) != post.end()) continue; bool is_mutex = false; for (const FactPair &fluent : post) { if (variables[fluent.var].get_fact(fluent.value).is_mutex( variables[lm_fact.var].get_fact(lm_fact.value))) { is_mutex = true; break; } } if (is_mutex) { break; } for (const FactPair &fluent : pre) { // we know that lm_val is not added by the operator // so if it incompatible with the pc, this can't be an achiever if (variables[fluent.var].get_fact(fluent.value).is_mutex( variables[lm_fact.var].get_fact(lm_fact.value))) { is_mutex = true; break; } } if (is_mutex) { break; } } if (j == lmn->facts.size()) { // not inconsistent with any of the other landmark fluents lmn->possible_achievers.insert(op_id); } } } } void LandmarkFactoryHM::free_unneeded_memory() { utils::release_vector_memory(h_m_table_); utils::release_vector_memory(pm_ops_); utils::release_vector_memory(unsat_pc_count_); set_indices_.clear(); lm_node_table_.clear(); } // called when a fact is discovered or its landmarks change // to trigger required actions at next level // newly_discovered = first time fact becomes reachable void LandmarkFactoryHM::propagate_pm_fact(int factindex, bool newly_discovered, TriggerSet &trigger) { // for each action/noop for which fact is a pc for (const FactPair &info : h_m_table_[factindex].pc_for) { // a pc for the action itself if (info.value == -1) { if (newly_discovered) { --unsat_pc_count_[info.var].first; } // add to queue if unsatcount at 0 if (unsat_pc_count_[info.var].first == 0) { // create empty set or clear prev entries -- signals do all possible noop effects trigger[info.var].clear(); } } // a pc for a conditional noop else { if (newly_discovered) { --unsat_pc_count_[info.var].second[info.value]; } // if associated action is applicable, and effect has become applicable // (if associated action is not applicable, all noops will be used when it first does) if ((unsat_pc_count_[info.var].first == 0) && (unsat_pc_count_[info.var].second[info.value] == 0)) { // if not already triggering all noops, add this one if ((trigger.find(info.var) == trigger.end()) || (!trigger[info.var].empty())) { trigger[info.var].insert(info.value); } } } } } void LandmarkFactoryHM::compute_h_m_landmarks(const TaskProxy &task_proxy) { // get subsets of initial state vector<FluentSet> init_subsets; get_m_sets(task_proxy.get_variables(), m_, init_subsets, task_proxy.get_initial_state()); TriggerSet current_trigger, next_trigger; // for all of the initial state <= m subsets, mark level = 0 for (size_t i = 0; i < init_subsets.size(); ++i) { int index = set_indices_[init_subsets[i]]; h_m_table_[index].level = 0; // set actions to be applied propagate_pm_fact(index, true, current_trigger); } // mark actions with no precondition to be applied for (size_t i = 0; i < pm_ops_.size(); ++i) { if (unsat_pc_count_[i].first == 0) { // create empty set or clear prev entries current_trigger[i].clear(); } } vector<int>::iterator it; TriggerSet::iterator op_it; list<int> local_landmarks; list<int> local_necessary; size_t prev_size; int level = 1; // while we have actions to apply while (!current_trigger.empty()) { for (op_it = current_trigger.begin(); op_it != current_trigger.end(); ++op_it) { local_landmarks.clear(); local_necessary.clear(); int op_index = op_it->first; PMOp &action = pm_ops_[op_index]; // gather landmarks for pcs // in the set of landmarks for each fact, the fact itself is not stored // (only landmarks preceding it) for (it = action.pc.begin(); it != action.pc.end(); ++it) { union_with(local_landmarks, h_m_table_[*it].landmarks); insert_into(local_landmarks, *it); if (use_orders) { insert_into(local_necessary, *it); } } for (it = action.eff.begin(); it != action.eff.end(); ++it) { if (h_m_table_[*it].level != -1) { prev_size = h_m_table_[*it].landmarks.size(); intersect_with(h_m_table_[*it].landmarks, local_landmarks); // if the add effect appears in local landmarks, // fact is being achieved for >1st time // no need to intersect for gn orderings // or add op to first achievers if (!contains(local_landmarks, *it)) { insert_into(h_m_table_[*it].first_achievers, op_index); if (use_orders) { intersect_with(h_m_table_[*it].necessary, local_necessary); } } if (h_m_table_[*it].landmarks.size() != prev_size) propagate_pm_fact(*it, false, next_trigger); } else { h_m_table_[*it].level = level; h_m_table_[*it].landmarks = local_landmarks; if (use_orders) { h_m_table_[*it].necessary = local_necessary; } insert_into(h_m_table_[*it].first_achievers, op_index); propagate_pm_fact(*it, true, next_trigger); } } // landmarks changed for action itself, have to recompute // landmarks for all noop effects if (op_it->second.empty()) { for (size_t i = 0; i < action.cond_noops.size(); ++i) { // actions pcs are satisfied, but cond. effects may still have // unsatisfied pcs if (unsat_pc_count_[op_index].second[i] == 0) { compute_noop_landmarks(op_index, i, local_landmarks, local_necessary, level, next_trigger); } } } // only recompute landmarks for conditions whose // landmarks have changed else { for (set<int>::iterator noop_it = op_it->second.begin(); noop_it != op_it->second.end(); ++noop_it) { assert(unsat_pc_count_[op_index].second[*noop_it] == 0); compute_noop_landmarks(op_index, *noop_it, local_landmarks, local_necessary, level, next_trigger); } } } current_trigger.swap(next_trigger); next_trigger.clear(); utils::g_log << "Level " << level << " completed." << endl; ++level; } utils::g_log << "h^m landmarks computed." << endl; } void LandmarkFactoryHM::compute_noop_landmarks( int op_index, int noop_index, list<int> const &local_landmarks, list<int> const &local_necessary, int level, TriggerSet &next_trigger) { list<int> cn_necessary, cn_landmarks; size_t prev_size; int pm_fluent; PMOp &action = pm_ops_[op_index]; vector<int> &pc_eff_pair = action.cond_noops[noop_index]; cn_landmarks.clear(); cn_landmarks = local_landmarks; if (use_orders) { cn_necessary.clear(); cn_necessary = local_necessary; } size_t i; for (i = 0; (pm_fluent = pc_eff_pair[i]) != -1; ++i) { union_with(cn_landmarks, h_m_table_[pm_fluent].landmarks); insert_into(cn_landmarks, pm_fluent); if (use_orders) { insert_into(cn_necessary, pm_fluent); } } // go to the beginning of the effects section ++i; for (; i < pc_eff_pair.size(); ++i) { pm_fluent = pc_eff_pair[i]; if (h_m_table_[pm_fluent].level != -1) { prev_size = h_m_table_[pm_fluent].landmarks.size(); intersect_with(h_m_table_[pm_fluent].landmarks, cn_landmarks); // if the add effect appears in cn_landmarks, // fact is being achieved for >1st time // no need to intersect for gn orderings // or add op to first achievers if (!contains(cn_landmarks, pm_fluent)) { insert_into(h_m_table_[pm_fluent].first_achievers, op_index); if (use_orders) { intersect_with(h_m_table_[pm_fluent].necessary, cn_necessary); } } if (h_m_table_[pm_fluent].landmarks.size() != prev_size) propagate_pm_fact(pm_fluent, false, next_trigger); } else { h_m_table_[pm_fluent].level = level; h_m_table_[pm_fluent].landmarks = cn_landmarks; if (use_orders) { h_m_table_[pm_fluent].necessary = cn_necessary; } insert_into(h_m_table_[pm_fluent].first_achievers, op_index); propagate_pm_fact(pm_fluent, true, next_trigger); } } } void LandmarkFactoryHM::add_lm_node(int set_index, bool goal) { set<FactPair> lm; map<int, LandmarkNode *>::iterator it = lm_node_table_.find(set_index); if (it == lm_node_table_.end()) { for (const FactPair &fluent : h_m_table_[set_index].fluents) { lm.insert(fluent); } LandmarkNode *node; if (lm.size() > 1) { // conjunctive landmark node = &lm_graph->add_conjunctive_landmark(lm); } else { // simple landmark node = &lm_graph->add_simple_landmark(h_m_table_[set_index].fluents[0]); } node->is_true_in_goal = goal; node->first_achievers.insert(h_m_table_[set_index].first_achievers.begin(), h_m_table_[set_index].first_achievers.end()); lm_node_table_[set_index] = node; } } void LandmarkFactoryHM::generate_landmarks( const shared_ptr<AbstractTask> &task) { TaskProxy task_proxy(*task); initialize(task_proxy); compute_h_m_landmarks(task_proxy); // now construct landmarks graph vector<FluentSet> goal_subsets; FluentSet goals = task_properties::get_fact_pairs(task_proxy.get_goals()); VariablesProxy variables = task_proxy.get_variables(); get_m_sets(variables, m_, goal_subsets, goals); list<int> all_lms; for (const FluentSet &goal_subset : goal_subsets) { assert(set_indices_.find(goal_subset) != set_indices_.end()); int set_index = set_indices_[goal_subset]; if (h_m_table_[set_index].level == -1) { utils::g_log << endl << endl << "Subset of goal not reachable !!." << endl << endl << endl; utils::g_log << "Subset is: "; print_fluentset(variables, h_m_table_[set_index].fluents); utils::g_log << endl; } // set up goals landmarks for processing union_with(all_lms, h_m_table_[set_index].landmarks); // the goal itself is also a lm insert_into(all_lms, set_index); // make a node for the goal, with in_goal = true; add_lm_node(set_index, true); } // now make remaining lm nodes for (int lm : all_lms) { add_lm_node(lm, false); } if (use_orders) { // do reduction of graph // if f2 is landmark for f1, subtract landmark set of f2 from that of f1 for (int f1 : all_lms) { list<int> everything_to_remove; for (int f2 : h_m_table_[f1].landmarks) { union_with(everything_to_remove, h_m_table_[f2].landmarks); } set_minus(h_m_table_[f1].landmarks, everything_to_remove); // remove necessaries here, otherwise they will be overwritten // since we are writing them as greedy nec. orderings. if (use_orders) set_minus(h_m_table_[f1].landmarks, h_m_table_[f1].necessary); } // and add the edges for (int set_index : all_lms) { for (int lm : h_m_table_[set_index].landmarks) { assert(lm_node_table_.find(lm) != lm_node_table_.end()); assert(lm_node_table_.find(set_index) != lm_node_table_.end()); edge_add(*lm_node_table_[lm], *lm_node_table_[set_index], EdgeType::NATURAL); } if (use_orders) { for (int gn : h_m_table_[set_index].necessary) { edge_add(*lm_node_table_[gn], *lm_node_table_[set_index], EdgeType::GREEDY_NECESSARY); } } } } free_unneeded_memory(); postprocess(task_proxy); } bool LandmarkFactoryHM::computes_reasonable_orders() const { return false; } bool LandmarkFactoryHM::supports_conditional_effects() const { return false; } static shared_ptr<LandmarkFactory> _parse(OptionParser &parser) { parser.document_synopsis( "h^m Landmarks", "The landmark generation method introduced by " "Keyder, Richter & Helmert (ECAI 2010)."); parser.add_option<int>( "m", "subset size (if unsure, use the default of 2)", "2"); parser.add_option<bool>( "conjunctive_landmarks", "keep conjunctive landmarks", "true"); _add_use_orders_option_to_parser(parser); Options opts = parser.parse(); if (parser.help_mode()) return nullptr; parser.document_language_support("conditional_effects", "ignored, i.e. not supported"); if (parser.dry_run()) return nullptr; else return make_shared<LandmarkFactoryHM>(opts); } static Plugin<LandmarkFactory> _plugin("lm_hm", _parse); }
37,106
C++
34.991271
110
0.540371
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_cost_assignment.cc
#include "landmark_cost_assignment.h" #include "landmark_graph.h" #include "landmark_status_manager.h" #include "util.h" #include "../utils/collections.h" #include "../utils/language.h" #include <algorithm> #include <cstdlib> #include <functional> #include <iostream> #include <limits> using namespace std; namespace landmarks { LandmarkCostAssignment::LandmarkCostAssignment( const vector<int> &operator_costs, const LandmarkGraph &graph) : empty(), lm_graph(graph), operator_costs(operator_costs) { } const set<int> &LandmarkCostAssignment::get_achievers( int lmn_status, const LandmarkNode &lmn) const { // Return relevant achievers of the landmark according to its status. if (lmn_status == lm_not_reached) return lmn.first_achievers; else if (lmn_status == lm_needed_again) return lmn.possible_achievers; else return empty; } // Uniform cost partioning LandmarkUniformSharedCostAssignment::LandmarkUniformSharedCostAssignment( const vector<int> &operator_costs, const LandmarkGraph &graph, bool use_action_landmarks) : LandmarkCostAssignment(operator_costs, graph), use_action_landmarks(use_action_landmarks) { } double LandmarkUniformSharedCostAssignment::cost_sharing_h_value( const LandmarkStatusManager &lm_status_manager) { vector<int> achieved_lms_by_op(operator_costs.size(), 0); vector<bool> action_landmarks(operator_costs.size(), false); const LandmarkGraph::Nodes &nodes = lm_graph.get_nodes(); double h = 0; /* First pass: compute which op achieves how many landmarks. Along the way, mark action landmarks and add their cost to h. */ for (auto &node : nodes) { int lmn_status = lm_status_manager.get_landmark_status(node->get_id()); if (lmn_status != lm_reached) { const set<int> &achievers = get_achievers(lmn_status, *node); assert(!achievers.empty()); if (use_action_landmarks && achievers.size() == 1) { // We have found an action landmark for this state. int op_id = *achievers.begin(); if (!action_landmarks[op_id]) { action_landmarks[op_id] = true; assert(utils::in_bounds(op_id, operator_costs)); h += operator_costs[op_id]; } } else { for (int op_id : achievers) { assert(utils::in_bounds(op_id, achieved_lms_by_op)); ++achieved_lms_by_op[op_id]; } } } } vector<LandmarkNode *> relevant_lms; /* Second pass: remove landmarks from consideration that are covered by an action landmark; decrease the counters accordingly so that no unnecessary cost is assigned to these landmarks. */ for (auto &node : nodes) { int lmn_status = lm_status_manager.get_landmark_status(node->get_id()); if (lmn_status != lm_reached) { const set<int> &achievers = get_achievers(lmn_status, *node); bool covered_by_action_lm = false; for (int op_id : achievers) { assert(utils::in_bounds(op_id, action_landmarks)); if (action_landmarks[op_id]) { covered_by_action_lm = true; break; } } if (covered_by_action_lm) { for (int op_id : achievers) { assert(utils::in_bounds(op_id, achieved_lms_by_op)); --achieved_lms_by_op[op_id]; } } else { relevant_lms.push_back(node.get()); } } } /* Third pass: count shared costs for the remaining landmarks. */ for (const LandmarkNode *node : relevant_lms) { int lmn_status = lm_status_manager.get_landmark_status(node->get_id()); const set<int> &achievers = get_achievers(lmn_status, *node); double min_cost = numeric_limits<double>::max(); for (int op_id : achievers) { assert(utils::in_bounds(op_id, achieved_lms_by_op)); int num_achieved = achieved_lms_by_op[op_id]; assert(num_achieved >= 1); assert(utils::in_bounds(op_id, operator_costs)); double shared_cost = static_cast<double>(operator_costs[op_id]) / num_achieved; min_cost = min(min_cost, shared_cost); } h += min_cost; } return h; } LandmarkEfficientOptimalSharedCostAssignment::LandmarkEfficientOptimalSharedCostAssignment( const vector<int> &operator_costs, const LandmarkGraph &graph, lp::LPSolverType solver_type) : LandmarkCostAssignment(operator_costs, graph), lp_solver(solver_type), lp(build_initial_lp()) { } lp::LinearProgram LandmarkEfficientOptimalSharedCostAssignment::build_initial_lp() { /* The LP has one variable (column) per landmark and one inequality (row) per operator. */ int num_cols = lm_graph.get_num_landmarks(); int num_rows = operator_costs.size(); named_vector::NamedVector<lp::LPVariable> lp_variables; /* We want to maximize 1 * cost(lm_1) + ... + 1 * cost(lm_n), so the coefficients are all 1. Variable bounds are state-dependent; we initialize the range to {0}. */ lp_variables.resize(num_cols, lp::LPVariable(0.0, 0.0, 1.0)); /* Set up lower bounds and upper bounds for the inequalities. These simply say that the operator's total cost must fall between 0 and the real operator cost. */ lp_constraints.resize(num_rows, lp::LPConstraint(0.0, 0.0)); for (size_t op_id = 0; op_id < operator_costs.size(); ++op_id) { lp_constraints[op_id].set_lower_bound(0); lp_constraints[op_id].set_upper_bound(operator_costs[op_id]); } // Coefficients of constraints will be updated and recreated in each state. We ignore them for the initial LP. return lp::LinearProgram(lp::LPObjectiveSense::MAXIMIZE, move(lp_variables), named_vector::NamedVector<lp::LPConstraint>()); } double LandmarkEfficientOptimalSharedCostAssignment::cost_sharing_h_value( const LandmarkStatusManager &lm_status_manager) { /* TODO: We could also do the same thing with action landmarks we do in the uniform cost partitioning case. */ /* Set up LP variable bounds for the landmarks. The range of cost(lm_1) is {0} if the landmark is already reached; otherwise it is [0, infinity]. The lower bounds are set to 0 in the constructor and never change. */ int num_cols = lm_graph.get_num_landmarks(); for (int lm_id = 0; lm_id < num_cols; ++lm_id) { if (lm_status_manager.get_landmark_status(lm_id) == lm_reached) { lp.get_variables()[lm_id].upper_bound = 0; } else { lp.get_variables()[lm_id].upper_bound = lp_solver.get_infinity(); } } /* Define the constraint matrix. The constraints are of the form cost(lm_i1) + cost(lm_i2) + ... + cost(lm_in) <= cost(o) where lm_i1 ... lm_in are the landmarks for which o is a relevant achiever. Hence, we add a triple (op, lm, 1.0) for each relevant achiever op of landmark lm, denoting that in the op-th row and lm-th column, the matrix has a 1.0 entry. */ // Reuse previous constraint objects to save the effort of recreating them. for (lp::LPConstraint &constraint : lp_constraints) { constraint.clear(); } for (int lm_id = 0; lm_id < num_cols; ++lm_id) { const LandmarkNode *lm = lm_graph.get_landmark(lm_id); int lm_status = lm_status_manager.get_landmark_status(lm_id); if (lm_status != lm_reached) { const set<int> &achievers = get_achievers(lm_status, *lm); assert(!achievers.empty()); for (int op_id : achievers) { assert(utils::in_bounds(op_id, lp_constraints)); lp_constraints[op_id].insert(lm_id, 1.0); } } } /* Copy non-empty constraints and use those in the LP. This significantly speeds up the heuristic calculation. See issue443. */ // TODO: do not copy the data here. lp.get_constraints().clear(); for (const lp::LPConstraint &constraint : lp_constraints) { if (!constraint.empty()) lp.get_constraints().push_back(constraint); } // Load the problem into the LP solver. lp_solver.load_problem(lp); // Solve the linear program. lp_solver.solve(); assert(lp_solver.has_optimal_solution()); double h = lp_solver.get_objective_value(); return h; } }
8,711
C++
36.714286
128
0.61451
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_cost_assignment.h
#ifndef LANDMARKS_LANDMARK_COST_ASSIGNMENT_H #define LANDMARKS_LANDMARK_COST_ASSIGNMENT_H #include "../lp/lp_solver.h" #include <set> #include <vector> class OperatorsProxy; namespace landmarks { class LandmarkGraph; class LandmarkNode; class LandmarkStatusManager; class LandmarkCostAssignment { const std::set<int> empty; protected: const LandmarkGraph &lm_graph; const std::vector<int> operator_costs; const std::set<int> &get_achievers(int lmn_status, const LandmarkNode &lmn) const; public: LandmarkCostAssignment(const std::vector<int> &operator_costs, const LandmarkGraph &graph); virtual ~LandmarkCostAssignment() = default; virtual double cost_sharing_h_value( const LandmarkStatusManager &lm_status_manager) = 0; }; class LandmarkUniformSharedCostAssignment : public LandmarkCostAssignment { bool use_action_landmarks; public: LandmarkUniformSharedCostAssignment(const std::vector<int> &operator_costs, const LandmarkGraph &graph, bool use_action_landmarks); virtual double cost_sharing_h_value( const LandmarkStatusManager &lm_status_manager) override; }; class LandmarkEfficientOptimalSharedCostAssignment : public LandmarkCostAssignment { lp::LPSolver lp_solver; // We keep an additional copy of the constraints around to avoid some effort with recreating the vector (see issue443). std::vector<lp::LPConstraint> lp_constraints; /* We keep the vectors for LP variables and constraints around instead of recreating them for every state. The actual constraints have to be recreated because the coefficient matrix of the LP changes from state to state. Reusing the vectors still saves some dynamic allocation overhead. */ lp::LinearProgram lp; lp::LinearProgram build_initial_lp(); public: LandmarkEfficientOptimalSharedCostAssignment( const std::vector<int> &operator_costs, const LandmarkGraph &graph, lp::LPSolverType solver_type); virtual double cost_sharing_h_value( const LandmarkStatusManager &lm_status_manager) override; }; } #endif
2,260
C
31.768115
123
0.699558
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_zhu_givan.cc
#include "landmark_factory_zhu_givan.h" #include "landmark_graph.h" #include "util.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../utils/language.h" #include "../utils/logging.h" #include <iostream> #include <unordered_map> #include <utility> using namespace std; namespace landmarks { LandmarkFactoryZhuGivan::LandmarkFactoryZhuGivan(const Options &opts) : use_orders(opts.get<bool>("use_orders")) { } void LandmarkFactoryZhuGivan::generate_relaxed_landmarks( const shared_ptr<AbstractTask> &task, Exploration &exploration) { TaskProxy task_proxy(*task); utils::g_log << "Generating landmarks using Zhu/Givan label propagation\n"; compute_triggers(task_proxy); PropositionLayer last_prop_layer = build_relaxed_plan_graph_with_labels(task_proxy); if (!satisfies_goal_conditions(task_proxy.get_goals(), last_prop_layer)) { utils::g_log << "Problem not solvable, even if relaxed.\n"; return; } extract_landmarks(task_proxy, exploration, last_prop_layer); if (!use_orders) { discard_all_orderings(); } } bool LandmarkFactoryZhuGivan::satisfies_goal_conditions( const GoalsProxy &goals, const PropositionLayer &layer) const { for (FactProxy goal : goals) if (!layer[goal.get_variable().get_id()][goal.get_value()].reached()) return false; return true; } void LandmarkFactoryZhuGivan::extract_landmarks( const TaskProxy &task_proxy, Exploration &exploration, const PropositionLayer &last_prop_layer) { utils::unused_variable(exploration); State initial_state = task_proxy.get_initial_state(); // insert goal landmarks and mark them as goals for (FactProxy goal : task_proxy.get_goals()) { FactPair goal_lm = goal.get_pair(); LandmarkNode *lmp; if (lm_graph->contains_simple_landmark(goal_lm)) { lmp = &lm_graph->get_simple_landmark(goal_lm); lmp->is_true_in_goal = true; } else { lmp = &lm_graph->add_simple_landmark(goal_lm); lmp->is_true_in_goal = true; } // extract landmarks from goal labels const plan_graph_node &goal_node = last_prop_layer[goal_lm.var][goal_lm.value]; assert(goal_node.reached()); for (const FactPair &lm : goal_node.labels) { if (lm == goal_lm) // ignore label on itself continue; LandmarkNode *node; // Add new landmarks if (!lm_graph->contains_simple_landmark(lm)) { node = &lm_graph->add_simple_landmark(lm); // if landmark is not in the initial state, // relaxed_task_solvable() should be false assert(initial_state[lm.var].get_value() == lm.value || !relaxed_task_solvable(task_proxy, exploration, true, node)); } else { node = &lm_graph->get_simple_landmark(lm); } // Add order: lm ->_{nat} lm assert(node->parents.find(lmp) == node->parents.end()); assert(lmp->children.find(node) == lmp->children.end()); edge_add(*node, *lmp, EdgeType::NATURAL); } } } LandmarkFactoryZhuGivan::PropositionLayer LandmarkFactoryZhuGivan::build_relaxed_plan_graph_with_labels( const TaskProxy &task_proxy) const { assert(!triggers.empty()); PropositionLayer current_prop_layer; unordered_set<int> triggered(task_proxy.get_operators().size() + task_proxy.get_axioms().size()); // set initial layer State initial_state = task_proxy.get_initial_state(); VariablesProxy variables = task_proxy.get_variables(); current_prop_layer.resize(variables.size()); for (VariableProxy var : variables) { int var_id = var.get_id(); current_prop_layer[var_id].resize(var.get_domain_size()); // label nodes from initial state int value = initial_state[var].get_value(); current_prop_layer[var_id][value].labels.emplace(var_id, value); triggered.insert(triggers[var_id][value].begin(), triggers[var_id][value].end()); } // Operators without preconditions do not propagate labels. So if they have // no conditional effects, is only necessary to apply them once. (If they // have conditional effects, they will be triggered at later stages again). triggered.insert(operators_without_preconditions.begin(), operators_without_preconditions.end()); bool changes = true; while (changes) { PropositionLayer next_prop_layer(current_prop_layer); unordered_set<int> next_triggered; changes = false; for (int op_or_axiom_id : triggered) { OperatorProxy op = get_operator_or_axiom(task_proxy, op_or_axiom_id); if (operator_applicable(op, current_prop_layer)) { lm_set changed = apply_operator_and_propagate_labels( op, current_prop_layer, next_prop_layer); if (!changed.empty()) { changes = true; for (const FactPair &lm : changed) next_triggered.insert( triggers[lm.var][lm.value].begin(), triggers[lm.var][lm.value].end()); } } } current_prop_layer = next_prop_layer; triggered = next_triggered; } return current_prop_layer; } bool LandmarkFactoryZhuGivan::operator_applicable(const OperatorProxy &op, const PropositionLayer &state) const { // test preconditions for (FactProxy fact : op.get_preconditions()) if (!state[fact.get_variable().get_id()][fact.get_value()].reached()) return false; return true; } bool LandmarkFactoryZhuGivan::operator_cond_effect_fires( const EffectConditionsProxy &effect_conditions, const PropositionLayer &layer) const { for (FactProxy effect_condition : effect_conditions) if (!layer[effect_condition.get_variable().get_id()][effect_condition.get_value()].reached()) return false; return true; } static lm_set _union(const lm_set &a, const lm_set &b) { if (a.size() < b.size()) return _union(b, a); lm_set result = a; for (lm_set::const_iterator it = b.begin(); it != b.end(); ++it) result.insert(*it); return result; } static lm_set _intersection(const lm_set &a, const lm_set &b) { if (a.size() > b.size()) return _intersection(b, a); lm_set result; for (lm_set::const_iterator it = a.begin(); it != a.end(); ++it) if (b.find(*it) != b.end()) result.insert(*it); return result; } lm_set LandmarkFactoryZhuGivan::union_of_precondition_labels(const OperatorProxy &op, const PropositionLayer &current) const { lm_set result; // TODO This looks like an O(n^2) algorithm where O(n log n) would do, a // bit like the Python string concatenation anti-pattern. for (FactProxy precondition : op.get_preconditions()) result = _union(result, current[precondition.get_variable().get_id()][precondition.get_value()].labels); return result; } lm_set LandmarkFactoryZhuGivan::union_of_condition_labels( const EffectConditionsProxy &effect_conditions, const PropositionLayer &current) const { lm_set result; for (FactProxy effect_condition : effect_conditions) result = _union(result, current[effect_condition.get_variable().get_id()][effect_condition.get_value()].labels); return result; } static bool _propagate_labels(lm_set &labels, const lm_set &new_labels, const FactPair &prop) { lm_set old_labels = labels; if (!labels.empty()) { labels = _intersection(labels, new_labels); } else { labels = new_labels; } labels.insert(prop); assert(old_labels.empty() || old_labels.size() >= labels.size()); assert(!labels.empty()); // test if labels have changed or proposition has just been reached: // if it has just been reached: // (old_labels.size() == 0) && (labels.size() >= 1) // if old_labels.size() == labels.size(), then labels have not been refined // by intersection. return old_labels.size() != labels.size(); } lm_set LandmarkFactoryZhuGivan::apply_operator_and_propagate_labels( const OperatorProxy &op, const PropositionLayer &current, PropositionLayer &next) const { assert(operator_applicable(op, current)); lm_set result; lm_set precond_label_union = union_of_precondition_labels(op, current); for (EffectProxy effect : op.get_effects()) { FactPair effect_fact = effect.get_fact().get_pair(); if (next[effect_fact.var][effect_fact.value].labels.size() == 1) continue; if (operator_cond_effect_fires(effect.get_conditions(), current)) { const lm_set precond_label_union_with_condeff = _union( precond_label_union, union_of_condition_labels( // NOTE: this equals precond_label_union, if effects[i] is // not a conditional effect. effect.get_conditions(), current)); if (_propagate_labels(next[effect_fact.var][effect_fact.value].labels, precond_label_union_with_condeff, effect_fact)) result.insert(effect_fact); } } return result; } void LandmarkFactoryZhuGivan::compute_triggers(const TaskProxy &task_proxy) { assert(triggers.empty()); // initialize empty triggers VariablesProxy variables = task_proxy.get_variables(); triggers.resize(variables.size()); for (size_t i = 0; i < variables.size(); ++i) triggers[i].resize(variables[i].get_domain_size()); // compute triggers for (OperatorProxy op : task_proxy.get_operators()) { add_operator_to_triggers(op); } for (OperatorProxy axiom : task_proxy.get_axioms()) { add_operator_to_triggers(axiom); } } void LandmarkFactoryZhuGivan::add_operator_to_triggers(const OperatorProxy &op) { // Collect possible triggers first. lm_set possible_triggers; int op_or_axiom_id = get_operator_or_axiom_id(op); PreconditionsProxy preconditions = op.get_preconditions(); for (FactProxy precondition : preconditions) possible_triggers.insert(precondition.get_pair()); for (EffectProxy effect : op.get_effects()) { for (FactProxy effect_condition : effect.get_conditions()) possible_triggers.insert(effect_condition.get_pair()); } if (preconditions.empty()) operators_without_preconditions.push_back(op_or_axiom_id); // Add operator to triggers vector. for (const FactPair &lm : possible_triggers) triggers[lm.var][lm.value].push_back(op_or_axiom_id); } bool LandmarkFactoryZhuGivan::computes_reasonable_orders() const { return false; } bool LandmarkFactoryZhuGivan::supports_conditional_effects() const { return true; } static shared_ptr<LandmarkFactory> _parse(OptionParser &parser) { parser.document_synopsis( "Zhu/Givan Landmarks", "The landmark generation method introduced by " "Zhu & Givan (ICAPS 2003 Doctoral Consortium)."); _add_use_orders_option_to_parser(parser); Options opts = parser.parse(); // TODO: Make sure that conditional effects are indeed supported. parser.document_language_support("conditional_effects", "We think they are supported, but this " "is not 100% sure."); if (parser.dry_run()) return nullptr; else return make_shared<LandmarkFactoryZhuGivan>(opts); } static Plugin<LandmarkFactory> _plugin("lm_zg", _parse); }
11,981
C++
34.874251
120
0.623654
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_reasonable_orders_hps.cc
#include "landmark_factory_reasonable_orders_hps.h" #include "landmark_graph.h" #include "util.h" #include "../option_parser.h" #include "../plugin.h" #include "../utils/logging.h" #include "../utils/markup.h" using namespace std; namespace landmarks { LandmarkFactoryReasonableOrdersHPS::LandmarkFactoryReasonableOrdersHPS(const Options &opts) : lm_factory(opts.get<shared_ptr<LandmarkFactory>>("lm_factory")) { } void LandmarkFactoryReasonableOrdersHPS::generate_landmarks(const shared_ptr<AbstractTask> &task) { utils::g_log << "Building a landmark graph with reasonable orders." << endl; lm_graph = lm_factory->compute_lm_graph(task); TaskProxy task_proxy(*task); utils::g_log << "approx. reasonable orders" << endl; approximate_reasonable_orders(task_proxy, false); utils::g_log << "approx. obedient reasonable orders" << endl; approximate_reasonable_orders(task_proxy, true); mk_acyclic_graph(); } void LandmarkFactoryReasonableOrdersHPS::approximate_reasonable_orders( const TaskProxy &task_proxy, bool obedient_orders) { /* Approximate reasonable and obedient reasonable orders according to Hoffmann et al. If flag "obedient_orders" is true, we calculate obedient reasonable orders, otherwise reasonable orders. If node_p is in goal, then any node2_p which interferes with node_p can be reasonably ordered before node_p. Otherwise, if node_p is greedy necessary predecessor of node2, and there is another predecessor "parent" of node2, then parent and all predecessors of parent can be ordered reasonably before node_p if they interfere with node_p. */ State initial_state = task_proxy.get_initial_state(); int variables_size = task_proxy.get_variables().size(); for (auto &node_p : lm_graph->get_nodes()) { if (node_p->disjunctive) continue; if (node_p->is_true_in_state(initial_state)) return; if (!obedient_orders && node_p->is_true_in_goal) { for (auto &node2_p : lm_graph->get_nodes()) { if (node2_p == node_p || node2_p->disjunctive) continue; if (interferes(task_proxy, node2_p.get(), node_p.get())) { edge_add(*node2_p, *node_p, EdgeType::REASONABLE); } } } else { // Collect candidates for reasonable orders in "interesting nodes". // Use hash set to filter duplicates. unordered_set<LandmarkNode *> interesting_nodes(variables_size); for (const auto &child : node_p->children) { const LandmarkNode &node2 = *child.first; const EdgeType &edge2 = child.second; if (edge2 >= EdgeType::GREEDY_NECESSARY) { // found node2: node_p ->_gn node2 for (const auto &p : node2.parents) { // find parent LandmarkNode &parent = *(p.first); const EdgeType &edge = p.second; if (parent.disjunctive) continue; if ((edge >= EdgeType::NATURAL || (obedient_orders && edge == EdgeType::REASONABLE)) && &parent != node_p.get()) { // find predecessors or parent and collect in // "interesting nodes" interesting_nodes.insert(&parent); collect_ancestors(interesting_nodes, parent, obedient_orders); } } } } // Insert reasonable orders between those members of "interesting nodes" that interfere // with node_p. for (LandmarkNode *node : interesting_nodes) { if (node == node_p.get() || node->disjunctive) continue; if (interferes(task_proxy, node, node_p.get())) { if (!obedient_orders) edge_add(*node, *node_p, EdgeType::REASONABLE); else edge_add(*node, *node_p, EdgeType::OBEDIENT_REASONABLE); } } } } } bool LandmarkFactoryReasonableOrdersHPS::interferes( const TaskProxy &task_proxy, const LandmarkNode *node_a, const LandmarkNode *node_b) const { /* Facts a and b interfere (i.e., achieving b before a would mean having to delete b and re-achieve it in order to achieve a) if one of the following condition holds: 1. a and b are mutex 2. All actions that add a also add e, and e and b are mutex 3. There is a greedy necessary predecessor x of a, and x and b are mutex This is the definition of Hoffmann et al. except that they have one more condition: "all actions that add a delete b". However, in our case (SAS+ formalism), this condition is the same as 2. */ assert(node_a != node_b); assert(!node_a->disjunctive && !node_b->disjunctive); VariablesProxy variables = task_proxy.get_variables(); for (const FactPair &lm_fact_b : node_b->facts) { FactProxy fact_b = variables[lm_fact_b.var].get_fact(lm_fact_b.value); for (const FactPair &lm_fact_a : node_a->facts) { FactProxy fact_a = variables[lm_fact_a.var].get_fact(lm_fact_a.value); if (lm_fact_a == lm_fact_b) { if (!node_a->conjunctive || !node_b->conjunctive) return false; else continue; } // 1. a, b mutex if (fact_a.is_mutex(fact_b)) return true; // 2. Shared effect e in all operators reaching a, and e, b are mutex // Skip this for conjunctive nodes a, as they are typically achieved through a // sequence of operators successively adding the parts of a if (node_a->conjunctive) continue; unordered_map<int, int> shared_eff; bool init = true; const vector<int> &op_or_axiom_ids = get_operators_including_eff(lm_fact_a); // Intersect operators that achieve a one by one for (int op_or_axiom_id : op_or_axiom_ids) { // If no shared effect among previous operators, break if (!init && shared_eff.empty()) break; // Else, insert effects of this operator into set "next_eff" if // it is an unconditional effect or a conditional effect that is sure to // happen. (Such "trivial" conditions can arise due to our translator, // e.g. in Schedule. There, the same effect is conditioned on a disjunction // of conditions of which one will always be true. We test for a simple kind // of these trivial conditions here.) EffectsProxy effects = get_operator_or_axiom(task_proxy, op_or_axiom_id).get_effects(); set<FactPair> trivially_conditioned_effects; bool trivial_conditioned_effects_found = effect_always_happens(variables, effects, trivially_conditioned_effects); unordered_map<int, int> next_eff; for (EffectProxy effect : effects) { FactPair effect_fact = effect.get_fact().get_pair(); if (effect.get_conditions().empty() && effect_fact.var != lm_fact_a.var) { next_eff.emplace(effect_fact.var, effect_fact.value); } else if (trivial_conditioned_effects_found && trivially_conditioned_effects.find(effect_fact) != trivially_conditioned_effects.end()) next_eff.emplace(effect_fact.var, effect_fact.value); } // Intersect effects of this operator with those of previous operators if (init) swap(shared_eff, next_eff); else { unordered_map<int, int> result; for (const auto &eff1 : shared_eff) { auto it2 = next_eff.find(eff1.first); if (it2 != next_eff.end() && it2->second == eff1.second) result.insert(eff1); } swap(shared_eff, result); } init = false; } // Test whether one of the shared effects is inconsistent with b for (const pair<const int, int> &eff : shared_eff) { const FactProxy &effect_fact = variables[eff.first].get_fact(eff.second); if (effect_fact != fact_a && effect_fact != fact_b && effect_fact.is_mutex(fact_b)) return true; } } /* // Experimentally commenting this out -- see issue202. // 3. Exists LM x, inconsistent x, b and x->_gn a for (const auto &parent : node_a->parents) { const LandmarkNode &node = *parent.first; edge_type edge = parent.second; for (const FactPair &parent_prop : node.facts) { const FactProxy &parent_prop_fact = variables[parent_prop.var].get_fact(parent_prop.value); if (edge >= greedy_necessary && parent_prop_fact != fact_b && parent_prop_fact.is_mutex(fact_b)) return true; } } */ } // No inconsistency found return false; } void LandmarkFactoryReasonableOrdersHPS::collect_ancestors( unordered_set<LandmarkNode *> &result, LandmarkNode &node, bool use_reasonable) { /* Returns all ancestors in the landmark graph of landmark node "start" */ // There could be cycles if use_reasonable == true list<LandmarkNode *> open_nodes; unordered_set<LandmarkNode *> closed_nodes; for (const auto &p : node.parents) { LandmarkNode &parent = *(p.first); const EdgeType &edge = p.second; if (edge >= EdgeType::NATURAL || (use_reasonable && edge == EdgeType::REASONABLE)) if (closed_nodes.count(&parent) == 0) { open_nodes.push_back(&parent); closed_nodes.insert(&parent); result.insert(&parent); } } while (!open_nodes.empty()) { LandmarkNode &node2 = *(open_nodes.front()); for (const auto &p : node2.parents) { LandmarkNode &parent = *(p.first); const EdgeType &edge = p.second; if (edge >= EdgeType::NATURAL || (use_reasonable && edge == EdgeType::REASONABLE)) { if (closed_nodes.count(&parent) == 0) { open_nodes.push_back(&parent); closed_nodes.insert(&parent); result.insert(&parent); } } } open_nodes.pop_front(); } } bool LandmarkFactoryReasonableOrdersHPS::effect_always_happens( const VariablesProxy &variables, const EffectsProxy &effects, set<FactPair> &eff) const { /* Test whether the condition of a conditional effect is trivial, i.e. always true. We test for the simple case that the same effect proposition is triggered by a set of conditions of which one will always be true. This is e.g. the case in Schedule, where the effect (forall (?oldpaint - colour) (when (painted ?x ?oldpaint) (not (painted ?x ?oldpaint)))) is translated by the translator to: if oldpaint == blue, then not painted ?x, and if oldpaint == red, then not painted ?x etc. If conditional effects are found that are always true, they are returned in "eff". */ // Go through all effects of operator and collect: // - all variables that are set to some value in a conditional effect (effect_vars) // - variables that can be set to more than one value in a cond. effect (nogood_effect_vars) // - a mapping from cond. effect propositions to all the conditions that they appear with set<int> effect_vars; set<int> nogood_effect_vars; map<int, pair<int, vector<FactPair>>> effect_conditions_by_variable; for (EffectProxy effect : effects) { EffectConditionsProxy effect_conditions = effect.get_conditions(); FactProxy effect_fact = effect.get_fact(); int var_id = effect_fact.get_variable().get_id(); int value = effect_fact.get_value(); if (effect_conditions.empty() || nogood_effect_vars.find(var_id) != nogood_effect_vars.end()) { // Var has no condition or can take on different values, skipping continue; } if (effect_vars.find(var_id) != effect_vars.end()) { // We have seen this effect var before assert(effect_conditions_by_variable.find(var_id) != effect_conditions_by_variable.end()); int old_eff = effect_conditions_by_variable.find(var_id)->second.first; if (old_eff != value) { // Was different effect nogood_effect_vars.insert(var_id); continue; } } else { // We have not seen this effect var before effect_vars.insert(var_id); } if (effect_conditions_by_variable.find(var_id) != effect_conditions_by_variable.end() && effect_conditions_by_variable.find(var_id)->second.first == value) { // We have seen this effect before, adding conditions for (FactProxy effect_condition : effect_conditions) { vector<FactPair> &vec = effect_conditions_by_variable.find(var_id)->second.second; vec.push_back(effect_condition.get_pair()); } } else { // We have not seen this effect before, making new effect entry vector<FactPair> &vec = effect_conditions_by_variable.emplace( var_id, make_pair( value, vector<FactPair> ())).first->second.second; for (FactProxy effect_condition : effect_conditions) { vec.push_back(effect_condition.get_pair()); } } } // For all those effect propositions whose variables do not take on different values... for (const auto &effect_conditions : effect_conditions_by_variable) { if (nogood_effect_vars.find(effect_conditions.first) != nogood_effect_vars.end()) { continue; } // ...go through all the conditions that the effect has, and map condition // variables to the set of values they take on (in unique_conds) map<int, set<int>> unique_conds; for (const FactPair &cond : effect_conditions.second.second) { if (unique_conds.find(cond.var) != unique_conds.end()) { unique_conds.find(cond.var)->second.insert( cond.value); } else { set<int> &the_set = unique_conds.emplace(cond.var, set<int>()).first->second; the_set.insert(cond.value); } } // Check for each condition variable whether the number of values it takes on is // equal to the domain of that variable... bool is_always_reached = true; for (auto &unique_cond : unique_conds) { bool is_surely_reached_by_var = false; int num_values_for_cond = unique_cond.second.size(); int num_values_of_variable = variables[unique_cond.first].get_domain_size(); if (num_values_for_cond == num_values_of_variable) { is_surely_reached_by_var = true; } // ...or else if the condition variable is the same as the effect variable, // check whether the condition variable takes on all other values except the // effect value else if (unique_cond.first == effect_conditions.first && num_values_for_cond == num_values_of_variable - 1) { // Number of different values is correct, now ensure that the effect value // was the one missing unique_cond.second.insert(effect_conditions.second.first); num_values_for_cond = unique_cond.second.size(); if (num_values_for_cond == num_values_of_variable) { is_surely_reached_by_var = true; } } // If one of the condition variables does not fulfill the criteria, the effect // is not certain to happen if (!is_surely_reached_by_var) is_always_reached = false; } if (is_always_reached) eff.insert(FactPair( effect_conditions.first, effect_conditions.second.first)); } return eff.empty(); } bool LandmarkFactoryReasonableOrdersHPS::computes_reasonable_orders() const { return true; } bool LandmarkFactoryReasonableOrdersHPS::supports_conditional_effects() const { return lm_factory->supports_conditional_effects(); } static shared_ptr<LandmarkFactory> _parse(OptionParser &parser) { parser.document_synopsis( "HPS Orders", "Adds reasonable orders and obedient reasonable orders " "described in the following paper" + utils::format_journal_reference( {"Jörg Hoffman", "JuliePorteous", "LauraSebastia"}, "Ordered Landmarks in Planning", "https://jair.org/index.php/jair/article/view/10390/24882", "Journal of Artificial Intelligence Research", "22", "215-278", "2004")); parser.add_option<shared_ptr<LandmarkFactory>>("lm_factory"); Options opts = parser.parse(); // TODO: correct? parser.document_language_support("conditional_effects", "supported if subcomponent supports them"); if (parser.dry_run()) return nullptr; else return make_shared<LandmarkFactoryReasonableOrdersHPS>(opts); } static Plugin<LandmarkFactory> _plugin("lm_reasonable_orders_hps", _parse); }
18,399
C++
45
111
0.572531
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_merged.cc
#include "landmark_factory_merged.h" #include "landmark_graph.h" #include "../option_parser.h" #include "../plugin.h" #include "../utils/logging.h" #include <set> using namespace std; using utils::ExitCode; namespace landmarks { class LandmarkNode; LandmarkFactoryMerged::LandmarkFactoryMerged(const Options &opts) : lm_factories(opts.get_list<shared_ptr<LandmarkFactory>>("lm_factories")) { } LandmarkNode *LandmarkFactoryMerged::get_matching_landmark(const LandmarkNode &lm) const { if (!lm.disjunctive && !lm.conjunctive) { const FactPair &lm_fact = lm.facts[0]; if (lm_graph->contains_simple_landmark(lm_fact)) return &lm_graph->get_simple_landmark(lm_fact); else return 0; } else if (lm.disjunctive) { set<FactPair> lm_facts(lm.facts.begin(), lm.facts.end()); if (lm_graph->contains_identical_disjunctive_landmark(lm_facts)) return &lm_graph->get_disjunctive_landmark(lm.facts[0]); else return 0; } else if (lm.conjunctive) { cerr << "Don't know how to handle conjunctive landmarks yet" << endl; utils::exit_with(ExitCode::SEARCH_UNSUPPORTED); } return 0; } void LandmarkFactoryMerged::generate_landmarks( const shared_ptr<AbstractTask> &task) { utils::g_log << "Merging " << lm_factories.size() << " landmark graphs" << endl; vector<shared_ptr<LandmarkGraph>> lm_graphs; lm_graphs.reserve(lm_factories.size()); for (const shared_ptr<LandmarkFactory> &lm_factory : lm_factories) { lm_graphs.push_back(lm_factory->compute_lm_graph(task)); } utils::g_log << "Adding simple landmarks" << endl; for (size_t i = 0; i < lm_graphs.size(); ++i) { const LandmarkGraph::Nodes &nodes = lm_graphs[i]->get_nodes(); for (auto &lm : nodes) { const LandmarkNode &node = *lm; const FactPair &lm_fact = node.facts[0]; if (!node.conjunctive && !node.disjunctive && !lm_graph->contains_landmark(lm_fact)) { LandmarkNode &new_node = lm_graph->add_simple_landmark(lm_fact); new_node.is_true_in_goal = node.is_true_in_goal; new_node.possible_achievers.insert( node.possible_achievers.begin(), node.possible_achievers.end()); new_node.first_achievers.insert( node.first_achievers.begin(), node.first_achievers.end()); new_node.is_derived = node.is_derived; } } } /* TODO: It seems that disjunctive landmarks are only added if none of the facts it is made of is also there as a simple landmark. This should either be more general (add only if none of its subset is already there) or it should be done only upon request (e.g., heuristics that consider orders might want to keep all landmarks). */ utils::g_log << "Adding disjunctive landmarks" << endl; for (size_t i = 0; i < lm_graphs.size(); ++i) { const LandmarkGraph::Nodes &nodes = lm_graphs[i]->get_nodes(); for (auto &lm : nodes) { const LandmarkNode &node = *lm; if (node.disjunctive) { set<FactPair> lm_facts; bool exists = false; for (const FactPair &lm_fact: node.facts) { if (lm_graph->contains_landmark(lm_fact)) { exists = true; break; } lm_facts.insert(lm_fact); } if (!exists) { LandmarkNode &new_node = lm_graph->add_disjunctive_landmark(lm_facts); new_node.is_true_in_goal = node.is_true_in_goal; new_node.possible_achievers.insert( node.possible_achievers.begin(), node.possible_achievers.end()); new_node.first_achievers.insert( node.first_achievers.begin(), node.first_achievers.end()); new_node.is_derived = node.is_derived; } } else if (node.conjunctive) { cerr << "Don't know how to handle conjunctive landmarks yet" << endl; utils::exit_with(ExitCode::SEARCH_UNSUPPORTED); } } } utils::g_log << "Adding orderings" << endl; for (size_t i = 0; i < lm_graphs.size(); ++i) { const LandmarkGraph::Nodes &nodes = lm_graphs[i]->get_nodes(); for (auto &from_orig : nodes) { LandmarkNode *from = get_matching_landmark(*from_orig); if (from) { for (const auto &to : from_orig->children) { const LandmarkNode &to_orig = *to.first; EdgeType e_type = to.second; LandmarkNode *to_node = get_matching_landmark(to_orig); if (to_node) { edge_add(*from, *to_node, e_type); } else { utils::g_log << "Discarded to ordering" << endl; } } } else { utils::g_log << "Discarded from ordering" << endl; } } } postprocess(); } void LandmarkFactoryMerged::postprocess() { lm_graph->set_landmark_ids(); mk_acyclic_graph(); } bool LandmarkFactoryMerged::computes_reasonable_orders() const { for (const shared_ptr<LandmarkFactory> &lm_factory : lm_factories) { if (lm_factory->computes_reasonable_orders()) { return true; } } return false; } bool LandmarkFactoryMerged::supports_conditional_effects() const { for (const shared_ptr<LandmarkFactory> &lm_factory : lm_factories) { if (!lm_factory->supports_conditional_effects()) { return false; } } return true; } static shared_ptr<LandmarkFactory> _parse(OptionParser &parser) { parser.document_synopsis( "Merged Landmarks", "Merges the landmarks and orderings from the parameter landmarks"); parser.document_note( "Precedence", "Fact landmarks take precedence over disjunctive landmarks, " "orderings take precedence in the usual manner " "(gn > nat > reas > o_reas). "); parser.document_note( "Note", "Does not currently support conjunctive landmarks"); parser.add_list_option<shared_ptr<LandmarkFactory>>("lm_factories"); Options opts = parser.parse(); opts.verify_list_non_empty<shared_ptr<LandmarkFactory>>("lm_factories"); parser.document_language_support("conditional_effects", "supported if all components support them"); if (parser.dry_run()) return nullptr; else return make_shared<LandmarkFactoryMerged>(opts); } static Plugin<LandmarkFactory> _plugin("lm_merged", _parse); }
6,907
C++
36.748634
98
0.576517
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/util.cc
#include "util.h" #include "landmark_graph.h" #include "../task_proxy.h" #include "../utils/logging.h" #include <limits> using namespace std; namespace landmarks { bool _possibly_fires(const EffectConditionsProxy &conditions, const vector<vector<int>> &lvl_var) { for (FactProxy cond : conditions) if (lvl_var[cond.get_variable().get_id()][cond.get_value()] == numeric_limits<int>::max()) return false; return true; } unordered_map<int, int> _intersect(const unordered_map<int, int> &a, const unordered_map<int, int> &b) { if (a.size() > b.size()) return _intersect(b, a); unordered_map<int, int> result; for (const auto &pair_a : a) { const auto it_b = b.find(pair_a.first); if (it_b != b.end() && it_b->second == pair_a.second) result.insert(pair_a); } return result; } bool _possibly_reaches_lm(const OperatorProxy &op, const vector<vector<int>> &lvl_var, const LandmarkNode *lmp) { /* Check whether operator o can possibly make landmark lmp true in a relaxed task (as given by the reachability information in lvl_var) */ assert(!lvl_var.empty()); // Test whether all preconditions of o can be reached // Otherwise, operator is not applicable PreconditionsProxy preconditions = op.get_preconditions(); for (FactProxy pre : preconditions) if (lvl_var[pre.get_variable().get_id()][pre.get_value()] == numeric_limits<int>::max()) return false; // Go through all effects of o and check whether one can reach a // proposition in lmp for (EffectProxy effect: op.get_effects()) { FactProxy effect_fact = effect.get_fact(); assert(!lvl_var[effect_fact.get_variable().get_id()].empty()); for (const FactPair &fact : lmp->facts) { if (effect_fact.get_pair() == fact) { if (_possibly_fires(effect.get_conditions(), lvl_var)) return true; break; } } } return false; } OperatorProxy get_operator_or_axiom(const TaskProxy &task_proxy, int op_or_axiom_id) { if (op_or_axiom_id < 0) { return task_proxy.get_axioms()[-op_or_axiom_id - 1]; } else { return task_proxy.get_operators()[op_or_axiom_id]; } } int get_operator_or_axiom_id(const OperatorProxy &op) { if (op.is_axiom()) { return -op.get_id() - 1; } else { return op.get_id(); } } static void dump_node(const TaskProxy &task_proxy, const LandmarkNode &node) { cout << " lm" << node.get_id() << " [label=\""; bool first = true; for (FactPair fact : node.facts) { if (!first) { if (node.disjunctive) { cout << " | "; } else if (node.conjunctive) { cout << " & "; } } first = false; VariableProxy var = task_proxy.get_variables()[fact.var]; cout << var.get_fact(fact.value).get_name(); } cout << "\""; if (node.is_true_in_state(task_proxy.get_initial_state())) { cout << ", style=bold"; } if (node.is_true_in_goal) { cout << ", style=filled"; } cout << "];\n"; } static void dump_edge(int from, int to, EdgeType edge) { cout << " lm" << from << " -> lm" << to << " [label="; switch (edge) { case EdgeType::NECESSARY: cout << "\"nec\""; break; case EdgeType::GREEDY_NECESSARY: cout << "\"gn\""; break; case EdgeType::NATURAL: cout << "\"n\""; break; case EdgeType::REASONABLE: cout << "\"r\", style=dashed"; break; case EdgeType::OBEDIENT_REASONABLE: cout << "\"o_r\", style=dashed"; break; } cout << "];\n"; } void dump_landmark_graph(const TaskProxy &task_proxy, const LandmarkGraph &graph) { utils::g_log << "Dumping landmark graph: " << endl; cout << "digraph G {\n"; for (const unique_ptr<LandmarkNode> &node : graph.get_nodes()) { dump_node(task_proxy, *node); for (const auto &child : node->children) { const LandmarkNode *child_node = child.first; const EdgeType &edge = child.second; dump_edge(node->get_id(), child_node->get_id(), edge); } } cout << "}" << endl; utils::g_log << "Landmark graph end." << endl; } }
4,381
C++
29.859155
113
0.56357
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_zhu_givan.h
#ifndef LANDMARKS_LANDMARK_FACTORY_ZHU_GIVAN_H #define LANDMARKS_LANDMARK_FACTORY_ZHU_GIVAN_H #include "landmark_factory_relaxation.h" #include "../utils/hash.h" #include <unordered_set> #include <utility> #include <vector> namespace landmarks { using lm_set = utils::HashSet<FactPair>; class LandmarkFactoryZhuGivan : public LandmarkFactoryRelaxation { class plan_graph_node { public: lm_set labels; inline bool reached() const { // NOTE: nodes are always labeled with itself, // if they have been reached return !labels.empty(); } }; using PropositionLayer = std::vector<std::vector<plan_graph_node>>; const bool use_orders; // triggers[i][j] is a list of operators that could reach/change // labels on some proposition, after proposition (i,j) has changed std::vector<std::vector<std::vector<int>>> triggers; void compute_triggers(const TaskProxy &task_proxy); // Note: must include operators that only have conditional effects std::vector<int> operators_without_preconditions; bool operator_applicable(const OperatorProxy &op, const PropositionLayer &state) const; bool operator_cond_effect_fires(const EffectConditionsProxy &effect_conditions, const PropositionLayer &layer) const; // Apply operator and propagate labels to next layer. Returns set of // propositions that: // (a) have just been reached OR (b) had their labels changed in next // proposition layer lm_set apply_operator_and_propagate_labels(const OperatorProxy &op, const PropositionLayer &current, PropositionLayer &next) const; // Calculate the union of precondition labels of op, using the // labels from current lm_set union_of_precondition_labels(const OperatorProxy &op, const PropositionLayer &current) const; // Calculate the union of precondition labels of a conditional effect, // using the labels from current lm_set union_of_condition_labels(const EffectConditionsProxy &effect_conditions, const PropositionLayer &current) const; // Relaxed exploration, returns the last proposition layer // (the fixpoint) with labels PropositionLayer build_relaxed_plan_graph_with_labels(const TaskProxy &task_proxy) const; // Extract landmarks from last proposition layer and add them to the // landmarks graph void extract_landmarks(const TaskProxy &task_proxy, Exploration &exploration, const PropositionLayer &last_prop_layer); // test if layer satisfies goal bool satisfies_goal_conditions(const GoalsProxy &goals, const PropositionLayer &layer) const; // Link operators to its propositions in trigger list. void add_operator_to_triggers(const OperatorProxy &op); virtual void generate_relaxed_landmarks( const std::shared_ptr<AbstractTask> &task, Exploration &exploration) override; public: explicit LandmarkFactoryZhuGivan(const options::Options &opts); virtual bool computes_reasonable_orders() const override; virtual bool supports_conditional_effects() const override; }; } #endif
3,293
C
36.011236
110
0.689037
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_status_manager.cc
#include "landmark_status_manager.h" #include "../utils/logging.h" using namespace std; namespace landmarks { /* By default we mark all landmarks as reached, since we do an intersection when computing new landmark information. */ LandmarkStatusManager::LandmarkStatusManager(LandmarkGraph &graph) : reached_lms(vector<bool>(graph.get_num_landmarks(), true)), lm_status(graph.get_num_landmarks(), lm_not_reached), lm_graph(graph) { } BitsetView LandmarkStatusManager::get_reached_landmarks(const State &state) { return reached_lms[state]; } void LandmarkStatusManager::set_landmarks_for_initial_state( const State &initial_state) { BitsetView reached = get_reached_landmarks(initial_state); // This is necessary since the default is "true for all" (see comment above). reached.reset(); int inserted = 0; int num_goal_lms = 0; for (auto &node_p : lm_graph.get_nodes()) { if (node_p->is_true_in_goal) { ++num_goal_lms; } if (!node_p->parents.empty()) { continue; } if (node_p->conjunctive) { bool lm_true = true; for (const FactPair &fact : node_p->facts) { if (initial_state[fact.var].get_value() != fact.value) { lm_true = false; break; } } if (lm_true) { reached.set(node_p->get_id()); ++inserted; } } else { for (const FactPair &fact : node_p->facts) { if (initial_state[fact.var].get_value() == fact.value) { reached.set(node_p->get_id()); ++inserted; break; } } } } utils::g_log << inserted << " initial landmarks, " << num_goal_lms << " goal landmarks" << endl; } bool LandmarkStatusManager::update_reached_lms(const State &parent_ancestor_state, OperatorID, const State &ancestor_state) { if (ancestor_state == parent_ancestor_state) { // This can happen, e.g., in Satellite-01. return false; } const BitsetView parent_reached = get_reached_landmarks(parent_ancestor_state); BitsetView reached = get_reached_landmarks(ancestor_state); int num_landmarks = lm_graph.get_num_landmarks(); assert(reached.size() == num_landmarks); assert(parent_reached.size() == num_landmarks); /* Set all landmarks not reached by this parent as "not reached". Over multiple paths, this has the effect of computing the intersection of "reached" for the parents. It is important here that upon first visit, all elements in "reached" are true because true is the neutral element of intersection. In the case where the landmark we are setting to false here is actually achieved right now, it is set to "true" again below. */ reached.intersect(parent_reached); // Mark landmarks reached right now as "reached" (if they are "leaves"). for (int id = 0; id < num_landmarks; ++id) { if (!reached.test(id)) { LandmarkNode *node = lm_graph.get_landmark(id); if (node->is_true_in_state(ancestor_state)) { if (landmark_is_leaf(*node, reached)) { reached.set(id); } } } } return true; } void LandmarkStatusManager::update_lm_status(const State &ancestor_state) { const BitsetView reached = get_reached_landmarks(ancestor_state); const int num_landmarks = lm_graph.get_num_landmarks(); /* This first loop is necessary as setup for the *needed again* check in the second loop. */ for (int id = 0; id < num_landmarks; ++id) { lm_status[id] = reached.test(id) ? lm_reached : lm_not_reached; } for (int id = 0; id < num_landmarks; ++id) { if (lm_status[id] == lm_reached && landmark_needed_again(id, ancestor_state)) { lm_status[id] = lm_needed_again; } } } bool LandmarkStatusManager::dead_end_exists() { for (auto &node : lm_graph.get_nodes()) { int id = node->get_id(); /* This dead-end detection works for the following case: X is a goal, it is true in the initial state, and has no achievers. Some action A has X as a delete effect. Then using this, we can detect that applying A leads to a dead-end. Note: this only tests for reachability of the landmark from the initial state. A (possibly) more effective option would be to test reachability of the landmark from the current state. */ if (!node->is_derived) { if ((lm_status[id] == lm_not_reached) && node->first_achievers.empty()) { return true; } if ((lm_status[id] == lm_needed_again) && node->possible_achievers.empty()) { return true; } } } return false; } bool LandmarkStatusManager::landmark_needed_again( int id, const State &state) { LandmarkNode *node = lm_graph.get_landmark(id); if (node->is_true_in_state(state)) { return false; } else if (node->is_true_in_goal) { return true; } else { /* For all A ->_gn B, if B is not reached and A currently not true, since A is a necessary precondition for actions achieving B for the first time, it must become true again. */ for (const auto &child : node->children) { if (child.second >= EdgeType::GREEDY_NECESSARY && lm_status[child.first->get_id()] == lm_not_reached) { return true; } } return false; } } bool LandmarkStatusManager::landmark_is_leaf(const LandmarkNode &node, const BitsetView &reached) const { //Note: this is the same as !check_node_orders_disobeyed for (const auto &parent : node.parents) { LandmarkNode *parent_node = parent.first; // Note: no condition on edge type here if (!reached.test(parent_node->get_id())) { return false; } } return true; } }
6,417
C++
32.957672
90
0.566932
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_reasonable_orders_hps.h
#ifndef LANDMARKS_LANDMARK_FACTORY_REASONABLE_ORDERS_HPS_H #define LANDMARKS_LANDMARK_FACTORY_REASONABLE_ORDERS_HPS_H #include "landmark_factory.h" namespace landmarks { class LandmarkFactoryReasonableOrdersHPS : public LandmarkFactory { std::shared_ptr<LandmarkFactory> lm_factory; virtual void generate_landmarks(const std::shared_ptr<AbstractTask> &task) override; void approximate_reasonable_orders( const TaskProxy &task_proxy, bool obedient_orders); bool interferes( const TaskProxy &task_proxy, const LandmarkNode *node_a, const LandmarkNode *node_b) const; void collect_ancestors( std::unordered_set<LandmarkNode *> &result, LandmarkNode &node, bool use_reasonable); bool effect_always_happens( const VariablesProxy &variables, const EffectsProxy &effects, std::set<FactPair> &eff) const; public: LandmarkFactoryReasonableOrdersHPS(const options::Options &opts); virtual bool computes_reasonable_orders() const override; virtual bool supports_conditional_effects() const override; }; } #endif
1,099
C
33.374999
88
0.739763
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_rpg_exhaust.cc
#include "landmark_factory_rpg_exhaust.h" #include "landmark_graph.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../utils/logging.h" #include <vector> using namespace std; namespace landmarks { /* Problem: We don't get any orders here. (All we have is the reasonable orders that are inferred later.) It's thus best to combine this landmark generation method with others, don't use it by itself. */ LandmarkFactoryRpgExhaust::LandmarkFactoryRpgExhaust(const Options &opts) : only_causal_landmarks(opts.get<bool>("only_causal_landmarks")) { } void LandmarkFactoryRpgExhaust::generate_relaxed_landmarks( const shared_ptr<AbstractTask> &task, Exploration &exploration) { TaskProxy task_proxy(*task); utils::g_log << "Generating landmarks by testing all facts with RPG method" << endl; // insert goal landmarks and mark them as goals for (FactProxy goal : task_proxy.get_goals()) { LandmarkNode &lmp = lm_graph->add_simple_landmark(goal.get_pair()); lmp.is_true_in_goal = true; } // test all other possible facts State initial_state = task_proxy.get_initial_state(); for (VariableProxy var : task_proxy.get_variables()) { for (int value = 0; value < var.get_domain_size(); ++value) { const FactPair lm(var.get_id(), value); if (!lm_graph->contains_simple_landmark(lm)) { vector<FactPair> facts = {lm}; LandmarkNode node(facts, false, false); if (initial_state[lm.var].get_value() == lm.value || !relaxed_task_solvable(task_proxy, exploration, true, &node)) { lm_graph->add_simple_landmark(lm); } } } } if (only_causal_landmarks) { discard_noncausal_landmarks(task_proxy, exploration); } } bool LandmarkFactoryRpgExhaust::computes_reasonable_orders() const { return false; } bool LandmarkFactoryRpgExhaust::supports_conditional_effects() const { return false; } static shared_ptr<LandmarkFactory> _parse(OptionParser &parser) { parser.document_synopsis( "Exhaustive Landmarks", "Exhaustively checks for each fact if it is a landmark." "This check is done using relaxed planning."); _add_only_causal_landmarks_option_to_parser(parser); Options opts = parser.parse(); parser.document_language_support("conditional_effects", "ignored, i.e. not supported"); if (parser.dry_run()) return nullptr; else return make_shared<LandmarkFactoryRpgExhaust>(opts); } static Plugin<LandmarkFactory> _plugin("lm_exhaust", _parse); }
2,721
C++
31.79518
88
0.649761
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_count_heuristic.cc
#include "landmark_count_heuristic.h" #include "landmark_cost_assignment.h" #include "landmark_factory.h" #include "landmark_status_manager.h" #include "../option_parser.h" #include "../per_state_bitset.h" #include "../plugin.h" #include "../lp/lp_solver.h" #include "../task_utils/successor_generator.h" #include "../task_utils/task_properties.h" #include "../tasks/cost_adapted_task.h" #include "../tasks/root_task.h" #include "../utils/logging.h" #include "../utils/markup.h" #include "../utils/memory.h" #include "../utils/system.h" #include <cmath> #include <limits> #include <unordered_map> using namespace std; using utils::ExitCode; namespace landmarks { LandmarkCountHeuristic::LandmarkCountHeuristic(const options::Options &opts) : Heuristic(opts), use_preferred_operators(opts.get<bool>("pref")), conditional_effects_supported( opts.get<shared_ptr<LandmarkFactory>>("lm_factory")->supports_conditional_effects()), admissible(opts.get<bool>("admissible")), dead_ends_reliable( admissible || (!task_properties::has_axioms(task_proxy) && (!task_properties::has_conditional_effects(task_proxy) || conditional_effects_supported))), successor_generator(nullptr) { utils::g_log << "Initializing landmark count heuristic..." << endl; /* Actually, we should like to test if this is the root task or a CostAdapatedTask *of the root task*, but there is currently no good way to do this, so we use this incomplete, slightly less safe test. */ if (task != tasks::g_root_task && dynamic_cast<tasks::CostAdaptedTask *>(task.get()) == nullptr) { cerr << "The landmark count heuristic currently only supports task " << "transformations that modify the operator costs. See issues 845 " << "and 686 for details." << endl; utils::exit_with(utils::ExitCode::SEARCH_UNSUPPORTED); } utils::Timer lm_graph_timer; utils::g_log << "Generating landmark graph..." << endl; shared_ptr<LandmarkFactory> lm_graph_factory = opts.get<shared_ptr<LandmarkFactory>>("lm_factory"); if (admissible) { if (lm_graph_factory->computes_reasonable_orders()) { cerr << "Reasonable orderings should not be used for admissible heuristics" << endl; utils::exit_with(ExitCode::SEARCH_INPUT_ERROR); } else if (task_properties::has_axioms(task_proxy)) { cerr << "cost partitioning does not support axioms" << endl; utils::exit_with(ExitCode::SEARCH_UNSUPPORTED); } else if (task_properties::has_conditional_effects(task_proxy) && !conditional_effects_supported) { cerr << "conditional effects not supported by the landmark generation method" << endl; utils::exit_with(ExitCode::SEARCH_UNSUPPORTED); } } lgraph = lm_graph_factory->compute_lm_graph(task); utils::g_log << "Landmark graph generation time: " << lm_graph_timer << endl; utils::g_log << "Landmark graph contains " << lgraph->get_num_landmarks() << " landmarks, of which " << lgraph->get_num_disjunctive_landmarks() << " are disjunctive and " << lgraph->get_num_conjunctive_landmarks() << " are conjunctive." << endl; utils::g_log << "Landmark graph contains " << lgraph->get_num_edges() << " orderings." << endl; lm_status_manager = utils::make_unique_ptr<LandmarkStatusManager>(*lgraph); if (admissible) { if (opts.get<bool>("optimal")) { lm_cost_assignment = utils::make_unique_ptr<LandmarkEfficientOptimalSharedCostAssignment>( task_properties::get_operator_costs(task_proxy), *lgraph, opts.get<lp::LPSolverType>("lpsolver")); } else { lm_cost_assignment = utils::make_unique_ptr<LandmarkUniformSharedCostAssignment>( task_properties::get_operator_costs(task_proxy), *lgraph, opts.get<bool>("alm")); } } else { lm_cost_assignment = nullptr; } if (use_preferred_operators) { /* Ideally, we should reuse the successor generator of the main task in cases where it's compatible. See issue564. */ successor_generator = utils::make_unique_ptr<successor_generator::SuccessorGenerator>(task_proxy); } } int LandmarkCountHeuristic::get_heuristic_value(const State &ancestor_state) { double epsilon = 0.01; // Need explicit test to see if state is a goal state. The landmark // heuristic may compute h != 0 for a goal state if landmarks are // achieved before their parents in the landmarks graph (because // they do not get counted as reached in that case). However, we // must return 0 for a goal state. lm_status_manager->update_lm_status(ancestor_state); if (lm_status_manager->dead_end_exists()) { return DEAD_END; } if (admissible) { double h_val = lm_cost_assignment->cost_sharing_h_value( *lm_status_manager); return static_cast<int>(ceil(h_val - epsilon)); } else { int h = 0; for (int id = 0; id < lgraph->get_num_landmarks(); ++id) { landmark_status status = lm_status_manager->get_landmark_status(id); if (status == lm_not_reached || status == lm_needed_again) { h += lgraph->get_landmark(id)->cost; } } return h; } } int LandmarkCountHeuristic::compute_heuristic(const State &ancestor_state) { State state = convert_ancestor_state(ancestor_state); if (task_properties::is_goal_state(task_proxy, state)) return 0; int h = get_heuristic_value(ancestor_state); if (use_preferred_operators) { BitsetView landmark_info = lm_status_manager->get_reached_landmarks(ancestor_state); LandmarkSet reached_lms = convert_to_landmark_set(landmark_info); generate_helpful_actions(state, reached_lms); } return h; } bool LandmarkCountHeuristic::check_node_orders_disobeyed(const LandmarkNode &node, const LandmarkSet &reached) const { for (const auto &parent : node.parents) { if (reached.count(parent.first) == 0) { return true; } } return false; } bool LandmarkCountHeuristic::generate_helpful_actions(const State &state, const LandmarkSet &reached) { /* Find actions that achieve new landmark leaves. If no such action exist, return false. If a simple landmark can be achieved, return only operators that achieve simple landmarks, else return operators that achieve disjunctive landmarks */ assert(successor_generator); vector<OperatorID> applicable_operators; successor_generator->generate_applicable_ops(state, applicable_operators); vector<OperatorID> ha_simple; vector<OperatorID> ha_disj; for (OperatorID op_id : applicable_operators) { OperatorProxy op = task_proxy.get_operators()[op_id]; EffectsProxy effects = op.get_effects(); for (EffectProxy effect : effects) { if (!does_fire(effect, state)) continue; FactProxy fact_proxy = effect.get_fact(); LandmarkNode *lm_p = lgraph->get_landmark(fact_proxy.get_pair()); if (lm_p != 0 && landmark_is_interesting(state, reached, *lm_p)) { if (lm_p->disjunctive) { ha_disj.push_back(op_id); } else { ha_simple.push_back(op_id); } } } } if (ha_disj.empty() && ha_simple.empty()) return false; OperatorsProxy operators = task_proxy.get_operators(); if (ha_simple.empty()) { for (OperatorID op_id : ha_disj) { set_preferred(operators[op_id]); } } else { for (OperatorID op_id : ha_simple) { set_preferred(operators[op_id]); } } return true; } bool LandmarkCountHeuristic::landmark_is_interesting( const State &state, const LandmarkSet &reached, LandmarkNode &lm) const { /* A landmark is interesting if it hasn't been reached before and its parents have all been reached, or if all landmarks have been reached before, the LM is a goal, and it's not true at moment */ int num_reached = reached.size(); if (num_reached != lgraph->get_num_landmarks()) { if (reached.find(&lm) != reached.end()) return false; else return !check_node_orders_disobeyed(lm, reached); } return lm.is_true_in_goal && !lm.is_true_in_state(state); } void LandmarkCountHeuristic::notify_initial_state(const State &initial_state) { lm_status_manager->set_landmarks_for_initial_state(initial_state); } void LandmarkCountHeuristic::notify_state_transition( const State &parent_state, OperatorID op_id, const State &state) { lm_status_manager->update_reached_lms(parent_state, op_id, state); if (cache_evaluator_values) { /* TODO: It may be more efficient to check that the reached landmark set has actually changed and only then mark the h value as dirty. */ heuristic_cache[state].dirty = true; } } bool LandmarkCountHeuristic::dead_ends_are_reliable() const { return dead_ends_reliable; } // This function exists purely so we don't have to change all the // functions in this class that use LandmarkSets for the reached LMs // (HACK). LandmarkSet LandmarkCountHeuristic::convert_to_landmark_set( const BitsetView &landmark_bitset) { LandmarkSet landmark_set; for (int i = 0; i < landmark_bitset.size(); ++i) if (landmark_bitset.test(i)) landmark_set.insert(lgraph->get_landmark(i)); return landmark_set; } static shared_ptr<Heuristic> _parse(OptionParser &parser) { parser.document_synopsis( "Landmark-count heuristic", "For the inadmissible variant see the papers" + utils::format_conference_reference( {"Silvia Richter", "Malte Helmert", "Matthias Westphal"}, "Landmarks Revisited", "https://ai.dmi.unibas.ch/papers/richter-et-al-aaai2008.pdf", "Proceedings of the 23rd AAAI Conference on Artificial " "Intelligence (AAAI 2008)", "975-982", "AAAI Press", "2008") + "and" + utils::format_journal_reference( {"Silvia Richter", "Matthias Westphal"}, "The LAMA Planner: Guiding Cost-Based Anytime Planning with Landmarks", "http://www.aaai.org/Papers/JAIR/Vol39/JAIR-3903.pdf", "Journal of Artificial Intelligence Research", "39", "127-177", "2010") + "For the admissible variant see the papers" + utils::format_conference_reference( {"Erez Karpas", "Carmel Domshlak"}, "Cost-Optimal Planning with Landmarks", "https://www.ijcai.org/Proceedings/09/Papers/288.pdf", "Proceedings of the 21st International Joint Conference on " "Artificial Intelligence (IJCAI 2009)", "1728-1733", "AAAI Press", "2009") + "and" + utils::format_conference_reference( {"Emil Keyder and Silvia Richter and Malte Helmert"}, "Sound and Complete Landmarks for And/Or Graphs", "https://ai.dmi.unibas.ch/papers/keyder-et-al-ecai2010.pdf", "Proceedings of the 19th European Conference on Artificial " "Intelligence (ECAI 2010)", "335-340", "IOS Press", "2010")); parser.document_note( "Optimal search", "When using landmarks for optimal search (``admissible=true``), " "you probably also want to add this heuristic as a lazy_evaluator " "in the A* algorithm to improve heuristic estimates."); parser.document_note( "Note", "To use ``optimal=true``, you must build the planner with LP support. " "See LPBuildInstructions."); parser.document_note( "Differences to the literature", "This heuristic differs from the description in the literature (see " "references above) in the set of preferred operators computed. The " "original implementation described in the literature computes two " "kinds of preferred operators:\n\n" "+ If there is an applicable operator that reaches a landmark, all " "such operators are preferred.\n" "+ If no such operators exist, perform an FF-style relaxed exploration " "towards the nearest landmarks (according to the landmark orderings) " "and use the preferred operators of this exploration.\n\n\n" "Our implementation of the heuristic only considers preferred " "operators of the first type and does not include the second type. The " "rationale for this change is that it reduces code complexity and " "helps more cleanly separate landmark-based and FF-based computations " "in LAMA-like planner configurations. In our experiments, only " "considering preferred operators of the first type reduces performance " "when using the heuristic and its preferred operators in isolation but " "improves performance when using this heuristic in conjunction with " "the FF heuristic, as in LAMA-like planner configurations."); parser.document_language_support("action costs", "supported"); parser.document_language_support("conditional_effects", "supported if the LandmarkFactory supports " "them; otherwise ignored with " "``admissible=false`` and not allowed with " "``admissible=true``"); parser.document_language_support("axioms", "ignored with ``admissible=false``; not " "allowed with ``admissible=true``"); parser.document_property("admissible", "yes if ``admissible=true``"); // TODO: this was "yes with admissible=true and optimal cost // partitioning; otherwise no" before. parser.document_property("consistent", "complicated; needs further thought"); parser.document_property("safe", "yes except on tasks with axioms or on tasks with " "conditional effects when using a LandmarkFactory " "not supporting them"); parser.document_property("preferred operators", "yes (if enabled; see ``pref`` option)"); parser.add_option<shared_ptr<LandmarkFactory>>( "lm_factory", "the set of landmarks to use for this heuristic. " "The set of landmarks can be specified here, " "or predefined (see LandmarkFactory)."); parser.add_option<bool>("admissible", "get admissible estimate", "false"); parser.add_option<bool>( "optimal", "use optimal (LP-based) cost sharing " "(only makes sense with ``admissible=true``)", "false"); parser.add_option<bool>("pref", "identify preferred operators " "(see OptionCaveats#Using_preferred_operators_" "with_the_lmcount_heuristic)", "false"); parser.add_option<bool>("alm", "use action landmarks", "true"); lp::add_lp_solver_option_to_parser(parser); Heuristic::add_options_to_parser(parser); Options opts = parser.parse(); if (parser.dry_run()) return nullptr; else return make_shared<LandmarkCountHeuristic>(opts); } static Plugin<Evaluator> _plugin("lmcount", _parse); }
16,023
C++
41.617021
106
0.617487
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_relaxation.h
#ifndef LANDMARKS_LANDMARK_FACTORY_RELAXATION_H #define LANDMARKS_LANDMARK_FACTORY_RELAXATION_H #include "landmark_factory.h" namespace landmarks { class Exploration; class LandmarkFactoryRelaxation : public LandmarkFactory { protected: LandmarkFactoryRelaxation() = default; bool relaxed_task_solvable(const TaskProxy &task_proxy, Exploration &exploration, bool level_out, const LandmarkNode *exclude, bool compute_lvl_op = false) const; bool relaxed_task_solvable(const TaskProxy &task_proxy, Exploration &exploration, std::vector<std::vector<int>> &lvl_var, std::vector<utils::HashMap<FactPair, int>> &lvl_op, bool level_out, const LandmarkNode *exclude, bool compute_lvl_op = false) const; private: void generate_landmarks(const std::shared_ptr<AbstractTask> &task) override; virtual void generate_relaxed_landmarks(const std::shared_ptr<AbstractTask> &task, Exploration &exploration) = 0; void postprocess(const TaskProxy &task_proxy, Exploration &exploration); void calc_achievers(const TaskProxy &task_proxy, Exploration &exploration); bool achieves_non_conditional(const OperatorProxy &o, const LandmarkNode *lmp) const; void add_operator_and_propositions_to_list( const OperatorProxy &op, std::vector<utils::HashMap<FactPair, int>> &lvl_op) const; protected: /* The method discard_noncausal_landmarks assumes the graph has no conjunctive landmarks, and will not process conjunctive landmarks correctly. */ void discard_noncausal_landmarks(const TaskProxy &task_proxy, Exploration &exploration); bool is_causal_landmark(const TaskProxy &task_proxy, Exploration &exploration, const LandmarkNode &landmark) const; }; } #endif
2,132
C
40.823529
91
0.613508
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_rpg_sasp.cc
#include "landmark_factory_rpg_sasp.h" #include "landmark_graph.h" #include "util.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../utils/logging.h" #include "../utils/system.h" #include <cassert> #include <limits> using namespace std; using utils::ExitCode; namespace landmarks { LandmarkFactoryRpgSasp::LandmarkFactoryRpgSasp(const Options &opts) : disjunctive_landmarks(opts.get<bool>("disjunctive_landmarks")), use_orders(opts.get<bool>("use_orders")), only_causal_landmarks(opts.get<bool>("only_causal_landmarks")) { } void LandmarkFactoryRpgSasp::build_dtg_successors(const TaskProxy &task_proxy) { // resize data structure VariablesProxy variables = task_proxy.get_variables(); dtg_successors.resize(variables.size()); for (VariableProxy var : variables) dtg_successors[var.get_id()].resize(var.get_domain_size()); for (OperatorProxy op : task_proxy.get_operators()) { // build map for precondition unordered_map<int, int> precondition_map; for (FactProxy precondition : op.get_preconditions()) precondition_map[precondition.get_variable().get_id()] = precondition.get_value(); for (EffectProxy effect : op.get_effects()) { // build map for effect condition unordered_map<int, int> eff_condition; for (FactProxy effect_condition : effect.get_conditions()) eff_condition[effect_condition.get_variable().get_id()] = effect_condition.get_value(); // whenever the operator can change the value of a variable from pre to // post, we insert post into dtg_successors[var_id][pre] FactProxy effect_fact = effect.get_fact(); int var_id = effect_fact.get_variable().get_id(); int post = effect_fact.get_value(); if (precondition_map.count(var_id)) { int pre = precondition_map[var_id]; if (eff_condition.count(var_id) && eff_condition[var_id] != pre) continue; // confliction pre- and effect condition add_dtg_successor(var_id, pre, post); } else { if (eff_condition.count(var_id)) { add_dtg_successor(var_id, eff_condition[var_id], post); } else { int dom_size = effect_fact.get_variable().get_domain_size(); for (int pre = 0; pre < dom_size; ++pre) add_dtg_successor(var_id, pre, post); } } } } } void LandmarkFactoryRpgSasp::add_dtg_successor(int var_id, int pre, int post) { if (pre != post) dtg_successors[var_id][pre].insert(post); } void LandmarkFactoryRpgSasp::get_greedy_preconditions_for_lm( const TaskProxy &task_proxy, const LandmarkNode *lmp, const OperatorProxy &op, unordered_map<int, int> &result) const { // Computes a subset of the actual preconditions of o for achieving lmp - takes into account // operator preconditions, but only reports those effect conditions that are true for ALL // effects achieving the LM. vector<bool> has_precondition_on_var(task_proxy.get_variables().size(), false); for (FactProxy precondition : op.get_preconditions()) { result.emplace(precondition.get_variable().get_id(), precondition.get_value()); has_precondition_on_var[precondition.get_variable().get_id()] = true; } // If there is an effect but no precondition on a variable v with domain // size 2 and initially the variable has the other value than required by // the landmark then at the first time the landmark is reached the // variable must still have the initial value. State initial_state = task_proxy.get_initial_state(); EffectsProxy effects = op.get_effects(); for (EffectProxy effect : effects) { FactProxy effect_fact = effect.get_fact(); int var_id = effect_fact.get_variable().get_id(); if (!has_precondition_on_var[var_id] && effect_fact.get_variable().get_domain_size() == 2) { for (const FactPair &lm_fact : lmp->facts) { if (lm_fact.var == var_id && initial_state[var_id].get_value() != lm_fact.value) { result.emplace(var_id, initial_state[var_id].get_value()); break; } } } } // Check for lmp in conditional effects set<int> lm_props_achievable; for (EffectProxy effect : effects) { FactProxy effect_fact = effect.get_fact(); for (size_t j = 0; j < lmp->facts.size(); ++j) if (lmp->facts[j] == effect_fact.get_pair()) lm_props_achievable.insert(j); } // Intersect effect conditions of all effects that can achieve lmp unordered_map<int, int> intersection; bool init = true; for (int lm_prop : lm_props_achievable) { for (EffectProxy effect : effects) { FactProxy effect_fact = effect.get_fact(); if (!init && intersection.empty()) break; unordered_map<int, int> current_cond; if (lmp->facts[lm_prop] == effect_fact.get_pair()) { EffectConditionsProxy effect_conditions = effect.get_conditions(); if (effect_conditions.empty()) { intersection.clear(); break; } else { for (FactProxy effect_condition : effect_conditions) current_cond.emplace(effect_condition.get_variable().get_id(), effect_condition.get_value()); } } if (init) { init = false; intersection = current_cond; } else intersection = _intersect(intersection, current_cond); } } result.insert(intersection.begin(), intersection.end()); } int LandmarkFactoryRpgSasp::min_cost_for_landmark(const TaskProxy &task_proxy, LandmarkNode *bp, vector<vector<int>> &lvl_var) { int min_cost = numeric_limits<int>::max(); // For each proposition in bp... for (const FactPair &lm_fact : bp->facts) { // ...look at all achieving operators const vector<int> &op_or_axiom_ids = get_operators_including_eff(lm_fact); for (int op_or_axiom_id : op_or_axiom_ids) { OperatorProxy op = get_operator_or_axiom(task_proxy, op_or_axiom_id); // and calculate the minimum cost of those that can make // bp true for the first time according to lvl_var if (_possibly_reaches_lm(op, lvl_var, bp)) { min_cost = min(min_cost, op.get_cost()); } } } /* TODO: The following assertion fails for the unsolvable tasks that are created if the translator detects unsolvability. To reproduce, search with "astar(lmcount(lm_rhw()))" on mystery/prob07.pddl in debug mode. See issue 467 */ assert(min_cost < numeric_limits<int>::max()); return min_cost; } void LandmarkFactoryRpgSasp::found_simple_lm_and_order( const FactPair &a, LandmarkNode &b, EdgeType t) { if (lm_graph->contains_simple_landmark(a)) { LandmarkNode &simple_lm = lm_graph->get_simple_landmark(a); edge_add(simple_lm, b, t); return; } if (lm_graph->contains_disjunctive_landmark(a)) { // In issue1004, we fixed a bug in this part of the code. It now removes // the disjunctive landmark along with all its orderings from the // landmark graph and adds a new simple landmark node. Before this // change, incoming orderings were maintained, which is not always // correct for greedy necessary orderings. We now replace those // incoming orderings with natural orderings. // Simple landmarks are more informative than disjunctive ones, // remove disj. landmark and add simple one LandmarkNode *disj_lm = &lm_graph->get_disjunctive_landmark(a); // Remove all pointers to disj_lm from internal data structures (i.e., // the list of open landmarks and forward orders) auto it = find(open_landmarks.begin(), open_landmarks.end(), disj_lm); if (it != open_landmarks.end()) { open_landmarks.erase(it); } forward_orders.erase(disj_lm); // Retrieve incoming edges from disj_lm vector<LandmarkNode *> predecessors; for (auto &pred : disj_lm->parents) { predecessors.push_back(pred.first); } // Remove disj_lm from landmark graph lm_graph->remove_node(disj_lm); // Add simple landmark node LandmarkNode &simple_lm = lm_graph->add_simple_landmark(a); open_landmarks.push_back(&simple_lm); edge_add(simple_lm, b, t); // Add incoming orderings of replaced disj_lm as natural orderings to // simple_lm for (LandmarkNode *pred : predecessors) { edge_add(*pred, simple_lm, EdgeType::NATURAL); } } else { LandmarkNode &simple_lm = lm_graph->add_simple_landmark(a); open_landmarks.push_back(&simple_lm); edge_add(simple_lm, b, t); } } void LandmarkFactoryRpgSasp::found_disj_lm_and_order( const TaskProxy &task_proxy, const set<FactPair> &a, LandmarkNode &b, EdgeType t) { bool simple_lm_exists = false; // TODO: assign with FactPair::no_fact FactPair lm_prop = FactPair::no_fact; State initial_state = task_proxy.get_initial_state(); for (const FactPair &lm : a) { if (initial_state[lm.var].get_value() == lm.value) { //utils::g_log << endl << "not adding LM that's true in initial state: " //<< g_variable_name[it->first] << " -> " << it->second << endl; return; } if (lm_graph->contains_simple_landmark(lm)) { // Propositions in this disj. LM exist already as simple LMs. simple_lm_exists = true; lm_prop = lm; break; } } LandmarkNode *new_lm; if (simple_lm_exists) { // Note: don't add orders as we can't be sure that they're correct return; } else if (lm_graph->contains_overlapping_disjunctive_landmark(a)) { if (lm_graph->contains_identical_disjunctive_landmark(a)) { // LM already exists, just add order. new_lm = &lm_graph->get_disjunctive_landmark(*a.begin()); edge_add(*new_lm, b, t); return; } // LM overlaps with existing disj. LM, do not add. return; } // This LM and no part of it exist, add the LM to the landmarks graph. new_lm = &lm_graph->add_disjunctive_landmark(a); open_landmarks.push_back(new_lm); edge_add(*new_lm, b, t); } void LandmarkFactoryRpgSasp::compute_shared_preconditions( const TaskProxy &task_proxy, unordered_map<int, int> &shared_pre, vector<vector<int>> &lvl_var, LandmarkNode *bp) { /* Compute the shared preconditions of all operators that can potentially achieve landmark bp, given lvl_var (reachability in relaxed planning graph) */ bool init = true; for (const FactPair &lm_fact : bp->facts) { const vector<int> &op_ids = get_operators_including_eff(lm_fact); for (int op_or_axiom_id : op_ids) { OperatorProxy op = get_operator_or_axiom(task_proxy, op_or_axiom_id); if (!init && shared_pre.empty()) break; if (_possibly_reaches_lm(op, lvl_var, bp)) { unordered_map<int, int> next_pre; get_greedy_preconditions_for_lm(task_proxy, bp, op, next_pre); if (init) { init = false; shared_pre = next_pre; } else shared_pre = _intersect(shared_pre, next_pre); } } } } static string get_predicate_for_fact(const VariablesProxy &variables, int var_no, int value) { const string fact_name = variables[var_no].get_fact(value).get_name(); if (fact_name == "<none of those>") return ""; int predicate_pos = 0; if (fact_name.substr(0, 5) == "Atom ") { predicate_pos = 5; } else if (fact_name.substr(0, 12) == "NegatedAtom ") { predicate_pos = 12; } size_t paren_pos = fact_name.find('(', predicate_pos); if (predicate_pos == 0 || paren_pos == string::npos) { cerr << "error: cannot extract predicate from fact: " << fact_name << endl; utils::exit_with(ExitCode::SEARCH_INPUT_ERROR); } return string(fact_name.begin() + predicate_pos, fact_name.begin() + paren_pos); } void LandmarkFactoryRpgSasp::build_disjunction_classes(const TaskProxy &task_proxy) { /* The RHW landmark generation method only allows disjunctive landmarks where all atoms stem from the same PDDL predicate. This functionality is implemented via this method. The approach we use is to map each fact (var/value pair) to an equivalence class (representing all facts with the same predicate). The special class "-1" means "cannot be part of any disjunctive landmark". This is used for facts that do not belong to any predicate. Similar methods for restricting disjunctive landmarks could be implemented by just changing this function, as long as the restriction could also be implemented as an equivalence class. For example, we might simply use the finite-domain variable number as the equivalence class, which would be a cleaner method than what we currently use since it doesn't care about where the finite-domain representation comes from. (But of course making such a change would require a performance evaluation.) */ typedef map<string, int> PredicateIndex; PredicateIndex predicate_to_index; VariablesProxy variables = task_proxy.get_variables(); disjunction_classes.resize(variables.size()); for (VariableProxy var : variables) { int num_values = var.get_domain_size(); disjunction_classes[var.get_id()].reserve(num_values); for (int value = 0; value < num_values; ++value) { string predicate = get_predicate_for_fact(variables, var.get_id(), value); int disj_class; if (predicate.empty()) { disj_class = -1; } else { // Insert predicate into unordered_map or extract value that // is already there. pair<string, int> entry(predicate, predicate_to_index.size()); disj_class = predicate_to_index.insert(entry).first->second; } disjunction_classes[var.get_id()].push_back(disj_class); } } } void LandmarkFactoryRpgSasp::compute_disjunctive_preconditions( const TaskProxy &task_proxy, vector<set<FactPair>> &disjunctive_pre, vector<vector<int>> &lvl_var, LandmarkNode *bp) { /* Compute disjunctive preconditions from all operators than can potentially achieve landmark bp, given lvl_var (reachability in relaxed planning graph). A disj. precondition is a set of facts which contains one precondition fact from each of the operators, which we additionally restrict so that each fact in the set stems from the same PDDL predicate. */ vector<int> op_or_axiom_ids; for (const FactPair &lm_fact : bp->facts) { const vector<int> &tmp_op_or_axiom_ids = get_operators_including_eff(lm_fact); for (int op_or_axiom_id : tmp_op_or_axiom_ids) op_or_axiom_ids.push_back(op_or_axiom_id); } int num_ops = 0; unordered_map<int, vector<FactPair>> preconditions; // maps from // pddl_proposition_indeces to props unordered_map<int, set<int>> used_operators; // tells for each // proposition which operators use it for (size_t i = 0; i < op_or_axiom_ids.size(); ++i) { OperatorProxy op = get_operator_or_axiom(task_proxy, op_or_axiom_ids[i]); if (_possibly_reaches_lm(op, lvl_var, bp)) { ++num_ops; unordered_map<int, int> next_pre; get_greedy_preconditions_for_lm(task_proxy, bp, op, next_pre); for (const auto &pre : next_pre) { int disj_class = disjunction_classes[pre.first][pre.second]; if (disj_class == -1) { // This fact may not participate in any disjunctive LMs // since it has no associated predicate. continue; } // Only deal with propositions that are not shared preconditions // (those have been found already and are simple landmarks). const FactPair pre_fact(pre.first, pre.second); if (!lm_graph->contains_simple_landmark(pre_fact)) { preconditions[disj_class].push_back(pre_fact); used_operators[disj_class].insert(i); } } } } for (const auto &pre : preconditions) { if (static_cast<int>(used_operators[pre.first].size()) == num_ops) { set<FactPair> pre_set; // the set gets rid of duplicate predicates pre_set.insert(pre.second.begin(), pre.second.end()); if (pre_set.size() > 1) { // otherwise this LM is not actually a disjunctive LM disjunctive_pre.push_back(pre_set); } } } } void LandmarkFactoryRpgSasp::generate_relaxed_landmarks( const shared_ptr<AbstractTask> &task, Exploration &exploration) { TaskProxy task_proxy(*task); utils::g_log << "Generating landmarks using the RPG/SAS+ approach\n"; build_dtg_successors(task_proxy); build_disjunction_classes(task_proxy); for (FactProxy goal : task_proxy.get_goals()) { LandmarkNode &lmn = lm_graph->add_simple_landmark(goal.get_pair()); lmn.is_true_in_goal = true; open_landmarks.push_back(&lmn); } State initial_state = task_proxy.get_initial_state(); while (!open_landmarks.empty()) { LandmarkNode *bp = open_landmarks.front(); open_landmarks.pop_front(); assert(forward_orders[bp].empty()); if (!bp->is_true_in_state(initial_state)) { // Backchain from landmark bp and compute greedy necessary predecessors. // Firstly, collect information about the earliest possible time step in a // relaxed plan that propositions are achieved (in lvl_var) and operators // applied (in lvl_ops). vector<vector<int>> lvl_var; vector<utils::HashMap<FactPair, int>> lvl_op; relaxed_task_solvable(task_proxy, exploration, lvl_var, lvl_op, true, bp); // Use this information to determine all operators that can possibly achieve bp // for the first time, and collect any precondition propositions that all such // operators share (if there are any). unordered_map<int, int> shared_pre; compute_shared_preconditions(task_proxy, shared_pre, lvl_var, bp); // All such shared preconditions are landmarks, and greedy necessary predecessors of bp. for (const auto &pre : shared_pre) { found_simple_lm_and_order(FactPair(pre.first, pre.second), *bp, EdgeType::GREEDY_NECESSARY); } // Extract additional orders from relaxed planning graph and DTG. approximate_lookahead_orders(task_proxy, lvl_var, bp); // Use the information about possibly achieving operators of bp to set its min cost. bp->cost = min_cost_for_landmark(task_proxy, bp, lvl_var); // Process achieving operators again to find disj. LMs vector<set<FactPair>> disjunctive_pre; compute_disjunctive_preconditions(task_proxy, disjunctive_pre, lvl_var, bp); for (const auto &preconditions : disjunctive_pre) if (preconditions.size() < 5) { // We don't want disj. LMs to get too big found_disj_lm_and_order(task_proxy, preconditions, *bp, EdgeType::GREEDY_NECESSARY); } } } add_lm_forward_orders(); if (!disjunctive_landmarks) { discard_disjunctive_landmarks(); } if (!use_orders) { discard_all_orderings(); } if (only_causal_landmarks) { discard_noncausal_landmarks(task_proxy, exploration); } } void LandmarkFactoryRpgSasp::approximate_lookahead_orders( const TaskProxy &task_proxy, const vector<vector<int>> &lvl_var, LandmarkNode *lmp) { // Find all var-val pairs that can only be reached after the landmark // (according to relaxed plan graph as captured in lvl_var) // the result is saved in the node member variable forward_orders, and will be // used later, when the phase of finding LMs has ended (because at the // moment we don't know which of these var-val pairs will be LMs). VariablesProxy variables = task_proxy.get_variables(); find_forward_orders(variables, lvl_var, lmp); // Use domain transition graphs to find further orders. Only possible if lmp is // a simple landmark. if (lmp->disjunctive) return; const FactPair &lmk = lmp->facts[0]; // Collect in "unreached" all values of the LM variable that cannot be reached // before the LM value (in the relaxed plan graph) int domain_size = variables[lmk.var].get_domain_size(); unordered_set<int> unreached(domain_size); for (int value = 0; value < domain_size; ++value) if (lvl_var[lmk.var][value] == numeric_limits<int>::max() && lmk.value != value) unreached.insert(value); // The set "exclude" will contain all those values of the LM variable that // cannot be reached before the LM value (as in "unreached") PLUS // one value that CAN be reached State initial_state = task_proxy.get_initial_state(); for (int value = 0; value < domain_size; ++value) if (unreached.find(value) == unreached.end() && lmk.value != value) { unordered_set<int> exclude(domain_size); exclude = unreached; exclude.insert(value); // If that value is crucial for achieving the LM from the initial state, // we have found a new landmark. if (!domain_connectivity(initial_state, lmk, exclude)) found_simple_lm_and_order(FactPair(lmk.var, value), *lmp, EdgeType::NATURAL); } } bool LandmarkFactoryRpgSasp::domain_connectivity(const State &initial_state, const FactPair &landmark, const unordered_set<int> &exclude) { /* Tests whether in the domain transition graph of the LM variable, there is a path from the initial state value to the LM value, without passing through any value in "exclude". If not, that means that one of the values in "exclude" is crucial for achieving the landmark (i.e. is on every path to the LM). */ int var = landmark.var; assert(landmark.value != initial_state[var].get_value()); // no initial state landmarks // The value that we want to achieve must not be excluded: assert(exclude.find(landmark.value) == exclude.end()); // If the value in the initial state is excluded, we won't achieve our goal value: if (exclude.find(initial_state[var].get_value()) != exclude.end()) return false; list<int> open; unordered_set<int> closed(initial_state[var].get_variable().get_domain_size()); closed = exclude; open.push_back(initial_state[var].get_value()); closed.insert(initial_state[var].get_value()); const vector<unordered_set<int>> &successors = dtg_successors[var]; while (closed.find(landmark.value) == closed.end()) { if (open.empty()) // landmark not in closed and nothing more to insert return false; const int c = open.front(); open.pop_front(); for (int val : successors[c]) { if (closed.find(val) == closed.end()) { open.push_back(val); closed.insert(val); } } } return true; } void LandmarkFactoryRpgSasp::find_forward_orders(const VariablesProxy &variables, const vector<vector<int>> &lvl_var, LandmarkNode *lmp) { /* lmp is ordered before any var-val pair that cannot be reached before lmp according to relaxed planning graph (as captured in lvl_var). These orders are saved in the node member variable "forward_orders". */ for (VariableProxy var : variables) for (int value = 0; value < var.get_domain_size(); ++value) { if (lvl_var[var.get_id()][value] != numeric_limits<int>::max()) continue; const FactPair fact(var.get_id(), value); bool insert = true; for (const FactPair &lm_fact : lmp->facts) { if (fact != lm_fact) { // Make sure there is no operator that reaches both lm and (var, value) at the same time bool intersection_empty = true; const vector<int> &reach_fact = get_operators_including_eff(fact); const vector<int> &reach_lm = get_operators_including_eff(lm_fact); for (size_t j = 0; j < reach_fact.size() && intersection_empty; ++j) for (size_t k = 0; k < reach_lm.size() && intersection_empty; ++k) if (reach_fact[j] == reach_lm[k]) intersection_empty = false; if (!intersection_empty) { insert = false; break; } } else { insert = false; break; } } if (insert) forward_orders[lmp].insert(fact); } } void LandmarkFactoryRpgSasp::add_lm_forward_orders() { for (auto &node : lm_graph->get_nodes()) { for (const auto &node2_pair : forward_orders[node.get()]) { if (lm_graph->contains_simple_landmark(node2_pair)) { LandmarkNode &node2 = lm_graph->get_simple_landmark(node2_pair); edge_add(*node, node2, EdgeType::NATURAL); } } forward_orders[node.get()].clear(); } } void LandmarkFactoryRpgSasp::discard_disjunctive_landmarks() { /* Using disjunctive landmarks during landmark generation can be beneficial even if we don't want to use disjunctive landmarks during search. So we allow removing disjunctive landmarks after landmark generation. */ if (lm_graph->get_num_disjunctive_landmarks() > 0) { utils::g_log << "Discarding " << lm_graph->get_num_disjunctive_landmarks() << " disjunctive landmarks" << endl; lm_graph->remove_node_if( [](const LandmarkNode &node) {return node.disjunctive;}); } } bool LandmarkFactoryRpgSasp::computes_reasonable_orders() const { return false; } bool LandmarkFactoryRpgSasp::supports_conditional_effects() const { return true; } static shared_ptr<LandmarkFactory> _parse(OptionParser &parser) { parser.document_synopsis( "RHW Landmarks", "The landmark generation method introduced by " "Richter, Helmert and Westphal (AAAI 2008)."); parser.add_option<bool>("disjunctive_landmarks", "keep disjunctive landmarks", "true"); _add_use_orders_option_to_parser(parser); _add_only_causal_landmarks_option_to_parser(parser); Options opts = parser.parse(); parser.document_language_support("conditional_effects", "supported"); if (parser.dry_run()) return nullptr; else return make_shared<LandmarkFactoryRpgSasp>(opts); } static Plugin<LandmarkFactory> _plugin("lm_rhw", _parse); }
28,535
C++
42.633027
108
0.600035
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/exploration.cc
#include "exploration.h" #include "util.h" #include "../task_utils/task_properties.h" #include "../utils/collections.h" #include "../utils/hash.h" #include "../utils/logging.h" #include <algorithm> #include <cassert> #include <limits> using namespace std; namespace landmarks { /* Integration Note: this class is the same as (rich man's) FF heuristic (taken from hector branch) except for the following: - Added-on functionality for excluding certain operators from the relaxed exploration (these operators are never applied, as necessary for landmark computation) - Exploration can be done either using h_max or h_add criterion (h_max is needed during landmark generation, h_add later for heuristic computations) - Unary operators are not simplified, because this may conflict with excluded operators. (For an example, consider that unary operator o1 is thrown out during simplify() because it is dominated by unary operator o2, but then o2 is excluded during an exploration ==> the shared effect of o1 and o2 is wrongly never reached in the exploration.) - Added-on functionality to check for a set of propositions which one is reached first by the relaxed exploration, and extract preferred operators for this cheapest proposition (needed for planning to nearest landmark). */ const int Exploration::MAX_COST_VALUE; // Construction and destruction Exploration::Exploration(const TaskProxy &task_proxy) : task_proxy(task_proxy), did_write_overflow_warning(false) { utils::g_log << "Initializing Exploration..." << endl; // Build propositions. for (VariableProxy var : task_proxy.get_variables()) { int var_id = var.get_id(); propositions.push_back(vector<ExProposition>(var.get_domain_size())); for (int value = 0; value < var.get_domain_size(); ++value) { propositions[var_id][value].fact = FactPair(var_id, value); } } // Build goal propositions. for (FactProxy goal_fact : task_proxy.get_goals()) { int var_id = goal_fact.get_variable().get_id(); int value = goal_fact.get_value(); propositions[var_id][value].is_goal_condition = true; propositions[var_id][value].is_termination_condition = true; goal_propositions.push_back(&propositions[var_id][value]); termination_propositions.push_back(&propositions[var_id][value]); } // Build unary operators for operators and axioms. OperatorsProxy operators = task_proxy.get_operators(); for (OperatorProxy op : operators) build_unary_operators(op); AxiomsProxy axioms = task_proxy.get_axioms(); for (OperatorProxy op : axioms) build_unary_operators(op); // Cross-reference unary operators. for (ExUnaryOperator &op : unary_operators) { for (ExProposition *pre : op.precondition) pre->precondition_of.push_back(&op); } } void Exploration::increase_cost(int &cost, int amount) { assert(cost >= 0); assert(amount >= 0); cost += amount; if (cost > MAX_COST_VALUE) { write_overflow_warning(); cost = MAX_COST_VALUE; } } void Exploration::write_overflow_warning() { if (!did_write_overflow_warning) { // TODO: Should have a planner-wide warning mechanism to handle // things like this. utils::g_log << "WARNING: overflow on landmark exploration h^add! Costs clamped to " << MAX_COST_VALUE << endl; did_write_overflow_warning = true; } } void Exploration::build_unary_operators(const OperatorProxy &op) { // Note: changed from the original to allow sorting of operator conditions int base_cost = op.get_cost(); vector<ExProposition *> precondition; vector<FactPair> precondition_facts1; for (FactProxy pre : op.get_preconditions()) { precondition_facts1.push_back(pre.get_pair()); } for (EffectProxy effect : op.get_effects()) { vector<FactPair> precondition_facts2(precondition_facts1); EffectConditionsProxy effect_conditions = effect.get_conditions(); for (FactProxy effect_condition : effect_conditions) { precondition_facts2.push_back(effect_condition.get_pair()); } sort(precondition_facts2.begin(), precondition_facts2.end()); for (const FactPair &precondition_fact : precondition_facts2) precondition.push_back(&propositions[precondition_fact.var] [precondition_fact.value]); FactProxy effect_fact = effect.get_fact(); ExProposition *effect_proposition = &propositions[effect_fact.get_variable().get_id()][effect_fact.get_value()]; int op_or_axiom_id = get_operator_or_axiom_id(op); unary_operators.emplace_back(precondition, effect_proposition, op_or_axiom_id, base_cost); precondition.clear(); precondition_facts2.clear(); } } // heuristic computation void Exploration::setup_exploration_queue(const State &state, const vector<FactPair> &excluded_props, const unordered_set<int> &excluded_op_ids, bool use_h_max) { prop_queue.clear(); for (size_t var_id = 0; var_id < propositions.size(); ++var_id) { for (size_t value = 0; value < propositions[var_id].size(); ++value) { ExProposition &prop = propositions[var_id][value]; prop.h_add_cost = -1; prop.h_max_cost = -1; prop.depth = -1; prop.marked = false; } } for (const FactPair &fact : excluded_props) { ExProposition &prop = propositions[fact.var][fact.value]; prop.h_add_cost = -2; } // Deal with current state. for (FactProxy fact : state) { ExProposition *init_prop = &propositions[fact.get_variable().get_id()][fact.get_value()]; enqueue_if_necessary(init_prop, 0, 0, 0, use_h_max); } // Initialize operator data, deal with precondition-free operators/axioms. for (ExUnaryOperator &op : unary_operators) { op.unsatisfied_preconditions = op.precondition.size(); if (!excluded_op_ids.empty() && (op.effect->h_add_cost == -2 || excluded_op_ids.count(op.op_or_axiom_id))) { op.h_add_cost = -2; // operator will not be applied during relaxed exploration continue; } op.h_add_cost = op.base_cost; // will be increased by precondition costs op.h_max_cost = op.base_cost; op.depth = -1; if (op.unsatisfied_preconditions == 0) { op.depth = 0; int depth = op.is_induced_by_axiom(task_proxy) ? 0 : 1; enqueue_if_necessary(op.effect, op.base_cost, depth, &op, use_h_max); } } } void Exploration::relaxed_exploration(bool use_h_max, bool level_out) { int unsolved_goals = termination_propositions.size(); while (!prop_queue.empty()) { pair<int, ExProposition *> top_pair = prop_queue.pop(); int distance = top_pair.first; ExProposition *prop = top_pair.second; int prop_cost; if (use_h_max) prop_cost = prop->h_max_cost; else prop_cost = prop->h_add_cost; assert(prop_cost <= distance); if (prop_cost < distance) continue; if (!level_out && prop->is_termination_condition && --unsolved_goals == 0) return; const vector<ExUnaryOperator *> &triggered_operators = prop->precondition_of; for (size_t i = 0; i < triggered_operators.size(); ++i) { ExUnaryOperator *unary_op = triggered_operators[i]; if (unary_op->h_add_cost == -2) // operator is not applied continue; --unary_op->unsatisfied_preconditions; increase_cost(unary_op->h_add_cost, prop_cost); unary_op->h_max_cost = max(prop_cost + unary_op->base_cost, unary_op->h_max_cost); unary_op->depth = max(unary_op->depth, prop->depth); assert(unary_op->unsatisfied_preconditions >= 0); if (unary_op->unsatisfied_preconditions == 0) { int depth = unary_op->is_induced_by_axiom(task_proxy) ? unary_op->depth : unary_op->depth + 1; if (use_h_max) enqueue_if_necessary(unary_op->effect, unary_op->h_max_cost, depth, unary_op, use_h_max); else enqueue_if_necessary(unary_op->effect, unary_op->h_add_cost, depth, unary_op, use_h_max); } } } } void Exploration::enqueue_if_necessary(ExProposition *prop, int cost, int depth, ExUnaryOperator *op, bool use_h_max) { assert(cost >= 0); if (use_h_max && (prop->h_max_cost == -1 || prop->h_max_cost > cost)) { prop->h_max_cost = cost; prop->depth = depth; prop->reached_by = op; prop_queue.push(cost, prop); } else if (!use_h_max && (prop->h_add_cost == -1 || prop->h_add_cost > cost)) { prop->h_add_cost = cost; prop->depth = depth; prop->reached_by = op; prop_queue.push(cost, prop); } if (use_h_max) assert(prop->h_max_cost != -1 && prop->h_max_cost <= cost); else assert(prop->h_add_cost != -1 && prop->h_add_cost <= cost); } void Exploration::compute_reachability_with_excludes(vector<vector<int>> &lvl_var, vector<utils::HashMap<FactPair, int>> &lvl_op, bool level_out, const vector<FactPair> &excluded_props, const unordered_set<int> &excluded_op_ids, bool compute_lvl_ops) { // Perform exploration using h_max-values setup_exploration_queue(task_proxy.get_initial_state(), excluded_props, excluded_op_ids, true); relaxed_exploration(true, level_out); // Copy reachability information into lvl_var and lvl_op for (size_t var_id = 0; var_id < propositions.size(); ++var_id) { for (size_t value = 0; value < propositions[var_id].size(); ++value) { ExProposition &prop = propositions[var_id][value]; if (prop.h_max_cost >= 0) lvl_var[var_id][value] = prop.h_max_cost; } } if (compute_lvl_ops) { for (ExUnaryOperator &op : unary_operators) { // H_max_cost of operator might be wrongly 0 or 1, if the operator // did not get applied during relaxed exploration. Look through // preconditions and adjust. for (ExProposition *prop : op.precondition) { if (prop->h_max_cost == -1) { // Operator cannot be applied due to unreached precondition op.h_max_cost = numeric_limits<int>::max(); break; } else if (op.h_max_cost < prop->h_max_cost + op.base_cost) op.h_max_cost = prop->h_max_cost + op.base_cost; } if (op.h_max_cost == numeric_limits<int>::max()) break; // We subtract 1 to keep semantics for landmark code: // if op can achieve prop at time step i+1, // its index (for prop) is i, where the initial state is time step 0. const FactPair &effect = op.effect->fact; assert(lvl_op[op.op_or_axiom_id].count(effect)); int new_lvl = op.h_max_cost - 1; // If we have found a cheaper achieving operator, adjust h_max cost of proposition. if (lvl_op[op.op_or_axiom_id].find(effect)->second > new_lvl) lvl_op[op.op_or_axiom_id].find(effect)->second = new_lvl; } } } }
12,140
C++
41.451049
120
0.583361
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory.h
#ifndef LANDMARKS_LANDMARK_FACTORY_H #define LANDMARKS_LANDMARK_FACTORY_H #include "landmark_graph.h" #include <list> #include <map> #include <memory> #include <set> #include <unordered_map> #include <unordered_set> #include <vector> class TaskProxy; namespace options { class OptionParser; class Options; } namespace landmarks { /* TODO: Change order to private -> protected -> public (omitted so far to minimize diff) */ class LandmarkFactory { public: virtual ~LandmarkFactory() = default; LandmarkFactory(const LandmarkFactory &) = delete; std::shared_ptr<LandmarkGraph> compute_lm_graph(const std::shared_ptr<AbstractTask> &task); /* TODO: Currently reasonable orders are not supported for admissible landmark count heuristics, which is why the heuristic needs to know whether the factory computes reasonable orders. Once issue383 is dealt with we should be able to use reasonable orders for admissible heuristics and this method can be removed. */ virtual bool computes_reasonable_orders() const = 0; virtual bool supports_conditional_effects() const = 0; protected: LandmarkFactory() = default; std::shared_ptr<LandmarkGraph> lm_graph; void edge_add(LandmarkNode &from, LandmarkNode &to, EdgeType type); void discard_all_orderings(); void mk_acyclic_graph(); bool is_landmark_precondition(const OperatorProxy &op, const LandmarkNode *lmp) const; const std::vector<int> &get_operators_including_eff(const FactPair &eff) const { return operators_eff_lookup[eff.var][eff.value]; } private: AbstractTask *lm_graph_task; virtual void generate_landmarks(const std::shared_ptr<AbstractTask> &task) = 0; std::vector<std::vector<std::vector<int>>> operators_eff_lookup; int loop_acyclic_graph(LandmarkNode &lmn, std::unordered_set<LandmarkNode *> &acyclic_node_set); bool remove_first_weakest_cycle_edge(LandmarkNode *cur, std::list<std::pair<LandmarkNode *, EdgeType>> &path, std::list<std::pair<LandmarkNode *, EdgeType>>::iterator it); void generate_operators_lookups(const TaskProxy &task_proxy); }; extern void _add_use_orders_option_to_parser(options::OptionParser &parser); extern void _add_only_causal_landmarks_option_to_parser(options::OptionParser &parser); } #endif
2,424
C
30.493506
102
0.697607
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_graph.h
#ifndef LANDMARKS_LANDMARK_GRAPH_H #define LANDMARKS_LANDMARK_GRAPH_H #include "../task_proxy.h" #include "../utils/hash.h" #include <cassert> #include <list> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <vector> namespace landmarks { enum class EdgeType { /* NOTE: The code relies on the fact that larger numbers are stronger in the sense that, e.g., every greedy-necessary ordering is also natural and reasonable. (It is a sad fact of terminology that necessary is indeed a special case of greedy-necessary, i.e., every necessary ordering is greedy-necessary, but not vice versa. */ NECESSARY = 4, GREEDY_NECESSARY = 3, NATURAL = 2, REASONABLE = 1, OBEDIENT_REASONABLE = 0 }; class LandmarkNode { int id; public: LandmarkNode(std::vector<FactPair> &facts, bool disjunctive, bool conjunctive) : id(-1), facts(facts), disjunctive(disjunctive), conjunctive(conjunctive), is_true_in_goal(false), cost(1), is_derived(false) { } std::vector<FactPair> facts; bool disjunctive; bool conjunctive; std::unordered_map<LandmarkNode *, EdgeType> parents; std::unordered_map<LandmarkNode *, EdgeType> children; bool is_true_in_goal; // Cost of achieving the landmark (as determined by the landmark factory) int cost; bool is_derived; std::set<int> first_achievers; std::set<int> possible_achievers; int get_id() const { return id; } // TODO: Should possibly not be changeable void set_id(int new_id) { assert(id == -1 || new_id == id); id = new_id; } bool is_true_in_state(const State &state) const; }; using LandmarkSet = std::unordered_set<const LandmarkNode *>; class LandmarkGraph { public: /* TODO: get rid of this by removing get_nodes() and instead offering functions begin() and end() with an iterator class, so users of the LandmarkGraph can do loops like this: for (const LandmarkNode &n : graph) {...} */ using Nodes = std::vector<std::unique_ptr<LandmarkNode>>; private: int num_conjunctive_landmarks; int num_disjunctive_landmarks; utils::HashMap<FactPair, LandmarkNode *> simple_landmarks_to_nodes; utils::HashMap<FactPair, LandmarkNode *> disjunctive_landmarks_to_nodes; Nodes nodes; void remove_node_occurrences(LandmarkNode *node); public: /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ LandmarkGraph(); // needed by both landmarkgraph-factories and non-landmarkgraph-factories const Nodes &get_nodes() const { return nodes; } // needed by both landmarkgraph-factories and non-landmarkgraph-factories int get_num_landmarks() const { return nodes.size(); } /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ int get_num_disjunctive_landmarks() const { return num_disjunctive_landmarks; } /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ int get_num_conjunctive_landmarks() const { return num_conjunctive_landmarks; } /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ int get_num_edges() const; // only needed by non-landmarkgraph-factories LandmarkNode *get_landmark(int index) const; // only needed by non-landmarkgraph-factories LandmarkNode *get_landmark(const FactPair &fact) const; /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ LandmarkNode &get_simple_landmark(const FactPair &fact) const; /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ LandmarkNode &get_disjunctive_landmark(const FactPair &fact) const; /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. It is not needed by HMLandmarkFactory*/ bool contains_simple_landmark(const FactPair &lm) const; /* Only used internally. */ bool contains_disjunctive_landmark(const FactPair &lm) const; /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. It is not needed by HMLandmarkFactory*/ bool contains_overlapping_disjunctive_landmark(const std::set<FactPair> &lm) const; /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ bool contains_identical_disjunctive_landmark(const std::set<FactPair> &lm) const; /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. It is not needed by HMLandmarkFactory*/ bool contains_landmark(const FactPair &fact) const; /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ LandmarkNode &add_simple_landmark(const FactPair &lm); /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ LandmarkNode &add_disjunctive_landmark(const std::set<FactPair> &lm); /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ LandmarkNode &add_conjunctive_landmark(const std::set<FactPair> &lm); /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ void remove_node(LandmarkNode *node); void remove_node_if( const std::function<bool (const LandmarkNode &)> &remove_node_condition); /* This is needed only by landmark graph factories and will disappear when moving landmark graph creation there. */ void set_landmark_ids(); }; } #endif
6,165
C
35.922155
87
0.698135
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_rpg_exhaust.h
#ifndef LANDMARKS_LANDMARK_FACTORY_RPG_EXHAUST_H #define LANDMARKS_LANDMARK_FACTORY_RPG_EXHAUST_H #include "landmark_factory_relaxation.h" namespace landmarks { class LandmarkFactoryRpgExhaust : public LandmarkFactoryRelaxation { const bool only_causal_landmarks; virtual void generate_relaxed_landmarks(const std::shared_ptr<AbstractTask> &task, Exploration &exploration) override; public: explicit LandmarkFactoryRpgExhaust(const options::Options &opts); virtual bool computes_reasonable_orders() const override; virtual bool supports_conditional_effects() const override; }; } #endif
656
C
30.285713
86
0.739329
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory.cc
#include "landmark_factory.h" #include "landmark_graph.h" #include "util.h" #include "../option_parser.h" #include "../plugin.h" #include "../task_proxy.h" #include "../utils/logging.h" #include "../utils/memory.h" #include "../utils/timer.h" #include <fstream> #include <limits> using namespace std; namespace landmarks { /* TODO: Update this comment Note: To allow reusing landmark graphs, we use the following temporary solution. Landmark factories cache the first landmark graph they compute, so each call to this function returns the same graph. Asking for landmark graphs of different tasks is an error and will exit with SEARCH_UNSUPPORTED. If you want to compute different landmark graphs for different Exploration objects, you have to use separate landmark factories. This solution remains temporary as long as the question of when and how to reuse landmark graphs is open. As all heuristics will work on task transformations in the future, this function will also get access to a TaskProxy. Then we need to ensure that the TaskProxy used by the Exploration object is the same as the TaskProxy object passed to this function. */ shared_ptr<LandmarkGraph> LandmarkFactory::compute_lm_graph( const shared_ptr<AbstractTask> &task) { if (lm_graph) { if (lm_graph_task != task.get()) { cerr << "LandmarkFactory was asked to compute landmark graphs for " << "two different tasks. This is currently not supported." << endl; utils::exit_with(utils::ExitCode::SEARCH_UNSUPPORTED); } return lm_graph; } lm_graph_task = task.get(); utils::Timer lm_generation_timer; lm_graph = make_shared<LandmarkGraph>(); TaskProxy task_proxy(*task); generate_operators_lookups(task_proxy); generate_landmarks(task); utils::g_log << "Landmarks generation time: " << lm_generation_timer << endl; if (lm_graph->get_num_landmarks() == 0) utils::g_log << "Warning! No landmarks found. Task unsolvable?" << endl; else { utils::g_log << "Discovered " << lm_graph->get_num_landmarks() << " landmarks, of which " << lm_graph->get_num_disjunctive_landmarks() << " are disjunctive and " << lm_graph->get_num_conjunctive_landmarks() << " are conjunctive." << endl; utils::g_log << lm_graph->get_num_edges() << " edges" << endl; } return lm_graph; } bool LandmarkFactory::is_landmark_precondition(const OperatorProxy &op, const LandmarkNode *lmp) const { /* Test whether the landmark is used by the operator as a precondition. A disjunctive landmarks is used if one of its disjuncts is used. */ assert(lmp); for (FactProxy pre : op.get_preconditions()) { for (const FactPair &lm_fact : lmp->facts) { if (pre.get_pair() == lm_fact) return true; } } return false; } void LandmarkFactory::edge_add(LandmarkNode &from, LandmarkNode &to, EdgeType type) { /* Adds an edge in the landmarks graph if there is no contradicting edge (simple measure to reduce cycles. If the edge is already present, the stronger edge type wins. */ assert(&from != &to); assert(from.parents.find(&to) == from.parents.end() || type <= EdgeType::REASONABLE); assert(to.children.find(&from) == to.children.end() || type <= EdgeType::REASONABLE); if (type == EdgeType::REASONABLE || type == EdgeType::OBEDIENT_REASONABLE) { // simple cycle test if (from.parents.find(&to) != from.parents.end()) { // Edge in opposite direction exists //utils::g_log << "edge in opposite direction exists" << endl; if (from.parents.find(&to)->second > type) // Stronger order present, return return; // Edge in opposite direction is weaker, delete from.parents.erase(&to); to.children.erase(&from); } } // If edge already exists, remove if weaker if (from.children.find(&to) != from.children.end() && from.children.find( &to)->second < type) { from.children.erase(&to); assert(to.parents.find(&from) != to.parents.end()); to.parents.erase(&from); assert(to.parents.find(&from) == to.parents.end()); assert(from.children.find(&to) == from.children.end()); } // If edge does not exist (or has just been removed), insert if (from.children.find(&to) == from.children.end()) { assert(to.parents.find(&from) == to.parents.end()); from.children.emplace(&to, type); to.parents.emplace(&from, type); //utils::g_log << "added parent with address " << &from << endl; } assert(from.children.find(&to) != from.children.end()); assert(to.parents.find(&from) != to.parents.end()); } void LandmarkFactory::discard_all_orderings() { utils::g_log << "Removing all orderings." << endl; for (auto &node : lm_graph->get_nodes()) { node->children.clear(); node->parents.clear(); } } void LandmarkFactory::mk_acyclic_graph() { unordered_set<LandmarkNode *> acyclic_node_set(lm_graph->get_num_landmarks()); int removed_edges = 0; for (auto &node : lm_graph->get_nodes()) { if (acyclic_node_set.find(node.get()) == acyclic_node_set.end()) removed_edges += loop_acyclic_graph(*node, acyclic_node_set); } // [Malte] Commented out the following assertion because // the old method for this is no longer available. // assert(acyclic_node_set.size() == number_of_landmarks()); utils::g_log << "Removed " << removed_edges << " reasonable or obedient reasonable orders" << endl; } bool LandmarkFactory::remove_first_weakest_cycle_edge(LandmarkNode *cur, list<pair<LandmarkNode *, EdgeType>> &path, list<pair<LandmarkNode *, EdgeType>>::iterator it) { LandmarkNode *parent_p = 0; LandmarkNode *child_p = 0; for (list<pair<LandmarkNode *, EdgeType>>::iterator it2 = it; it2 != path.end(); ++it2) { EdgeType edge = it2->second; if (edge == EdgeType::REASONABLE || edge == EdgeType::OBEDIENT_REASONABLE) { parent_p = it2->first; if (*it2 == path.back()) { child_p = cur; break; } else { list<pair<LandmarkNode *, EdgeType>>::iterator child_it = it2; ++child_it; child_p = child_it->first; } if (edge == EdgeType::OBEDIENT_REASONABLE) break; // else no break since o_r order could still appear in list } } assert(parent_p != 0 && child_p != 0); assert(parent_p->children.find(child_p) != parent_p->children.end()); assert(child_p->parents.find(parent_p) != child_p->parents.end()); parent_p->children.erase(child_p); child_p->parents.erase(parent_p); return true; } int LandmarkFactory::loop_acyclic_graph(LandmarkNode &lmn, unordered_set<LandmarkNode *> &acyclic_node_set) { assert(acyclic_node_set.find(&lmn) == acyclic_node_set.end()); int nr_removed = 0; list<pair<LandmarkNode *, EdgeType>> path; unordered_set<LandmarkNode *> visited = unordered_set<LandmarkNode *>(lm_graph->get_num_landmarks()); LandmarkNode *cur = &lmn; while (true) { assert(acyclic_node_set.find(cur) == acyclic_node_set.end()); if (visited.find(cur) != visited.end()) { // cycle // find other occurrence of cur node in path list<pair<LandmarkNode *, EdgeType>>::iterator it; for (it = path.begin(); it != path.end(); ++it) { if (it->first == cur) break; } assert(it != path.end()); // remove edge from graph remove_first_weakest_cycle_edge(cur, path, it); //assert(removed); ++nr_removed; path.clear(); cur = &lmn; visited.clear(); continue; } visited.insert(cur); bool empty = true; for (const auto &child : cur->children) { LandmarkNode *child_p = child.first; EdgeType edge = child.second; if (acyclic_node_set.find(child_p) == acyclic_node_set.end()) { path.emplace_back(cur, edge); cur = child_p; empty = false; break; } } if (!empty) continue; // backtrack visited.erase(cur); acyclic_node_set.insert(cur); if (!path.empty()) { cur = path.back().first; path.pop_back(); visited.erase(cur); } else break; } assert(acyclic_node_set.find(&lmn) != acyclic_node_set.end()); return nr_removed; } void LandmarkFactory::generate_operators_lookups(const TaskProxy &task_proxy) { /* Build datastructures for efficient landmark computation. Map propositions to the operators that achieve them or have them as preconditions */ VariablesProxy variables = task_proxy.get_variables(); operators_eff_lookup.resize(variables.size()); for (VariableProxy var : variables) { operators_eff_lookup[var.get_id()].resize(var.get_domain_size()); } OperatorsProxy operators = task_proxy.get_operators(); for (OperatorProxy op : operators) { const EffectsProxy effects = op.get_effects(); for (EffectProxy effect : effects) { const FactProxy effect_fact = effect.get_fact(); operators_eff_lookup[effect_fact.get_variable().get_id()][effect_fact.get_value()].push_back( get_operator_or_axiom_id(op)); } } for (OperatorProxy axiom : task_proxy.get_axioms()) { const EffectsProxy effects = axiom.get_effects(); for (EffectProxy effect : effects) { const FactProxy effect_fact = effect.get_fact(); operators_eff_lookup[effect_fact.get_variable().get_id()][effect_fact.get_value()].push_back( get_operator_or_axiom_id(axiom)); } } } void _add_use_orders_option_to_parser(OptionParser &parser) { parser.add_option<bool>("use_orders", "use orders between landmarks", "true"); } void _add_only_causal_landmarks_option_to_parser(OptionParser &parser) { parser.add_option<bool>("only_causal_landmarks", "keep only causal landmarks", "false"); } static PluginTypePlugin<LandmarkFactory> _type_plugin( "LandmarkFactory", "A landmark factory specification is either a newly created " "instance or a landmark factory that has been defined previously. " "This page describes how one can specify a new landmark factory instance. " "For re-using landmark factories, see OptionSyntax#Landmark_Predefinitions.", "landmarks"); }
11,236
C++
38.017361
106
0.59434
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_count_heuristic.h
#ifndef LANDMARKS_LANDMARK_COUNT_HEURISTIC_H #define LANDMARKS_LANDMARK_COUNT_HEURISTIC_H #include "landmark_graph.h" #include "../heuristic.h" class BitsetView; namespace successor_generator { class SuccessorGenerator; } namespace landmarks { class LandmarkCostAssignment; class LandmarkStatusManager; class LandmarkCountHeuristic : public Heuristic { std::shared_ptr<LandmarkGraph> lgraph; const bool use_preferred_operators; const bool conditional_effects_supported; const bool admissible; const bool dead_ends_reliable; std::unique_ptr<LandmarkStatusManager> lm_status_manager; std::unique_ptr<LandmarkCostAssignment> lm_cost_assignment; std::unique_ptr<successor_generator::SuccessorGenerator> successor_generator; int get_heuristic_value(const State &ancestor_state); bool check_node_orders_disobeyed( const LandmarkNode &node, const LandmarkSet &reached) const; void add_node_children(LandmarkNode &node, const LandmarkSet &reached) const; bool landmark_is_interesting( const State &state, const LandmarkSet &reached, LandmarkNode &lm) const; bool generate_helpful_actions( const State &state, const LandmarkSet &reached); LandmarkSet convert_to_landmark_set(const BitsetView &landmark_bitset); protected: virtual int compute_heuristic(const State &ancestor_state) override; public: explicit LandmarkCountHeuristic(const options::Options &opts); virtual void get_path_dependent_evaluators( std::set<Evaluator *> &evals) override { evals.insert(this); } virtual void notify_initial_state(const State &initial_state) override; virtual void notify_state_transition(const State &parent_state, OperatorID op_id, const State &state) override; virtual bool dead_ends_are_reliable() const override; }; } #endif
1,931
C
30.672131
81
0.718799
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_graph.cc
#include "landmark_graph.h" #include "../utils/memory.h" #include <cassert> #include <list> #include <set> #include <sstream> #include <vector> using namespace std; namespace landmarks { bool LandmarkNode::is_true_in_state(const State &state) const { if (disjunctive) { for (const FactPair &fact : facts) { if (state[fact.var].get_value() == fact.value) { return true; } } return false; } else { // conjunctive or simple for (const FactPair &fact : facts) { if (state[fact.var].get_value() != fact.value) { return false; } } return true; } } LandmarkGraph::LandmarkGraph() : num_conjunctive_landmarks(0), num_disjunctive_landmarks(0) { } int LandmarkGraph::get_num_edges() const { int total = 0; for (auto &node : nodes) total += node->children.size(); return total; } LandmarkNode *LandmarkGraph::get_landmark(int i) const { return nodes[i].get(); } LandmarkNode *LandmarkGraph::get_landmark(const FactPair &fact) const { /* Return pointer to landmark node that corresponds to the given fact, or nullptr if no such landmark exists. */ LandmarkNode *node_p = nullptr; auto it = simple_landmarks_to_nodes.find(fact); if (it != simple_landmarks_to_nodes.end()) node_p = it->second; else { auto it2 = disjunctive_landmarks_to_nodes.find(fact); if (it2 != disjunctive_landmarks_to_nodes.end()) node_p = it2->second; } return node_p; } LandmarkNode &LandmarkGraph::get_simple_landmark(const FactPair &fact) const { assert(contains_simple_landmark(fact)); return *(simple_landmarks_to_nodes.find(fact)->second); } // needed only by landmarkgraph-factories. LandmarkNode &LandmarkGraph::get_disjunctive_landmark(const FactPair &fact) const { /* Note: this only works because every proposition appears in only one disjunctive landmark. */ assert(!contains_simple_landmark(fact)); assert(contains_disjunctive_landmark(fact)); return *(disjunctive_landmarks_to_nodes.find(fact)->second); } bool LandmarkGraph::contains_simple_landmark(const FactPair &lm) const { return simple_landmarks_to_nodes.count(lm) != 0; } bool LandmarkGraph::contains_disjunctive_landmark(const FactPair &lm) const { return disjunctive_landmarks_to_nodes.count(lm) != 0; } bool LandmarkGraph::contains_overlapping_disjunctive_landmark( const set<FactPair> &lm) const { // Test whether ONE of the facts is present in some disjunctive landmark. for (const FactPair &lm_fact : lm) { if (contains_disjunctive_landmark(lm_fact)) return true; } return false; } bool LandmarkGraph::contains_identical_disjunctive_landmark( const set<FactPair> &lm) const { /* Test whether a disjunctive landmark exists which consists EXACTLY of the facts in lm. */ LandmarkNode *lmn = nullptr; for (const FactPair &lm_fact : lm) { auto it2 = disjunctive_landmarks_to_nodes.find(lm_fact); if (it2 == disjunctive_landmarks_to_nodes.end()) return false; else { if (lmn && lmn != it2->second) { return false; } else if (!lmn) lmn = it2->second; } } return true; } bool LandmarkGraph::contains_landmark(const FactPair &lm) const { /* Note: this only checks for one fact whether it's part of a landmark, hence only simple and disjunctive landmarks are checked. */ return contains_simple_landmark(lm) || contains_disjunctive_landmark(lm); } LandmarkNode &LandmarkGraph::add_simple_landmark(const FactPair &lm) { assert(!contains_landmark(lm)); vector<FactPair> facts{lm}; unique_ptr<LandmarkNode> new_node = utils::make_unique_ptr<LandmarkNode>(facts, false, false); LandmarkNode *new_node_p = new_node.get(); nodes.push_back(move(new_node)); simple_landmarks_to_nodes.emplace(lm, new_node_p); return *new_node_p; } LandmarkNode &LandmarkGraph::add_disjunctive_landmark(const set<FactPair> &lm) { assert(all_of(lm.begin(), lm.end(), [&](const FactPair &lm_fact) { return !contains_landmark(lm_fact); })); vector<FactPair> facts(lm.begin(), lm.end()); unique_ptr<LandmarkNode> new_node = utils::make_unique_ptr<LandmarkNode>(facts, true, false); LandmarkNode *new_node_p = new_node.get(); nodes.push_back(move(new_node)); for (const FactPair &lm_fact : lm) { disjunctive_landmarks_to_nodes.emplace(lm_fact, new_node_p); } ++num_disjunctive_landmarks; return *new_node_p; } LandmarkNode &LandmarkGraph::add_conjunctive_landmark(const set<FactPair> &lm) { assert(all_of(lm.begin(), lm.end(), [&](const FactPair &lm_fact) { return !contains_landmark(lm_fact); })); vector<FactPair> facts(lm.begin(), lm.end()); unique_ptr<LandmarkNode> new_node = utils::make_unique_ptr<LandmarkNode>(facts, false, true); LandmarkNode *new_node_p = new_node.get(); nodes.push_back(move(new_node)); ++num_conjunctive_landmarks; return *new_node_p; } void LandmarkGraph::remove_node_occurrences(LandmarkNode *node) { for (const auto &parent : node->parents) { LandmarkNode &parent_node = *(parent.first); parent_node.children.erase(node); assert(parent_node.children.find(node) == parent_node.children.end()); } for (const auto &child : node->children) { LandmarkNode &child_node = *(child.first); child_node.parents.erase(node); assert(child_node.parents.find(node) == child_node.parents.end()); } if (node->disjunctive) { --num_disjunctive_landmarks; for (const FactPair &lm_fact : node->facts) { disjunctive_landmarks_to_nodes.erase(lm_fact); } } else if (node->conjunctive) { --num_conjunctive_landmarks; } else { simple_landmarks_to_nodes.erase(node->facts[0]); } } void LandmarkGraph::remove_node(LandmarkNode *node) { remove_node_occurrences(node); auto it = find_if(nodes.begin(), nodes.end(), [&node](unique_ptr<LandmarkNode> &n) { return n.get() == node; }); assert(it != nodes.end()); nodes.erase(it); } void LandmarkGraph::remove_node_if( const function<bool (const LandmarkNode &)> &remove_node_condition) { for (auto &node : nodes) { if (remove_node_condition(*node)) { remove_node_occurrences(node.get()); } } nodes.erase(remove_if(nodes.begin(), nodes.end(), [&remove_node_condition](const unique_ptr<LandmarkNode> &node) { return remove_node_condition(*node); }), nodes.end()); } void LandmarkGraph::set_landmark_ids() { int id = 0; for (auto &lmn : nodes) { lmn->set_id(id); ++id; } } }
7,087
C++
31.967442
90
0.620573
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_status_manager.h
#ifndef LANDMARKS_LANDMARK_STATUS_MANAGER_H #define LANDMARKS_LANDMARK_STATUS_MANAGER_H #include "landmark_graph.h" #include "../per_state_bitset.h" namespace landmarks { class LandmarkGraph; class LandmarkNode; enum landmark_status {lm_reached = 0, lm_not_reached = 1, lm_needed_again = 2}; class LandmarkStatusManager { PerStateBitset reached_lms; std::vector<landmark_status> lm_status; LandmarkGraph &lm_graph; bool landmark_is_leaf(const LandmarkNode &node, const BitsetView &reached) const; bool landmark_needed_again(int id, const State &state); public: explicit LandmarkStatusManager(LandmarkGraph &graph); BitsetView get_reached_landmarks(const State &state); void update_lm_status(const State &ancestor_state); bool dead_end_exists(); void set_landmarks_for_initial_state(const State &initial_state); bool update_reached_lms(const State &parent_ancestor_state, OperatorID op_id, const State &ancestor_state); /* TODO: The status of a landmark is actually dependent on the state. This is not represented in the function below. Furthermore, the status manager only stores the status for one particular state at a time. At the day of writing this comment, this works as *update_reached_lms()* is always called before the status information is used (by calling *get_landmark_status()*). It would be a good idea to ensure that the status for the desired state is returned at all times, or an error is thrown if the desired information does not exist. */ landmark_status get_landmark_status(size_t id) const { assert(static_cast<int>(id) < lm_graph.get_num_landmarks()); return lm_status[id]; } }; } #endif
1,818
C
30.91228
85
0.691419
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_relaxation.cc
#include "landmark_factory_relaxation.h" #include "../task_utils/task_properties.h" #include "exploration.h" using namespace std; namespace landmarks { void LandmarkFactoryRelaxation::generate_landmarks(const shared_ptr<AbstractTask> &task) { TaskProxy task_proxy(*task); Exploration exploration(task_proxy); generate_relaxed_landmarks(task, exploration); postprocess(task_proxy, exploration); } void LandmarkFactoryRelaxation::postprocess(const TaskProxy &task_proxy, Exploration &exploration) { lm_graph->set_landmark_ids(); mk_acyclic_graph(); calc_achievers(task_proxy, exploration); } void LandmarkFactoryRelaxation::discard_noncausal_landmarks( const TaskProxy &task_proxy, Exploration &exploration) { // TODO: Check if the code works correctly in the presence of axioms. task_properties::verify_no_conditional_effects(task_proxy); int num_all_landmarks = lm_graph->get_num_landmarks(); lm_graph->remove_node_if( [this, &task_proxy, &exploration](const LandmarkNode &node) { return !is_causal_landmark(task_proxy, exploration, node); }); int num_causal_landmarks = lm_graph->get_num_landmarks(); utils::g_log << "Discarded " << num_all_landmarks - num_causal_landmarks << " non-causal landmarks" << endl; } bool LandmarkFactoryRelaxation::is_causal_landmark( const TaskProxy &task_proxy, Exploration &exploration, const LandmarkNode &landmark) const { /* Test whether the relaxed planning task is unsolvable without using any operator that has "landmark" as a precondition. Similar to "relaxed_task_solvable" above. */ assert(!landmark.conjunctive); if (landmark.is_true_in_goal) return true; vector<vector<int>> lvl_var; vector<utils::HashMap<FactPair, int>> lvl_op; // Initialize lvl_var to numeric_limits<int>::max() VariablesProxy variables = task_proxy.get_variables(); lvl_var.resize(variables.size()); for (VariableProxy var : variables) { lvl_var[var.get_id()].resize(var.get_domain_size(), numeric_limits<int>::max()); } unordered_set<int> exclude_op_ids; vector<FactPair> exclude_props; for (OperatorProxy op : task_proxy.get_operators()) { if (is_landmark_precondition(op, &landmark)) { exclude_op_ids.insert(op.get_id()); } } // Do relaxed exploration exploration.compute_reachability_with_excludes( lvl_var, lvl_op, true, exclude_props, exclude_op_ids, false); // Test whether all goal propositions have a level of less than numeric_limits<int>::max() for (FactProxy goal : task_proxy.get_goals()) if (lvl_var[goal.get_variable().get_id()][goal.get_value()] == numeric_limits<int>::max()) return true; return false; } void LandmarkFactoryRelaxation::calc_achievers(const TaskProxy &task_proxy, Exploration &exploration) { VariablesProxy variables = task_proxy.get_variables(); for (auto &lmn : lm_graph->get_nodes()) { for (const FactPair &lm_fact : lmn->facts) { const vector<int> &ops = get_operators_including_eff(lm_fact); lmn->possible_achievers.insert(ops.begin(), ops.end()); if (variables[lm_fact.var].is_derived()) lmn->is_derived = true; } vector<vector<int>> lvl_var; vector<utils::HashMap<FactPair, int>> lvl_op; relaxed_task_solvable(task_proxy, exploration, lvl_var, lvl_op, true, lmn.get()); for (int op_or_axom_id : lmn->possible_achievers) { OperatorProxy op = get_operator_or_axiom(task_proxy, op_or_axom_id); if (_possibly_reaches_lm(op, lvl_var, lmn.get())) { lmn->first_achievers.insert(op_or_axom_id); } } } } bool LandmarkFactoryRelaxation::relaxed_task_solvable( const TaskProxy &task_proxy, Exploration &exploration, bool level_out, const LandmarkNode *exclude, bool compute_lvl_op) const { vector<vector<int>> lvl_var; vector<utils::HashMap<FactPair, int>> lvl_op; return relaxed_task_solvable(task_proxy, exploration, lvl_var, lvl_op, level_out, exclude, compute_lvl_op); } bool LandmarkFactoryRelaxation::relaxed_task_solvable( const TaskProxy &task_proxy, Exploration &exploration, vector<vector<int>> &lvl_var, vector<utils::HashMap<FactPair, int>> &lvl_op, bool level_out, const LandmarkNode *exclude, bool compute_lvl_op) const { /* Test whether the relaxed planning task is solvable without achieving the propositions in "exclude" (do not apply operators that would add a proposition from "exclude"). As a side effect, collect in lvl_var and lvl_op the earliest possible point in time when a proposition / operator can be achieved / become applicable in the relaxed task. */ OperatorsProxy operators = task_proxy.get_operators(); AxiomsProxy axioms = task_proxy.get_axioms(); // Initialize lvl_op and lvl_var to numeric_limits<int>::max() if (compute_lvl_op) { lvl_op.resize(operators.size() + axioms.size()); for (OperatorProxy op : operators) { add_operator_and_propositions_to_list(op, lvl_op); } for (OperatorProxy axiom : axioms) { add_operator_and_propositions_to_list(axiom, lvl_op); } } VariablesProxy variables = task_proxy.get_variables(); lvl_var.resize(variables.size()); for (VariableProxy var : variables) { lvl_var[var.get_id()].resize(var.get_domain_size(), numeric_limits<int>::max()); } // Extract propositions from "exclude" unordered_set<int> exclude_op_ids; vector<FactPair> exclude_props; if (exclude) { for (OperatorProxy op : operators) { if (achieves_non_conditional(op, exclude)) exclude_op_ids.insert(op.get_id()); } exclude_props.insert(exclude_props.end(), exclude->facts.begin(), exclude->facts.end()); } // Do relaxed exploration exploration.compute_reachability_with_excludes( lvl_var, lvl_op, level_out, exclude_props, exclude_op_ids, compute_lvl_op); // Test whether all goal propositions have a level of less than numeric_limits<int>::max() for (FactProxy goal : task_proxy.get_goals()) if (lvl_var[goal.get_variable().get_id()][goal.get_value()] == numeric_limits<int>::max()) return false; return true; } bool LandmarkFactoryRelaxation::achieves_non_conditional( const OperatorProxy &o, const LandmarkNode *lmp) const { /* Test whether the landmark is achieved by the operator unconditionally. A disjunctive landmark is achieved if one of its disjuncts is achieved. */ assert(lmp); for (EffectProxy effect: o.get_effects()) { for (const FactPair &lm_fact : lmp->facts) { FactProxy effect_fact = effect.get_fact(); if (effect_fact.get_pair() == lm_fact) { if (effect.get_conditions().empty()) return true; } } } return false; } void LandmarkFactoryRelaxation::add_operator_and_propositions_to_list( const OperatorProxy &op, vector<utils::HashMap<FactPair, int>> &lvl_op) const { int op_or_axiom_id = get_operator_or_axiom_id(op); for (EffectProxy effect : op.get_effects()) { lvl_op[op_or_axiom_id].emplace(effect.get_fact().get_pair(), numeric_limits<int>::max()); } } }
7,582
C++
39.335106
111
0.648642
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_rpg_sasp.h
#ifndef LANDMARKS_LANDMARK_FACTORY_RPG_SASP_H #define LANDMARKS_LANDMARK_FACTORY_RPG_SASP_H #include "landmark_factory_relaxation.h" #include <unordered_map> #include <unordered_set> #include <vector> namespace landmarks { class LandmarkFactoryRpgSasp : public LandmarkFactoryRelaxation { const bool disjunctive_landmarks; const bool use_orders; const bool only_causal_landmarks; std::list<LandmarkNode *> open_landmarks; std::vector<std::vector<int>> disjunction_classes; std::unordered_map<LandmarkNode *, utils::HashSet<FactPair>> forward_orders; // dtg_successors[var_id][val] contains all successor values of val in the // domain transition graph for the variable std::vector<std::vector<std::unordered_set<int>>> dtg_successors; void build_dtg_successors(const TaskProxy &task_proxy); void add_dtg_successor(int var_id, int pre, int post); void find_forward_orders(const VariablesProxy &variables, const std::vector<std::vector<int>> &lvl_var, LandmarkNode *lmp); void add_lm_forward_orders(); void get_greedy_preconditions_for_lm(const TaskProxy &task_proxy, const LandmarkNode *lmp, const OperatorProxy &op, std::unordered_map<int, int> &result) const; void compute_shared_preconditions(const TaskProxy &task_proxy, std::unordered_map<int, int> &shared_pre, std::vector<std::vector<int>> &lvl_var, LandmarkNode *bp); void compute_disjunctive_preconditions( const TaskProxy &task_proxy, std::vector<std::set<FactPair>> &disjunctive_pre, std::vector<std::vector<int>> &lvl_var, LandmarkNode *bp); int min_cost_for_landmark(const TaskProxy &task_proxy, LandmarkNode *bp, std::vector<std::vector<int>> &lvl_var); virtual void generate_relaxed_landmarks( const std::shared_ptr<AbstractTask> &task, Exploration &exploration) override; void found_simple_lm_and_order(const FactPair &a, LandmarkNode &b, EdgeType t); void found_disj_lm_and_order(const TaskProxy &task_proxy, const std::set<FactPair> &a, LandmarkNode &b, EdgeType t); void approximate_lookahead_orders(const TaskProxy &task_proxy, const std::vector<std::vector<int>> &lvl_var, LandmarkNode *lmp); bool domain_connectivity(const State &initial_state, const FactPair &landmark, const std::unordered_set<int> &exclude); void build_disjunction_classes(const TaskProxy &task_proxy); void discard_disjunctive_landmarks(); public: explicit LandmarkFactoryRpgSasp(const options::Options &opts); virtual bool computes_reasonable_orders() const override; virtual bool supports_conditional_effects() const override; }; } #endif
3,266
C
42.559999
85
0.594611
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_merged.h
#ifndef LANDMARKS_LANDMARK_FACTORY_MERGED_H #define LANDMARKS_LANDMARK_FACTORY_MERGED_H #include "landmark_factory.h" #include <vector> namespace landmarks { class LandmarkFactoryMerged : public LandmarkFactory { std::vector<std::shared_ptr<LandmarkFactory>> lm_factories; virtual void generate_landmarks(const std::shared_ptr<AbstractTask> &task) override; void postprocess(); LandmarkNode *get_matching_landmark(const LandmarkNode &lm) const; public: explicit LandmarkFactoryMerged(const options::Options &opts); virtual bool computes_reasonable_orders() const override; virtual bool supports_conditional_effects() const override; }; } #endif
679
C
27.333332
88
0.768778
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/exploration.h
#ifndef LANDMARKS_EXPLORATION_H #define LANDMARKS_EXPLORATION_H #include "util.h" #include "../task_proxy.h" #include "../algorithms/priority_queues.h" #include <unordered_map> #include <unordered_set> #include <vector> namespace landmarks { struct ExProposition; struct ExUnaryOperator; struct ExProposition { FactPair fact; bool is_goal_condition; bool is_termination_condition; std::vector<ExUnaryOperator *> precondition_of; int h_add_cost; int h_max_cost; int depth; bool marked; // used when computing preferred operators ExUnaryOperator *reached_by; ExProposition() : fact(FactPair::no_fact), is_goal_condition(false), is_termination_condition(false), h_add_cost(-1), h_max_cost(-1), depth(-1), marked(false), reached_by(nullptr) {} bool operator<(const ExProposition &other) const { return fact < other.fact; } }; struct ExUnaryOperator { int op_or_axiom_id; std::vector<ExProposition *> precondition; ExProposition *effect; int base_cost; // 0 for axioms, 1 for regular operators int unsatisfied_preconditions; int h_add_cost; int h_max_cost; int depth; ExUnaryOperator(const std::vector<ExProposition *> &pre, ExProposition *eff, int op_or_axiom_id, int base) : op_or_axiom_id(op_or_axiom_id), precondition(pre), effect(eff), base_cost(base) {} bool operator<(const ExUnaryOperator &other) const { if (*(other.effect) < *effect) return false; else if (*effect < *(other.effect)) return true; else { for (size_t i = 0; i < precondition.size(); ++i) { if (i == other.precondition.size() || *(other.precondition[i]) < *(precondition[i])) return false; else if (*(precondition[i]) < *(other.precondition[i])) return true; } return true; } } bool is_induced_by_axiom(const TaskProxy &task_proxy) const { return get_operator_or_axiom(task_proxy, op_or_axiom_id).is_axiom(); } }; class Exploration { static const int MAX_COST_VALUE = 100000000; // See additive_heuristic.h. TaskProxy task_proxy; std::vector<ExUnaryOperator> unary_operators; std::vector<std::vector<ExProposition>> propositions; std::vector<ExProposition *> goal_propositions; std::vector<ExProposition *> termination_propositions; priority_queues::AdaptiveQueue<ExProposition *> prop_queue; bool did_write_overflow_warning; void build_unary_operators(const OperatorProxy &op); void setup_exploration_queue(const State &state, const std::vector<FactPair> &excluded_props, const std::unordered_set<int> &excluded_op_ids, bool use_h_max); void relaxed_exploration(bool use_h_max, bool level_out); void enqueue_if_necessary(ExProposition *prop, int cost, int depth, ExUnaryOperator *op, bool use_h_max); void increase_cost(int &cost, int amount); void write_overflow_warning(); public: explicit Exploration(const TaskProxy &task_proxy); void compute_reachability_with_excludes(std::vector<std::vector<int>> &lvl_var, std::vector<utils::HashMap<FactPair, int>> &lvl_op, bool level_out, const std::vector<FactPair> &excluded_props, const std::unordered_set<int> &excluded_op_ids, bool compute_lvl_ops); }; } #endif
3,824
C
31.142857
95
0.585774
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/util.h
#ifndef LANDMARKS_UTIL_H #define LANDMARKS_UTIL_H #include <unordered_map> #include <vector> class OperatorProxy; class TaskProxy; namespace landmarks { class LandmarkNode; class LandmarkGraph; extern std::unordered_map<int, int> _intersect( const std::unordered_map<int, int> &a, const std::unordered_map<int, int> &b); extern bool _possibly_reaches_lm( const OperatorProxy &op, const std::vector<std::vector<int>> &lvl_var, const LandmarkNode *lmp); extern OperatorProxy get_operator_or_axiom(const TaskProxy &task_proxy, int op_or_axiom_id); extern int get_operator_or_axiom_id(const OperatorProxy &op); extern void dump_landmark_graph(const TaskProxy &task_proxy, const LandmarkGraph &graph); } #endif
730
C
24.206896
92
0.749315
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/landmarks/landmark_factory_h_m.h
#ifndef LANDMARKS_LANDMARK_FACTORY_H_M_H #define LANDMARKS_LANDMARK_FACTORY_H_M_H #include "landmark_factory.h" namespace landmarks { using FluentSet = std::vector<FactPair>; std::ostream & operator<<(std::ostream &os, const FluentSet &fs); struct FluentSetComparer { bool operator()(const FluentSet &fs1, const FluentSet &fs2) const { if (fs1.size() != fs2.size()) { return fs1.size() < fs2.size(); } for (size_t i = 0; i < fs1.size(); ++i) { if (fs1[i] != fs2[i]) return fs1[i] < fs2[i]; } return false; } }; // an operator in P_m. Corresponds to an operator from the original problem, // as well as a set of conditional effects that correspond to noops struct PMOp { std::vector<int> pc; std::vector<int> eff; // pc separated from effect by a value of -1 std::vector<std::vector<int>> cond_noops; int index; }; // represents a fluent in the P_m problem struct HMEntry { // propositions that belong to this set FluentSet fluents; // -1 -> current cost infinite // 0 -> present in initial state int level; std::list<int> landmarks; std::list<int> necessary; // greedy necessary landmarks, disjoint from landmarks std::list<int> first_achievers; // first int = op index, second int conditional noop effect // -1 for op itself std::vector<FactPair> pc_for; HMEntry() : level(-1) { } }; using FluentSetToIntMap = std::map<FluentSet, int, FluentSetComparer>; class LandmarkFactoryHM : public LandmarkFactory { using TriggerSet = std::unordered_map<int, std::set<int>>; virtual void generate_landmarks(const std::shared_ptr<AbstractTask> &task) override; void compute_h_m_landmarks(const TaskProxy &task_proxy); void compute_noop_landmarks(int op_index, int noop_index, std::list<int> const &local_landmarks, std::list<int> const &local_necessary, int level, TriggerSet &next_trigger); void propagate_pm_fact(int factindex, bool newly_discovered, TriggerSet &trigger); bool possible_noop_set(const VariablesProxy &variables, const FluentSet &fs1, const FluentSet &fs2); void build_pm_ops(const TaskProxy &task_proxy); bool interesting(const VariablesProxy &variables, const FactPair &fact1, const FactPair &fact2) const; void postprocess(const TaskProxy &task_proxy); void discard_conjunctive_landmarks(); void calc_achievers(const TaskProxy &task_proxy); void add_lm_node(int set_index, bool goal = false); void initialize(const TaskProxy &task_proxy); void free_unneeded_memory(); void print_fluentset(const VariablesProxy &variables, const FluentSet &fs); void print_pm_op(const VariablesProxy &variables, const PMOp &op); const int m_; const bool conjunctive_landmarks; const bool use_orders; std::map<int, LandmarkNode *> lm_node_table_; std::vector<HMEntry> h_m_table_; std::vector<PMOp> pm_ops_; // maps each <m set to an int FluentSetToIntMap set_indices_; // first is unsat pcs for operator // second is unsat pcs for conditional noops std::vector<std::pair<int, std::vector<int>>> unsat_pc_count_; void get_m_sets_(const VariablesProxy &variables, int m, int num_included, int current_var, FluentSet &current, std::vector<FluentSet> &subsets); void get_m_sets_of_set(const VariablesProxy &variables, int m, int num_included, int current_var_index, FluentSet &current, std::vector<FluentSet> &subsets, const FluentSet &superset); void get_split_m_sets(const VariablesProxy &variables, int m, int ss1_num_included, int ss2_num_included, int ss1_var_index, int ss2_var_index, FluentSet &current, std::vector<FluentSet> &subsets, const FluentSet &superset1, const FluentSet &superset2); void get_m_sets(const VariablesProxy &variables, int m, std::vector<FluentSet> &subsets); void get_m_sets(const VariablesProxy &variables, int m, std::vector<FluentSet> &subsets, const FluentSet &superset); void get_m_sets(const VariablesProxy &variables, int m, std::vector<FluentSet> &subsets, const State &state); void get_split_m_sets(const VariablesProxy &variables, int m, std::vector<FluentSet> &subsets, const FluentSet &superset1, const FluentSet &superset2); void print_proposition(const VariablesProxy &variables, const FactPair &fluent) const; public: explicit LandmarkFactoryHM(const options::Options &opts); virtual bool computes_reasonable_orders() const override; virtual bool supports_conditional_effects() const override; }; } #endif
5,220
C
34.040268
98
0.615326
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/dynamic_bitset.h
#ifndef ALGORITHMS_DYNAMIC_BITSET_H #define ALGORITHMS_DYNAMIC_BITSET_H #include <cassert> #include <limits> #include <vector> /* Poor man's version of boost::dynamic_bitset, mostly copied from there. */ namespace dynamic_bitset { template<typename Block = unsigned int> class DynamicBitset { static_assert( !std::numeric_limits<Block>::is_signed, "Block type must be unsigned"); std::vector<Block> blocks; const std::size_t num_bits; static const Block zeros; static const Block ones; static const int bits_per_block = std::numeric_limits<Block>::digits; static int compute_num_blocks(std::size_t num_bits) { return num_bits / bits_per_block + static_cast<int>(num_bits % bits_per_block != 0); } static std::size_t block_index(std::size_t pos) { return pos / bits_per_block; } static std::size_t bit_index(std::size_t pos) { return pos % bits_per_block; } static Block bit_mask(std::size_t pos) { return Block(1) << bit_index(pos); } int count_bits_in_last_block() const { return bit_index(num_bits); } void zero_unused_bits() { const int bits_in_last_block = count_bits_in_last_block(); if (bits_in_last_block != 0) { assert(!blocks.empty()); blocks.back() &= ~(ones << bits_in_last_block); } } public: explicit DynamicBitset(std::size_t num_bits) : blocks(compute_num_blocks(num_bits), zeros), num_bits(num_bits) { } std::size_t size() const { return num_bits; } /* Count the number of set bits. The computation could be made faster by using a more sophisticated algorithm (see https://en.wikipedia.org/wiki/Hamming_weight). */ int count() const { int result = 0; for (std::size_t pos = 0; pos < num_bits; ++pos) { result += static_cast<int>(test(pos)); } return result; } void set() { std::fill(blocks.begin(), blocks.end(), ones); zero_unused_bits(); } void reset() { std::fill(blocks.begin(), blocks.end(), zeros); } void set(std::size_t pos) { assert(pos < num_bits); blocks[block_index(pos)] |= bit_mask(pos); } void reset(std::size_t pos) { assert(pos < num_bits); blocks[block_index(pos)] &= ~bit_mask(pos); } bool test(std::size_t pos) const { assert(pos < num_bits); return (blocks[block_index(pos)] & bit_mask(pos)) != 0; } bool operator[](std::size_t pos) const { return test(pos); } bool intersects(const DynamicBitset &other) const { assert(size() == other.size()); for (std::size_t i = 0; i < blocks.size(); ++i) { if (blocks[i] & other.blocks[i]) return true; } return false; } bool is_subset_of(const DynamicBitset &other) const { assert(size() == other.size()); for (std::size_t i = 0; i < blocks.size(); ++i) { if (blocks[i] & ~other.blocks[i]) return false; } return true; } }; template<typename Block> const Block DynamicBitset<Block>::zeros = Block(0); template<typename Block> // MSVC's bitwise negation always returns a signed type. const Block DynamicBitset<Block>::ones = Block(~Block(0)); } /* This source file was derived from the boost::dynamic_bitset library version 1.54. Original copyright statement and license for this original source follow. Copyright (c) 2001-2002 Chuck Allison and Jeremy Siek Copyright (c) 2003-2006, 2008 Gennaro Prota Distributed under the Boost Software License, Version 1.0. Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endif
5,093
C
28.616279
75
0.647555
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/equivalence_relation.h
#ifndef ALGORITHMS_EQUIVALENCE_RELATION_H #define ALGORITHMS_EQUIVALENCE_RELATION_H #include <algorithm> #include <cmath> #include <list> #include <unordered_map> #include <vector> namespace equivalence_relation { class Block; typedef std::list<int>::iterator ElementListIter; typedef std::list<int>::const_iterator ElementListConstIter; typedef std::list<Block>::iterator BlockListIter; typedef std::list<Block>::const_iterator BlockListConstIter; class EquivalenceRelation; class Block { std::list<int> elements; /* During the refinement step of EquivalenceRelation, every existing block B is split along every new block X into the intersection and difference of B and X. The way the algorithm is set up, the difference remains in the block that previously represented B. To store the intersection, a new block is created and stored in B for easier access. */ friend class EquivalenceRelation; BlockListIter it_intersection_block; public: bool empty() const; ElementListIter insert(int element); void erase(ElementListIter it); ElementListIter begin() {return elements.begin();} ElementListIter end() {return elements.end();} ElementListConstIter begin() const {return elements.begin();} ElementListConstIter end() const {return elements.end();} }; class EquivalenceRelation { int num_elements; std::list<Block> blocks; /* With each element we associate a pair of iterators (block_it, element_it). block_it is an iterator from the list blocks pointing to the block that contains the element and element_it is an iterator from the list in this block and points to the element within it. */ typedef std::pair<BlockListIter, ElementListIter> ElementPosition; typedef std::unordered_map<int, ElementPosition> ElementPositionMap; ElementPositionMap element_positions; /* Refining a relation with a block X is equivalent to splitting every block B into two blocks (B \cap X) and (B \setminus X). */ void refine(const Block &block); BlockListIter add_empty_block(); public: EquivalenceRelation(int n); EquivalenceRelation(int n, const std::list<Block> &blocks_); ~EquivalenceRelation(); int get_num_elements() const; int get_num_explicit_elements() const; int get_num_blocks() const; int get_num_explicit_blocks() const; // TODO: There may or may not be an implicitly defined Block. Should this be // created and returned, too? // The same question goes for get_num_blocks(). // This is also a problem with get_num_elements() as there can be less // explicitly specified elements than num_elements. BlockListConstIter begin() const {return blocks.begin();} BlockListConstIter end() const {return blocks.end();} /* Refines the current relation with an other relation. After refining, two items A and B are in the same block if and only if they were in the same block before and they are in one block in the other relation. For both relations, items that are not in any block are assumed to be in one implicitly defined block. The amortized runtime is linear in the number of elements specified in other. */ void refine(const EquivalenceRelation &other); // See refine(const Block &block) void refine(ElementListConstIter block_x_begin, ElementListConstIter block_x_end); /* Creates an equivalence relation over the numbers 0 to n -1. The vector annotated_elements cointains pairs (A, e) where A is an arbitrary annotation for element e. Elements must not occur more than once in this vector. Two elements are equivalent iff they are annotated with an equivalent annotation. All elements that are not mentioned in this vector are assumed to have one specific annotation that does not occur in annotated_elements, i.e. they are equivalent to each other, but not equivalent to anything mentioned in annotated_elements. The vector annotated_elements will be sorted by the constructor. */ // NOTE Unfortunately this is not possible as a constructor, since C++ // does not support templated constructors that only use the template // parameter in a nested context. // Also, default parameters are not allowed for function templates in // the current C++ standard. template<class T> static EquivalenceRelation *from_annotated_elements( int n, std::vector<std::pair<T, int>> &annotated_elements); template<class T, class Equal> static EquivalenceRelation *from_annotated_elements( int n, std::vector<std::pair<T, int>> &annotated_elements); }; template<class T> EquivalenceRelation *EquivalenceRelation::from_annotated_elements(int n, std::vector<std::pair<T, int>> &annotated_elements) { return EquivalenceRelation::from_annotated_elements<T, std::equal_to<T>>(n, annotated_elements); } template<class T, class Equal> EquivalenceRelation *EquivalenceRelation::from_annotated_elements(int n, std::vector<std::pair<T, int>> &annotated_elements) { EquivalenceRelation *relation = new EquivalenceRelation(n); if (!annotated_elements.empty()) { sort(annotated_elements.begin(), annotated_elements.end()); Equal equal; T current_class_label = annotated_elements[0].first; BlockListIter it_current_block = relation->add_empty_block(); for (size_t i = 0; i < annotated_elements.size(); ++i) { T label = annotated_elements[i].first; int element = annotated_elements[i].second; if (!equal(label, current_class_label)) { current_class_label = label; it_current_block = relation->add_empty_block(); } ElementListIter it_element = it_current_block->insert(element); relation->element_positions[element] = make_pair(it_current_block, it_element); } } return relation; } } #endif
6,214
C
41.278911
119
0.683618
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/max_cliques.h
#ifndef ALGORITHMS_MAX_CLIQUES_H #define ALGORITHMS_MAX_CLIQUES_H #include <vector> namespace max_cliques { /* Implementation of the Max Cliques algorithm by Tomita et al. See: Etsuji Tomita, Akira Tanaka and Haruhisa Takahashi, The Worst-Case Time Complexity for Generating All Maximal Cliques. Proceedings of the 10th Annual International Conference on Computing and Combinatorics (COCOON 2004), pp. 161-170, 2004. In the paper the authors use a compressed output of the cliques, such that the algorithm is in O(3^{n/3}). This implementation is in O(n 3^{n/3}) because the cliques are output explicitly. For a better runtime it could be useful to use bit vectors instead of vectors. */ extern void compute_max_cliques( const std::vector<std::vector<int>> &graph, std::vector<std::vector<int>> &max_cliques); } #endif
861
C
30.925925
69
0.738676
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/subscriber.h
#ifndef ALGORITHMS_SUBSCRIBER_H #define ALGORITHMS_SUBSCRIBER_H #include <cassert> #include <unordered_set> /* The classes in this file allow objects of one class to react to the destruction of objects of another class. If a class T1 wants to react to the destruction of objects of a class T2, derive T2 from SubscriberService<T2>, derive T1 from Subscriber<T1> and override the method notify_service_destroyed in T1. Example: class Star : public SubscriberService<Star> { string name; ... } vector<const Star *> galaxy; class Astronomer : public Subscriber<Star> { Astronomer() { for (const Star *star : galaxy) { star.subscribe(this); } } virtual void notify_service_destroyed(const Star *star) { utils::g_log << star->name << " is going supernova!\n"; } } */ namespace subscriber { template<typename T> class SubscriberService; /* A Subscriber can subscribe to a SubscriberService and is notified if that service is destroyed. The template parameter T should be the class of the SubscriberService (see usage example above). */ template<typename T> class Subscriber { friend class SubscriberService<T>; std::unordered_set<const SubscriberService<T> *> services; virtual void notify_service_destroyed(const T *) = 0; public: virtual ~Subscriber() { /* We have to copy the services because unsubscribing erases the current service during the iteration. */ std::unordered_set<const SubscriberService<T> *> services_copy(services); for (const SubscriberService<T> *service : services_copy) { service->unsubscribe(this); } } }; template<typename T> class SubscriberService { /* We make the set of subscribers mutable, which means that it is possible to subscribe to `const` objects. This can be justified by arguing that subscribing to an object is not conceptually a mutation of the object, and the set of subscribers is only incidentally (for implementation efficiency) stored along with the object. Of course it is possible to argue the other way, too. We made this design decision because being able to subscribe to const objects is very useful in the planner. */ mutable std::unordered_set<Subscriber<T> *> subscribers; public: virtual ~SubscriberService() { /* We have to copy the subscribers because unsubscribing erases the current subscriber during the iteration. */ std::unordered_set<Subscriber<T> *> subscribers_copy(subscribers); for (Subscriber<T> *subscriber : subscribers_copy) { subscriber->notify_service_destroyed(static_cast<T *>(this)); unsubscribe(subscriber); } } void subscribe(Subscriber<T> *subscriber) const { assert(subscribers.find(subscriber) == subscribers.end()); subscribers.insert(subscriber); assert(subscriber->services.find(this) == subscriber->services.end()); subscriber->services.insert(this); } void unsubscribe(Subscriber<T> *subscriber) const { assert(subscribers.find(subscriber) != subscribers.end()); subscribers.erase(subscriber); assert(subscriber->services.find(this) != subscriber->services.end()); subscriber->services.erase(this); } }; } #endif
3,434
C
31.40566
81
0.672976
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/int_hash_set.h
#ifndef ALGORITHMS_INT_HASH_SET_H #define ALGORITHMS_INT_HASH_SET_H #include "../utils/collections.h" #include "../utils/language.h" #include "../utils/logging.h" #include "../utils/system.h" #include <algorithm> #include <cassert> #include <iostream> #include <limits> #include <utility> #include <vector> namespace int_hash_set { /* Hash set for storing non-negative integer keys. Compared to unordered_set<int> in the standard library, this implementation is much more memory-efficient. It requires 8 bytes per bucket, so roughly 12-16 bytes per entry with typical load factors. Usage: IntHashSet<MyHasher, MyEqualityTester> s; pair<int, bool> result1 = s.insert(3); assert(result1 == make_pair(3, true)); pair<int, bool> result2 = s.insert(3); assert(result2 == make_pair(3, false)); Limitations: We use 32-bit (signed and unsigned) integers instead of larger data types for keys and hashes to save memory. Consequently, the range of valid keys is [0, 2^31 - 1]. This range could be extended to [0, 2^32 - 2] without using more memory by using unsigned integers for the keys and a different designated value for empty buckets (currently we use -1 for this). The maximum capacity (i.e., number of buckets) is 2^30 because we use a signed integer to store it, we grow the hash set by doubling its capacity, and the next larger power of 2 (2^31) is too big for an int. The maximum capacity could be increased by storing the number of buckets in a larger data type. Note on hash functions: Because the hash table uses open addressing, it is important to use hash functions that distribute the values roughly uniformly. Hash implementations intended for use with C++ standard containers often do not satisfy this requirement, for example hashing ints or pointers to themselves, which is not problematic for hash implementations based on chaining but can be catastrophic for this implementation. Implementation: All data and hashes are stored in a single vector, using open addressing. We use ideas from hopscotch hashing (https://en.wikipedia.org/wiki/Hopscotch_hashing) to ensure that each key is at most "max_distance" buckets away from its ideal bucket. This ensures constant lookup times since we always need to check at most "max_distance" buckets. Since all buckets we need to check for a given key are aligned in memory, the lookup has good cache locality. */ using KeyType = int; using HashType = unsigned int; static_assert(sizeof(KeyType) == 4, "KeyType does not use 4 bytes"); static_assert(sizeof(HashType) == 4, "HashType does not use 4 bytes"); template<typename Hasher, typename Equal> class IntHashSet { // Max distance from the ideal bucket to the actual bucket for each key. static const int MAX_DISTANCE = 32; static const unsigned int MAX_BUCKETS = std::numeric_limits<unsigned int>::max(); struct Bucket { KeyType key; HashType hash; static const KeyType empty_bucket_key = -1; Bucket() : key(empty_bucket_key), hash(0) { } Bucket(KeyType key, HashType hash) : key(key), hash(hash) { } bool full() const { return key != empty_bucket_key; } }; Hasher hasher; Equal equal; std::vector<Bucket> buckets; int num_entries; int num_resizes; int capacity() const { return buckets.size(); } void rehash(int new_capacity) { assert(new_capacity >= 1); int num_entries_before = num_entries; std::vector<Bucket> old_buckets = std::move(buckets); assert(buckets.empty()); num_entries = 0; buckets.resize(new_capacity); for (const Bucket &bucket : old_buckets) { if (bucket.full()) { insert(bucket.key, bucket.hash); } } utils::unused_variable(num_entries_before); assert(num_entries == num_entries_before); ++num_resizes; } void enlarge() { unsigned int num_buckets = buckets.size(); // Verify that the number of buckets is a power of 2. assert((num_buckets & (num_buckets - 1)) == 0); if (num_buckets > MAX_BUCKETS / 2) { std::cerr << "IntHashSet surpassed maximum capacity. This means" " you either use IntHashSet for high-memory" " applications for which it was not designed, or there" " is an unexpectedly high number of hash collisions" " that should be investigated. Aborting." << std::endl; utils::exit_with(utils::ExitCode::SEARCH_CRITICAL_ERROR); } rehash(num_buckets * 2); } int get_bucket(HashType hash) const { assert(!buckets.empty()); unsigned int num_buckets = buckets.size(); // Verify that the number of buckets is a power of 2. assert((num_buckets & (num_buckets - 1)) == 0); /* We want to return hash % num_buckets. The following line does this because we know that num_buckets is a power of 2. */ return hash & (num_buckets - 1); } /* Return distance from index1 to index2, only moving right and wrapping from the last to the first bucket. */ int get_distance(int index1, int index2) const { assert(utils::in_bounds(index1, buckets)); assert(utils::in_bounds(index2, buckets)); if (index2 >= index1) { return index2 - index1; } else { return capacity() + index2 - index1; } } int find_next_free_bucket_index(int index) const { assert(num_entries < capacity()); assert(utils::in_bounds(index, buckets)); while (buckets[index].full()) { index = get_bucket(index + 1); } return index; } KeyType find_equal_key(KeyType key, HashType hash) const { assert(hasher(key) == hash); int ideal_index = get_bucket(hash); for (int i = 0; i < MAX_DISTANCE; ++i) { int index = get_bucket(ideal_index + i); const Bucket &bucket = buckets[index]; if (bucket.full() && bucket.hash == hash && equal(bucket.key, key)) { return bucket.key; } } return Bucket::empty_bucket_key; } /* Private method that inserts a key and its corresponding hash into the hash set. The method ensures that each key is at most "max_distance" buckets away from its ideal bucket by moving the closest free bucket towards the ideal bucket. If this can't be achieved, we resize the vector, reinsert the old keys and try inserting the new key again. For the return type, see the public insert() method. Note that the private insert() may call enlarge() and therefore rehash(), which itself calls the private insert() again. */ std::pair<KeyType, bool> insert(KeyType key, HashType hash) { assert(hasher(key) == hash); /* If the hash set already contains the key, return the key and a Boolean indicating that no new key has been inserted. */ KeyType equal_key = find_equal_key(key, hash); if (equal_key != Bucket::empty_bucket_key) { return std::make_pair(equal_key, false); } assert(num_entries <= capacity()); if (num_entries == capacity()) { enlarge(); } assert(num_entries < capacity()); // Compute ideal bucket. int ideal_index = get_bucket(hash); // Find first free bucket left of the ideal bucket. int free_index = find_next_free_bucket_index(ideal_index); /* While the free bucket is too far from the ideal bucket, move the free bucket towards the ideal bucket by swapping a suitable third bucket with the free bucket. A full and an empty bucket can be swapped if the swap doesn't move the full bucket too far from its ideal position. */ while (get_distance(ideal_index, free_index) >= MAX_DISTANCE) { bool swapped = false; int num_buckets = capacity(); int max_offset = std::min(MAX_DISTANCE, num_buckets) - 1; for (int offset = max_offset; offset >= 1; --offset) { assert(offset < num_buckets); int candidate_index = free_index + num_buckets - offset; assert(candidate_index >= 0); candidate_index = get_bucket(candidate_index); HashType candidate_hash = buckets[candidate_index].hash; int candidate_ideal_index = get_bucket(candidate_hash); if (get_distance(candidate_ideal_index, free_index) < MAX_DISTANCE) { // Candidate can be swapped. std::swap(buckets[candidate_index], buckets[free_index]); free_index = candidate_index; swapped = true; break; } } if (!swapped) { /* Free bucket could not be moved close enough to ideal bucket. -> Enlarge and try inserting again. */ enlarge(); return insert(key, hash); } } assert(utils::in_bounds(free_index, buckets)); assert(!buckets[free_index].full()); buckets[free_index] = Bucket(key, hash); ++num_entries; return std::make_pair(key, true); } public: IntHashSet(const Hasher &hasher, const Equal &equal) : hasher(hasher), equal(equal), buckets(1), num_entries(0), num_resizes(0) { } int size() const { return num_entries; } /* Insert a key into the hash set. Return a pair whose first item is the given key, or an equivalent key already contained in the hash set. The second item in the pair is a bool indicating whether a new key was inserted into the hash set. */ std::pair<KeyType, bool> insert(KeyType key) { assert(key >= 0); return insert(key, hasher(key)); } void dump() const { int num_buckets = capacity(); utils::g_log << "["; for (int i = 0; i < num_buckets; ++i) { const Bucket &bucket = buckets[i]; if (bucket.full()) { utils::g_log << bucket.key; } else { utils::g_log << "_"; } if (i < num_buckets - 1) { utils::g_log << ", "; } } utils::g_log << "]" << std::endl; } void print_statistics() const { assert(!buckets.empty()); int num_buckets = capacity(); assert(num_buckets != 0); utils::g_log << "Int hash set load factor: " << num_entries << "/" << num_buckets << " = " << static_cast<double>(num_entries) / num_buckets << std::endl; utils::g_log << "Int hash set resizes: " << num_resizes << std::endl; } }; template<typename Hasher, typename Equal> const int IntHashSet<Hasher, Equal>::MAX_DISTANCE; template<typename Hasher, typename Equal> const unsigned int IntHashSet<Hasher, Equal>::MAX_BUCKETS; } #endif
11,436
C
33.448795
85
0.597324
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/max_cliques.cc
#include "max_cliques.h" #include "../utils/collections.h" #include "../utils/logging.h" #include <algorithm> #include <cassert> #include <iostream> #include <iterator> #include <vector> using namespace std; namespace max_cliques { class MaxCliqueComputer { const vector<vector<int>> &graph; vector<vector<int>> &max_cliques; vector<int> current_max_clique; int get_maximizing_vertex( const vector<int> &subg, const vector<int> &cand) { assert(utils::is_sorted_unique(subg)); assert(utils::is_sorted_unique(cand)); //utils::g_log << "subg: " << subg << endl; //utils::g_log << "cand: " << cand << endl; size_t max = 0; // We will take the first vertex if there is no better one. int vertex = subg[0]; for (size_t i = 0; i < subg.size(); ++i) { vector<int> intersection; intersection.reserve(subg.size()); // for vertex u in subg get u's adjacent vertices: graph[subg[i]]; set_intersection(cand.begin(), cand.end(), graph[subg[i]].begin(), graph[subg[i]].end(), back_inserter(intersection)); if (intersection.size() > max) { max = intersection.size(); vertex = subg[i]; //utils::g_log << "success: there is a maximizing vertex." << endl; } } return vertex; } void expand(vector<int> &subg, vector<int> &cand) { // utils::g_log << "subg: " << subg << endl; // utils::g_log << "cand: " << cand << endl; if (subg.empty()) { //utils::g_log << "clique" << endl; max_cliques.push_back(current_max_clique); } else { int u = get_maximizing_vertex(subg, cand); vector<int> ext_u; ext_u.reserve(cand.size()); set_difference(cand.begin(), cand.end(), graph[u].begin(), graph[u].end(), back_inserter(ext_u)); while (!ext_u.empty()) { int q = ext_u.back(); ext_u.pop_back(); //utils::g_log << q << ","; current_max_clique.push_back(q); // subg_q = subg n gamma(q) vector<int> subg_q; subg_q.reserve(subg.size()); set_intersection(subg.begin(), subg.end(), graph[q].begin(), graph[q].end(), back_inserter(subg_q)); // cand_q = cand n gamma(q) vector<int> cand_q; cand_q.reserve(cand.size()); set_intersection(cand.begin(), cand.end(), graph[q].begin(), graph[q].end(), back_inserter(cand_q)); expand(subg_q, cand_q); // remove q from cand --> cand = cand - q cand.erase(lower_bound(cand.begin(), cand.end(), q)); //utils::g_log << "back" << endl; current_max_clique.pop_back(); } } } public: MaxCliqueComputer(const vector<vector<int>> &graph_, vector<vector<int>> &max_cliques_) : graph(graph_), max_cliques(max_cliques_) { } void compute() { vector<int> vertices_1; vertices_1.reserve(graph.size()); for (size_t i = 0; i < graph.size(); ++i) { vertices_1.push_back(i); } vector<int> vertices_2(vertices_1); current_max_clique.reserve(graph.size()); expand(vertices_1, vertices_2); } }; void compute_max_cliques( const vector<vector<int>> &graph, vector<vector<int>> &max_cliques) { MaxCliqueComputer clique_computer(graph, max_cliques); clique_computer.compute(); } }
3,892
C++
31.714285
83
0.491521
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/sccs.cc
#include "sccs.h" #include <algorithm> using namespace std; namespace sccs { void dfs( const vector<vector<int>> &graph, int vertex, vector<int> &dfs_numbers, vector<int> &dfs_minima, vector<int> &stack_indices, vector<int> &stack, int &current_dfs_number, vector<vector<int>> &sccs) { int vertex_dfs_number = current_dfs_number++; dfs_numbers[vertex] = dfs_minima[vertex] = vertex_dfs_number; stack_indices[vertex] = stack.size(); stack.push_back(vertex); const vector<int> &successors = graph[vertex]; for (size_t i = 0; i < successors.size(); i++) { int succ = successors[i]; int succ_dfs_number = dfs_numbers[succ]; if (succ_dfs_number == -1) { dfs(graph, succ, dfs_numbers, dfs_minima, stack_indices, stack, current_dfs_number, sccs); dfs_minima[vertex] = min(dfs_minima[vertex], dfs_minima[succ]); } else if (succ_dfs_number < vertex_dfs_number && stack_indices[succ] != -1) { dfs_minima[vertex] = min(dfs_minima[vertex], succ_dfs_number); } } if (dfs_minima[vertex] == vertex_dfs_number) { int stack_index = stack_indices[vertex]; vector<int> scc; for (size_t i = stack_index; i < stack.size(); i++) { scc.push_back(stack[i]); stack_indices[stack[i]] = -1; } stack.erase(stack.begin() + stack_index, stack.end()); sccs.push_back(scc); } } vector<vector<int>> compute_maximal_sccs( const vector<vector<int>> &graph) { int node_count = graph.size(); vector<int> dfs_numbers(node_count, -1); vector<int> dfs_minima(node_count, -1); vector<int> stack_indices(node_count, -1); vector<int> stack; stack.reserve(node_count); int current_dfs_number = 0; vector<vector<int>> sccs; for (int i = 0; i < node_count; i++) { if (dfs_numbers[i] == -1) { dfs(graph, i, dfs_numbers, dfs_minima, stack_indices, stack, current_dfs_number, sccs); } } reverse(sccs.begin(), sccs.end()); return sccs; } }
2,094
C++
30.268656
102
0.590735
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/segmented_vector.h
#ifndef ALGORITHMS_SEGMENTED_VECTOR_H #define ALGORITHMS_SEGMENTED_VECTOR_H #include <algorithm> #include <cassert> #include <iostream> #include <vector> /* SegmentedVector is a vector-like class with the following advantages over vector: 1. Resizing has no memory spike. (*) 2. Should work more nicely with fragmented memory because data is partitioned into fixed-size chunks of size SEGMENT_BYTES. 3. Overallocation is only additive (by SEGMENT_BYTES), not multiplicative as in vector. (*) 4. References stay stable forever, so there is no need to be careful about invalidating references upon growing the vector. (*) Assumes that the size of the "segments" vector can be neglected, which is true if SEGMENT_BYTES isn't chosen too small. For example, with 1 GB of data and SEGMENT_BYTES = 8192, we can have 131072 segments. The main disadvantage to vector is that there is an additional indirection for each lookup, but we hope that the first lookup will usually hit the cache. The implementation is basically identical to that of deque (at least the g++ version), but with the advantage that we can control SEGMENT_BYTES. A test on all optimal planning instances with several planner configurations showed a modest advantage over deque. The class can also be used as a simple "memory pool" to reduce allocation costs (time and memory) when allocating many objects of the same type. SegmentedArrayVector is a similar class that can be used for compactly storing many fixed-size arrays. It's essentially a variant of SegmentedVector where the size of the stored data is only known at runtime, not at compile time. */ // TODO: Get rid of the code duplication here. How to do it without // paying a performance penalty? issue388. // For documentation on classes relevant to storing and working with registered // states see the file state_registry.h. namespace segmented_vector { template<class Entry, class Allocator = std::allocator<Entry>> class SegmentedVector { typedef typename Allocator::template rebind<Entry>::other EntryAllocator; // TODO: Try to find a good value for SEGMENT_BYTES. static const size_t SEGMENT_BYTES = 8192; static const size_t SEGMENT_ELEMENTS = (SEGMENT_BYTES / sizeof(Entry)) >= 1 ? (SEGMENT_BYTES / sizeof(Entry)) : 1; EntryAllocator entry_allocator; std::vector<Entry *> segments; size_t the_size; size_t get_segment(size_t index) const { return index / SEGMENT_ELEMENTS; } size_t get_offset(size_t index) const { return index % SEGMENT_ELEMENTS; } void add_segment() { Entry *new_segment = entry_allocator.allocate(SEGMENT_ELEMENTS); segments.push_back(new_segment); } // No implementation to forbid copies and assignment SegmentedVector(const SegmentedVector<Entry> &); SegmentedVector &operator=(const SegmentedVector<Entry> &); public: SegmentedVector() : the_size(0) { } SegmentedVector(const EntryAllocator &allocator_) : entry_allocator(allocator_), the_size(0) { } ~SegmentedVector() { for (size_t i = 0; i < the_size; ++i) { entry_allocator.destroy(&operator[](i)); } for (size_t segment = 0; segment < segments.size(); ++segment) { entry_allocator.deallocate(segments[segment], SEGMENT_ELEMENTS); } } Entry &operator[](size_t index) { assert(index < the_size); size_t segment = get_segment(index); size_t offset = get_offset(index); return segments[segment][offset]; } const Entry &operator[](size_t index) const { assert(index < the_size); size_t segment = get_segment(index); size_t offset = get_offset(index); return segments[segment][offset]; } size_t size() const { return the_size; } void push_back(const Entry &entry) { size_t segment = get_segment(the_size); size_t offset = get_offset(the_size); if (segment == segments.size()) { assert(offset == 0); // Must add a new segment. add_segment(); } entry_allocator.construct(segments[segment] + offset, entry); ++the_size; } void pop_back() { entry_allocator.destroy(&operator[](the_size - 1)); --the_size; // If the removed element was the last in its segment, the segment // is not removed (memory is not deallocated). This way a subsequent // push_back does not have to allocate the memory again. } void resize(size_t new_size, Entry entry = Entry()) { // NOTE: We currently grow/shrink one element at a time. // Revision 6ee5ff7b8873 contains an implementation that can // handle other resizes more efficiently. while (new_size < the_size) { pop_back(); } while (new_size > the_size) { push_back(entry); } } }; template<class Element, class Allocator = std::allocator<Element>> class SegmentedArrayVector { typedef typename Allocator::template rebind<Element>::other ElementAllocator; // TODO: Try to find a good value for SEGMENT_BYTES. static const size_t SEGMENT_BYTES = 8192; const size_t elements_per_array; const size_t arrays_per_segment; const size_t elements_per_segment; ElementAllocator element_allocator; std::vector<Element *> segments; size_t the_size; size_t get_segment(size_t index) const { return index / arrays_per_segment; } size_t get_offset(size_t index) const { return (index % arrays_per_segment) * elements_per_array; } void add_segment() { Element *new_segment = element_allocator.allocate(elements_per_segment); segments.push_back(new_segment); } // No implementation to forbid copies and assignment SegmentedArrayVector(const SegmentedArrayVector<Element> &); SegmentedArrayVector &operator=(const SegmentedArrayVector<Element> &); public: SegmentedArrayVector(size_t elements_per_array_) : elements_per_array(elements_per_array_), arrays_per_segment( std::max(SEGMENT_BYTES / (elements_per_array * sizeof(Element)), size_t(1))), elements_per_segment(elements_per_array * arrays_per_segment), the_size(0) { } SegmentedArrayVector(size_t elements_per_array_, const ElementAllocator &allocator_) : element_allocator(allocator_), elements_per_array(elements_per_array_), arrays_per_segment( std::max(SEGMENT_BYTES / (elements_per_array * sizeof(Element)), size_t(1))), elements_per_segment(elements_per_array * arrays_per_segment), the_size(0) { } ~SegmentedArrayVector() { // TODO Factor out common code with SegmentedVector. In particular // we could destroy the_size * elements_per_array elements here // wihtout looping over the arrays first. for (size_t i = 0; i < the_size; ++i) { for (size_t offset = 0; offset < elements_per_array; ++offset) { element_allocator.destroy(operator[](i) + offset); } } for (size_t i = 0; i < segments.size(); ++i) { element_allocator.deallocate(segments[i], elements_per_segment); } } Element *operator[](size_t index) { assert(index < the_size); size_t segment = get_segment(index); size_t offset = get_offset(index); return segments[segment] + offset; } const Element *operator[](size_t index) const { assert(index < the_size); size_t segment = get_segment(index); size_t offset = get_offset(index); return segments[segment] + offset; } size_t size() const { return the_size; } void push_back(const Element *entry) { size_t segment = get_segment(the_size); size_t offset = get_offset(the_size); if (segment == segments.size()) { assert(offset == 0); // Must add a new segment. add_segment(); } Element *dest = segments[segment] + offset; for (size_t i = 0; i < elements_per_array; ++i) element_allocator.construct(dest++, *entry++); ++the_size; } void pop_back() { for (size_t offset = 0; offset < elements_per_array; ++offset) { element_allocator.destroy(operator[](the_size - 1) + offset); } --the_size; // If the removed element was the last in its segment, the segment // is not removed (memory is not deallocated). This way a subsequent // push_back does not have to allocate the memory again. } void resize(size_t new_size, const Element *entry) { // NOTE: We currently grow/shrink one element at a time. // Revision 6ee5ff7b8873 contains an implementation that can // handle other resizes more efficiently. while (new_size < the_size) { pop_back(); } while (new_size > the_size) { push_back(entry); } } }; } #endif
9,292
C
33.418518
91
0.632372
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/named_vector.h
#ifndef ALGORITHMS_NAMED_VECTOR_H #define ALGORITHMS_NAMED_VECTOR_H #include <cassert> #include <string> #include <vector> namespace named_vector { /* NamedVector is a vector-like collection with optional names associated with each element. It is intended for attaching names to objects in vectors for debugging purposes and is optimized to have minimal overhead when there are no names. Any name which is not specified is the empty string. Accessing a name with an invalid index will result in an error in debug mode. */ template<typename T> class NamedVector { std::vector<T> elements; std::vector<std::string> names; public: template<typename ... _Args> void emplace_back(_Args && ... __args) { elements.emplace_back(std::forward<_Args>(__args) ...); } void push_back(const T &element) { elements.push_back(element); } T &operator[](int index) { return elements[index]; } const T &operator[](int index) const { return elements[index]; } bool has_names() const { return !names.empty(); } void set_name(int index, const std::string &name) { assert(index >= 0 && index < size()); if (index >= names.size()) { if (name.empty()) { // All unspecified names are empty by default. return; } names.resize(index + 1, ""); } names[index] = name; } std::string get_name(int index) const { assert(index >= 0 && index < size()); int num_names = names.size(); if (index < num_names) { return names[index]; } else { // All unspecified names are empty by default. return ""; } } int size() const { return elements.size(); } typename std::vector<T>::reference back() { return elements.back(); } typename std::vector<T>::iterator begin() { return elements.begin(); } typename std::vector<T>::iterator end() { return elements.end(); } typename std::vector<T>::const_iterator begin() const { return elements.begin(); } typename std::vector<T>::const_iterator end() const { return elements.end(); } void clear() { elements.clear(); names.clear(); } void reserve(int capacity) { /* No space is reserved in the names vector because it is kept at minimal size and space is only used when necessary. */ elements.reserve(capacity); } void resize(int count) { /* The names vector is not resized because it is kept at minimal size and only resized when necessary. */ elements.resize(count); } void resize(int count, const T &value) { /* The names vector is not resized because it is kept at minimal size and only resized when necessary. */ elements.resize(count, value); } }; } #endif
3,000
C
24.870689
70
0.587333
makolon/hsr_isaac_tamp/hsr_tamp/downward/src/search/algorithms/sccs.h
#ifndef ALGORITHMS_SCCS_H #define ALGORITHMS_SCCS_H #include <vector> namespace sccs { /* This function implements Tarjan's algorithm for finding the strongly connected components of a directed graph. The runtime is O(n + m) for a directed graph with n vertices and m arcs. Input: a directed graph represented as a vector of vectors, where graph[i] is the vector of successors of vertex i. Output: a vector of strongly connected components, each of which is a vector of vertices (ints). This is a partitioning of all vertices where each SCC is a maximal subset such that each vertex in an SCC is reachable from all other vertexs in the SCC. Note that the derived graph where each SCC is a single "supervertex" is necessarily acyclic. The SCCs returned by this function are in a topological sort order with regard to this derived DAG. */ std::vector<std::vector<int>> compute_maximal_sccs( const std::vector<std::vector<int>> &graph); } #endif
973
C
36.461537
79
0.756423