use super::category_tree::CategoryTree;
use std::collections::{HashMap, HashSet};
use crate::collection::error::OvertureMapsCollectionError;
#[derive(Debug, Clone)]
pub struct TaxonomyModel {
group_mappings: HashMap<String, HashSet<String>>,
}
impl TaxonomyModel {
pub fn from_tree_nodes(
tree_nodes: Vec<(String, Option<String>)>,
group_mappings: HashMap<String, Vec<String>>,
) -> Self {
let category_tree = CategoryTree::new(tree_nodes);
let activity_mappings = group_mappings
.into_iter()
.map(|(activity, categories)| {
(activity, category_tree.get_linearized_query(categories))
})
.collect::<HashMap<String, HashSet<String>>>();
TaxonomyModel {
group_mappings: activity_mappings,
}
}
pub fn from_mapping(mapping: HashMap<String, HashSet<String>>) -> Self {
Self {
group_mappings: mapping,
}
}
pub fn get_unique_categories(&self) -> HashSet<String> {
let mut result = HashSet::<String>::new();
for set in self
.group_mappings
.values()
.cloned()
.collect::<Vec<HashSet<String>>>()
{
result.extend(set);
}
result
}
pub fn reverse_map(
&self,
categories: &[String],
group_labels: Vec<String>,
) -> Result<Vec<Vec<bool>>, OvertureMapsCollectionError> {
categories
.iter()
.map(|category| {
group_labels
.iter()
.map(|group| {
Ok::<bool, OvertureMapsCollectionError>(
self.group_mappings
.get(group)
.ok_or(OvertureMapsCollectionError::GroupMappingError(format!(
"Group {group} was not found in mapping"
)))?
.contains(category),
)
})
.collect::<Result<Vec<bool>, OvertureMapsCollectionError>>()
})
.collect::<Result<Vec<Vec<bool>>, OvertureMapsCollectionError>>()
}
}