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
//! Utility functions and helpers
use std::collections::HashMap;
/// Utility functions for data conversion and validation
pub mod conversion {
use super::*;
/// Convert JavaScript data to Polars DataFrame
pub fn js_data_to_dataframe(
js_data: &serde_json::Value,
) -> Result<crate::DataFrame, crate::data_processing::DataError> {
use polars::prelude::*;
if let Some(array) = js_data.as_array() {
if array.is_empty() {
return Ok(DataFrame::empty());
}
let mut columns = HashMap::new();
// Extract columns from first object
if let Some(first_obj) = array[0].as_object() {
for key in first_obj.keys() {
columns.insert(key.clone(), Vec::new());
}
}
// Collect values for each column
for item in array {
if let Some(obj) = item.as_object() {
for (key, value) in obj {
if let Some(column_vec) = columns.get_mut(key) {
column_vec.push(value.clone());
}
}
}
}
// Convert to Polars Series
let series: Vec<Series> = columns
.into_iter()
.map(|(name, values)| {
// Convert JSON values to appropriate Polars types
let polars_values: Vec<_> = values
.iter()
.map(|v| match v {
serde_json::Value::Number(n) => {
if n.is_f64() {
polars::prelude::AnyValue::Float64(n.as_f64().unwrap())
} else {
polars::prelude::AnyValue::Int64(n.as_i64().unwrap())
}
}
serde_json::Value::String(s) => polars::prelude::AnyValue::String(s),
serde_json::Value::Bool(b) => polars::prelude::AnyValue::Boolean(*b),
serde_json::Value::Null => polars::prelude::AnyValue::Null,
_ => polars::prelude::AnyValue::String(Box::leak(
v.to_string().into_boxed_str(),
)),
})
.collect();
Series::new((&name).into(), polars_values)
})
.collect();
Ok(DataFrame::new(
series.into_iter().map(|s| s.into()).collect(),
)?)
} else {
Err(crate::data_processing::DataError::Format(
"Expected JSON array".to_string(),
))
}
}
/// Convert Polars DataFrame to JavaScript-compatible format
pub fn dataframe_to_js(
df: &crate::DataFrame,
) -> Result<serde_json::Value, crate::data_processing::DataError> {
let mut result = Vec::new();
for row in 0..df.height() {
let mut obj = serde_json::Map::new();
for col_name in df.get_column_names() {
let series = df.column(col_name)?;
let value = series
.get(row)
.map_err(|e| crate::data_processing::DataError::Processing(e.to_string()))?;
let json_value = match value {
polars::prelude::AnyValue::Int32(i) => serde_json::Value::Number(i.into()),
polars::prelude::AnyValue::Int64(i) => serde_json::Value::Number(i.into()),
polars::prelude::AnyValue::Float32(f) => {
serde_json::Value::Number(serde_json::Number::from_f64(f as f64).unwrap())
}
polars::prelude::AnyValue::Float64(f) => {
serde_json::Value::Number(serde_json::Number::from_f64(f).unwrap())
}
polars::prelude::AnyValue::String(s) => {
serde_json::Value::String(s.to_string())
}
polars::prelude::AnyValue::Boolean(b) => serde_json::Value::Bool(b),
polars::prelude::AnyValue::Null => serde_json::Value::Null,
_ => serde_json::Value::String(value.to_string()),
};
obj.insert(col_name.to_string(), json_value);
}
result.push(serde_json::Value::Object(obj));
}
Ok(serde_json::Value::Array(result))
}
}
/// Performance measurement utilities
pub mod performance {
use std::time::{Duration, Instant};
/// Measure execution time of a function
pub fn measure_time<F, R>(f: F) -> (R, Duration)
where
F: FnOnce() -> R,
{
let start = Instant::now();
let result = f();
let duration = start.elapsed();
(result, duration)
}
/// Benchmark a function multiple times
pub fn benchmark<F, R>(f: F, iterations: usize) -> BenchmarkResult
where
F: Fn() -> R,
{
let mut times = Vec::with_capacity(iterations);
for _ in 0..iterations {
let (_, duration) = measure_time(&f);
times.push(duration);
}
times.sort();
BenchmarkResult {
min: times[0],
max: times[iterations - 1],
mean: times.iter().sum::<Duration>() / iterations as u32,
median: times[iterations / 2],
p95: times[(iterations as f64 * 0.95) as usize],
p99: times[(iterations as f64 * 0.99) as usize],
}
}
/// Results from performance benchmarking
#[derive(Debug, Clone)]
pub struct BenchmarkResult {
/// Minimum execution time
pub min: Duration,
/// Maximum execution time
pub max: Duration,
/// Mean execution time
pub mean: Duration,
/// Median execution time
pub median: Duration,
/// 95th percentile execution time
pub p95: Duration,
/// 99th percentile execution time
pub p99: Duration,
}
}
/// Memory utilities
pub mod memory {
use std::sync::atomic::{AtomicUsize, Ordering};
/// Global memory tracker
pub struct MemoryTracker {
allocated: AtomicUsize,
peak: AtomicUsize,
}
impl Default for MemoryTracker {
fn default() -> Self {
Self::new()
}
}
impl MemoryTracker {
/// Creates a new memory tracker
///
/// # Returns
///
/// Returns a new `MemoryTracker` instance
pub const fn new() -> Self {
Self {
allocated: AtomicUsize::new(0),
peak: AtomicUsize::new(0),
}
}
/// Returns the current allocated memory in bytes
///
/// # Returns
///
/// Returns the number of bytes currently allocated
pub fn allocated(&self) -> usize {
self.allocated.load(Ordering::Relaxed)
}
/// Returns the peak memory usage in bytes
///
/// # Returns
///
/// Returns the maximum number of bytes allocated at any point
pub fn peak(&self) -> usize {
self.peak.load(Ordering::Relaxed)
}
/// Records a memory allocation
///
/// # Arguments
///
/// * `size` - The size of the allocation in bytes
pub fn record_allocation(&self, size: usize) {
let current = self.allocated.fetch_add(size, Ordering::Relaxed);
let new_total = current + size;
let mut peak = self.peak.load(Ordering::Relaxed);
while peak < new_total {
match self.peak.compare_exchange_weak(
peak,
new_total,
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => break,
Err(p) => peak = p,
}
}
}
/// Records a memory deallocation
///
/// # Arguments
///
/// * `size` - The size of the deallocation in bytes
pub fn record_deallocation(&self, size: usize) {
self.allocated.fetch_sub(size, Ordering::Relaxed);
}
}
/// Global memory tracker instance
pub static MEMORY_TRACKER: MemoryTracker = MemoryTracker::new();
}
/// Validation utilities
pub mod validation {
use crate::chart::{ChartSpec, ValidationError};
/// Validate chart specification
pub fn validate_chart_spec(spec: &ChartSpec) -> Result<(), ValidationError> {
spec.validate()
}
/// Validate data types
pub fn validate_data_types(spec: &ChartSpec) -> Result<(), ValidationError> {
// Check that encoding data types match actual data
// Note: DataReference doesn't directly contain DataFrame, would need to load data
// For now, skip this validation
if false {
for (_field, _encoding) in spec.encoding.get_field_encodings() {
// Would need to load data from DataReference first
// For now, skip validation
}
}
Ok(())
}
fn types_compatible(
actual: &polars::prelude::DataType,
expected: &crate::chart::DataType,
) -> bool {
matches!(
(actual, expected),
(
polars::prelude::DataType::Int32 | polars::prelude::DataType::Int64,
crate::chart::DataType::Quantitative,
) | (
polars::prelude::DataType::Float32 | polars::prelude::DataType::Float64,
crate::chart::DataType::Quantitative,
) | (
polars::prelude::DataType::String,
crate::chart::DataType::Nominal | crate::chart::DataType::Ordinal,
) | (
polars::prelude::DataType::Boolean,
crate::chart::DataType::Nominal
) | (
polars::prelude::DataType::Date | polars::prelude::DataType::Datetime(_, _),
crate::chart::DataType::Temporal,
)
)
}
}
/// Error handling utilities
pub mod error {
use crate::HeliosError;
/// Convert error to user-friendly message
pub fn user_friendly_error(error: &HeliosError) -> String {
error.user_message()
}
/// Get suggested actions for an error
pub fn suggested_actions(error: &HeliosError) -> Vec<String> {
error.suggested_actions()
}
/// Check if error is recoverable
pub fn is_recoverable(error: &HeliosError) -> bool {
error.is_recoverable()
}
}
/// Testing utilities
pub mod test_utils {
use polars::prelude::*;
/// Create test DataFrame
pub fn create_test_dataframe() -> DataFrame {
df! {
"x" => [1, 2, 3, 4, 5],
"y" => [2, 4, 1, 5, 3],
"category" => ["A", "B", "A", "C", "B"],
}
.unwrap()
}
/// Create large test DataFrame
pub fn create_large_test_dataframe(size: usize) -> DataFrame {
let x: Vec<i32> = (0..size as i32).collect();
let y: Vec<f64> = (0..size).map(|i| (i as f64).sin()).collect();
let category: Vec<String> = (0..size).map(|i| format!("Category_{}", i % 10)).collect();
df! {
"x" => x,
"y" => y,
"category" => category,
}
.unwrap()
}
/// Create test chart specification
pub fn create_test_chart_spec() -> crate::chart::ChartSpec {
crate::chart::ChartSpec {
data: crate::chart::DataReference {
source: "test".to_string(),
format: crate::chart::DataFormat::Inline,
schema: None,
},
mark: crate::chart::MarkType::Point {
size: Some(5.0),
shape: None,
opacity: None,
},
encoding: crate::chart::Encoding {
x: Some(crate::chart::PositionEncoding {
field: "x".to_string(),
data_type: crate::chart::DataType::Quantitative,
scale: None,
axis: None,
legend: None,
bin: None,
aggregate: None,
sort: None,
}),
y: Some(crate::chart::PositionEncoding {
field: "y".to_string(),
data_type: crate::chart::DataType::Quantitative,
scale: None,
axis: None,
legend: None,
bin: None,
aggregate: None,
sort: None,
}),
color: Some(crate::chart::ColorEncoding {
field: "category".to_string(),
data_type: crate::chart::DataType::Nominal,
scale: None,
axis: None,
legend: None,
bin: None,
aggregate: None,
sort: None,
}),
..Default::default()
},
transform: Vec::new(),
selection: Vec::new(),
intelligence: None,
config: crate::chart::ChartConfig::default(),
}
}
/// Assert two DataFrames are approximately equal
pub fn assert_dataframes_approx_equal(df1: &DataFrame, df2: &DataFrame, tolerance: f64) {
assert_eq!(df1.height(), df2.height(), "DataFrame heights differ");
assert_eq!(df1.width(), df2.width(), "DataFrame widths differ");
for col_name in df1.get_column_names() {
let series1 = df1.column(col_name).unwrap();
let series2 = df2.column(col_name).unwrap();
assert_eq!(
series1.dtype(),
series2.dtype(),
"Column '{}' types differ",
col_name
);
for i in 0..series1.len() {
let val1 = series1.get(i).unwrap();
let val2 = series2.get(i).unwrap();
match (val1.clone(), val2.clone()) {
(AnyValue::Float64(f1), AnyValue::Float64(f2)) => {
assert!(
(f1 - f2).abs() < tolerance,
"Column '{}' row {}: {} != {} (tolerance: {})",
col_name,
i,
f1,
f2,
tolerance
);
}
(AnyValue::Float32(f1), AnyValue::Float32(f2)) => {
assert!(
(f1 - f2).abs() < tolerance as f32,
"Column '{}' row {}: {} != {} (tolerance: {})",
col_name,
i,
f1,
f2,
tolerance
);
}
_ => assert_eq!(val1, val2, "Column '{}' row {} values differ", col_name, i),
}
}
}
}
}
// Add extension trait for Encoding to get field encodings
impl crate::chart::Encoding {
/// Returns a vector of field encodings with their names
///
/// # Returns
///
/// Returns a vector of tuples containing field names and their position encodings
pub fn get_field_encodings(&self) -> Vec<(String, &crate::chart::PositionEncoding)> {
let mut encodings = Vec::new();
if let Some(ref x) = self.x {
encodings.push((x.field.clone(), x));
}
if let Some(ref y) = self.y {
encodings.push((y.field.clone(), y));
}
encodings
}
}
// Add extension trait for PositionEncoding to get data type
impl crate::chart::PositionEncoding {
/// Returns the data type of the position encoding
///
/// # Returns
///
/// Returns a reference to the data type
pub fn data_type(&self) -> &crate::chart::DataType {
&self.data_type
}
}