use crisol_core::data::Bounds;
use crate::axis::Scale;
pub fn point_bounds(data: &[[f64; 2]], y_errors: Option<&[f64]>, x_scale: Scale, y_scale: Scale) -> Bounds {
let mut bounds = Bounds::NOTHING;
let error = |index: usize| y_errors.and_then(|errors| errors.get(index)).copied();
for (index, point) in data.iter().enumerate() {
let x = x_scale.forward(point[0]);
match error(index) {
Some(error) => {
bounds.extend([x, y_scale.forward(point[1] - error)]);
bounds.extend([x, y_scale.forward(point[1] + error)]);
}
None => bounds.extend([x, y_scale.forward(point[1])]),
}
}
bounds
}
pub fn candle_bounds(
rows: &[[f64; 5]],
x_scale: Scale,
y_scale: Scale,
width: Option<f64>,
min_spacing: f64,
) -> Bounds {
let mut bounds = Bounds::NOTHING;
for row in rows {
let x = x_scale.forward(row[0]);
for value in &row[1..] {
bounds.extend([x, y_scale.forward(*value)]);
}
}
if bounds.is_valid() && x_scale == Scale::Linear {
let half = width.unwrap_or(min_spacing * 0.65) * 0.5;
bounds.min_x -= half;
bounds.max_x += half;
}
bounds
}
pub fn heatmap_bounds(cells: &[[f64; 3]], x_scale: Scale, y_scale: Scale) -> Bounds {
let mut bounds = Bounds::NOTHING;
for cell in cells {
bounds.extend([x_scale.forward(cell[0]), y_scale.forward(cell[1])]);
}
if bounds.is_valid() {
let x_half = smallest_step(cells.iter().map(|cell| cell[0])) * 0.5;
let y_half = smallest_step(cells.iter().map(|cell| cell[1])) * 0.5;
bounds.min_x -= x_half;
bounds.max_x += x_half;
bounds.min_y -= y_half;
bounds.max_y += y_half;
}
bounds
}
pub fn waterfall_bounds(
data: &[[f64; 2]],
x_scale: Scale,
y_scale: Scale,
width: Option<f64>,
min_spacing: f64,
) -> Bounds {
let mut bounds = Bounds::NOTHING;
let mut base = 0.0;
for point in data {
let next = base + point[1];
let x = x_scale.forward(point[0]);
bounds.extend([x, y_scale.forward(base)]);
bounds.extend([x, y_scale.forward(next)]);
base = next;
}
if bounds.is_valid() && x_scale == Scale::Linear {
bounds.extend([bounds.min_x, y_scale.forward(0.0)]);
let half = width.unwrap_or(min_spacing * 0.65) * 0.5;
bounds.min_x -= half;
bounds.max_x += half;
}
bounds
}
pub fn sorted_x(data: &[[f64; 2]]) -> bool {
data.windows(2)
.all(|pair| pair[1][0] >= pair[0][0] || pair[1][0].is_nan() || pair[0][0].is_nan())
}
pub fn smallest_step(values: impl Iterator<Item = f64>) -> f64 {
let mut previous: Option<f64> = None;
let mut smallest = f64::INFINITY;
for value in values {
if !value.is_finite() {
continue;
}
if let Some(previous) = previous {
let delta = (value - previous).abs();
if delta > 0.0 {
smallest = smallest.min(delta);
}
}
previous = Some(value);
}
if smallest.is_finite() { smallest } else { 1.0 }
}