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

Clean up code #25

Merged
merged 4 commits into from
Mar 28, 2023
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
249 changes: 76 additions & 173 deletions src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,43 +46,7 @@ pub fn primary_chain(
panic!("unique_branches is empty!")
}

// 1
let most_primary_groups = chain_with_most_primary_groups(unique_branches);
if let Ok(it) = most_primary_groups {
return Ok(it);
}
let filtration = most_primary_groups.unwrap_err();

// 2
let most_multiple_bonds = chain_with_most_multiple_bonds(filtration);
if let Ok(it) = most_multiple_bonds {
return Ok(it);
}
let filtration = most_multiple_bonds.unwrap_err();

// 3
let longest = longest_chain(filtration);
if let Ok(it) = longest {
return Ok(it);
}
let filtration = longest.unwrap_err();

// 4
let most_prefix_subst = chain_with_most_prefix_subst(filtration);
if let Ok(it) = most_prefix_subst {
return Ok(it);
}
let filtration = most_prefix_subst.unwrap_err();

// TODO 5

Ok(filtration[0].chain.to_owned())
}

pub(crate) fn chain_with_most_primary_groups(
branches: Vec<Branch>,
) -> Result<Vec<Atom>, Vec<Branch>> {
let primary_group = &branches
let primary_group = &unique_branches
.iter()
.flat_map(|it| it.groups.to_owned())
.flatten()
Expand All @@ -94,162 +58,95 @@ pub(crate) fn chain_with_most_primary_groups(
panic!("call to filter() failed")
}
})
.max_by_key(|it| it.priority())
.ok_or(branches.to_owned())?;
.max_by_key(|it| it.seniority());

let max_occurrences =
&branches
.iter()
.map(|branch| {
branch
let mut filtration = unique_branches.to_owned();

// 1
if let Some(it) = &primary_group {
let most_primary_groups = chain_max_by(unique_branches, |branch| {
branch
.groups
.iter()
.flatten()
.filter(|&subst| matches!(subst, Substituent::Group(group) if group == it))
.count()
});
if let Ok(it) = most_primary_groups {
return Ok(it);
}
filtration = most_primary_groups.unwrap_err();
}

// 2
let most_multiple_bonds = chain_max_by(filtration, |branch| {
branch
.groups
.iter()
.flatten()
.filter(|&subst| matches!(subst, Substituent::Group(group) if group == primary_group))
.count()
.filter(|&subst| {
matches!(
subst,
Substituent::Group(Alkene) | Substituent::Group(Alkyne)
)
})
.max()
.ok_or(branches.to_owned())?;
.count()
});
if let Ok(it) = most_multiple_bonds {
return Ok(it);
}
let filtration = most_multiple_bonds.unwrap_err();

let primary_by_max =
branches
.iter()
.filter(|&branch| {
branch
// 3
let longest = chain_max_by(filtration, |branch| branch.chain.len());
if let Ok(it) = longest {
return Ok(it);
}
let filtration = longest.unwrap_err();

// 4
let most_prefix_subst = chain_max_by(filtration, |branch| {
branch
.groups
.iter()
.flatten()
.filter(|&subst| matches!(subst, Substituent::Group(group) if group == primary_group))
.count() == *max_occurrences
.filter(|&subst| {
if let Some(it) = primary_group {
matches!(subst, Substituent::Group(group) if group != it)
|| matches!(subst, Substituent::Branch(_))
} else {
true
}
})
.map(Branch::to_owned)
.collect::<Vec<Branch>>();

if primary_by_max.len() == 1 {
Ok(primary_by_max[0].to_owned().chain)
} else {
Err(primary_by_max)
.count()
});
if let Ok(it) = most_prefix_subst {
return Ok(it);
}
}

fn chain_with_most_multiple_bonds(branches: Vec<Branch>) -> Result<Vec<Atom>, Vec<Branch>> {
let max_occurrences = branches
.iter()
.map(|branch| {
branch
.groups
.iter()
.flatten()
.filter(|&subst| {
matches!(
subst,
Substituent::Group(Alkene) | Substituent::Group(Alkyne)
)
})
.count()
})
.max()
.ok_or(branches.to_owned())?;
let filtration = most_prefix_subst.unwrap_err();

let primary_by_max = branches
.iter()
.filter(|&branch| {
branch
.groups
.iter()
.flatten()
.filter(|&subst| {
matches!(
subst,
Substituent::Group(Alkene) | Substituent::Group(Alkyne)
)
})
.count()
== max_occurrences
})
.map(Branch::to_owned)
.collect::<Vec<Branch>>();
// TODO 5

if primary_by_max.len() == 1 {
Ok(primary_by_max[0].to_owned().chain)
} else {
Err(primary_by_max)
}
Ok(filtration[0].chain.to_owned())
}

/// Gets the longest of the given [`Vec`] of chains, assuming that it is non-empty. If there
/// are multiple chains of the greatest length, [`None`] is returned.
/// Returns the maximum of the given `branches` based on the values yielded by given `f` or filters
/// them.
///
/// ## Errors
///
/// If there are no `chains`, this function will return an `Err`.
pub(crate) fn longest_chain(branches: Vec<Branch>) -> Result<Vec<Atom>, Vec<Branch>> {
let max_length = branches
.iter()
.map(|chain| chain.chain.len())
.max()
.ok_or(branches.to_owned())?;
let longest_chains = branches
.into_iter()
.filter(|chain| chain.chain.len() == max_length)
.collect::<Vec<Branch>>();

if longest_chains.len() == 1 {
Ok(longest_chains[0].chain.to_owned())
} else {
Err(longest_chains)
}
}

pub(crate) fn chain_with_most_prefix_subst(
branches: Vec<Branch>,
) -> Result<Vec<Atom>, Vec<Branch>> {
let primary_group = branches
.iter()
.flat_map(|it| it.groups.to_owned())
.flatten()
.filter(|it| matches!(it, Substituent::Group(_)))
.map(|it| {
if let Substituent::Group(group) = it {
group
} else {
panic!("call to filter() failed")
}
})
.max_by_key(|it| it.priority())
.ok_or(branches.to_owned())?;

let max_occurrences = branches
.iter()
.map(|branch| {
branch
.groups
.iter()
.flatten()
.filter(|&subst| {
matches!(subst, Substituent::Group(group) if *group != primary_group)
|| matches!(subst, Substituent::Branch(_))
})
.count()
})
.max()
.ok_or(branches.to_owned())?;
/// If a maximum cannot be attained (e.g., if there are no branches), an [`Err`] containing all
/// original [`Branch`]es is returned. If there are multiple branches matching the maximum, an
/// [`Err`] containing matching [`Branch`]es is returned.
pub(crate) fn chain_max_by<F>(branches: Vec<Branch>, f: F) -> Result<Vec<Atom>, Vec<Branch>>
where
F: Fn(&Branch) -> usize,
{
let max: usize = branches.iter().map(&f).max().ok_or(branches.to_owned())?;

let primary_by_max = branches
.iter()
.filter(|&branch| {
branch
.groups
.iter()
.flatten()
.filter(|&subst| {
matches!(subst, Substituent::Group(group) if *group != primary_group)
|| matches!(subst, Substituent::Branch(_))
})
.count()
== max_occurrences
})
.map(Branch::to_owned)
.into_iter()
.filter(|it| f(it) == max)
.collect::<Vec<Branch>>();

if primary_by_max.len() == 1 {
Expand All @@ -259,6 +156,12 @@ pub(crate) fn chain_with_most_prefix_subst(
}
}

/// Returns a [`Vec`] of chains between every endpoint on the graph, thereby yielding every
/// possible candidate for the primary chain.
///
/// ## Errors
///
/// Returns [`InvalidGraphError`] if any invalid structures are found while traversing the graph.
pub(crate) fn get_all_chains(graph: &GridState) -> Fallible<Vec<Vec<Atom>>> {
let endpoints = endpoint_carbons(graph)?
.iter()
Expand Down
10 changes: 8 additions & 2 deletions src/groups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,9 @@ fn group_patterns(mut groups: Vec<Group>) -> Vec<Substituent> {
[Carbonyl, Amine => Amide],
[Carbonyl, Hydrogen => Aldehyde],
);
groups.retain(|it| it != &Hydrogen);
break;
}
groups.retain(|it| it != &Hydrogen);

let mut rest = groups
.into_iter()
Expand All @@ -154,7 +154,12 @@ macro_rules! compound {
($groups:expr, $out:expr, $([$first:expr, $second:expr => $comp:expr],)*) => {
$(
if $groups.contains(&$first) && $groups.contains(&$second) {
$groups.retain(|it| it != &$first && it != &$second);
if let Some(index) = $groups.iter().position(|&x| x == $first) {
$groups.remove(index);
}
if let Some(index) = $groups.iter().position(|&x| x == $second) {
$groups.remove(index);
}
$out.push(Substituent::Group($comp));
continue;
}
Expand Down Expand Up @@ -292,6 +297,7 @@ fn group_directions(
Ok(directions)
}

/// A type that is only available when the [`GridState`] is valid.
pub(crate) type Fallible<T> = Result<T, InvalidGraphError>;

/// The group of invalid structures that can appear on the [`GridState`].
Expand Down
Loading