use toml_edit::{InlineTable, Value};
use crate::{
data::{BindingGeneration, BindingSelector, DataSourceInfo, SourceRows, VectorSource},
BooleanValues, CategoryValues, NumericValues, Result,
};
use super::{
codec::{invalid, Codec},
keys::selector_pending,
resolve::{DataReference, ValueScope},
RecipeWarning,
};
pub(crate) struct Capture {
groups: Vec<Group>,
names: Vec<String>,
explicit_names: Vec<(String, String)>,
prefix: String,
table_base: Option<String>,
collection: Option<DataSourceInfo>,
pub(crate) warnings: Vec<RecipeWarning>,
}
struct Group {
name: String,
owner: String,
sources: Vec<Captured>,
}
struct Captured {
source: DataSourceInfo,
columns: Vec<Snapshot>,
}
#[derive(Clone)]
enum SnapshotValues {
Numeric(NumericValues),
Category(CategoryValues),
Raw(crate::data::RawKeyValues),
Boolean(BooleanValues),
Rows(SourceRows),
Status(crate::data::EstimateStatusBinding),
Targets(std::sync::Arc<[crate::elements::SignificanceTarget]>),
Marks(std::sync::Arc<[crate::elements::SignificanceMark]>),
Facets(std::sync::Arc<[crate::layout::FacetCell]>),
}
#[derive(Clone)]
struct Snapshot {
values: SnapshotValues,
start: usize,
stride: usize,
len: usize,
}
impl Snapshot {
fn whole(values: SnapshotValues) -> Self {
let len = match &values {
SnapshotValues::Numeric(values) => values.len(),
SnapshotValues::Category(values) => values.len(),
SnapshotValues::Raw(values) => values.len(),
SnapshotValues::Boolean(values) => values.len(),
SnapshotValues::Rows(values) => values.len(),
SnapshotValues::Status(values) => values.statuses().len(),
SnapshotValues::Targets(values) => values.len(),
SnapshotValues::Marks(values) => values.len(),
SnapshotValues::Facets(values) => values.len(),
};
Self {
values,
start: 0,
stride: 1,
len,
}
}
fn strided(&self, start: usize, stride: usize, len: usize) -> Self {
Self {
values: self.values.clone(),
start,
stride,
len,
}
}
fn agrees(&self, other: &Self) -> Result<Option<bool>> {
if self.len != other.len {
return Ok(Some(false));
}
macro_rules! compare {
($a:expr, $b:expr) => {{
for row in 0..self.len {
crate::operation::check()?;
if $a(self.start + row * self.stride) != $b(other.start + row * other.stride) {
return Ok(Some(false));
}
}
Ok(Some(true))
}};
}
match (&self.values, &other.values) {
(SnapshotValues::Numeric(a), SnapshotValues::Numeric(b)) => {
compare!(|row| a.get(row).flatten().map(f64::to_bits), |row| b
.get(row)
.flatten()
.map(f64::to_bits))
}
(SnapshotValues::Category(a), SnapshotValues::Category(b)) => {
compare!(|row| a.key_at(row), |row| b.key_at(row))
}
(SnapshotValues::Raw(a), SnapshotValues::Raw(b)) => {
compare!(|row| a.get(row), |row| b.get(row))
}
(SnapshotValues::Boolean(a), SnapshotValues::Boolean(b)) => {
compare!(|row| a.get(row), |row| b.get(row))
}
(SnapshotValues::Rows(a), SnapshotValues::Rows(b)) => {
compare!(|row| a.get(row), |row| b.get(row))
}
(SnapshotValues::Status(a), SnapshotValues::Status(b)) => {
let (a, b) = (a.statuses(), b.statuses());
compare!(|row| a.get(row), |row| b.get(row))
}
(SnapshotValues::Targets(a), SnapshotValues::Targets(b)) => {
compare!(|row| a.get(row), |row| b.get(row))
}
(SnapshotValues::Facets(a), SnapshotValues::Facets(b)) => {
compare!(|row| a.get(row), |row| b.get(row))
}
(SnapshotValues::Marks(a), SnapshotValues::Marks(b)) => {
use crate::elements::SignificanceMark;
for row in 0..self.len {
crate::operation::check()?;
let a = &a[self.start + row * self.stride];
let b = &b[other.start + row * other.stride];
let same = match (a, b) {
(SignificanceMark::PValue(a), SignificanceMark::PValue(b)) => {
a.to_bits() == b.to_bits()
}
_ => a == b,
};
if !same {
return Ok(Some(false));
}
}
Ok(Some(true))
}
_ => Ok(None),
}
}
}
impl Capture {
pub(crate) fn independent(&mut self, role: &str) -> Value {
DataReference {
binding: self.name(role),
selector: BindingSelector::Whole,
value_name: None,
verbatim_label: false,
scope: None,
}
.encode()
}
pub(crate) fn new() -> Self {
Self {
groups: Vec::new(),
names: Vec::new(),
explicit_names: Vec::new(),
prefix: String::new(),
table_base: None,
collection: None,
warnings: Vec::new(),
}
}
pub(crate) fn owner<T>(
&mut self,
owner: &str,
call: impl FnOnce(&mut Self) -> Result<T>,
) -> Result<T> {
let prefix = format!("{}{owner}_", self.prefix);
let previous = std::mem::replace(&mut self.prefix, prefix);
let result = call(self);
self.prefix = previous;
result
}
pub(crate) fn table_group<T>(
&mut self,
base: &str,
call: impl FnOnce(&mut Self) -> Result<T>,
) -> Result<T> {
let previous = self.table_base.replace(base.to_owned());
let result = call(self);
self.table_base = previous;
result
}
fn name(&mut self, base: &str) -> String {
let base = format!("{}{base}", self.prefix);
let mut name = base.clone();
let mut ordinal = 2;
while self.names.contains(&name) {
name = format!("{base}_{ordinal}");
ordinal += 1;
}
self.names.push(name.clone());
name
}
fn group(&mut self, capture: Captured, role: &str) -> Result<String> {
let source = &capture.source;
if source.selector().is_some() || source.binding_name().is_some() {
for same_batch in [true, false] {
'groups: for group in self.groups.iter_mut().rev() {
if group.owner != self.prefix
&& !source.binding_name().is_some_and(|name| {
group.sources.iter().any(|previous| {
previous.source.binding_name() == Some(name)
&& source.reference().same_source(previous.source.reference())
})
})
{
continue;
}
if group
.sources
.iter()
.any(|previous| previous.source.reference() == source.reference())
!= same_batch
{
continue;
}
for previous in &group.sources {
if !compatible(previous, &capture)? {
continue 'groups;
}
}
let name = group.name.clone();
group.sources.push(capture);
return Ok(name);
}
}
let base = source
.binding_name()
.or(self.table_base.as_deref())
.unwrap_or("data")
.to_owned();
let name = self.name(&base);
if let Some(explicit) = source.binding_name() {
self.explicit_names
.push((name.clone(), explicit.to_owned()));
}
self.groups.push(Group {
name: name.clone(),
owner: self.prefix.clone(),
sources: vec![capture],
});
return Ok(name);
}
Ok(self.name(role))
}
pub(crate) fn content_reference(
&mut self,
source: &DataSourceInfo,
role: &str,
path: &str,
) -> Result<Value> {
let binding = self.group(
Captured {
source: source.clone(),
columns: Vec::new(),
},
role,
)?;
let selector = source.selector().cloned().unwrap_or(BindingSelector::Whole);
if selector_pending(&selector) {
self.warnings.push(RecipeWarning::new(
path,
&binding,
"original key cannot be serialized",
));
}
Ok(DataReference {
binding,
selector,
value_name: None,
verbatim_label: false,
scope: None,
}
.encode())
}
fn reference(
&mut self,
source: &DataSourceInfo,
columns: Vec<Snapshot>,
name: &str,
role: &str,
field: &str,
verbatim_label: bool,
) -> Result<Value> {
let binding = self.group(
Captured {
source: source.clone(),
columns,
},
role,
)?;
let selector = source.selector().cloned().unwrap_or(BindingSelector::Whole);
if selector_pending(&selector) {
self.warnings.push(RecipeWarning::new(
field,
&binding,
"original key cannot be serialized",
));
}
Ok(DataReference {
binding,
value_name: (selector == BindingSelector::Whole).then(|| name.to_owned()),
selector,
verbatim_label,
scope: None,
}
.encode())
}
pub(crate) fn variables(
&mut self,
source: &DataSourceInfo,
values: &[crate::data::NamedNumericValues],
field: &str,
) -> Result<Value> {
self.reference(
source,
values
.iter()
.map(|value| Snapshot::whole(SnapshotValues::Numeric(value.values.clone())))
.collect(),
"variables",
"variables",
field,
values
.iter()
.any(|value| value.values.name() != value.values.raw_name()),
)
}
pub(crate) fn begin_plot(&mut self) {
self.collection = None;
}
pub(crate) fn primary_rectangle(
&mut self,
values: &NumericValues,
role: &str,
field: &str,
) -> Result<Value> {
let source = values.get_source();
let columns = rectangle_snapshots(
source,
&Snapshot::whole(SnapshotValues::Numeric(values.clone())),
)?;
if !values.vector_source().is_identity() {
return Err(invalid(format!(
"{field}: primary rectangle is not a complete row-major capture"
)));
}
self.collection = Some(source.clone());
let value = self.reference(source, columns, values.name(), role, field, false)?;
Ok(with_value_name(value, values.name()))
}
fn projected(
&mut self,
projection: &VectorSource,
snapshot: Snapshot,
name: &str,
role: &str,
field: &str,
verbatim_label: bool,
) -> Result<Value> {
let source = projection.info();
let (columns, scope) = if let Some(copies) = projection.row_repetition() {
let [rows] = source.member_shape() else {
return Err(invalid(format!(
"{field}: repeated rows require a one-dimensional original source"
)));
};
let Some(rectangle) = &self.collection else {
return Err(invalid(format!(
"{field}: row scope requires the actual collection"
)));
};
if rectangle.selected_shape() != [*rows, copies] {
return Err(invalid(format!(
"{field}: row projection does not match the collection"
)));
}
(
vec![snapshot.strided(0, copies, *rows)],
Some(ValueScope::Rows),
)
} else if projection.is_identity() && source.selected_shape().len() == 2 {
let Some(rectangle) = &self.collection else {
return Err(invalid(format!(
"{field}: cell rectangle requires the actual collection"
)));
};
if source.selected_shape() != rectangle.selected_shape() {
return Err(invalid(format!(
"{field}: cell rectangle does not match the primary input"
)));
}
(
rectangle_snapshots(source, &snapshot)?,
Some(
if source.generation() == Some(BindingGeneration::WideExpansion) {
ValueScope::Wide
} else {
ValueScope::Cells
},
),
)
} else if projection.is_identity() && source.generation().is_none() {
(vec![snapshot], None)
} else {
return Err(invalid(format!(
"{field}: source projection requires its actual collection declaration"
)));
};
let value = self.reference(source, columns, name, role, field, verbatim_label)?;
let value = if matches!(scope, Some(ValueScope::Cells | ValueScope::Wide)) {
with_value_name(value, name)
} else {
value
};
Ok(with_scope(value, scope))
}
pub(crate) fn numeric(
&mut self,
values: &NumericValues,
role: &str,
field: &str,
) -> Result<Value> {
self.projected(
values.vector_source(),
Snapshot::whole(SnapshotValues::Numeric(values.clone())),
values.name(),
role,
field,
values.raw_name() != values.name(),
)
}
fn generated_category(
&self,
projection: &VectorSource,
len: usize,
field: &str,
) -> Result<Option<Value>> {
let source = projection.info();
if source.generation() == Some(BindingGeneration::ColumnNames) {
let collection = self.collection.as_ref().ok_or_else(|| {
invalid(format!(
"{field}: generated column identity requires its actual primary collection"
))
})?;
if source.reference() != collection.reference()
|| source.selector() != collection.selector()
|| source.selected_shape() != collection.selected_shape()
{
return Err(invalid(format!(
"{field}: generated column identity belongs to another collection"
)));
}
let [rows, columns] = collection.selected_shape() else {
return Err(invalid(
"generated column identity requires an actual rectangle",
));
};
if projection.column_cycle() != Some(*columns)
|| rows.checked_mul(*columns) != Some(len)
{
return Err(invalid(format!(
"{field}: selected column identities are not a complete generated projection"
)));
}
let policy = source
.column_generation()
.ok_or_else(|| invalid("missing original generated-column identity policy"))?;
if collection.column_generation() != Some(policy) {
return Err(invalid(
"generated column identity differs from its actual collection policy",
));
}
let mut fields = InlineTable::new();
fields.insert("generated", "columns".into());
return Ok(Some(fields.into()));
}
Ok(None)
}
pub(crate) fn alpha_numeric(
&mut self,
values: &NumericValues,
name: &str,
path: &str,
) -> Result<Value> {
if values.get_source().generation() == Some(BindingGeneration::RowPosition) {
let source = values.get_source();
let collection = self.collection.as_ref().ok_or_else(|| {
invalid("generated row positions require the actual primary collection")
})?;
if source.reference() != collection.reference()
|| source.selector() != collection.selector()
|| source.selected_shape() != collection.selected_shape()
{
return Err(invalid("row positions belong to another collection"));
}
let [rows, columns] = collection.selected_shape() else {
return Err(invalid("row positions require an actual rectangle"));
};
let projection = values.vector_source();
if rows.checked_mul(*columns) != Some(values.len())
|| !(projection.row_repetition() == Some(*columns)
|| (*columns == 1 && projection.is_identity()))
{
return Err(invalid(
"row positions are not a complete generated projection",
));
}
let mut fields = InlineTable::new();
fields.insert("generated", "rows".into());
return Ok(fields.into());
}
self.numeric(values, name, path)
}
pub(crate) fn category(
&mut self,
values: &CategoryValues,
role: &str,
field: &str,
) -> Result<Value> {
if let Some(generated) =
self.generated_category(values.vector_source(), values.len(), field)?
{
return Ok(generated);
}
self.projected(
values.vector_source(),
Snapshot::whole(SnapshotValues::Category(values.clone())),
values.original_name(),
role,
field,
values.name() != values.original_name(),
)
}
pub(crate) fn keys(
&mut self,
values: &crate::data::KeyValues,
role: &str,
field: &str,
) -> Result<Value> {
match values {
crate::data::KeyValues::Strings(values) => self.category(values, role, field),
crate::data::KeyValues::Raw(values) => {
if let Some(generated) =
self.generated_category(values.vector_source(), values.len(), field)?
{
return Ok(generated);
}
self.projected(
values.vector_source(),
Snapshot::whole(SnapshotValues::Raw(values.clone())),
values.name(),
role,
field,
false,
)
}
}
}
pub(crate) fn boolean(
&mut self,
values: &BooleanValues,
role: &str,
field: &str,
) -> Result<Value> {
self.projected(
values.vector_source(),
Snapshot::whole(SnapshotValues::Boolean(values.clone())),
values.name(),
role,
field,
false,
)
}
pub(crate) fn rows(&mut self, values: &SourceRows, role: &str, field: &str) -> Result<Value> {
self.projected(
values.vector_source(),
Snapshot::whole(SnapshotValues::Rows(values.clone())),
"row_id",
role,
field,
false,
)
}
pub(crate) fn significance_targets(
&mut self,
source: &DataSourceInfo,
values: &std::sync::Arc<[crate::elements::SignificanceTarget]>,
role: &str,
field: &str,
) -> Result<Value> {
self.reference(
source,
vec![Snapshot::whole(SnapshotValues::Targets(values.clone()))],
role,
role,
field,
false,
)
}
pub(crate) fn significance_marks(
&mut self,
source: &DataSourceInfo,
values: &std::sync::Arc<[crate::elements::SignificanceMark]>,
field: &str,
) -> Result<Value> {
self.reference(
source,
vec![Snapshot::whole(SnapshotValues::Marks(values.clone()))],
"marks",
"marks",
field,
false,
)
}
pub(crate) fn facet_cells(
&mut self,
source: &DataSourceInfo,
values: &std::sync::Arc<[crate::layout::FacetCell]>,
field: &str,
) -> Result<Value> {
self.reference(
source,
vec![Snapshot::whole(SnapshotValues::Facets(values.clone()))],
"result_facets",
"result_facets",
field,
false,
)
}
pub(crate) fn statuses(
&mut self,
values: &crate::data::EstimateStatusBinding,
field: &str,
) -> Result<Value> {
self.reference(
values.get_source(),
vec![Snapshot::whole(SnapshotValues::Status(values.clone()))],
"estimate_status",
"estimate_status",
field,
false,
)
}
pub(crate) fn final_names(&self) -> Vec<(String, String)> {
use std::collections::{HashMap, HashSet};
let mut counts = HashMap::new();
for (_, name) in &self.explicit_names {
*counts.entry(name.as_str()).or_insert(0_usize) += 1;
}
let preferred: HashMap<_, _> = self
.explicit_names
.iter()
.filter(|(_, name)| counts[name.as_str()] == 1)
.map(|(provisional, name)| (provisional.as_str(), name.as_str()))
.collect();
let mut used: HashSet<String> = preferred.values().map(|name| (*name).to_owned()).collect();
self.names
.iter()
.map(|current| {
let assigned = if let Some(name) = preferred.get(current.as_str()) {
(*name).to_owned()
} else {
let mut candidate = current.clone();
let mut ordinal = 2;
while !used.insert(candidate.clone()) {
candidate = format!("{current}_{ordinal}");
ordinal += 1;
}
candidate
};
(current.clone(), assigned)
})
.collect()
}
pub(crate) fn bindings(&self) -> toml_edit::Table {
let mut table = toml_edit::Table::new();
for name in &self.names {
table.insert(name, toml_edit::Item::Table(toml_edit::Table::new()));
}
table
}
}
fn rectangle_snapshots(source: &DataSourceInfo, snapshot: &Snapshot) -> Result<Vec<Snapshot>> {
let [rows, columns] = source.selected_shape() else {
return Err(invalid("expected actual rectangular source"));
};
if rows.checked_mul(*columns) != Some(snapshot.len) || *columns == 0 {
return Err(invalid("rectangle shape does not match captured members"));
}
crate::data::source::collect_source(
(0..*columns).map(|column| Ok(snapshot.strided(column, *columns, *rows))),
)
}
fn with_value_name(mut value: Value, name: &str) -> Value {
value
.as_inline_table_mut()
.expect("data reference")
.insert("value_name", name.into());
value
}
pub(crate) fn with_scope(mut value: Value, scope: Option<ValueScope>) -> Value {
if let Some(scope) = scope {
value
.as_inline_table_mut()
.expect("data reference")
.insert("scope", scope.encode());
}
value
}
fn compatible(left: &Captured, right: &Captured) -> Result<bool> {
let a = &left.source;
let b = &right.source;
if !a.reference().same_source(b.reference()) {
return Ok(false);
}
let same_capture = a.reference() == b.reference();
if left.columns.is_empty() || right.columns.is_empty() {
return Ok(same_capture
&& (a.selector() != b.selector()
|| (left.columns.is_empty() && right.columns.is_empty())));
}
let (Some(a_indices), Some(b_indices)) = (a.selected_indices(), b.selected_indices()) else {
if !same_capture {
return Ok(false);
}
return if a.selector() == b.selector() {
matching_column(left, right, 0, 0, same_capture)
} else {
Ok(true)
};
};
if a.source_shape() != b.source_shape() {
return Ok(false);
}
for (i, a_index) in a_indices.iter().enumerate() {
for (j, b_index) in b_indices.iter().enumerate() {
crate::operation::check()?;
let a_key = a.selected_keys().and_then(|keys| keys.get(i));
let b_key = b.selected_keys().and_then(|keys| keys.get(j));
if a_index == b_index {
if a_key != b_key || !matching_column(left, right, i, j, same_capture)? {
return Ok(false);
}
} else if a_key.is_some() && a_key == b_key {
return Ok(false);
}
}
}
Ok(true)
}
fn matching_column(
left: &Captured,
right: &Captured,
i: usize,
j: usize,
same_capture: bool,
) -> Result<bool> {
if let (Some(a), Some(b)) = (left.columns.get(i), right.columns.get(j)) {
if let Some(agrees) = a.agrees(b)? {
return Ok(agrees);
}
}
Ok(same_capture)
}
pub(crate) fn group_record(mode: &str, fields: InlineTable) -> Value {
let mut input = InlineTable::new();
input.insert(mode, fields.into());
input.into()
}
pub(crate) fn portable_key(key: &crate::data::RawKey) -> Result<Value> {
if selector_pending(&BindingSelector::Key(key.clone())) {
return Err(invalid("original authored key has no portable declaration"));
}
Ok(key.encode())
}