Skip to content

Commit

Permalink
Updated Readme and comment cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Hexorg committed Nov 8, 2023
1 parent 8a46ae6 commit 624ba68
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 46 deletions.
35 changes: 13 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,20 @@ From PDDL4J's Readme:

```rust
use std::fs;
use pddl_rs::{compiler::{CompiledProblem, compile_problem}, search::a_star, parser::{parse_domain, parse_problem}};
let domain_filename = "sample_problems/simple_domain.pddl";
let problem_filename = "sample_problems/simple_problem.pddl"
let domain_src = fs::read_to_string(domain_filename).unwrap();
let domain = match parse_domain(&domain_src) {
Err(e) => {e.report(domain_filename).eprint((domain_filename, ariadne::Source::from(&domain_src))); panic!() },
Ok(d) => d,
};
let problem_src = fs::read_to_string(problem_filename).unwrap();
let problem = match parse_problem(&problem_src, domain.requirements) {
Err(e) => {e.report(problem_filename).eprint((problem_filename, ariadne::Source::from(&problem_src))); panic!() },
Ok(p) => p
};
let c_problem = match compile_problem(&domain, &problem) {
Err(e) => {e.report(problem_filename).eprint((problem_filename, ariadne::Source::from(&problem_src))); panic!() },
Ok(cd) => cd,
};
use std::path::PathBuf;
use pddl_rs::{Sources, Objects, search::{a_star, AstarInternals}};
let domain_filename = PathBuf::from("sample_problems/simple_domain.pddl");
let problem_filename = PathBuf::from("sample_problems/simple_problem.pddl");
let sources = Sources::load(domain_filename, problem_filename);
let (domain, problem, c_problem) = sources.compile();
println!("Compiled problem needs {} bits of memory and uses {} actions.", c_problem.memory_size, c_problem.actions.len());
let solution = a_star(&c_problem);
println!("Solution is {} actions long.", solution.len());
for action_id in &solution {
let action = c_problem.actions.get(*action_id).unwrap();
println!("\t{}{:?}", action.name.1, action.args.iter().map(|(_, s)| *s).collect::<Vec<&str>>());
let mut args = AstarInternals::new();
if let Some(solution) = a_star(&c_problem, &mut args) {
println!("Solution is {} actions long.", solution.len());
for action_id in &solution {
let action = c_problem.actions.get(*action_id as usize).unwrap();
println!("\t{}{:?}", domain.actions[action.domain_action_idx as usize].name(), action.args.iter().map(|(row, col)| problem.objects.get_object(*row,*col).item.1).collect::<Vec<&str>>());
}
}
```

Expand Down
9 changes: 9 additions & 0 deletions src/compiler/action_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use super::{inertia::Inertia, CompiledActionUsize};
// use rand::seq::SliceRandom;

#[derive(Debug, PartialEq)]
/// A graph of actions to be executed in sequence to speed up domain planning.
pub struct ActionGraph {
/// The priority matrix of actions - a square matrix where N is the number of actions in domain
/// (unexpanded to objects in a problem) The offset is the current action index,
Expand All @@ -22,7 +23,9 @@ impl ActionGraph {
}
}

/// Re-initializes the priority matrix to be action-index based. And `size`by`size` long.
pub fn set_size(&mut self, size: usize) {
self.priority.clear();
for _ in 0..size {
let inner_vec: Vec<CompiledActionUsize> =
(0..size).map(|u| u as CompiledActionUsize).collect();
Expand All @@ -31,6 +34,8 @@ impl ActionGraph {
}
}

/// Re-arrange action priorities to try actions that are enabled by this action first
/// And actions that are disabled by this action - last
pub fn apply_inertia<'src, O>(&mut self, inertia: &Vec<Inertia<O>>)
where
O: Eq + PartialEq + Hash,
Expand All @@ -48,6 +53,8 @@ impl ActionGraph {
}

Check warning on line 53 in src/compiler/action_graph.rs

View workflow job for this annotation

GitHub Actions / pddl_rs

Diff in /home/runner/work/pddl_rs/pddl_rs/src/compiler/action_graph.rs
}

/// Given the action pair - modify the priority matrix to get the search algorithm
/// to check the `to` action right after `from` action.
fn prioritize(&mut self, from: CompiledActionUsize, to: CompiledActionUsize) {
let vec = &mut self.priority[from as usize];
if let Some((idx, _)) = vec.iter().enumerate().find(|(_, dst)| (**dst) == to) {
Expand All @@ -56,6 +63,8 @@ impl ActionGraph {
}
}

/// Given the action pair - modify the priority matrix to get the search algorithm
/// to check the `to` action as the last one after `from` action.
fn deprioritize(&mut self, from: CompiledActionUsize, to: CompiledActionUsize) {
let vec = &mut self.priority[from as usize];
if let Some((idx, _)) = vec.iter().enumerate().find(|(_, dst)| (**dst) == to) {
Expand Down
7 changes: 7 additions & 0 deletions src/compiler/domain_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,16 @@ pub struct DomainData<'src> {
// Optimization structures:
/// Each offset in this vector matches the offset of action list vector.
pub action_graph: ActionGraph,
/// Set of all predicate names that have been identified as constant
pub constant_predicates: HashSet<Name<'src>>,
/// Set of all concrete atomic formulas that have been identified to stay true

Check warning on line 38 in src/compiler/domain_data.rs

View workflow job for this annotation

GitHub Actions / pddl_rs

Diff in /home/runner/work/pddl_rs/pddl_rs/src/compiler/domain_data.rs
/// no matter what actions have been executed
pub const_true_predicates: HashSet<AtomicFormula<'src, Name<'src>>>,
/// Set of all concrete atomic formulas that have been identified to stay false
/// no matter what actions have been executed
pub const_false_predicates: HashSet<AtomicFormula<'src, Name<'src>>>,
/// A map of AST Actions to Compiled action ranges. The range represents
/// All possible calls of a given action (for permutated objects)
pub compiled_action_ranges: Vec<Range<usize>>,
}

Expand Down
30 changes: 6 additions & 24 deletions src/compiler/final_pass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ use super::{inertia::Inertia, *};
#[derive(PartialEq, Eq)]
enum ContextKind {
Goal,
/// The argument is the ID of this Action in the Domain's action vector
/// (without concrete object calls).
Action(ASTActionUsize),
Precondition,
Effect,

Check warning on line 12 in src/compiler/final_pass.rs

View workflow job for this annotation

GitHub Actions / pddl_rs

Diff in /home/runner/work/pddl_rs/pddl_rs/src/compiler/final_pass.rs
}

/// Gets passed to all AST visitors to keep track of inter-node state as we are
/// traversing the Abstract Systax Tree
struct Context<'src, 'ast, 'pass> {
pub kind: ContextKind,
pub instructions: Vec<Instruction>,
Expand Down Expand Up @@ -40,6 +44,7 @@ impl<'src, 'ast, 'pass> Context<'src, 'ast, 'pass> {
variable_to_object,
}
}
/// Helper to construct Context::Goal
pub fn goal(
instruction_capacity: usize,
problem: &'ast Problem<'src>,
Expand All @@ -57,13 +62,13 @@ impl<'src, 'ast, 'pass> Context<'src, 'ast, 'pass> {
}
}

/// Final pass over the Abstract Syntax Tree - will generate the final CompiledProblem.
pub fn final_pass<'src>(
mut domain_data: DomainData<'src>,
domain: &Domain<'src>,
problem: &Problem<'src>,
) -> Result<CompiledProblem, Error> {
let (actions, action_inertia) = create_concrete_actions(&mut domain_data, domain, problem)?;

let mut action_graph = ActionGraph::new();
action_graph.set_size(actions.len());
action_graph.apply_inertia(&action_inertia);
Expand Down Expand Up @@ -141,10 +146,6 @@ fn visit_basic_action<'src>(
domain_data: &DomainData<'src>,
action: &BasicAction<'src>,
context: &mut Context<'src, '_, '_>,
// args: Option<&[(&Name<'src>, &Name<'src>)]>,
// domain_action_idx: usize,
// compiled_action_count: usize,
// state_inertia: &mut Vec<Inertia>,
) -> Result<Option<CompiledAction>, Error> {
let (args, domain_action_idx) = match context.kind {
ContextKind::Action(domain_action_idx) => {
Expand Down Expand Up @@ -198,7 +199,6 @@ fn visit_basic_action<'src>(
args,
precondition,
effect: effect_context.instructions,
// try_next: Vec::with_capacity(domain_data.action_graph.priority.len() * 10),
}))
}

Expand All @@ -224,11 +224,6 @@ fn visit_term_atomic_formula<'src>(
domain_data: &DomainData<'src>,
af: &AtomicFormula<'src, Term<'src>>,
context: &mut Context,
// args: Option<&[(&Name<'src>, &Name<'src>)]>,
// compiled_action_count: usize,
// instructions: &mut Vec<Instruction>,
// state_inertia: &mut Vec<Inertia>,
// is_effect: bool,
) -> Result<bool, Error> {
let call_vec = if context.kind == ContextKind::Goal {
// Goal formulas use objects already anyway
Expand Down Expand Up @@ -355,10 +350,6 @@ fn visit_precondition<'src>(
domain_data: &DomainData<'src>,
precondition: &PreconditionExpr<'src>,
context: &mut Context,
// args: Option<&[(&Name<'src>, &Name<'src>)]>,
// compiled_action_count: usize,
// instructions: &mut Vec<Instruction>,
// state_inertia: &mut Vec<Inertia>,
) -> Result<bool, Error> {
match precondition {
PreconditionExpr::And(vec) => {
Expand Down Expand Up @@ -386,11 +377,6 @@ fn visit_term_negative_formula<'src>(
domain_data: &DomainData<'src>,
formula: &NegativeFormula<'src, Term<'src>>,
context: &mut Context,
// args: Option<&[(&Name<'src>, &Name<'src>)]>,
// compiled_action_count: usize,
// instructions: &mut Vec<Instruction>,
// state_inertia: &mut Vec<Inertia>,
// is_effect: bool,
) -> Result<bool, Error> {
match formula {
NegativeFormula::Direct(af) => visit_term_atomic_formula(domain_data, af, context),
Expand Down Expand Up @@ -488,10 +474,6 @@ fn visit_effect<'src>(
domain_data: &DomainData<'src>,
effect: &Effect<'src>,
context: &mut Context,
// args: Option<&[(&Name<'src>, &Name<'src>)]>,
// compiled_action_count: usize,
// instructions: &mut Vec<Instruction>,
// state_inertia: &mut Vec<Inertia>,
) -> Result<bool, Error> {
match effect {
Effect::And(vec) => {
Expand Down
5 changes: 5 additions & 0 deletions src/compiler/first_pass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use super::{
PreconditionExpr, Problem, Term, Type, GD,

Check warning on line 8 in src/compiler/first_pass.rs

View workflow job for this annotation

GitHub Actions / pddl_rs

Diff in /home/runner/work/pddl_rs/pddl_rs/src/compiler/first_pass.rs
};

/// Compiler context that gets passed to all AST visitors to keep track of
/// inter-node state as we are traversing the Abstract Systax Tree
struct Context<'ast, 'src> {
pub is_negative: bool,
pub parameters: &'ast Vec<List<'src>>,
Expand All @@ -26,6 +28,9 @@ impl<'ast, 'src> Context<'ast, 'src> {
}

Check warning on line 28 in src/compiler/first_pass.rs

View workflow job for this annotation

GitHub Actions / pddl_rs

Diff in /home/runner/work/pddl_rs/pddl_rs/src/compiler/first_pass.rs
}

/// First pass over the Abstract Syntax Tree - performs basic sanity checks,
/// And populates structures needed for optimization of the [`CompiledProblem`]
/// emitted in the [`final_pass`]
pub fn first_pass<'src>(
domain: &Domain<'src>,
problem: &'src Problem<'src>,
Expand Down
2 changes: 2 additions & 0 deletions src/compiler/inertia.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ where
}

pub trait DomainInertia {
/// Check if action `from` enables any state that action `to` requires
fn is_enables(&self, from: usize, to: usize) -> bool;
/// Check if action `from` disables any state that action `to` requires
fn is_disables(&self, from: usize, to: usize) -> bool;
}

Expand Down
4 changes: 4 additions & 0 deletions src/parser/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use enumset::{EnumSet, EnumSetType};
use crate::{compiler::PredicateUsize, ErrorKind};

#[derive(PartialEq, Eq, Clone, Copy)]
/// Span of an AST element in the source code. `start` and `end` represet byte-offsets in the source code
/// Also keeps track if the AST element is in the problem source or domain.
pub struct Span {
pub start: usize,
pub end: usize,
Expand Down Expand Up @@ -63,10 +65,12 @@ impl<'src> Into<Range<usize>> for Span {
}
}

/// Any AST Node that spans some source code characters.
pub trait SpannedAst<'src> {
fn span(&self) -> Span;
}

/// Any AST Node that spans some source code characters and allows that span to be changed.
pub trait SpannedAstMut<'src>: SpannedAst<'src> {
fn span_mut(&mut self) -> &mut Span;
}
Expand Down

0 comments on commit 624ba68

Please sign in to comment.