-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathaesthetic.rs
More file actions
577 lines (490 loc) · 21.2 KB
/
aesthetic.rs
File metadata and controls
577 lines (490 loc) · 21.2 KB
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
//! Aesthetic classification and validation utilities
//!
//! This module provides centralized functions and constants for working with
//! aesthetic names in ggsql. Aesthetics are visual properties that can be mapped
//! to data columns or set to literal values.
//!
//! # Positional vs Legend Aesthetics
//!
//! Aesthetics fall into two categories:
//! - **Positional**: Map to axes (x, y, and variants like xmin, xmax, etc.)
//! - **Legend**: Map to visual properties shown in legends (color, size, shape, etc.)
//!
//! # Aesthetic Families
//!
//! Some aesthetics belong to "families" where variants map to a primary aesthetic.
//! For example, `xmin`, `xmax`, and `xend` all belong to the "x" family.
//! This is used for scale resolution and label computation.
//!
//! # Internal vs User-Facing Aesthetics
//!
//! The pipeline uses internal positional aesthetic names (pos1, pos2, etc.) that are
//! transformed from user-facing names (x/y or theta/radius) early in the pipeline
//! and transformed back for output. This is handled by `AestheticContext`.
use std::collections::HashMap;
// =============================================================================
// Positional Suffixes (applied to primary names automatically)
// =============================================================================
/// Positional aesthetic suffixes - applied to primary names to create variant aesthetics
/// e.g., "x" + "min" = "xmin", "pos1" + "end" = "pos1end"
pub const POSITIONAL_SUFFIXES: &[&str] = &["min", "max", "end"];
// =============================================================================
// Static Constants (for backward compatibility with existing code)
// =============================================================================
/// User-facing facet aesthetics (for creating small multiples)
///
/// These aesthetics control faceting layout:
/// - `panel`: Single variable faceting (wrap layout)
/// - `row`: Row variable for grid faceting
/// - `column`: Column variable for grid faceting
///
/// After aesthetic transformation, these become internal names:
/// - `panel` → `facet1`
/// - `row` → `facet1`, `column` → `facet2`
pub const USER_FACET_AESTHETICS: &[&str] = &["panel", "row", "column"];
/// Non-positional aesthetics (visual properties shown in legends or applied to marks)
///
/// These include:
/// - Color aesthetics: color, colour, fill, stroke, opacity
/// - Size/shape aesthetics: size, shape, linetype, linewidth
/// - Dimension aesthetics: width, height
/// - Text aesthetics: label, family, fontface, hjust, vjust
pub const NON_POSITIONAL: &[&str] = &[
"color",
"colour",
"fill",
"stroke",
"opacity",
"size",
"shape",
"linetype",
"linewidth",
"width",
"height",
"label",
"family",
"fontface",
"fontsize",
"hjust",
"vjust",
];
// =============================================================================
// AestheticContext - Comprehensive context for aesthetic operations
// =============================================================================
/// Comprehensive context for aesthetic operations.
///
/// Uses HashMaps for efficient O(1) lookups between user-facing and internal aesthetic names.
/// Used to transform between user-facing aesthetic names (x/y or theta/radius)
/// and internal names (pos1/pos2), as well as facet aesthetics (panel/row/column)
/// to internal facet names (facet1/facet2).
///
/// # Example
///
/// ```ignore
/// use ggsql::plot::AestheticContext;
///
/// // For cartesian coords
/// let ctx = AestheticContext::from_static(&["x", "y"], &[]);
/// assert_eq!(ctx.map_user_to_internal("x"), Some("pos1"));
/// assert_eq!(ctx.map_user_to_internal("ymin"), Some("pos2min"));
///
/// // For polar coords
/// let ctx = AestheticContext::from_static(&["theta", "radius"], &[]);
/// assert_eq!(ctx.map_user_to_internal("theta"), Some("pos1"));
/// assert_eq!(ctx.map_user_to_internal("radius"), Some("pos2"));
///
/// // With facets
/// let ctx = AestheticContext::from_static(&["x", "y"], &["panel"]);
/// assert_eq!(ctx.map_user_to_internal("panel"), Some("facet1"));
///
/// let ctx = AestheticContext::from_static(&["x", "y"], &["row", "column"]);
/// assert_eq!(ctx.map_user_to_internal("row"), Some("facet1"));
/// assert_eq!(ctx.map_user_to_internal("column"), Some("facet2"));
/// ```
#[derive(Debug, Clone)]
pub struct AestheticContext {
// User → Internal mapping (O(1) lookups)
user_to_internal: HashMap<String, String>,
// Family lookups (internal names only)
internal_to_primary: HashMap<String, String>,
primary_to_internal_family: HashMap<String, Vec<String>>,
// For iteration (ordered lists)
user_primaries: Vec<String>,
internal_primaries: Vec<String>,
// Facet mappings
user_facet: Vec<&'static str>,
internal_facet: Vec<String>,
// Non-positional (static reference)
non_positional: &'static [&'static str],
}
impl AestheticContext {
/// Create context from coord's positional names and facet's aesthetic names.
///
/// # Arguments
///
/// * `positional_names` - Primary positional aesthetic names (e.g., ["x", "y"] or custom names)
/// * `facet_names` - User-facing facet aesthetic names from facet layout
/// (e.g., ["panel"] for wrap, ["row", "column"] for grid)
pub fn new(positional_names: &[String], facet_names: &[&'static str]) -> Self {
// Initialize all HashMaps and vectors
let mut user_to_internal = HashMap::new();
let mut internal_to_primary = HashMap::new();
let mut primary_to_internal_family = HashMap::new();
let mut user_primaries = Vec::new();
let mut internal_primaries = Vec::new();
// Build positional mappings
for (i, user_primary) in positional_names.iter().enumerate() {
let pos_num = i + 1;
let internal_primary = format!("pos{}", pos_num);
// Track primaries
user_primaries.push(user_primary.clone());
internal_primaries.push(internal_primary.clone());
// Build internal family
let mut internal_family = vec![internal_primary.clone()];
// Add primary to mappings
user_to_internal.insert(user_primary.clone(), internal_primary.clone());
internal_to_primary.insert(internal_primary.clone(), internal_primary.clone());
// Add suffixed variants
for suffix in POSITIONAL_SUFFIXES {
let user_variant = format!("{}{}", user_primary, suffix);
let internal_variant = format!("{}{}", internal_primary, suffix);
user_to_internal.insert(user_variant, internal_variant.clone());
internal_to_primary.insert(internal_variant.clone(), internal_primary.clone());
internal_family.push(internal_variant);
}
// Store internal family
primary_to_internal_family.insert(internal_primary, internal_family);
}
// Build internal facet names for active facets (from FACET clause or layer mappings)
let internal_facet: Vec<String> = (1..=facet_names.len())
.map(|i| format!("facet{}", i))
.collect();
Self {
user_to_internal,
internal_to_primary,
primary_to_internal_family,
user_primaries,
internal_primaries,
user_facet: facet_names.to_vec(),
internal_facet,
non_positional: NON_POSITIONAL,
}
}
/// Create context from static positional names and facet names.
///
/// Convenience method for creating context from static string slices (e.g., from coord defaults).
pub fn from_static(positional_names: &[&'static str], facet_names: &[&'static str]) -> Self {
let owned_positional: Vec<String> =
positional_names.iter().map(|s| s.to_string()).collect();
Self::new(&owned_positional, facet_names)
}
// === Mapping: User → Internal ===
/// Map user aesthetic (positional or facet) to internal name.
///
/// Positional: "x" → "pos1", "ymin" → "pos2min", "theta" → "pos1"
/// Facet: "panel" → "facet1", "row" → "facet1", "column" → "facet2"
///
/// Note: Facet mappings work regardless of whether a FACET clause exists,
/// allowing layer-declared facet aesthetics to be transformed.
pub fn map_user_to_internal(&self, user_aesthetic: &str) -> Option<&str> {
// Check positional first (O(1) HashMap lookup)
if let Some(internal) = self.user_to_internal.get(user_aesthetic) {
return Some(internal.as_str());
}
// Check active facet (from FACET clause)
if let Some(idx) = self.user_facet.iter().position(|u| *u == user_aesthetic) {
return Some(self.internal_facet[idx].as_str());
}
// Always map user-facing facet names to internal names,
// even when no FACET clause exists (allows layer-declared facets)
// panel → facet1 (wrap layout)
// row → facet1, column → facet2 (grid layout)
match user_aesthetic {
"panel" => Some("facet1"),
"row" => Some("facet1"),
"column" => Some("facet2"),
_ => None,
}
}
// === Checking (O(1) HashMap lookups) ===
/// Check if internal aesthetic is primary positional (pos1, pos2, ...)
pub fn is_primary_internal(&self, name: &str) -> bool {
self.internal_primaries.iter().any(|s| s == name)
}
/// Check if aesthetic is non-positional (color, size, etc.)
pub fn is_non_positional(&self, name: &str) -> bool {
self.non_positional.contains(&name)
}
/// Check if name is a user-facing facet aesthetic (panel, row, column)
pub fn is_user_facet(&self, name: &str) -> bool {
self.user_facet.contains(&name)
}
/// Check if name is an internal facet aesthetic (facet1, facet2)
pub fn is_internal_facet(&self, name: &str) -> bool {
self.internal_facet.iter().any(|f| f == name)
}
/// Check if name is a facet aesthetic (user or internal)
pub fn is_facet(&self, name: &str) -> bool {
self.is_user_facet(name) || self.is_internal_facet(name)
}
// === Aesthetic Families (O(1) HashMap lookups) ===
/// Get the primary aesthetic for an internal family member.
///
/// e.g., "pos1min" → "pos1", "pos2end" → "pos2"
/// Non-positional aesthetics return themselves.
pub fn primary_internal_positional<'a>(&'a self, name: &'a str) -> Option<&'a str> {
// Check internal positional (O(1) lookup)
if let Some(primary) = self.internal_to_primary.get(name) {
return Some(primary.as_str());
}
// Non-positional aesthetics are their own primary
if self.is_non_positional(name) {
return Some(name);
}
None
}
/// Get the internal aesthetic family for a primary aesthetic.
///
/// e.g., "pos1" → ["pos1", "pos1min", "pos1max", "pos1end"]
pub fn internal_positional_family(&self, primary: &str) -> Option<&[String]> {
self.primary_to_internal_family
.get(primary)
.map(|v| v.as_slice())
}
// === Accessors ===
/// Get primary internal positional aesthetics (pos1, pos2, ...)
pub fn internal_positional(&self) -> &[String] {
&self.internal_primaries
}
/// Get user positional aesthetics (x, y or theta, radius or custom names)
pub fn user_positional(&self) -> &[String] {
&self.user_primaries
}
/// Get user-facing facet aesthetics (panel, row, column)
pub fn user_facet(&self) -> &[&'static str] {
&self.user_facet
}
}
/// Check if aesthetic is a user-facing facet aesthetic (panel, row, column)
///
/// Use this function for checks BEFORE aesthetic transformation.
/// For checks after transformation, use `is_facet_aesthetic`.
#[inline]
pub fn is_user_facet_aesthetic(aesthetic: &str) -> bool {
USER_FACET_AESTHETICS.contains(&aesthetic)
}
/// Check if aesthetic is an internal facet aesthetic (facet1, facet2, etc.)
///
/// Facet aesthetics control the creation of small multiples (faceted plots).
/// They only support Discrete and Binned scale types, and cannot have output ranges (TO clause).
///
/// This function works with **internal** aesthetic names after transformation.
/// For user-facing checks before transformation, use `is_user_facet_aesthetic`.
#[inline]
pub fn is_facet_aesthetic(aesthetic: &str) -> bool {
// Check pattern: facet followed by digits only (facet1, facet2, etc.)
if aesthetic.starts_with("facet") && aesthetic.len() > 5 {
return aesthetic[5..].chars().all(|c| c.is_ascii_digit());
}
false
}
/// Check if aesthetic is an internal positional (pos1, pos1min, pos2max, etc.)
///
/// This function works with **internal** aesthetic names after transformation.
/// Matches patterns like: pos1, pos2, pos1min, pos2max, pos1end, etc.
///
/// For user-facing checks before transformation, use `AestheticContext::is_user_positional()`.
#[inline]
pub fn is_positional_aesthetic(name: &str) -> bool {
if !name.starts_with("pos") || name.len() <= 3 {
return false;
}
// Check for primary: pos followed by only digits (pos1, pos2, pos10, etc.)
let after_pos = &name[3..];
if after_pos.chars().all(|c| c.is_ascii_digit()) {
return true;
}
// Check for variants: posN followed by a suffix
for suffix in POSITIONAL_SUFFIXES {
if let Some(base) = name.strip_suffix(suffix) {
if base.starts_with("pos") && base.len() > 3 {
let num_part = &base[3..];
if num_part.chars().all(|c| c.is_ascii_digit()) {
return true;
}
}
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_facet_aesthetic() {
// Internal facet aesthetics (after transformation)
assert!(is_facet_aesthetic("facet1"));
assert!(is_facet_aesthetic("facet2"));
assert!(is_facet_aesthetic("facet10")); // supports any number
assert!(!is_facet_aesthetic("facet")); // too short
assert!(!is_facet_aesthetic("facetx")); // not a number
// User-facing names are NOT internal facet aesthetics
assert!(!is_facet_aesthetic("panel"));
assert!(!is_facet_aesthetic("row"));
assert!(!is_facet_aesthetic("column"));
// Other aesthetics
assert!(!is_facet_aesthetic("x"));
assert!(!is_facet_aesthetic("color"));
assert!(!is_facet_aesthetic("pos1"));
}
#[test]
fn test_user_facet_aesthetic() {
// User-facing facet aesthetics (before transformation)
assert!(is_user_facet_aesthetic("panel"));
assert!(is_user_facet_aesthetic("row"));
assert!(is_user_facet_aesthetic("column"));
// Internal names are NOT user-facing
assert!(!is_user_facet_aesthetic("facet1"));
assert!(!is_user_facet_aesthetic("facet2"));
// Other aesthetics
assert!(!is_user_facet_aesthetic("x"));
assert!(!is_user_facet_aesthetic("color"));
}
#[test]
fn test_positional_aesthetic() {
// Checks internal positional names (pos1, pos2, etc. and variants)
// For user-facing checks, use AestheticContext::is_user_positional()
// Primary internal
assert!(is_positional_aesthetic("pos1"));
assert!(is_positional_aesthetic("pos2"));
assert!(is_positional_aesthetic("pos10")); // supports any number
// Variants
assert!(is_positional_aesthetic("pos1min"));
assert!(is_positional_aesthetic("pos1max"));
assert!(is_positional_aesthetic("pos2min"));
assert!(is_positional_aesthetic("pos2max"));
assert!(is_positional_aesthetic("pos1end"));
assert!(is_positional_aesthetic("pos2end"));
// User-facing names are NOT positional (handled by AestheticContext)
assert!(!is_positional_aesthetic("x"));
assert!(!is_positional_aesthetic("y"));
assert!(!is_positional_aesthetic("xmin"));
assert!(!is_positional_aesthetic("theta"));
// Non-positional
assert!(!is_positional_aesthetic("color"));
assert!(!is_positional_aesthetic("size"));
assert!(!is_positional_aesthetic("fill"));
// Edge cases
assert!(!is_positional_aesthetic("pos")); // too short
assert!(!is_positional_aesthetic("position")); // not a valid pattern
}
// ========================================================================
// AestheticContext Tests
// ========================================================================
#[test]
fn test_aesthetic_context_cartesian() {
let ctx = AestheticContext::from_static(&["x", "y"], &[]);
// User positional names
assert_eq!(ctx.user_positional(), &["x", "y"]);
// Primary internal names
let primary: Vec<&str> = ctx
.internal_positional()
.iter()
.map(|s| s.as_str())
.collect();
assert_eq!(primary, vec!["pos1", "pos2"]);
}
#[test]
fn test_aesthetic_context_polar() {
let ctx = AestheticContext::from_static(&["theta", "radius"], &[]);
// User positional names
assert_eq!(ctx.user_positional(), &["theta", "radius"]);
// Primary internal names
let primary: Vec<&str> = ctx
.internal_positional()
.iter()
.map(|s| s.as_str())
.collect();
assert_eq!(primary, vec!["pos1", "pos2"]);
}
#[test]
fn test_aesthetic_context_user_to_internal() {
let ctx = AestheticContext::from_static(&["x", "y"], &[]);
// Primary aesthetics
assert_eq!(ctx.map_user_to_internal("x"), Some("pos1"));
assert_eq!(ctx.map_user_to_internal("y"), Some("pos2"));
// Variants
assert_eq!(ctx.map_user_to_internal("xmin"), Some("pos1min"));
assert_eq!(ctx.map_user_to_internal("xmax"), Some("pos1max"));
assert_eq!(ctx.map_user_to_internal("xend"), Some("pos1end"));
assert_eq!(ctx.map_user_to_internal("ymin"), Some("pos2min"));
assert_eq!(ctx.map_user_to_internal("ymax"), Some("pos2max"));
assert_eq!(ctx.map_user_to_internal("yend"), Some("pos2end"));
// Non-positional returns None
assert_eq!(ctx.map_user_to_internal("color"), None);
assert_eq!(ctx.map_user_to_internal("fill"), None);
}
#[test]
fn test_aesthetic_context_polar_mapping() {
let ctx = AestheticContext::from_static(&["theta", "radius"], &[]);
// User to internal
assert_eq!(ctx.map_user_to_internal("theta"), Some("pos1"));
assert_eq!(ctx.map_user_to_internal("radius"), Some("pos2"));
assert_eq!(ctx.map_user_to_internal("thetaend"), Some("pos1end"));
assert_eq!(ctx.map_user_to_internal("radiusmin"), Some("pos2min"));
}
#[test]
fn test_aesthetic_context_is_primary_internal() {
let ctx = AestheticContext::from_static(&["x", "y"], &[]);
// Primary internal
assert!(ctx.is_primary_internal("pos1"));
assert!(ctx.is_primary_internal("pos2"));
assert!(!ctx.is_primary_internal("pos1min"));
assert!(!ctx.is_primary_internal("x"));
assert!(!ctx.is_primary_internal("color"));
}
#[test]
fn test_aesthetic_context_with_facets() {
let ctx = AestheticContext::from_static(&["x", "y"], &["panel"]);
// Check user facet
assert!(ctx.is_user_facet("panel"));
assert!(!ctx.is_user_facet("row"));
assert_eq!(ctx.user_facet(), &["panel"]);
// Check internal facet
assert!(ctx.is_internal_facet("facet1"));
assert!(!ctx.is_internal_facet("panel"));
// Check mapping
assert_eq!(ctx.map_user_to_internal("panel"), Some("facet1"));
// Check combined is_facet
assert!(ctx.is_facet("panel")); // user
assert!(ctx.is_facet("facet1")); // internal
}
#[test]
fn test_aesthetic_context_with_grid_facets() {
let ctx = AestheticContext::from_static(&["x", "y"], &["row", "column"]);
// Check user facet
assert!(ctx.is_user_facet("row"));
assert!(ctx.is_user_facet("column"));
assert!(!ctx.is_user_facet("panel"));
assert_eq!(ctx.user_facet(), &["row", "column"]);
// Check internal facet
assert!(ctx.is_internal_facet("facet1"));
assert!(ctx.is_internal_facet("facet2"));
// Check mappings
assert_eq!(ctx.map_user_to_internal("row"), Some("facet1"));
assert_eq!(ctx.map_user_to_internal("column"), Some("facet2"));
}
#[test]
fn test_aesthetic_context_families() {
let ctx = AestheticContext::from_static(&["x", "y"], &[]);
// Get internal family
let pos1_family = ctx.internal_positional_family("pos1").unwrap();
let pos1_strs: Vec<&str> = pos1_family.iter().map(|s| s.as_str()).collect();
assert_eq!(pos1_strs, vec!["pos1", "pos1min", "pos1max", "pos1end"]);
// Primary internal aesthetic
assert_eq!(ctx.primary_internal_positional("pos1"), Some("pos1"));
assert_eq!(ctx.primary_internal_positional("pos1min"), Some("pos1"));
assert_eq!(ctx.primary_internal_positional("pos2end"), Some("pos2"));
assert_eq!(ctx.primary_internal_positional("color"), Some("color"));
}
}