datasynth-eval 3.1.1

Evaluation framework for synthetic financial data quality and coherence
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
//! Format consistency evaluation.
//!
//! Analyzes format variations in dates, amounts, identifiers, and currency codes.

use crate::error::EvalResult;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Results of format consistency analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormatAnalysis {
    /// Date format variations.
    pub date_formats: Vec<FormatVariation>,
    /// Amount format variations.
    pub amount_formats: Vec<FormatVariation>,
    /// Identifier format variations.
    pub identifier_formats: Vec<FormatVariation>,
    /// Currency code compliance.
    pub currency_compliance: f64,
    /// Overall format consistency score (0.0-1.0).
    pub consistency_score: f64,
    /// Format issues detected.
    pub issues: Vec<FormatIssue>,
}

/// Variation in a specific format type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormatVariation {
    /// Field name.
    pub field_name: String,
    /// Format type (e.g., "ISO", "US", "EU").
    pub format_type: String,
    /// Count of values in this format.
    pub count: usize,
    /// Percentage of total.
    pub percentage: f64,
    /// Example values.
    pub examples: Vec<String>,
}

/// A format issue detected.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormatIssue {
    /// Field name.
    pub field_name: String,
    /// Issue type.
    pub issue_type: FormatIssueType,
    /// Description.
    pub description: String,
    /// Example problematic values.
    pub examples: Vec<String>,
}

/// Type of format issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FormatIssueType {
    /// Multiple date formats in same field.
    InconsistentDateFormat,
    /// Multiple amount formats in same field.
    InconsistentAmountFormat,
    /// Case inconsistency in identifiers.
    InconsistentCase,
    /// Invalid currency code.
    InvalidCurrencyCode,
    /// Invalid decimal places.
    InvalidDecimalPlaces,
    /// Invalid separator usage.
    InvalidSeparator,
}

/// Detected date format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DateFormat {
    /// ISO 8601 (2024-01-15).
    ISO,
    /// US format (01/15/2024).
    US,
    /// European format (15.01.2024).
    EU,
    /// Long format (January 15, 2024).
    Long,
    /// Unknown format.
    Unknown,
}

/// Detected amount format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AmountFormat {
    /// Plain (1234.56).
    Plain,
    /// US with comma thousands (1,234.56).
    USComma,
    /// European (1.234,56).
    European,
    /// With currency prefix ($1,234.56).
    CurrencyPrefix,
    /// With currency suffix (1.234,56 EUR).
    CurrencySuffix,
    /// Unknown format.
    Unknown,
}

/// Input data for format analysis.
#[derive(Debug, Clone, Default)]
pub struct FormatData {
    /// Date field values: field_name -> values.
    pub date_fields: HashMap<String, Vec<String>>,
    /// Amount field values: field_name -> values.
    pub amount_fields: HashMap<String, Vec<String>>,
    /// Identifier field values: field_name -> values.
    pub identifier_fields: HashMap<String, Vec<String>>,
    /// Currency codes used.
    pub currency_codes: Vec<String>,
}

/// Analyzer for format consistency.
pub struct FormatAnalyzer {
    /// Valid ISO 4217 currency codes.
    valid_currencies: std::collections::HashSet<String>,
    /// Minimum consistency threshold for a single field.
    min_field_consistency: f64,
}

impl FormatAnalyzer {
    /// Create a new analyzer.
    pub fn new() -> Self {
        let valid_currencies: std::collections::HashSet<String> = [
            "USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD", "CNY", "HKD", "SGD", "INR", "BRL",
            "MXN", "KRW", "RUB", "ZAR", "SEK", "NOK", "DKK", "NZD", "THB", "MYR", "IDR", "PHP",
        ]
        .iter()
        .map(std::string::ToString::to_string)
        .collect();

        Self {
            valid_currencies,
            min_field_consistency: 0.95,
        }
    }

    /// Analyze format consistency.
    pub fn analyze(&self, data: &FormatData) -> EvalResult<FormatAnalysis> {
        let mut date_formats = Vec::new();
        let mut amount_formats = Vec::new();
        let mut identifier_formats = Vec::new();
        let mut issues = Vec::new();
        let mut consistency_scores = Vec::new();

        // Analyze date formats
        for (field_name, values) in &data.date_fields {
            let (formats, field_issues, consistency) = self.analyze_date_field(field_name, values);
            date_formats.extend(formats);
            issues.extend(field_issues);
            consistency_scores.push(consistency);
        }

        // Analyze amount formats
        for (field_name, values) in &data.amount_fields {
            let (formats, field_issues, consistency) =
                self.analyze_amount_field(field_name, values);
            amount_formats.extend(formats);
            issues.extend(field_issues);
            consistency_scores.push(consistency);
        }

        // Analyze identifier formats
        for (field_name, values) in &data.identifier_fields {
            let (formats, field_issues, consistency) =
                self.analyze_identifier_field(field_name, values);
            identifier_formats.extend(formats);
            issues.extend(field_issues);
            consistency_scores.push(consistency);
        }

        // Check currency code compliance
        let valid_count = data
            .currency_codes
            .iter()
            .filter(|c| self.valid_currencies.contains(c.to_uppercase().as_str()))
            .count();
        let currency_compliance = if data.currency_codes.is_empty() {
            1.0
        } else {
            valid_count as f64 / data.currency_codes.len() as f64
        };

        if currency_compliance < 1.0 {
            let invalid: Vec<_> = data
                .currency_codes
                .iter()
                .filter(|c| !self.valid_currencies.contains(c.to_uppercase().as_str()))
                .take(5)
                .cloned()
                .collect();
            issues.push(FormatIssue {
                field_name: "currency_code".to_string(),
                issue_type: FormatIssueType::InvalidCurrencyCode,
                description: format!(
                    "Found {} invalid currency codes",
                    data.currency_codes.len() - valid_count
                ),
                examples: invalid,
            });
        }

        consistency_scores.push(currency_compliance);

        let consistency_score = if consistency_scores.is_empty() {
            1.0
        } else {
            consistency_scores.iter().sum::<f64>() / consistency_scores.len() as f64
        };

        Ok(FormatAnalysis {
            date_formats,
            amount_formats,
            identifier_formats,
            currency_compliance,
            consistency_score,
            issues,
        })
    }

    /// Analyze date field formats.
    fn analyze_date_field(
        &self,
        field_name: &str,
        values: &[String],
    ) -> (Vec<FormatVariation>, Vec<FormatIssue>, f64) {
        let mut format_counts: HashMap<DateFormat, Vec<String>> = HashMap::new();

        for value in values {
            let format = self.detect_date_format(value);
            format_counts.entry(format).or_default().push(value.clone());
        }

        let total = values.len();
        let variations: Vec<FormatVariation> = format_counts
            .iter()
            .map(|(format, examples)| FormatVariation {
                field_name: field_name.to_string(),
                format_type: format!("{format:?}"),
                count: examples.len(),
                percentage: if total > 0 {
                    examples.len() as f64 / total as f64
                } else {
                    0.0
                },
                examples: examples.iter().take(3).cloned().collect(),
            })
            .collect();

        let mut issues = Vec::new();
        let dominant_count = format_counts
            .values()
            .map(std::vec::Vec::len)
            .max()
            .unwrap_or(0);
        let consistency = if total > 0 {
            dominant_count as f64 / total as f64
        } else {
            1.0
        };

        if consistency < self.min_field_consistency && format_counts.len() > 1 {
            issues.push(FormatIssue {
                field_name: field_name.to_string(),
                issue_type: FormatIssueType::InconsistentDateFormat,
                description: format!(
                    "Multiple date formats detected ({} variants)",
                    format_counts.len()
                ),
                examples: values.iter().take(5).cloned().collect(),
            });
        }

        (variations, issues, consistency)
    }

    /// Detect date format from a string.
    fn detect_date_format(&self, value: &str) -> DateFormat {
        let value = value.trim();

        // ISO format: 2024-01-15
        if value.len() == 10
            && value.chars().nth(4) == Some('-')
            && value.chars().nth(7) == Some('-')
        {
            return DateFormat::ISO;
        }

        // US format: 01/15/2024
        if value.len() == 10
            && value.chars().nth(2) == Some('/')
            && value.chars().nth(5) == Some('/')
        {
            return DateFormat::US;
        }

        // EU format: 15.01.2024
        if value.len() == 10
            && value.chars().nth(2) == Some('.')
            && value.chars().nth(5) == Some('.')
        {
            return DateFormat::EU;
        }

        // Long format contains month name
        if value.contains("January")
            || value.contains("February")
            || value.contains("March")
            || value.contains("April")
            || value.contains("May")
            || value.contains("June")
            || value.contains("July")
            || value.contains("August")
            || value.contains("September")
            || value.contains("October")
            || value.contains("November")
            || value.contains("December")
        {
            return DateFormat::Long;
        }

        DateFormat::Unknown
    }

    /// Analyze amount field formats.
    fn analyze_amount_field(
        &self,
        field_name: &str,
        values: &[String],
    ) -> (Vec<FormatVariation>, Vec<FormatIssue>, f64) {
        let mut format_counts: HashMap<AmountFormat, Vec<String>> = HashMap::new();

        for value in values {
            let format = self.detect_amount_format(value);
            format_counts.entry(format).or_default().push(value.clone());
        }

        let total = values.len();
        let variations: Vec<FormatVariation> = format_counts
            .iter()
            .map(|(format, examples)| FormatVariation {
                field_name: field_name.to_string(),
                format_type: format!("{format:?}"),
                count: examples.len(),
                percentage: if total > 0 {
                    examples.len() as f64 / total as f64
                } else {
                    0.0
                },
                examples: examples.iter().take(3).cloned().collect(),
            })
            .collect();

        let mut issues = Vec::new();
        let dominant_count = format_counts
            .values()
            .map(std::vec::Vec::len)
            .max()
            .unwrap_or(0);
        let consistency = if total > 0 {
            dominant_count as f64 / total as f64
        } else {
            1.0
        };

        if consistency < self.min_field_consistency && format_counts.len() > 1 {
            issues.push(FormatIssue {
                field_name: field_name.to_string(),
                issue_type: FormatIssueType::InconsistentAmountFormat,
                description: format!(
                    "Multiple amount formats detected ({} variants)",
                    format_counts.len()
                ),
                examples: values.iter().take(5).cloned().collect(),
            });
        }

        (variations, issues, consistency)
    }

    /// Detect amount format from a string.
    fn detect_amount_format(&self, value: &str) -> AmountFormat {
        let value = value.trim();

        // Currency prefix ($, €, £)
        if value.starts_with('$') || value.starts_with('€') || value.starts_with('£') {
            return AmountFormat::CurrencyPrefix;
        }

        // Currency suffix (EUR, USD at end)
        if value.ends_with("EUR")
            || value.ends_with("USD")
            || value.ends_with("GBP")
            || value.ends_with("JPY")
        {
            return AmountFormat::CurrencySuffix;
        }

        // European format (1.234,56)
        if value.contains('.') && value.contains(',') {
            let dot_pos = value.rfind('.').unwrap_or(0);
            let comma_pos = value.rfind(',').unwrap_or(0);
            if comma_pos > dot_pos {
                return AmountFormat::European;
            }
        }

        // US comma format (1,234.56)
        if value.contains(',') && value.contains('.') {
            return AmountFormat::USComma;
        }

        // Plain format (1234.56)
        if value.contains('.') || value.chars().all(|c| c.is_ascii_digit() || c == '-') {
            return AmountFormat::Plain;
        }

        AmountFormat::Unknown
    }

    /// Analyze identifier field formats.
    fn analyze_identifier_field(
        &self,
        field_name: &str,
        values: &[String],
    ) -> (Vec<FormatVariation>, Vec<FormatIssue>, f64) {
        let mut upper_count = 0;
        let mut lower_count = 0;
        let mut mixed_count = 0;

        for value in values {
            if value
                .chars()
                .filter(|c| c.is_alphabetic())
                .all(char::is_uppercase)
            {
                upper_count += 1;
            } else if value
                .chars()
                .filter(|c| c.is_alphabetic())
                .all(char::is_lowercase)
            {
                lower_count += 1;
            } else {
                mixed_count += 1;
            }
        }

        let total = values.len();
        let mut variations = Vec::new();

        if upper_count > 0 {
            variations.push(FormatVariation {
                field_name: field_name.to_string(),
                format_type: "UPPERCASE".to_string(),
                count: upper_count,
                percentage: upper_count as f64 / total.max(1) as f64,
                examples: values
                    .iter()
                    .filter(|v| {
                        v.chars()
                            .filter(|c| c.is_alphabetic())
                            .all(char::is_uppercase)
                    })
                    .take(3)
                    .cloned()
                    .collect(),
            });
        }

        if lower_count > 0 {
            variations.push(FormatVariation {
                field_name: field_name.to_string(),
                format_type: "lowercase".to_string(),
                count: lower_count,
                percentage: lower_count as f64 / total.max(1) as f64,
                examples: values
                    .iter()
                    .filter(|v| {
                        v.chars()
                            .filter(|c| c.is_alphabetic())
                            .all(char::is_lowercase)
                    })
                    .take(3)
                    .cloned()
                    .collect(),
            });
        }

        if mixed_count > 0 {
            variations.push(FormatVariation {
                field_name: field_name.to_string(),
                format_type: "MixedCase".to_string(),
                count: mixed_count,
                percentage: mixed_count as f64 / total.max(1) as f64,
                examples: values.iter().take(3).cloned().collect(),
            });
        }

        let dominant_count = upper_count.max(lower_count).max(mixed_count);
        let consistency = if total > 0 {
            dominant_count as f64 / total as f64
        } else {
            1.0
        };

        let mut issues = Vec::new();
        if consistency < self.min_field_consistency && variations.len() > 1 {
            issues.push(FormatIssue {
                field_name: field_name.to_string(),
                issue_type: FormatIssueType::InconsistentCase,
                description: format!(
                    "Mixed case formats detected ({} variants)",
                    variations.len()
                ),
                examples: values.iter().take(5).cloned().collect(),
            });
        }

        (variations, issues, consistency)
    }
}

impl Default for FormatAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn test_consistent_formats() {
        let mut data = FormatData::default();
        data.date_fields.insert(
            "posting_date".to_string(),
            vec![
                "2024-01-15".to_string(),
                "2024-01-16".to_string(),
                "2024-01-17".to_string(),
            ],
        );

        let analyzer = FormatAnalyzer::new();
        let result = analyzer.analyze(&data).unwrap();

        assert_eq!(result.date_formats.len(), 1);
        assert!(result.consistency_score > 0.95);
    }

    #[test]
    fn test_date_format_detection() {
        let analyzer = FormatAnalyzer::new();

        assert_eq!(analyzer.detect_date_format("2024-01-15"), DateFormat::ISO);
        assert_eq!(analyzer.detect_date_format("01/15/2024"), DateFormat::US);
        assert_eq!(analyzer.detect_date_format("15.01.2024"), DateFormat::EU);
        assert_eq!(
            analyzer.detect_date_format("January 15, 2024"),
            DateFormat::Long
        );
    }

    #[test]
    fn test_currency_compliance() {
        let mut data = FormatData::default();
        data.currency_codes = vec!["USD".to_string(), "EUR".to_string(), "INVALID".to_string()];

        let analyzer = FormatAnalyzer::new();
        let result = analyzer.analyze(&data).unwrap();

        assert!(result.currency_compliance < 1.0);
        assert!(result.currency_compliance > 0.5);
    }
}