charton 0.5.8

A high-performance, layered charting system for Rust, featuring a flexible data core and multi-backend rendering.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use crate::Precision;
use crate::TEMP_SUFFIX;
use crate::chart::Chart;
use crate::core::context::PanelContext;
use crate::core::layer::{
    CircleConfig, MarkRenderer, PointElementConfig, PolygonConfig, RectConfig, RenderBackend,
};
use crate::core::utils::IntoParallelizable;
use crate::error::ChartonError;
use crate::mark::point::{MarkPoint, PointLayout};
use crate::visual::color::SingleColor;
use crate::visual::shape::PointShape;

#[cfg(feature = "parallel")]
use rayon::prelude::*;

// ============================================================================
// MARK RENDERING (High-Performance Parallel Implementation)
// ============================================================================

impl MarkRenderer for Chart<MarkPoint> {
    fn render_marks(
        &self,
        backend: &mut dyn RenderBackend,
        context: &PanelContext,
    ) -> Result<(), ChartonError> {
        let df_source = &self.data;
        let row_count = df_source.height();
        if row_count == 0 {
            return Ok(());
        }

        // --- STEP 1: SPECIFICATION & ENCODINGS ---
        let x_enc = self
            .encoding
            .x
            .as_ref()
            .ok_or_else(|| ChartonError::Encoding("X missing".into()))?;
        let y_enc = self
            .encoding
            .y
            .as_ref()
            .ok_or_else(|| ChartonError::Encoding("Y missing".into()))?;
        let mark_config = self
            .mark
            .as_ref()
            .ok_or_else(|| ChartonError::Mark("MarkPoint config missing".into()))?;

        // --- STEP 2: SCALES & NORMALIZATION ---
        let x_scale = context.coord.get_x_scale();
        let y_scale = context.coord.get_y_scale();
        let is_flipped = context.coord.is_flipped();

        let unit_step_norm = (x_scale.normalize(1.0) - x_scale.normalize(0.0)).abs();

        let x_norms = x_scale
            .scale_type()
            .normalize_column(x_scale, df_source.column(&x_enc.field)?);
        let y_norms = y_scale
            .scale_type()
            .normalize_column(y_scale, df_source.column(&y_enc.field)?);

        let sub_idx_col = df_source.column(&format!("{}_sub_idx", TEMP_SUFFIX)).ok();
        let groups_count_col = df_source
            .column(&format!("{}_groups_count", TEMP_SUFFIX))
            .ok();

        let color_norms = context.spec.aesthetics.color.as_ref().map(|m| {
            m.scale_impl
                .scale_type()
                .normalize_column(m.scale_impl.as_ref(), df_source.column(&m.field).unwrap())
        });
        let size_norms = context.spec.aesthetics.size.as_ref().map(|m| {
            m.scale_impl
                .scale_type()
                .normalize_column(m.scale_impl.as_ref(), df_source.column(&m.field).unwrap())
        });
        let shape_norms = context.spec.aesthetics.shape.as_ref().map(|m| {
            m.scale_impl
                .scale_type()
                .normalize_column(m.scale_impl.as_ref(), df_source.column(&m.field).unwrap())
        });

        // --- STEP 3: LAYOUT EXECUTION ---
        // Note: We now return a tuple of (row_index, PointElementConfig) to retain
        // the mapping between the calculated geometry and its original row in the dataset.
        let render_configs: Vec<(usize, PointElementConfig)> = match mark_config.layout {
            PointLayout::Beeswarm => {
                // BEESWARM: Stateful collision resolution
                self.resolve_beeswarm_layout(
                    row_count,
                    &x_norms,
                    &y_norms,
                    &color_norms,
                    &size_norms,
                    &shape_norms,
                    sub_idx_col,
                    groups_count_col,
                    unit_step_norm,
                    context,
                    mark_config,
                )
            }
            _ => {
                // STANDARD / JITTER: Parallel processing
                (0..row_count)
                    .maybe_into_par_iter()
                    .filter_map(|i| {
                        let x_n = x_norms[i]?;
                        let y_n = y_norms[i]?;

                        let mut x_final_n = x_n;
                        let mut lane_width_norm = 0.0;

                        // Apply BoxPlot-style Dodge Logic to calculate categorical center
                        if let (Some(sub_col), Some(cnt_col)) = (sub_idx_col, groups_count_col) {
                            let total_groups = cnt_col.get_f64(i).unwrap_or(1.0);
                            let sub_idx = sub_col.get_f64(i).unwrap_or(0.0);

                            let box_width_data = mark_config.width.min(
                                mark_config.span
                                    / (total_groups + (total_groups - 1.0) * mark_config.spacing),
                            );
                            let box_width_norm = box_width_data * unit_step_norm;
                            let spacing_norm = box_width_norm * mark_config.spacing;

                            x_final_n += (sub_idx - (total_groups - 1.0) / 2.0)
                                * (box_width_norm + spacing_norm);
                            lane_width_norm = box_width_norm;
                        }

                        // Project logic coordinates to screen pixels
                        let (mut px, mut py) =
                            context.coord.transform(x_final_n, y_n, &context.panel);

                        // Pixel-based Jitter: Offset applied to categorical dimension
                        if matches!(mark_config.layout, PointLayout::Jitter) {
                            let seed = (i as u64).wrapping_mul(1103515245).wrapping_add(12345);
                            let noise = ((seed & 0x7FFFFFFF) as f64 / 2147483647.0) - 0.5;

                            // Adjust horizontal (px) or vertical (py) based on orientation
                            if is_flipped {
                                let lane_px_limit = lane_width_norm * context.panel.height;
                                py += noise * lane_px_limit;
                            } else {
                                let lane_px_limit = lane_width_norm * context.panel.width;
                                px += noise * lane_px_limit;
                            }
                        }

                        // Return the original row index 'i' alongside the config
                        Some((
                            i,
                            self.build_element_config(
                                i,
                                px,
                                py,
                                &color_norms,
                                &size_norms,
                                &shape_norms,
                                context,
                                mark_config,
                            ),
                        ))
                    })
                    .collect()
            }
        };

        // --- STEP 4: GROUPING & EMISSION ---
        // Determine the field to group by for deterministic Z-indexing and WGPU batching.
        // We prioritize Color, then Shape. If neither is mapped, group_by(None) will
        // put all points in a single, massive continuous batch.
        let group_field = context
            .spec
            .aesthetics
            .color
            .as_ref()
            .map(|c| &c.field)
            .or_else(|| context.spec.aesthetics.shape.as_ref().map(|s| &s.field));

        // group_by guarantees "First Appearance" order.
        let grouped_indices = df_source.group_by(group_field.map(|s| s.as_str()));

        // Create a fast lookup table to map row indices to their computed rendering configs.
        // We use repeat_with to avoid requiring the Clone trait on PointElementConfig.
        let mut config_lookup: Vec<Option<PointElementConfig>> =
            std::iter::repeat_with(|| None).take(row_count).collect();

        for (i, config) in render_configs {
            config_lookup[i] = Some(config);
        }

        // Emit draw calls sequentially by group.
        // This ensures identical shapes/colors are drawn contiguously, massively reducing
        // pipeline state changes (Draw Calls) in the WGPU backend via interleaved batching.
        for (_group_key, row_indices) in grouped_indices.groups {
            for &idx in &row_indices {
                // take() moves the value out, leaving None, which is perfectly safe and fast.
                if let Some(config) = config_lookup[idx].take() {
                    self.emit_draw_call(backend, config);
                }
            }
        }

        Ok(())
    }
}

impl Chart<MarkPoint> {
    #[allow(clippy::too_many_arguments)]
    #[allow(clippy::type_complexity)]
    fn resolve_beeswarm_layout(
        &self,
        row_count: usize,
        x_norms: &[Option<f64>],
        y_norms: &[Option<f64>],
        color_norms: &Option<Vec<Option<f64>>>,
        size_norms: &Option<Vec<Option<f64>>>,
        shape_norms: &Option<Vec<Option<f64>>>,
        sub_idx_col: Option<&crate::core::data::ColumnVector>,
        groups_count_col: Option<&crate::core::data::ColumnVector>,
        unit_step_norm: f64,
        context: &PanelContext,
        mark_config: &MarkPoint,
    ) -> Vec<(usize, PointElementConfig)> {
        // Signature updated to return the row index
        let mut configs = Vec::with_capacity(row_count);
        let mut occupancy: std::collections::HashMap<(usize, usize), Vec<(f64, f64, f64)>> =
            std::collections::HashMap::new();

        let is_flipped = context.coord.is_flipped();

        for i in 0..row_count {
            let x_n = match x_norms[i] {
                Some(v) => v,
                None => continue,
            };
            let y_n = match y_norms[i] {
                Some(v) => v,
                None => continue,
            };

            let mut x_final_n = x_n;
            let mut lane_id = 0;

            // Step 1: Categorical axis screen width calculation
            let mut lane_px_width = if is_flipped {
                unit_step_norm * mark_config.span * context.panel.height
            } else {
                unit_step_norm * mark_config.span * context.panel.width
            };

            if let (Some(sub_col), Some(cnt_col)) = (sub_idx_col, groups_count_col) {
                let total_groups = cnt_col.get_f64(i).unwrap_or(1.0);
                let sub_idx = sub_col.get_f64(i).unwrap_or(0.0);
                lane_id = sub_idx as usize;

                let box_width_data = mark_config.width.min(
                    mark_config.span / (total_groups + (total_groups - 1.0) * mark_config.spacing),
                );
                let box_width_norm = box_width_data * unit_step_norm;
                let spacing_norm = box_width_norm * mark_config.spacing;

                x_final_n +=
                    (sub_idx - (total_groups - 1.0) / 2.0) * (box_width_norm + spacing_norm);

                lane_px_width = if is_flipped {
                    box_width_norm * context.panel.height
                } else {
                    box_width_norm * context.panel.width
                };
            }

            // Get the base projection (the center point of the swarm lane)
            let (base_px, base_py) = context.coord.transform(x_final_n, y_n, &context.panel);
            let size = self.resolve_size_from_value(
                size_norms.as_ref().and_then(|n| n[i]),
                context,
                mark_config.size,
            );

            // Step 2: Symmetric Collision Resolution
            let cat_key = ((x_n * 1000.0) as usize, lane_id);
            let siblings = occupancy.entry(cat_key).or_default();

            let mut best_displacement = 0.0;
            let max_shift = lane_px_width * 0.5;
            let mut found = false;
            let step_px = 1.0;

            let max_attempts = (max_shift / step_px) as i32 + 1;

            for offset_step in 0..max_attempts {
                for sign in [1.0, -1.0] {
                    if offset_step == 0 && sign == -1.0 {
                        continue;
                    }

                    let displacement = offset_step as f64 * step_px * sign;

                    // Determine test coordinates by applying displacement to the categorical axis
                    let (test_x, test_y) = if is_flipped {
                        (base_px, base_py + displacement)
                    } else {
                        (base_px + displacement, base_py)
                    };

                    let mut collision = false;
                    for &(ox, oy, or) in siblings.iter() {
                        let dx = test_x - ox;
                        let dy = test_y - oy;
                        let dist_sq = dx * dx + dy * dy;
                        let min_d = (size + or) * 1.02; // 2% visual buffer

                        if dist_sq < min_d * min_d {
                            collision = true;
                            break;
                        }
                    }

                    if !collision {
                        best_displacement = displacement;
                        found = true;
                        break;
                    }
                }
                if found {
                    break;
                }
            }

            // Step 3: Boundary Clamping (Force overlap at high density)
            if best_displacement.abs() > max_shift {
                best_displacement = best_displacement.signum() * max_shift;
            }

            // Apply final displacement to the categorical axis
            let (final_px, final_py) = if is_flipped {
                (base_px, base_py + best_displacement)
            } else {
                (base_px + best_displacement, base_py)
            };

            siblings.push((final_px, final_py, size));

            // Push the config wrapped in a tuple with its row index 'i'
            configs.push((
                i,
                self.build_element_config(
                    i,
                    final_px,
                    final_py,
                    color_norms,
                    size_norms,
                    shape_norms,
                    context,
                    mark_config,
                ),
            ));
        }
        configs
    }

    /// Helper to build the visual configuration for a single point element.
    #[allow(clippy::too_many_arguments)]
    fn build_element_config(
        &self,
        i: usize,
        x: f64,
        y: f64,
        color_norms: &Option<Vec<Option<f64>>>,
        size_norms: &Option<Vec<Option<f64>>>,
        shape_norms: &Option<Vec<Option<f64>>>,
        context: &PanelContext,
        mark_config: &MarkPoint,
    ) -> PointElementConfig {
        PointElementConfig {
            x,
            y,
            fill: self.resolve_color_from_value(
                color_norms.as_ref().and_then(|n| n[i]),
                context,
                &mark_config.color,
            ),
            size: self.resolve_size_from_value(
                size_norms.as_ref().and_then(|n| n[i]),
                context,
                mark_config.size,
            ),
            shape: self.resolve_shape_from_value(
                shape_norms.as_ref().and_then(|n| n[i]),
                context,
                mark_config.shape,
            ),
            stroke: mark_config.stroke,
            stroke_width: mark_config.stroke_width,
            opacity: mark_config.opacity,
        }
    }
}

// ============================================================================
// HELPER METHODS & GEOMETRY DISPATCH
// ============================================================================

impl Chart<MarkPoint> {
    /// Maps a normalized value to a color using the registered scale mapper.
    fn resolve_color_from_value(
        &self,
        val: Option<f64>,
        context: &PanelContext,
        fallback: &SingleColor,
    ) -> SingleColor {
        if let (Some(v), Some(mapping)) = (val, &context.spec.aesthetics.color) {
            let s_trait = mapping.scale_impl.as_ref();
            s_trait
                .mapper()
                .as_ref()
                .map(|m| m.map_to_color(v, s_trait.logical_max()))
                .unwrap_or(*fallback)
        } else {
            *fallback
        }
    }

    /// Maps a normalized value to a point size.
    fn resolve_size_from_value(
        &self,
        val: Option<f64>,
        context: &PanelContext,
        fallback: f64,
    ) -> f64 {
        if let (Some(v), Some(mapping)) = (val, &context.spec.aesthetics.size) {
            mapping
                .scale_impl
                .mapper()
                .as_ref()
                .map(|m| m.map_to_size(v))
                .unwrap_or(fallback)
        } else {
            fallback
        }
    }

    /// Maps a normalized value to a specific PointShape.
    fn resolve_shape_from_value(
        &self,
        val: Option<f64>,
        context: &PanelContext,
        fallback: PointShape,
    ) -> PointShape {
        if let (Some(v), Some(mapping)) = (val, &context.spec.aesthetics.shape) {
            let s_trait = mapping.scale_impl.as_ref();
            mapping
                .scale_impl
                .mapper()
                .as_ref()
                .map(|m| m.map_to_shape(v, s_trait.logical_max()))
                .unwrap_or(fallback)
        } else {
            fallback
        }
    }

    /// Dispatches the appropriate backend draw call for the given PointShape.
    fn emit_draw_call(&self, backend: &mut dyn RenderBackend, config: PointElementConfig) {
        let PointElementConfig {
            x,
            y,
            shape,
            size,
            fill,
            stroke,
            stroke_width,
            opacity,
        } = config;

        match shape {
            PointShape::Circle => {
                backend.draw_circle(CircleConfig {
                    x: x as Precision,
                    y: y as Precision,
                    radius: size as Precision,
                    fill,
                    stroke,
                    stroke_width: stroke_width as Precision,
                    opacity: opacity as Precision,
                });
            }
            PointShape::Square => {
                // Scale factor = sqrt(pi / 4) ≈ 0.886 to equalize square area with baseline circle
                let adj_size = size * 0.88623;
                backend.draw_rect(RectConfig {
                    x: (x - adj_size) as Precision,
                    y: (y - adj_size) as Precision,
                    width: (adj_size * 2.0) as Precision,
                    height: (adj_size * 2.0) as Precision,
                    fill,
                    stroke,
                    stroke_width: stroke_width as Precision,
                    opacity: opacity as Precision,
                });
            }
            _ => {
                // scale_adj is calculated to equalize the physical pixel area of each shape
                // against a baseline Circle of the same size (radius).
                let (sides, rotation, scale_adj) = match shape {
                    // Diamond (Square rotated 45 deg): Area = 2 * r^2. Circle Area = pi * r^2.
                    // Scale factor = sqrt(pi / 2) ≈ 1.253
                    PointShape::Diamond => (4, 0.0, 1.253),

                    // Equilateral Triangle: Area = (3 * sqrt(3) / 4) * r^2 ≈ 1.299 * r^2.
                    // Scale factor = sqrt(pi / 1.299) ≈ 1.555
                    PointShape::Triangle => (3, -std::f64::consts::FRAC_PI_2, 1.555),

                    // Regular Pentagon: Area ≈ 2.377 * r^2.
                    // Scale factor = sqrt(pi / 2.377) ≈ 1.150
                    PointShape::Pentagon => (5, -std::f64::consts::FRAC_PI_2, 1.150),

                    // Regular Hexagon: Area = (3 * sqrt(3) / 2) * r^2 ≈ 2.598 * r^2.
                    // Scale factor = sqrt(pi / 2.598) ≈ 1.099
                    PointShape::Hexagon => (6, 0.0, 1.099),

                    // Regular Octagon: Area = 2 * sqrt(2) * r^2 ≈ 2.828 * r^2.
                    // Scale factor = sqrt(pi / 2.828) ≈ 1.054
                    PointShape::Octagon => (8, std::f64::consts::FRAC_PI_8, 1.054),

                    _ => (0, 0.0, 0.0),
                };

                let points = if shape == PointShape::Star {
                    // For Star, we adjust the outer radius to roughly match circle area
                    // A 5-point star with inner_r = 0.382 * outer_r needs ~1.6 scale to match circle area
                    self.calculate_star(x, y, size * 1.6, size * 0.6, 5)
                } else {
                    self.calculate_polygon(x, y, size * scale_adj, sides, rotation)
                };

                backend.draw_polygon(PolygonConfig {
                    points: points
                        .iter()
                        .map(|p| (p.0 as Precision, p.1 as Precision))
                        .collect(),
                    fill,
                    stroke,
                    stroke_width: stroke_width as Precision,
                    opacity: opacity as Precision,
                });
            }
        }
    }

    fn calculate_polygon(
        &self,
        cx: f64,
        cy: f64,
        r: f64,
        sides: usize,
        rot: f64,
    ) -> Vec<(f64, f64)> {
        (0..sides)
            .map(|i| {
                let angle = rot + 2.0 * std::f64::consts::PI * (i as f64) / (sides as f64);
                (cx + r * angle.cos(), cy + r * angle.sin())
            })
            .collect()
    }

    fn calculate_star(
        &self,
        cx: f64,
        cy: f64,
        out_r: f64,
        in_r: f64,
        pts: usize,
    ) -> Vec<(f64, f64)> {
        (0..(pts * 2))
            .map(|i| {
                let angle =
                    -std::f64::consts::FRAC_PI_2 + std::f64::consts::PI * (i as f64) / (pts as f64);
                let r = if i % 2 == 0 { out_r } else { in_r };
                (cx + r * angle.cos(), cy + r * angle.sin())
            })
            .collect()
    }
}