Skip to content

Commit

Permalink
cargo fmt lbf
Browse files Browse the repository at this point in the history
  • Loading branch information
JeroenGar committed Feb 24, 2024
1 parent 4b425eb commit b67b1d3
Show file tree
Hide file tree
Showing 22 changed files with 654 additions and 388 deletions.
101 changes: 63 additions & 38 deletions lbf/benches/edge_sensitivity_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ use std::fs::File;
use std::io::BufReader;
use std::path::Path;

use criterion::{BenchmarkGroup, BenchmarkId, Criterion, criterion_group, criterion_main};
use criterion::measurement::WallTime;
use criterion::{criterion_group, criterion_main, BenchmarkGroup, BenchmarkId, Criterion};
use itertools::Itertools;
use rand::prelude::SmallRng;
use rand::SeedableRng;
use jagua_rs::entities::instances::bin_packing::BPInstance;
use jagua_rs::entities::instances::instance::Instance;
use jagua_rs::entities::instances::instance_generic::InstanceGeneric;
use jagua_rs::entities::instances::strip_packing::SPInstance;
use rand::prelude::SmallRng;
use rand::SeedableRng;

use jagua_rs::entities::item::Item;
use jagua_rs::entities::problems::problem_generic::{LayoutIndex, ProblemGeneric};
Expand All @@ -26,7 +26,11 @@ use lbf::samplers::hpg_sampler::HPGSampler;
use crate::util::{N_ITEMS_REMOVED, SWIM_PATH};

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

mod util;

Expand All @@ -35,7 +39,7 @@ const EDGE_MULTIPLIERS: [u8; 5] = [1, 2, 4, 8, 16];
const N_TOTAL_SAMPLES: usize = 100_000;
const N_SAMPLES_PER_ITER: usize = 1000;

fn edge_sensitivity_bench_no_ff(c: &mut Criterion){
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;
Expand All @@ -44,31 +48,41 @@ fn edge_sensitivity_bench_no_ff(c: &mut Criterion){
edge_sensitivity_bench(config, group);
}

fn edge_sensitivity_bench_with_ff(c: &mut Criterion){
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();
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);
let instance =
util::create_instance(&json_instance, config.cde_config, config.poly_simpl_config);
modify_instance(&instance, edge_multiplier as usize, config)
};

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

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

let mut rng = SmallRng::seed_from_u64(0);
Expand All @@ -82,10 +96,11 @@ fn edge_sensitivity_bench(config: Config, mut g: BenchmarkGroup<WallTime>) {
};*/

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

let mut samples_cycler = samples.chunks(N_SAMPLES_PER_ITER).cycle();
Expand All @@ -100,7 +115,11 @@ fn edge_sensitivity_bench(config: Config, mut g: BenchmarkGroup<WallTime>) {
let item = instance.item(pi_uid.item_id);
let mut buffer_shape = item.shape.as_ref().clone();
for transf in samples_cycler.next().unwrap() {
let collides = match layout.cde().surrogate_collides(item.shape.surrogate(), transf, &[]) {
let collides = match layout.cde().surrogate_collides(
item.shape.surrogate(),
transf,
&[],
) {
true => true,
false => {
buffer_shape.transform_from(&item.shape, transf);
Expand All @@ -109,42 +128,49 @@ fn edge_sensitivity_bench(config: Config, mut g: BenchmarkGroup<WallTime>) {
};
match collides {
true => n_invalid += 1,
false => n_valid += 1
false => n_valid += 1,
}
}
}
})
});
println!("{:.3}% valid", n_valid as f64 / (n_invalid + n_valid) as f64 * 100.0);
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();
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();

match instance {
Instance::SP(spi) => Instance::SP(SPInstance::new(modified_items, spi.strip_height)),
Instance::BP(bpi) => Instance::BP(BPInstance::new(modified_items, bpi.bins.clone()))
Instance::BP(bpi) => Instance::BP(BPInstance::new(modified_items, bpi.bins.clone())),
}
}
fn multiply_edge_count(shape: &SimplePolygon, multiplier: usize) -> SimplePolygon{
fn multiply_edge_count(shape: &SimplePolygon, multiplier: usize) -> SimplePolygon {
let mut new_points = vec![];

for edge in shape.edge_iter(){
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;
Expand All @@ -153,9 +179,8 @@ fn multiply_edge_count(shape: &SimplePolygon, multiplier: usize) -> SimplePolygo
new_points.push(start);
start = Point(start.0 + x_step, start.1 + y_step);
}

}
let new_polygon = SimplePolygon::new(new_points);
assert!(almost::equal(shape.area(), new_polygon.area()));
new_polygon
}
}
122 changes: 81 additions & 41 deletions lbf/benches/fast_fail_bench.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use std::fs::File;
use std::io::BufReader;

use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use itertools::Itertools;
use jagua_rs::entities::instances::instance_generic::InstanceGeneric;
use rand::prelude::SmallRng;
use rand::SeedableRng;
use jagua_rs::entities::instances::instance_generic::InstanceGeneric;

use jagua_rs::entities::problems::problem_generic::{LayoutIndex, ProblemGeneric};
use jagua_rs::geometry::convex_hull;
use jagua_rs::geometry::fail_fast::{piers, poi};
use jagua_rs::geometry::fail_fast::sp_surrogate::SPSurrogate;
use jagua_rs::geometry::fail_fast::{piers, poi};
use jagua_rs::geometry::geo_traits::TransformableFrom;
use jagua_rs::geometry::primitives::circle::Circle;
use jagua_rs::geometry::primitives::simple_polygon::SimplePolygon;
Expand All @@ -24,8 +24,8 @@ criterion_group!(benches, fast_fail_query_bench);

mod util;

const FF_POLES: &[usize] = &[0,1,2,3,4];
const FF_PIERS: &[usize] = &[0,1,2,3,4];
const FF_POLES: &[usize] = &[0, 1, 2, 3, 4];
const FF_PIERS: &[usize] = &[0, 1, 2, 3, 4];

const ITEMS_ID_TO_TEST: &[usize] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Expand All @@ -35,39 +35,63 @@ const N_SAMPLES_PER_ITER: usize = 1000;
/// Benchmark the query operation of the quadtree for different depths
/// We validate 1000 sampled transformations for each of the 5 removed items
fn fast_fail_query_bench(c: &mut Criterion) {
let json_instance: JsonInstance = serde_json::from_reader(BufReader::new(File::open(SWIM_PATH).unwrap())).unwrap();
let json_instance: JsonInstance =
serde_json::from_reader(BufReader::new(File::open(SWIM_PATH).unwrap())).unwrap();

let mut group = c.benchmark_group("fast_fail_query_bench");

let config_combos = FF_POLES.iter().map(|n_ff_poles|
FF_PIERS.iter().map(|n_ff_piers| (*n_ff_poles, *n_ff_piers)).collect_vec())
.flatten().collect_vec();
let config_combos = FF_POLES
.iter()
.map(|n_ff_poles| {
FF_PIERS
.iter()
.map(|n_ff_piers| (*n_ff_poles, *n_ff_piers))
.collect_vec()
})
.flatten()
.collect_vec();

let mut config = create_base_config();
config.cde_config.quadtree_depth = 5;
config.cde_config.hpg_n_cells = 2000;

let instance = util::create_instance(&json_instance, config.cde_config, config.poly_simpl_config);
let instance =
util::create_instance(&json_instance, config.cde_config, config.poly_simpl_config);
let (problem, _) = util::create_blf_problem(instance.clone(), config, N_ITEMS_REMOVED);

println!("avg number of edges per item: {}", ITEMS_ID_TO_TEST.iter().map(|&item_id| instance.item(item_id).shape.number_of_points()).sum::<usize>() as f64 / ITEMS_ID_TO_TEST.len() as f64);
println!(
"avg number of edges per item: {}",
ITEMS_ID_TO_TEST
.iter()
.map(|&item_id| instance.item(item_id).shape.number_of_points())
.sum::<usize>() as f64
/ ITEMS_ID_TO_TEST.len() as f64
);

let mut rng = SmallRng::seed_from_u64(0);
let layout = problem.get_layout(LayoutIndex::Real(0));
let samples = ITEMS_ID_TO_TEST.iter()
let samples = ITEMS_ID_TO_TEST
.iter()
.map(|&item_id| {
let sampler = HPGSampler::new(instance.item(item_id), layout).unwrap();
(0..N_TOTAL_SAMPLES).map(|_| sampler.sample(&mut rng)).collect_vec()
}).collect_vec();
(0..N_TOTAL_SAMPLES)
.map(|_| sampler.sample(&mut rng))
.collect_vec()
})
.collect_vec();

for ff_surr_config in config_combos {
let (n_ff_poles, n_ff_piers) = ff_surr_config;

let custom_surrogates = ITEMS_ID_TO_TEST.iter()
.map(|&item_id| create_custom_surrogate(&instance.item(item_id).shape, n_ff_poles, n_ff_piers))
let custom_surrogates = ITEMS_ID_TO_TEST
.iter()
.map(|&item_id| {
create_custom_surrogate(&instance.item(item_id).shape, n_ff_poles, n_ff_piers)
})
.collect_vec();

let mut samples_cyclers = samples.iter()
let mut samples_cyclers = samples
.iter()
.map(|s| s.chunks(N_SAMPLES_PER_ITER).cycle())
.collect_vec();

Expand All @@ -76,41 +100,57 @@ fn fast_fail_query_bench(c: &mut Criterion) {

let mut i_cycler = ITEMS_ID_TO_TEST.iter().enumerate().cycle();

let mut buffer_shapes = ITEMS_ID_TO_TEST.iter()
let mut buffer_shapes = ITEMS_ID_TO_TEST
.iter()
.map(|&item_id| instance.item(item_id))
.map(|item| item.shape.clone_and_strip_surrogate())
.collect_vec();

group.bench_function(BenchmarkId::from_parameter(format!("{n_ff_poles}_poles_{n_ff_piers}_piers")), |b| {
b.iter(|| {
let (i, &item_id) = i_cycler.next().unwrap();
let item = instance.item(item_id);
let surrogate = &custom_surrogates[i];
let buffer_shape = &mut buffer_shapes[i];
for transf in samples_cyclers[i].next().unwrap() {
let collides = match layout.cde().surrogate_collides(surrogate, transf, &[]) {
true => true,
false => {
buffer_shape.transform_from(&item.shape, transf);
layout.cde().shape_collides(&buffer_shape, &[])
group.bench_function(
BenchmarkId::from_parameter(format!("{n_ff_poles}_poles_{n_ff_piers}_piers")),
|b| {
b.iter(|| {
let (i, &item_id) = i_cycler.next().unwrap();
let item = instance.item(item_id);
let surrogate = &custom_surrogates[i];
let buffer_shape = &mut buffer_shapes[i];
for transf in samples_cyclers[i].next().unwrap() {
let collides = match layout.cde().surrogate_collides(surrogate, transf, &[])
{
true => true,
false => {
buffer_shape.transform_from(&item.shape, transf);
layout.cde().shape_collides(&buffer_shape, &[])
}
};
match collides {
true => n_invalid += 1,
false => n_valid += 1,
}
};
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);
})
},
);
println!(
"{:.3}% valid",
n_valid as f64 / (n_invalid + n_valid) as f64 * 100.0
);
}
group.finish();
}

pub fn create_custom_surrogate(simple_poly: &SimplePolygon, n_poles: usize, n_piers: usize) -> SPSurrogate {
pub fn create_custom_surrogate(
simple_poly: &SimplePolygon,
n_poles: usize,
n_piers: usize,
) -> SPSurrogate {
let convex_hull_indices = convex_hull::convex_hull_indices(simple_poly);
let mut poles = vec![simple_poly.poi.clone()];
poles.extend(poi::generate_additional_surrogate_poles(simple_poly, n_poles.saturating_sub(1), 0.9));
poles.extend(poi::generate_additional_surrogate_poles(
simple_poly,
n_poles.saturating_sub(1),
0.9,
));
let poles_bounding_circle = Circle::bounding_circle(&poles);

let n_ff_poles = usize::min(n_poles, poles.len());
Expand All @@ -127,4 +167,4 @@ pub fn create_custom_surrogate(simple_poly: &SimplePolygon, n_poles: usize, n_pi

dbg!(surrogate.ff_poles().len(), surrogate.ff_piers().len());
surrogate
}
}
Loading

0 comments on commit b67b1d3

Please sign in to comment.