use super::*;
use lichtung_plot::text::{FontFamily, FontStack};
#[test]
fn fixed_and_mapped_alpha_guide_identity_preserves_distinct_coefficients() {
use lichtung_plot::{
guides::CanvasLegendPolicy,
scales::{AlphaEncoding, AlphaValues},
};
let make_plot = || {
context_plot()
.hue(CategoryValues::new("cohort", ["Control"; 2]).unwrap())
.size(700, 500)
};
let first = make_plot().point_alpha(0.5).unwrap();
let second = make_plot().point_alpha(128.0 / 255.0).unwrap();
let svg = render_svg(&first, "alpha-fixed-guide").unwrap();
assert_eq!(svg.matches("fill-opacity=\"0.5\"").count(), 3);
let shared = |first, second| {
Canvas::grid(1, 2)
.unwrap()
.panel(0, 0, first)
.unwrap()
.panel(0, 1, second)
.unwrap()
.legend_policy(CanvasLegendPolicy::Shared)
.size(1500, 550)
};
assert!(shared(first.clone(), second).preflight().is_err());
let compatible = render_canvas(shared(first.clone(), first), "equal-fixed-alpha").unwrap();
assert_eq!(compatible.matches(">Control</text>").count(), 1);
let mapped = |coefficient| {
make_plot()
.point_alpha(AlphaEncoding::observations(
AlphaValues::categorical(CategoryValues::new("Quality", ["A"; 2]).unwrap(), |_| {
coefficient
})
.unwrap(),
))
.unwrap()
};
assert!(shared(mapped(0.5), mapped(128.0 / 255.0))
.preflight()
.is_err());
}
fn themed_surface(root: lichtung_plot::Color, panel: lichtung_plot::Color) -> Theme {
Theme::publication()
.customize()
.surfaces(lichtung_plot::theme::SurfaceTheme::new(root, panel).unwrap())
.build()
.unwrap()
}
fn context_plot() -> Plot<lichtung_plot::kind::Scatter> {
Plot::scatter(
NumericValues::new("x", [0., 1.]),
NumericValues::new("y", [1., 2.]),
)
}
#[test]
fn construction_defaults_are_captured_and_parent_theme_has_precedence() {
use lichtung_plot::Color;
let paper = themed_surface(Color::rgb(222, 233, 244), Color::rgb(212, 223, 234));
let detail = themed_surface(Color::rgb(211, 234, 222), Color::rgb(201, 224, 212));
let explicit = themed_surface(Color::rgb(244, 222, 233), Color::rgb(234, 212, 223));
let outside = context_plot();
let (child, canvas) = paper.with_context(|| {
let captured = context_plot();
let other = context_plot();
assert!(std::ptr::eq(
captured.get_default_theme().unwrap(),
other.get_default_theme().unwrap(),
));
let child = detail.with_context(context_plot);
let canvas = Canvas::grid(1, 2)
.unwrap()
.panel(0, 0, child.clone())
.unwrap()
.panel(0, 1, child.clone().theme(explicit.clone()))
.unwrap();
assert_eq!(canvas.get_default_theme(), Some(&paper));
assert_eq!(captured.get_default_theme(), Some(&paper));
(child, canvas)
});
assert!(outside.get_default_theme().is_none());
assert!(context_plot().get_default_theme().is_none());
assert!(child.get_theme().is_none());
assert_eq!(child.get_default_theme(), Some(&detail));
assert!(canvas.get_theme().is_none());
let svg = explicit
.with_context(|| render_canvas(&canvas, "captured-context"))
.unwrap();
assert!(svg.contains("#DEE9F4") && svg.contains("#D4DFEA"));
assert!(svg.contains("#EAD4DF"));
assert!(!svg.contains("#C9E0D4") && !svg.contains("#F4DEE9"));
let svg = render_svg(&child, "standalone-context").unwrap();
assert!(svg.contains("#D3EADE") && svg.contains("#C9E0D4"));
let cleared = child.clone().theme(explicit.clone()).theme(None);
assert_eq!(cleared.get_default_theme(), Some(&detail));
assert!(cleared.get_theme().is_none());
assert_eq!(render_svg(cleared, "cleared-context").unwrap(), svg);
assert!(child
.clone()
.default_theme(None)
.get_default_theme()
.is_none());
let publication = Canvas::grid(1, 1).unwrap().panel(0, 0, child).unwrap();
assert!(!render_canvas(publication, "publication-parent")
.unwrap()
.contains("#C9E0D4"));
}
#[test]
fn native_theme_scope_restores_on_unwind_and_is_thread_local() {
let a = Theme::nature();
let b = Theme::science();
let barrier = std::sync::Barrier::new(2);
let (left, right) = std::thread::scope(|scope| {
let left = scope.spawn(|| {
a.with_context(|| {
barrier.wait();
context_plot()
})
});
let right = scope.spawn(|| {
b.with_context(|| {
barrier.wait();
context_plot()
})
});
(left.join().unwrap(), right.join().unwrap())
});
assert_eq!(left.get_default_theme(), Some(&a));
assert_eq!(right.get_default_theme(), Some(&b));
std::thread::scope(|scope| {
let left = scope.spawn(|| left.render().unwrap());
let right = scope.spawn(|| right.render().unwrap());
left.join().unwrap();
right.join().unwrap();
});
a.with_context(|| {
let caught = std::panic::catch_unwind(|| b.with_context(|| panic!("scope unwind")));
assert!(caught.is_err());
assert_eq!(context_plot().get_default_theme(), Some(&a));
assert!(std::thread::spawn(context_plot)
.join()
.unwrap()
.get_default_theme()
.is_none());
});
assert!(context_plot().get_default_theme().is_none());
}
#[test]
fn built_in_legends_are_frameless_and_explicit_frames_work_in_both_canvas_policies() {
use lichtung_plot::{
guides::CanvasLegendPolicy,
layout::RelativeSpacing,
theme::{LegendFrameTheme, OutlineTheme},
Color,
};
for theme in [
Theme::publication(),
Theme::nature(),
Theme::science(),
Theme::chi(),
] {
assert!(theme.legend().get_frame().is_none());
assert!(theme.marks().get_cells().get_cell_outline().is_none());
assert!(theme
.marks()
.get_cells()
.get_missing_row_outline()
.is_none());
assert!(theme
.marks()
.get_cells()
.get_missing_key_outline()
.is_some());
}
let publication = Theme::publication();
let frame = LegendFrameTheme::new(
Color::rgb(231, 241, 251),
Some(OutlineTheme::new(Color::rgb(13, 17, 19), 1.0).unwrap()),
RelativeSpacing::ratio(2, 11).unwrap(),
)
.unwrap();
let framed = publication
.customize()
.legend(publication.legend().clone().frame(Some(frame)).unwrap())
.build()
.unwrap();
let plot =
context_plot().hue(CategoryValues::new("treatment", ["Control", "Treated"]).unwrap());
let page = Canvas::grid(1, 2)
.unwrap()
.size(1600, 700)
.panel(0, 0, plot.clone())
.unwrap()
.panel(0, 1, plot)
.unwrap();
for (policy, count) in [
(CanvasLegendPolicy::PerPlot, 2),
(CanvasLegendPolicy::Shared, 1),
] {
let page = page.clone().legend_policy(policy);
let default = render_canvas(&page, "frameless").unwrap();
assert_eq!(default.matches(">Control</text>").count(), count);
assert_eq!(default.matches(">Treated</text>").count(), count);
assert!(!default.contains(" rx=\""));
let explicit = render_canvas(page.theme(framed.clone()), "explicit-frame").unwrap();
assert_eq!(explicit.matches(">Control</text>").count(), count);
assert_eq!(explicit.matches("fill=\"#E7F1FB\"").count(), count);
assert_eq!(explicit.matches("stroke=\"#0D1113\"").count(), count);
}
}
#[test]
fn active_custom_font_roles_are_required_while_unused_preferences_are_not() {
let base = Theme::publication();
let title = base
.typography()
.get_root()
.get_title()
.clone()
.stack(
FontStack::new([FontFamily::named("Unavailable public heading role").unwrap()])
.unwrap(),
)
.unwrap();
let root = base.typography().get_root().clone().title(title).unwrap();
let typography = base.typography().clone().root(root).unwrap();
let theme = base.customize().typography(typography).build().unwrap();
let plot = Plot::scatter(
NumericValues::new("x", [1.0, 2.0]),
NumericValues::new("y", [2.0, 1.0]),
)
.theme(theme);
plot.preflight().unwrap();
let error = plot
.title("This role is now consumed")
.preflight()
.unwrap_err();
assert!(matches!(error, lichtung_plot::Error::Render(_)), "{error}");
assert!(
error.to_string().contains("font candidate list is empty"),
"{error}"
);
}
#[test]
#[expect(
clippy::too_many_lines,
reason = "explicit semantic inventory of all twenty-five current families"
)]
fn original_role_inventory_covers_every_current_family() {
use lichtung_plot::{
data::{Bounds, DataRole as R},
plots::{CoefficientInput, DumbbellEndpoints, HistogramInput, RaincloudInput},
Color,
};
let n = || NumericValues::new("measurement", [1., 2.]);
let c = || CategoryValues::new("category", ["A", "B"]).unwrap();
let g = || CategoryValues::new("group", ["first", "second"]).unwrap();
let bounds = || Bounds::new(n(), n());
let samples = || BarInput::samples(n());
let estimates = || BarInput::estimates_with_error_bars(n(), bounds());
let endpoints =
DumbbellEndpoints::new("A", Color::rgb(0, 0, 0), "B", Color::rgb(1, 2, 3)).unwrap();
let cases = vec![
(Plot::scatter(n(), n()).erase(), vec![R::X, R::Y]),
(
Plot::histogram(HistogramInput::samples(n())).erase(),
vec![R::Samples],
),
(Plot::density(n()).erase(), vec![R::Value]),
(Plot::qq(n()).erase(), vec![R::Value]),
(
Plot::point_interval(c(), n(), bounds()).erase(),
vec![R::Category, R::Estimate, R::Lower, R::Upper],
),
(Plot::line(n(), n()).erase(), vec![R::X, R::Y]),
(
Plot::trajectory(c(), n(), g()).erase(),
vec![R::X, R::Y, R::Group],
),
(Plot::line_path(n(), n()).erase(), vec![R::X, R::Y]),
(
Plot::interaction(c(), n(), g(), bounds()).erase(),
vec![R::Condition, R::Estimate, R::Group, R::Lower, R::Upper],
),
(
Plot::coefficient(c(), CoefficientInput::estimates(n())).erase(),
vec![R::Term, R::Estimate],
),
(
Plot::forest(c(), n(), bounds(), 1.).erase(),
vec![R::Term, R::Estimate, R::Lower, R::Upper],
),
(
Plot::dumbbell(c(), n(), n(), endpoints).erase(),
vec![R::Category, R::Left, R::Right],
),
(
Plot::heatmap(c(), g(), n()).erase(),
vec![R::X, R::Y, R::Fill],
),
(
Plot::bar(c(), samples()).erase(),
vec![R::Category, R::Samples],
),
(
Plot::horizontal_bar(c(), estimates()).erase(),
vec![R::Category, R::Estimate, R::Lower, R::Upper],
),
(
Plot::stacked_bar(c(), n(), g()).erase(),
vec![R::Category, R::Value, R::Series],
),
(
Plot::stacked_horizontal_bar(c(), n(), g()).erase(),
vec![R::Category, R::Value, R::Series],
),
(Plot::boxplot(c(), n()).erase(), vec![R::Category, R::Value]),
(Plot::violin(c(), n()).erase(), vec![R::Category, R::Value]),
(
Plot::raincloud(RaincloudInput::samples(c(), n())).erase(),
vec![R::Category, R::Value],
),
(Plot::regression(n(), n()).erase(), vec![R::X, R::Y]),
(Plot::marginal(n(), n()).erase(), vec![R::X, R::Y]),
(
Plot::matrix(vec![n(), NumericValues::new("second", [3., 4.])]).erase(),
vec![R::Variables],
),
(
Plot::beeswarm(c(), n()).erase(),
vec![R::Category, R::Value],
),
(
Plot::waterfall(c(), n(), 0.).erase(),
vec![R::Category, R::Delta],
),
];
for (plot, expected) in cases {
let roles = plot.data_roles().unwrap();
assert_eq!(
roles
.iter()
.map(|info| info.role().unwrap())
.collect::<Vec<_>>(),
expected,
"{:?}",
plot.kind()
);
for info in roles {
let value = plot.data(info.reference()).unwrap();
assert_eq!(value.info().reference(), info.reference());
assert_eq!(info.plot_kind(), Some(plot.kind()));
}
}
}
#[test]
fn original_role_reference_revisions_and_explicit_member_ids() {
use lichtung_plot::{
data::{DataRole as R, MemberAddress, SourceRows},
elements::LayerSlot,
scales::AlphaEncoding,
};
let plot = Plot::scatter(
NumericValues::new("x", [1., 2.]),
NumericValues::nullable("y", [Some(-0.), None]),
)
.source_rows(SourceRows::new([27, 91]).unwrap())
.hue(CategoryValues::new("hue", ["A", "B"]).unwrap());
let x = plot.data(R::X).unwrap();
let old = plot.data(R::Hue).unwrap();
let layer = plot
.read_element(&plot.element_ref(LayerSlot::Primary).unwrap())
.unwrap();
let y = layer.values(R::Y).unwrap();
assert_eq!(y.info().domain(), x.info().domain());
assert!(y.info().domains()[0].components()[0].has_nulls());
assert_eq!(y.numeric().unwrap().get(1), Some(None));
let members = y.members(MemberAddress::RowId(91)).unwrap().unwrap();
let entry = &members.entries()[0];
let member = &entry.members().unwrap()[0];
assert_eq!(member.address(), &MemberAddress::Slot(1));
assert_eq!(member.row_id(), Some(91));
assert_eq!(y.source_rows().unwrap().as_slice(), &[27, 91]);
let plot = plot
.hue(CategoryValues::new("hue", ["B", "A"]).unwrap())
.point_alpha(AlphaEncoding::fixed(0.5).unwrap())
.unwrap();
assert!(plot.data(old.info().reference()).is_err());
assert_eq!(
plot.data(x.info().reference())
.unwrap()
.numeric()
.unwrap()
.get(0),
Some(Some(1.))
);
assert!(plot.data(R::PointAlpha).is_err());
assert_eq!(
layer.category(old.info().reference()).unwrap().get(0),
Some(Some("A"))
);
let incomplete = Plot::scatter(
NumericValues::new("x", [1., 2.]),
NumericValues::new("y", [3.]),
);
assert_eq!(
incomplete.data(R::Y).unwrap().info().shape(),
Some(&[1][..])
);
assert!(incomplete.preflight().is_err());
}