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

Add combination compartments #30

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
18 changes: 18 additions & 0 deletions src/pack/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ impl std::fmt::Display for Shape {
}
}

#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CombinationExpression {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that we want a proper and and xor combinator in here as well.

Not(Box<Self>),
Or(Vec<Self>),
ID(CompartmentID),
}

#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum Mask {
Expand All @@ -38,6 +46,7 @@ pub(crate) enum Mask {
Voxels {
path: PathBuf,
},
Combination(Vec<CombinationExpression>),
}

#[derive(Deserialize)]
Expand All @@ -47,6 +56,15 @@ pub struct Compartment {
pub mask: Mask,
}

impl Compartment {
pub fn is_predefined(&self) -> bool {
match &self.mask {
Mask::Shape(_) | Mask::Analytical { .. } | Mask::Voxels { .. } => true,
Mask::Combination(_) => false,
}
}
}

pub(crate) fn true_by_default() -> bool {
true
}
Expand Down
167 changes: 138 additions & 29 deletions src/pack/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ use rand::{Rng as _, SeedableRng};

use crate::args::{Args, RearrangeMethod};
use crate::config::{
Configuration, Mask as ConfigMask, Quantity, RuleExpression, Shape as ConfigShape,
TopolIncludes,
CombinationExpression, Compartment as ConfigCompartment, Configuration, Mask as ConfigMask,
Quantity, RuleExpression, Shape as ConfigShape, TopolIncludes,
};
use crate::mask::{distance_mask, distance_mask_grow, Dimensions, Mask};
use crate::placement::{Batch, Placement};
Expand Down Expand Up @@ -377,44 +377,153 @@ impl State {
.map(|d| (d / config.space.resolution) as u64);
let resolution = config.space.resolution;
eprintln!("Setting up compartments...");
let compartments = config
let (predefined, combinations): (Vec<_>, Vec<_>) = config
.space
.compartments
.into_iter()
.partition(ConfigCompartment::is_predefined);
let mut compartments: Vec<Compartment> = predefined
.into_iter()
.map(|comp| -> io::Result<_> {
Ok(Compartment {
let mask = match comp.mask {
ConfigMask::Shape(shape) => {
if verbose {
eprintln!("\tConstructing a {shape} mask...");
}
Mask::create_from_shape(shape, dimensions, None, None)
}
ConfigMask::Analytical {
shape,
center,
radius,
} => {
if verbose {
eprintln!("\tConstructing a {shape} mask...");
}
let center = center.map(|c| (Vec3::from_array(c) / resolution).as_uvec3());
let radius = radius.map(|r| (r / resolution) as u32);
Mask::create_from_shape(shape, dimensions, center, radius)
}
ConfigMask::Voxels { path } => {
if verbose {
eprintln!("\tLoading mask from {path:?}...");
}
Mask::load_from_path(&path).map_err(|err| report_opening(err, path))?
}
ConfigMask::Combination(_) => {
unreachable!() // We partitioned the list above.
}
};
let c = Compartment {
id: comp.id,
mask: match comp.mask {
ConfigMask::Shape(shape) => {
if verbose {
eprintln!("\tConstructing a {shape} mask...");
mask,
distance_masks: Default::default(),
};
Ok(c)
})
.collect::<io::Result<_>>()?;
for combination in combinations {
let ConfigMask::Combination(ces) = combination.mask else {
unreachable!() // We partitioned the list above.
};

// TODO: Really disliking this code duplication. `or` and `and` are more or less the same
// function, except for their mask bit operation.
fn or(ces: &[CombinationExpression], compartments: &[Compartment]) -> Mask {
// TODO: Think about how we should address this case. It feels like something we
// should just be chill about. But perhaps a warning?
if ces.is_empty() {
panic!("combination expression cannot be empty");
}

// TODO: Replace this with a fold or something.
let mut mask = None;
for ce in ces {
match ce {
CombinationExpression::ID(id) => {
let comp = compartments
.iter()
.find(|comp| &comp.id == id)
.expect(&format!("mask with id {id:?} not (yet) defined"));
if let Some(mask) = &mut mask {
*mask |= comp.mask.clone(); // FIXME: We could get rid of this clone, perhaps.
} else {
mask = Some(comp.mask.clone());
}
Mask::create_from_shape(shape, dimensions, None, None)
}
ConfigMask::Analytical {
shape,
center,
radius,
} => {
if verbose {
eprintln!("\tConstructing a {shape} mask...");
CombinationExpression::Or(ces) => {
let res = or(ces, compartments);
if let Some(mask) = &mut mask {
*mask |= res;
} else {
mask = Some(res);
}
let center =
center.map(|c| (Vec3::from_array(c) / resolution).as_uvec3());
let radius = radius.map(|r| (r / resolution) as u32);
Mask::create_from_shape(shape, dimensions, center, radius)
}
ConfigMask::Voxels { path } => {
if verbose {
eprintln!("\tLoading mask from {path:?}...");
CombinationExpression::Not(ces) => {
let res = !or(std::slice::from_ref(ces), compartments);
if let Some(mask) = &mut mask {
*mask &= res;
} else {
mask = Some(res);
}
Mask::load_from_path(&path).map_err(|err| report_opening(err, path))?
}
},
distance_masks: Default::default(),
})
})
.collect::<io::Result<_>>()?;
};
}

mask.unwrap() // We know ecs is not empty.
}

fn and(ces: &[CombinationExpression], compartments: &[Compartment]) -> Mask {
// TODO: Think about how we should address this case. It feels like something we
// should just be chill about. But perhaps a warning?
if ces.is_empty() {
panic!("combination expression cannot be empty");
}

// TODO: Replace this with a fold or something.
let mut mask = None;
for ce in ces {
match ce {
CombinationExpression::ID(id) => {
let comp = compartments
.iter()
.find(|comp| &comp.id == id)
.expect(&format!("mask with id {id:?} not (yet) defined"));
if let Some(mask) = &mut mask {
*mask &= comp.mask.clone(); // FIXME: We could get rid of this clone, perhaps.
} else {
mask = Some(comp.mask.clone());
}
}
CombinationExpression::Or(ces) => {
let res = or(ces, compartments);
if let Some(mask) = &mut mask {
*mask &= res;
} else {
mask = Some(res);
}
}
CombinationExpression::Not(ces) => {
let res = !or(std::slice::from_ref(ces), compartments);
if let Some(mask) = &mut mask {
*mask &= res;
} else {
mask = Some(res);
}
}
};
}

mask.unwrap() // We know ecs is not empty.
}

let baked = Compartment {
id: combination.id,
mask: and(&ces, &compartments),
distance_masks: Default::default(),
};
compartments.push(baked);
}
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code duplication in the above section screams for refactoring.

let space = Space {
size: config.space.size,
dimensions,
Expand Down