Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Voxel refactor #315

Merged
merged 8 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions experiments/voxel/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,16 @@ docker build . -f experiments/voxel/enviroment.Dockerfile -t voxel-experiments
### Generate rofibots each to each tasks:
```sh
experiments/voxel/gen_tasks_args.py e2e -f old --both-directions \
$(find data/configurations/old/rofibots/ -type f | sort) |
experiments/voxel/gen_tasks_matrix.py - experiments/voxel/args_rofi-voxel.json
$(find data/configurations/old/m03-rofibots/ -type f | sort) |
experiments/voxel/gen_tasks_matrix.py - experiments/voxel/args-voxel.json
```

### Generate tangled to snake tasks:
```sh
experiments/voxel/gen_tasks_args.py snake -f old \
$(find experiments/voxel/snake_10_tangled_10/ -type f | sort) \
$(find experiments/voxel/snake_5_tangled_100/ -type f | sort) |
experiments/voxel/gen_tasks_matrix.py - experiments/voxel/args_rofi-voxel.json
experiments/voxel/gen_tasks_matrix.py - experiments/voxel/args-voxel.json
```

## Files
Expand Down
1 change: 1 addition & 0 deletions softwareComponents/voxelReconfig/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ crate-type = ["lib", "cdylib", "staticlib"]
[dependencies]
amplify = "4.0"
bimap = "0.6"
educe = "0.4"
enum-iterator = "1.2"
iter_fixed = "0.3"
itertools = "0.11"
Expand Down
144 changes: 144 additions & 0 deletions softwareComponents/voxelReconfig/src/algs/astar/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
//! Compute any path using the [A* search algorithm](https://en.wikipedia.org/wiki/A*_search_algorithm) with early return.

pub mod opt;

use crate::algs::{reconstruct_path_to, Error, StateGraph};
use crate::counters::Counter;
use crate::reconfig::metric::cost::{Cost, CostHolder};
use crate::reconfig::metric::Metric;
use rustc_hash::FxHashMap;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::rc::Rc;

type ParentMap<TItem, TCost> = FxHashMap<Rc<TItem>, (Option<Rc<TItem>>, Cost<TCost>)>;

/// metric will be called only once on each equivalent state
pub fn compute_path<TGraph, TMetric>(
init: &TGraph::StateType,
goal: &TGraph::StateType,
) -> Result<Vec<Rc<TGraph::StateType>>, Error>
where
TGraph: StateGraph,
TMetric: Metric<TGraph::StateType>,
{
TGraph::debug_check_state(init);
TGraph::debug_check_state(goal);

if !TGraph::init_check(init, goal) {
return Err(Error::InitCheckError);
}

let mut metric = TMetric::new(goal);
debug_assert!(metric.get_potential(init) >= metric.get_potential(goal));

let parent_map = compute_parents::<TGraph, _>(init, goal, metric).ok_or(Error::PathNotFound)?;

let goal = parent_map
.get_key_value(goal)
.expect("Parent map has to contain goal")
.0
.clone();

Ok(reconstruct_path_to(goal, parent_map, |p| p.0))
}

fn compute_parents<TGraph, TMetric>(
init: &TGraph::StateType,
goal: &TGraph::StateType,
mut metric: TMetric,
) -> Option<ParentMap<TGraph::StateType, TMetric::Potential>>
where
TGraph: StateGraph,
TMetric: Metric<TGraph::StateType>,
{
TGraph::debug_check_state(init);
TGraph::debug_check_state(goal);

let mut init_states = TGraph::equivalent_states(init).map(Rc::new).peekable();
let init = init_states.peek().expect("No equivalent state").clone();
let mut parent_map = init_states
.map(|init| (init, (None, Cost::new(0, TMetric::Potential::default()))))
.collect::<ParentMap<_, _>>();
let mut states_to_visit = BinaryHeap::from([Reverse(CostHolder {
estimated_cost: TMetric::EstimatedCost::default(),
state: init,
})]);

while let Some(Reverse(CostHolder {
estimated_cost,
state: current,
})) = states_to_visit.pop()
{
TGraph::debug_check_state(&current);

let &(_, cost) = parent_map.get(&current).unwrap();

{
let old_estimated_cost = TMetric::estimated_cost(cost);
if estimated_cost > old_estimated_cost {
// There was a shorter way
continue;
}
assert_eq!(
estimated_cost, old_estimated_cost,
"The old estimated cost should be taken first"
);
}

for new_state in TGraph::next_states(&current) {
TGraph::debug_check_state(&new_state);

let new_real_cost = cost.real_cost + 1;

let new_state_rc;
let new_cost;
if let Some((key, &(_, old_cost))) = parent_map.get_key_value(&new_state) {
if new_real_cost >= old_cost.real_cost {
debug_assert!(TGraph::equivalent_states(&new_state).all(|eq_state| {
parent_map
.get(&eq_state)
.is_some_and(|(_, c)| c.real_cost == old_cost.real_cost)
}));
continue;
}
new_state_rc = key.clone();
new_cost = Cost::new(new_real_cost, old_cost.potential);
for eq_state in TGraph::equivalent_states(&new_state) {
let (eq_old_parent, eq_old_cost) = parent_map
.get_mut(&eq_state)
.expect("Parent map contains a state, but not all of its eq variants");
debug_assert!(eq_old_parent.is_some(), "Cannot get better path to init");
debug_assert_eq!(eq_old_cost, &old_cost);
*eq_old_parent = Some(current.clone());
*eq_old_cost = new_cost;
}
} else {
let mut eq_states = TGraph::equivalent_states(&new_state)
.map(Rc::new)
.peekable();
new_state_rc = eq_states.peek().expect("No equivalent state").clone();
new_cost = Cost::new(new_real_cost, metric.get_potential(&new_state_rc));

debug_assert!(TGraph::equivalent_states(&new_state_rc)
.all(|eq_state| !parent_map.contains_key(&eq_state)));

Counter::saved_new_unique_state();
parent_map.extend(
eq_states.map(|eq_state| (eq_state, (Some(current.clone()), new_cost))),
);

if parent_map.contains_key(goal) {
return Some(parent_map);
}
}
TGraph::debug_check_state(&new_state_rc);

states_to_visit.push(Reverse(CostHolder::new(
new_state_rc,
TMetric::estimated_cost(new_cost),
)));
}
}
None
}
144 changes: 144 additions & 0 deletions softwareComponents/voxelReconfig/src/algs/astar/opt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
//! Compute a shortest path (or all shorted paths) using the [A* search algorithm](https://en.wikipedia.org/wiki/A*_search_algorithm).

use crate::algs::{reconstruct_path_to, Error, StateGraph};
use crate::counters::Counter;
use crate::reconfig::metric::cost::{Cost, CostHolder};
use crate::reconfig::metric::Metric;
use rustc_hash::FxHashMap;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::rc::Rc;

type ParentMap<TItem, TCost> = FxHashMap<Rc<TItem>, (Option<Rc<TItem>>, Cost<TCost>)>;

/// metric will be called only once on each equivalent state
pub fn compute_path<TGraph, TMetric>(
init: &TGraph::StateType,
goal: &TGraph::StateType,
) -> Result<Vec<Rc<TGraph::StateType>>, Error>
where
TGraph: StateGraph,
TMetric: Metric<TGraph::StateType>,
{
TGraph::debug_check_state(init);
TGraph::debug_check_state(goal);

if !TGraph::init_check(init, goal) {
return Err(Error::InitCheckError);
}

let mut metric = TMetric::new(goal);
debug_assert!(metric.get_potential(init) >= metric.get_potential(goal));

let is_goal =
|state: &TGraph::StateType| TGraph::equivalent_states(state).any(|state| &state == goal);

let parent_map =
compute_parents::<TGraph, _>(init, is_goal, metric).ok_or(Error::PathNotFound)?;

let goal = parent_map
.get_key_value(goal)
.expect("Parent map has to contain goal")
.0
.clone();

Ok(reconstruct_path_to(goal, parent_map, |p| p.0))
}

fn compute_parents<TGraph, TMetric>(
init: &TGraph::StateType,
is_goal: impl Fn(&TGraph::StateType) -> bool,
mut metric: TMetric,
) -> Option<ParentMap<TGraph::StateType, TMetric::Potential>>
where
TGraph: StateGraph,
TMetric: Metric<TGraph::StateType>,
{
TGraph::debug_check_state(init);

let mut init_states = TGraph::equivalent_states(init).map(Rc::new).peekable();
let init = init_states.peek().expect("No equivalent state").clone();
let mut parent_map = init_states
.map(|init| (init, (None, Cost::new(0, TMetric::Potential::default()))))
.collect::<ParentMap<_, _>>();
let mut states_to_visit = BinaryHeap::from([Reverse(CostHolder {
estimated_cost: TMetric::EstimatedCost::default(),
state: init,
})]);

while let Some(Reverse(CostHolder {
estimated_cost,
state: current,
})) = states_to_visit.pop()
{
TGraph::debug_check_state(&current);

if is_goal(&current) {
return Some(parent_map);
}
let &(_, cost) = parent_map.get(&current).unwrap();

{
let old_estimated_cost = TMetric::estimated_cost(cost);
if estimated_cost > old_estimated_cost {
// There was a shorter way
continue;
}
assert_eq!(
estimated_cost, old_estimated_cost,
"The old estimated cost should be taken first"
);
}

for new_state in TGraph::next_states(&current) {
TGraph::debug_check_state(&new_state);

let new_real_cost = cost.real_cost + 1;

let new_state_rc;
let new_cost;
if let Some((key, &(_, old_cost))) = parent_map.get_key_value(&new_state) {
if new_real_cost >= old_cost.real_cost {
debug_assert!(TGraph::equivalent_states(&new_state).all(|eq_state| {
parent_map
.get(&eq_state)
.is_some_and(|(_, c)| c.real_cost == old_cost.real_cost)
}));
continue;
}
new_state_rc = key.clone();
new_cost = Cost::new(new_real_cost, old_cost.potential);
for eq_state in TGraph::equivalent_states(&new_state) {
let (eq_old_parent, eq_old_cost) = parent_map
.get_mut(&eq_state)
.expect("Parent map contains a state, but not all of its eq variants");
debug_assert!(eq_old_parent.is_some(), "Cannot get better path to init");
debug_assert_eq!(eq_old_cost, &old_cost);
*eq_old_parent = Some(current.clone());
*eq_old_cost = new_cost;
}
} else {
let mut eq_states = TGraph::equivalent_states(&new_state)
.map(Rc::new)
.peekable();
new_state_rc = eq_states.peek().expect("No equivalent state").clone();
new_cost = Cost::new(new_real_cost, metric.get_potential(&new_state_rc));

debug_assert!(TGraph::equivalent_states(&new_state_rc)
.all(|eq_state| !parent_map.contains_key(&eq_state)));

Counter::saved_new_unique_state();
parent_map.extend(
eq_states.map(|eq_state| (eq_state, (Some(current.clone()), new_cost))),
);
}
TGraph::debug_check_state(&new_state_rc);

states_to_visit.push(Reverse(CostHolder::new(
new_state_rc,
TMetric::estimated_cost(new_cost),
)));
}
}
None
}
Loading