Skip to content

Commit

Permalink
benches wip
Browse files Browse the repository at this point in the history
  • Loading branch information
JeroenGar committed Feb 5, 2024
1 parent fb52927 commit 4171b16
Show file tree
Hide file tree
Showing 19 changed files with 477 additions and 201 deletions.
10 changes: 5 additions & 5 deletions assets/config_lbf.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"cde_config": {
"quadtree": {
"FixedDepth": 4
"FixedDepth": 5
},
"haz_prox": {
"Enabled": {
Expand All @@ -12,7 +12,7 @@
"pole_coverage_goal": 0.9,
"max_poles": 10,
"n_ff_poles": 1,
"n_ff_piers": 0
"n_ff_piers": 1
}
},
"poly_simpl_config": {
Expand All @@ -21,11 +21,11 @@
}
},
"deterministic_mode": true,
"n_samples_per_item": 50000,
"ls_samples_fraction": 0.5,
"n_samples_per_item": 5000,
"ls_samples_fraction": 0.2,
"svg_draw_options": {
"quadtree": true,
"haz_prox_grid": false,
"surrogate": true
"surrogate": false
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::cmp::Ordering;
use log::{error, warn};

use crate::collision_detection::hazard::Hazard;
use crate::geometry::geo_traits::{DistanceFrom, Shape};
Expand All @@ -8,6 +9,7 @@ use crate::geometry::primitives::point::Point;
pub fn generate(bbox: AARectangle, hazards: &[Hazard], target_n_cells: usize) -> Vec<AARectangle> {
//generates a grid of equal sized square cells in the shape.
//the number of cells is approximately equal to target_n_cells, but can be slightly more or less
assert!(bbox.area() > 0.0, "bbox has zero area");

let mut cells = vec![];

Expand Down Expand Up @@ -37,7 +39,7 @@ pub fn generate(bbox: AARectangle, hazards: &[Hazard], target_n_cells: usize) ->
}
}
if n_iters >= 25 {
//warn!("grid generation is taking too long, aborting after 100 iterations ({} cells, instead of {})", cells.len(), target_n_cells);
warn!("grid generation is taking too long, aborting after 25 iterations ({} cells instead of target {})", cells.len(), target_n_cells);
break;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,15 @@ use crate::geometry::primitives::aa_rectangle::AARectangle;
#[derive(Debug, Clone)]
pub struct HazardProximityGrid {
grid: Grid<HPGCell>,
cell_radius: f64,
pending_deregisters: Vec<HazardEntity>
pending_deregisters: Vec<HazardEntity>,
cell_radius : f64,
}

impl HazardProximityGrid {
pub fn new(bbox: AARectangle, static_hazards: &[Hazard], n_cells: usize) -> Self {
assert!(n_cells > 0);
let cells = grid_generator::generate(bbox, static_hazards, n_cells);

let cell_radius = {
let half_width = cells[0].width() / 2.0;
f64::sqrt(2.0 * half_width.powi(2))
};

let cell_radius = cells[0].diameter() / 2.0;

let grid = {
let elements = cells.into_iter()
Expand All @@ -40,8 +36,8 @@ impl HazardProximityGrid {

HazardProximityGrid {
grid,
cell_radius,
pending_deregisters: vec![],
cell_radius
}
}

Expand Down
5 changes: 3 additions & 2 deletions jaguars/src/entities/problems/problem.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::borrow::Borrow;
use std::sync::Arc;

use enum_dispatch::enum_dispatch;
Expand Down Expand Up @@ -63,8 +64,8 @@ pub trait Problem: ProblemPrivate {
self.bin_qtys()[bin_id] > 0
}

fn get_layout(&self, index: &LayoutIndex) -> &Layout {
match index {
fn get_layout(&self, index: impl Borrow<LayoutIndex>) -> &Layout {
match index.borrow() {
LayoutIndex::Existing(i) => &self.layouts()[*i],
LayoutIndex::Empty(i) => &self.empty_layouts()[*i]
}
Expand Down
9 changes: 9 additions & 0 deletions lbf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ ordered-float = "4.2.0"
clap = { version = "4.4.18", features = ["derive"] }
mimalloc = "0.1.39"
tribool = "0.3.0"
almost = "0.2.0"

[dev-dependencies]
criterion = "0.5.1"
Expand All @@ -31,6 +32,14 @@ harness = false
name = "fast_fail_bench"
harness = false

[[bench]]
name = "edge_sensitivity_bench"
harness = false

[[bench]]
name = "hpg_bench"
harness = false

[profile.release]
opt-level = 3

Expand Down
150 changes: 150 additions & 0 deletions lbf/benches/edge_sensitivity_bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::sync::Arc;
use criterion::{BenchmarkGroup, BenchmarkId, Criterion, criterion_group, criterion_main};
use criterion::measurement::WallTime;
use itertools::Itertools;
use rand::prelude::{IteratorRandom, SmallRng};
use rand::SeedableRng;
use jaguars::entities::instance::Instance;
use jaguars::entities::item::Item;
use jaguars::entities::problems::problem::{LayoutIndex, Problem};
use jaguars::geometry::geo_traits::{Shape, TransformableFrom};
use jaguars::geometry::primitives::point::Point;
use jaguars::geometry::primitives::simple_polygon::SimplePolygon;
use jaguars::io::json_instance::JsonInstance;
use lbf::config::Config;

use lbf::io;
use lbf::io::svg_util::SvgDrawOptions;
use lbf::samplers::hpg_sampler::HPGSampler;
use lbf::samplers::uniform_rect_sampler::UniformAARectSampler;
use crate::util::{N_ITEMS_REMOVED, N_SAMPLES, SWIM_PATH};

criterion_main!(benches);
criterion_group!(benches, edge_sensitivity_bench_no_ff, edge_sensitivity_bench_with_ff);

mod util;

const EDGE_MULTIPLIERS: [u8; 5] = [1, 2, 4, 8, 16];

fn edge_sensitivity_bench_no_ff(c: &mut Criterion){
let mut config = util::create_base_config();
config.cde_config.item_surrogate_config.n_ff_poles = 0;
config.cde_config.item_surrogate_config.n_ff_piers = 0;

let group = c.benchmark_group("edge_sensitivity_bench_no_ff");
edge_sensitivity_bench(config, group);
}

fn edge_sensitivity_bench_with_ff(c: &mut Criterion){
let config = util::create_base_config();
let group = c.benchmark_group("edge_sensitivity_bench_ff");
edge_sensitivity_bench(config, group);
}

fn edge_sensitivity_bench(config: Config, mut g: BenchmarkGroup<WallTime>) {
let json_instance: JsonInstance = serde_json::from_reader(BufReader::new(File::open(SWIM_PATH).unwrap())).unwrap();

for edge_multiplier in EDGE_MULTIPLIERS {
let instance = {
let instance = util::create_instance(&json_instance, config.cde_config, config.poly_simpl_config);
Arc::new(modify_instance(&instance, edge_multiplier as usize, config))
};

let (mut problem,selected_pi_uids) = util::create_blf_problem(instance.clone(), config, N_ITEMS_REMOVED);

{
let draw_options = SvgDrawOptions{
quadtree: true,
surrogate: true,
..SvgDrawOptions::default()
};
let svg = io::layout_to_svg::layout_to_svg(problem.get_layout(LayoutIndex::Existing(0)), &instance, draw_options);
io::write_svg(&svg, Path::new(&format!("edge_sensitivity_{edge_multiplier}.svg")));
}

let mut rng = SmallRng::seed_from_u64(0);

let layout = problem.get_layout(LayoutIndex::Existing(0));
/*let samples = {
let sampler = UniformAARectSampler::new(layout.bin().bbox(), instance.item(0));
(0..N_SAMPLES).map(
|_| sampler.sample(&mut rng).compose()
).collect_vec()
};*/

let samples = {
let hpg_sampler = HPGSampler::new(instance.item(0), layout).expect("should be able to create HPGSampler");
(0..N_SAMPLES).map(
|_| hpg_sampler.sample(&mut rng)
).collect_vec()
};

let mut n_invalid: i64 = 0;
let mut n_valid: i64 = 0;

g.bench_function(BenchmarkId::from_parameter(edge_multiplier), |b| {
b.iter(|| {
for i in 0..N_ITEMS_REMOVED {
let pi_uid = &selected_pi_uids[i];
let item = instance.item(pi_uid.item_id);
let mut buffer_shape = item.shape().clone();
for transf in &samples {
let collides = match layout.cde().surrogate_collides(item.shape().surrogate(), transf, &[]) {
true => true,
false => {
buffer_shape.transform_from(item.shape(), transf);
layout.cde().poly_collides(&buffer_shape, &[])
}
};
match collides {
true => n_invalid += 1,
false => n_valid += 1
}
}
}
})
});
println!("{:.3}% valid", n_valid as f64 / (n_invalid + n_valid) as f64 * 100.0);
}
g.finish();
}

fn modify_instance(instance: &Instance, multiplier: usize, config: Config) -> Instance {
let modified_items = instance.items().iter().map(|(item, qty)| {
let modified_shape = multiply_edge_count(item.shape(), multiplier);

let modified_item = Item::new(
item.id(),
modified_shape,
item.value(),
item.allowed_rotation().clone(),
item.centering_transform().clone(),
item.base_quality(),
config.cde_config.item_surrogate_config
);
(modified_item, *qty)
}).collect_vec();

Instance::new(modified_items, instance.packing_type().clone())
}
fn multiply_edge_count(shape: &SimplePolygon, multiplier: usize) -> SimplePolygon{
let mut new_points = vec![];

for edge in shape.edge_iter(){
//split x and y into "times" parts
let x_step = (edge.end().0 - edge.start().0) / multiplier as f64;
let y_step = (edge.end().1 - edge.start().1) / multiplier as f64;
let mut start = edge.start();
for _ in 0..multiplier {
new_points.push(start);
start = Point(start.0 + x_step, start.1 + y_step);
}

}
let mut new_polygon = SimplePolygon::new(new_points);
assert!(almost::equal(shape.area(), new_polygon.area()));
new_polygon
}
Loading

0 comments on commit 4171b16

Please sign in to comment.