use std::collections::{HashMap, HashSet};
use indexmap::IndexMap;
use relate_core::{NodeId, Value};
use super::research::{live_neighbors, with_node};
use super::Graph;
use relate_ir::Direction;
pub struct SolRows {
pub columns: Vec<String>,
pub rows: Vec<Vec<Value>>,
}
fn label_candidates(graph: &Graph, lid: u32) -> Vec<NodeId> {
match graph.indexes.label_index.get(&lid) {
Some(set) => set.iter().copied().collect(),
None => Vec::new(),
}
}
fn carries_label_and_contains(
graph: &Graph,
node: NodeId,
lid: u32,
kid: u32,
needle: &str,
) -> bool {
with_node(graph, node, |n| {
n.labels.contains(&lid)
&& n.props
.get(kid)
.and_then(Value::as_string)
.is_some_and(|s| s.contains(needle))
})
.unwrap_or(false)
}
fn birthday_after(graph: &Graph, node: NodeId, lid: u32, kid: u32, cutoff: &str) -> bool {
with_node(graph, node, |n| {
n.labels.contains(&lid)
&& n.props
.get(kid)
.and_then(Value::as_string)
.is_some_and(|s| s > cutoff)
})
.unwrap_or(false)
}
fn carries_label(graph: &Graph, node: NodeId, lid: u32) -> bool {
with_node(graph, node, |n| n.labels.contains(&lid)).unwrap_or(false)
}
fn empty(columns: &[&str]) -> SolRows {
SolRows {
columns: columns.iter().map(|c| c.to_string()).collect(),
rows: Vec::new(),
}
}
const Q19_COLUMNS: &[&str] = &["l.name", "comment_count"];
struct Q19Groups {
counts: IndexMap<Option<String>, i64>,
names: HashMap<NodeId, Option<String>>,
}
fn place_name(graph: &Graph, place: NodeId, name_kid: u32) -> Option<String> {
with_node(graph, place, |n| {
n.props
.get(name_kid)
.and_then(Value::as_string)
.map(str::to_string)
})
.expect("q19 kernel: a walked place is live (adjacency is endpoint-checked)")
}
fn bump(graph: &Graph, place: NodeId, place_lid: u32, name_kid: u32, groups: &mut Q19Groups) {
if !carries_label(graph, place, place_lid) {
return;
}
let name = groups
.names
.entry(place)
.or_insert_with(|| place_name(graph, place, name_kid))
.clone();
*groups.counts.entry(name).or_insert(0) += 1;
}
pub fn q19(graph: &Graph, tag_first: bool) -> SolRows {
let (Some(tag_lid), Some(comment_lid), Some(place_lid)) = (
graph.label_id("Tag"),
graph.label_id("Comment"),
graph.label_id("Place"),
) else {
return empty(Q19_COLUMNS);
};
let Some(name_kid) = graph.prop_key_id("name") else {
return empty(Q19_COLUMNS);
};
if graph.prop_key_id("ID").is_none() {
return empty(Q19_COLUMNS);
}
let (Some(has_tag), Some(located_in)) = (
graph.rel_type_id("commentHasTag"),
graph.rel_type_id("commentIsLocatedIn"),
) else {
return empty(Q19_COLUMNS);
};
const NEEDLE: &str = "Copernicus";
let mut groups = Q19Groups {
counts: IndexMap::new(),
names: HashMap::new(),
};
let (mut tags, mut comments, mut places) = (Vec::new(), Vec::new(), Vec::new());
let mut walk_places = |comment: NodeId| {
live_neighbors(graph, comment, located_in, Direction::Outgoing, &mut places);
for place in places.iter().copied() {
bump(graph, place, place_lid, name_kid, &mut groups);
}
};
if tag_first {
for tag in label_candidates(graph, tag_lid) {
if !carries_label_and_contains(graph, tag, tag_lid, name_kid, NEEDLE) {
continue;
}
live_neighbors(graph, tag, has_tag, Direction::Incoming, &mut comments);
for comment in comments.iter().copied() {
if !carries_label(graph, comment, comment_lid) {
continue;
}
walk_places(comment);
}
}
} else {
for comment in label_candidates(graph, comment_lid) {
live_neighbors(graph, comment, has_tag, Direction::Outgoing, &mut tags);
for tag in tags.iter().copied() {
if !carries_label_and_contains(graph, tag, tag_lid, name_kid, NEEDLE) {
continue;
}
walk_places(comment);
}
}
}
let mut ranked: Vec<(Option<String>, i64)> = groups
.counts
.iter()
.map(|(name, count)| (name.clone(), *count))
.collect();
ranked.sort_by_key(|a| std::cmp::Reverse(a.1));
SolRows {
columns: Q19_COLUMNS.iter().map(|c| c.to_string()).collect(),
rows: ranked
.into_iter()
.map(|(name, count)| {
vec![
name.map(|s| Value::String(s.into())).unwrap_or(Value::Null),
Value::Int(count),
]
})
.collect(),
}
}
const Q8_COLUMNS: &[&str] = &["p.ID"];
fn record_person_id(
graph: &Graph,
person: NodeId,
id_kid: u32,
seen: &mut HashSet<NodeId>,
distinct: &mut Vec<i64>,
) {
if !seen.insert(person) {
return;
}
let id = with_node(graph, person, |n| {
n.props.get(id_kid).and_then(|v| match v {
Value::Int(i) => Some(*i),
_ => None,
})
})
.expect("q8 kernel: a birthday-filtered person is live");
if let Some(id) = id {
distinct.push(id);
}
}
pub fn q8(graph: &Graph, forum_first: bool) -> SolRows {
let (Some(forum_lid), Some(person_lid)) = (graph.label_id("Forum"), graph.label_id("Person"))
else {
return empty(Q8_COLUMNS);
};
let (Some(title_kid), Some(birthday_kid), Some(id_kid)) = (
graph.prop_key_id("title"),
graph.prop_key_id("birthday"),
graph.prop_key_id("ID"),
) else {
return empty(Q8_COLUMNS);
};
let Some(has_moderator) = graph.rel_type_id("hasModerator") else {
return empty(Q8_COLUMNS);
};
const TITLE_NEEDLE: &str = "Emilio Fernandez";
const BIRTHDAY_CUTOFF: &str = "1990-01-01";
let mut seen: HashSet<NodeId> = HashSet::new();
let mut distinct: Vec<i64> = Vec::new();
let (mut persons, mut forums) = (Vec::new(), Vec::new());
if forum_first {
for forum in label_candidates(graph, forum_lid) {
if !carries_label_and_contains(graph, forum, forum_lid, title_kid, TITLE_NEEDLE) {
continue;
}
live_neighbors(
graph,
forum,
has_moderator,
Direction::Outgoing,
&mut persons,
);
for person in persons.iter().copied() {
if birthday_after(graph, person, person_lid, birthday_kid, BIRTHDAY_CUTOFF) {
record_person_id(graph, person, id_kid, &mut seen, &mut distinct);
}
}
}
} else {
for person in label_candidates(graph, person_lid) {
if !birthday_after(graph, person, person_lid, birthday_kid, BIRTHDAY_CUTOFF) {
continue;
}
live_neighbors(
graph,
person,
has_moderator,
Direction::Incoming,
&mut forums,
);
for forum in forums.iter().copied() {
if carries_label_and_contains(graph, forum, forum_lid, title_kid, TITLE_NEEDLE) {
record_person_id(graph, person, id_kid, &mut seen, &mut distinct);
break;
}
}
}
}
SolRows {
columns: Q8_COLUMNS.iter().map(|c| c.to_string()).collect(),
rows: distinct
.into_iter()
.map(|id| vec![Value::Int(id)])
.collect(),
}
}
pub fn q30(graph: &Graph, early_exit: bool) -> SolRows {
let has_reply = 'walk: {
let (Some(comment_lid), Some(person_lid), Some(post_lid)) = (
graph.label_id("Comment"),
graph.label_id("Person"),
graph.label_id("Post"),
) else {
break 'walk false;
};
if graph.prop_key_id("ID").is_none() {
break 'walk false;
}
let (Some(has_creator), Some(reply_of_post), Some(post_has_creator)) = (
graph.rel_type_id("commentHasCreator"),
graph.rel_type_id("replyOfPost"),
graph.rel_type_id("postHasCreator"),
) else {
break 'walk false;
};
let mut seen: HashSet<NodeId> = HashSet::new();
let (mut creators, mut posts, mut post_creators) = (Vec::new(), Vec::new(), Vec::new());
'comments: for comment in label_candidates(graph, comment_lid) {
live_neighbors(
graph,
comment,
has_creator,
Direction::Outgoing,
&mut creators,
);
if creators.is_empty() {
continue;
}
live_neighbors(
graph,
comment,
reply_of_post,
Direction::Outgoing,
&mut posts,
);
if posts.is_empty() {
continue;
}
for creator in creators.iter().copied() {
if !carries_label(graph, creator, person_lid) {
continue;
}
for post in posts.iter().copied() {
if !carries_label(graph, post, post_lid) {
continue;
}
live_neighbors(
graph,
post,
post_has_creator,
Direction::Outgoing,
&mut post_creators,
);
if post_creators.contains(&creator) {
seen.insert(comment);
if early_exit {
break 'walk true;
}
continue 'comments;
}
}
}
}
!seen.is_empty()
};
SolRows {
columns: vec!["has_self_reply".into()],
rows: vec![vec![Value::Bool(has_reply)]],
}
}