fiasto 0.2.4

High-performance modern Wilkinson's formula parsing for statistical models. Parses R-style formulas into structured JSON metadata supporting linear models, mixed effects, and complex statistical specifications.
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
//! # Abstract Syntax Tree (AST) Definitions
//!
//! This module defines the core data structures that represent parsed statistical formulas.
//! The AST captures the hierarchical structure of formulas including terms, functions,
//! interactions, and random effects.
//!
//! ## Overview
//!
//! The AST is designed to represent R-style statistical formulas with support for:
//! - Basic terms and variables
//! - Function calls with arguments
//! - Interactions between terms
//! - Complex random effects structures
//! - Distribution families
//!
//! ## Examples
//!
//! ### Simple Linear Model
//! ```text
//! Formula: y ~ x + z
//! AST: Term::Column("y") ~ [Term::Column("x"), Term::Column("z")]
//! ```
//!
//! ### Model with Transformations
//! ```text
//! Formula: y ~ poly(x, 3) + log(z)
//! AST: Term::Column("y") ~ [
//!   Term::Function { name: "poly", args: [Ident("x"), Integer(3)] },
//!   Term::Function { name: "log", args: [Ident("z")] }
//! ]
//! ```
//!
//! ### Random Effects Model
//! ```text
//! Formula: y ~ x + (1 | group)
//! AST: Term::Column("y") ~ [
//!   Term::Column("x"),
//!   Term::RandomEffect(RandomEffect {
//!     terms: [RandomTerm::SuppressIntercept],
//!     grouping: Grouping::Simple("group"),
//!     correlation: CorrelationType::Correlated
//!   })
//! ]
//! ```

/// Distribution families for statistical models
///
/// These represent the error distribution family in generalized linear models.
/// Each family corresponds to a specific probability distribution and link function.
///
/// # Examples
///
/// ```rust
/// use fiasto::internal::ast::Family;
///
/// // Gaussian family for linear regression
/// let gaussian = Family::Gaussian;
///
/// // Binomial family for logistic regression
/// let binomial = Family::Binomial;
///
/// // Poisson family for count data
/// let poisson = Family::Poisson;
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum Family {
    /// Gaussian (normal) distribution - used for linear regression
    /// Link function: identity
    /// Variance function: constant
    Gaussian,
    /// Binomial distribution - used for logistic regression
    /// Link function: logit
    /// Variance function: μ(1-μ)
    Binomial,
    /// Poisson distribution - used for count data
    /// Link function: log
    /// Variance function: μ
    Poisson,
}

/// A term in a statistical formula
///
/// Terms represent the building blocks of statistical formulas. They can be
/// simple variables, function calls, interactions, or random effects.
///
/// # Examples
///
/// ```rust
/// use fiasto::internal::ast::{Term, Argument, RandomEffect, Grouping, CorrelationType};
///
/// // Simple variable
/// let var_term = Term::Column("x".to_string());
///
/// // Function call
/// let func_term = Term::Function {
///     name: "poly".to_string(),
///     args: vec![Argument::Ident("x".to_string()), Argument::Integer(3)]
/// };
///
/// // Interaction
/// let interaction = Term::Interaction {
///     left: Box::new(Term::Column("x".to_string())),
///     right: Box::new(Term::Column("z".to_string()))
/// };
///
/// // Random effect
/// let random_effect = Term::RandomEffect(RandomEffect {
///     terms: vec![],
///     grouping: Grouping::Simple("group".to_string()),
///     correlation: CorrelationType::Correlated,
///     correlation_id: None
/// });
/// ```
#[derive(Debug, Clone)]
pub enum Term {
    /// A simple variable or column name
    ///
    /// # Examples
    /// - `x` → `Term::Column("x")`
    /// - `response_var` → `Term::Column("response_var")`
    Column(String),

    /// A function call with arguments
    ///
    /// # Examples
    /// - `poly(x, 3)` → `Term::Function { name: "poly", args: [Ident("x"), Integer(3)] }`
    /// - `log(y)` → `Term::Function { name: "log", args: [Ident("y")] }`
    /// - `scale(z)` → `Term::Function { name: "scale", args: [Ident("z")] }`
    Function {
        /// The function name (e.g., "poly", "log", "scale")
        name: String,
        /// The function arguments
        args: Vec<Argument>,
    },

    /// An interaction between two terms
    ///
    /// # Examples
    /// - `x:z` → `Term::Interaction { left: Column("x"), right: Column("z") }`
    /// - `poly(x,2):log(y)` → `Term::Interaction { left: Function{...}, right: Function{...} }`
    Interaction {
        /// The left-hand side of the interaction
        left: Box<Term>,
        /// The right-hand side of the interaction
        right: Box<Term>,
    },

    /// A random effects term
    ///
    /// # Examples
    /// - `(1 | group)` → `Term::RandomEffect(RandomEffect{...})`
    /// - `(x | group)` → `Term::RandomEffect(RandomEffect{...})`
    /// - `(x || group)` → `Term::RandomEffect(RandomEffect{...})`
    RandomEffect(RandomEffect),
}

/// Arguments to function calls
///
/// Function arguments can be identifiers, integers, strings, or boolean values.
/// These are used in function calls like `poly(x, 3)` or `gr(group, cor = TRUE)`.
///
/// # Examples
///
/// ```rust
/// use fiasto::internal::ast::Argument;
///
/// // Identifier argument
/// let ident_arg = Argument::Ident("x".to_string());
///
/// // Integer argument
/// let int_arg = Argument::Integer(3);
///
/// // String argument
/// let str_arg = Argument::String("student".to_string());
///
/// // Boolean argument
/// let bool_arg = Argument::Boolean(true);
/// ```
#[derive(Debug, Clone)]
pub enum Argument {
    /// An identifier (variable name)
    ///
    /// # Examples
    /// - `x` → `Argument::Ident("x")`
    /// - `group_var` → `Argument::Ident("group_var")`
    Ident(String),

    /// An integer value
    ///
    /// # Examples
    /// - `3` → `Argument::Integer(3)`
    /// - `0` → `Argument::Integer(0)`
    Integer(u32),

    /// A string literal
    ///
    /// # Examples
    /// - `"student"` → `Argument::String("student")`
    /// - `"group_id"` → `Argument::String("group_id")`
    String(String),

    /// A boolean value
    ///
    /// # Examples
    /// - `TRUE` → `Argument::Boolean(true)`
    /// - `FALSE` → `Argument::Boolean(false)`
    Boolean(bool),
}

/// A random effects specification
///
/// Random effects define the grouping structure and correlation patterns
/// for mixed-effects models. They specify which variables have random effects
/// and how those effects are grouped and correlated.
///
/// # Examples
///
/// ```rust
/// use fiasto::internal::ast::{RandomEffect, RandomTerm, Grouping, CorrelationType};
///
/// // Random intercepts: (1 | group)
/// let random_intercept = RandomEffect {
///     terms: vec![RandomTerm::SuppressIntercept],
///     grouping: Grouping::Simple("group".to_string()),
///     correlation: CorrelationType::Correlated,
///     correlation_id: None
/// };
///
/// // Random slopes: (x | group)
/// let random_slope = RandomEffect {
///     terms: vec![RandomTerm::Column("x".to_string())],
///     grouping: Grouping::Simple("group".to_string()),
///     correlation: CorrelationType::Correlated,
///     correlation_id: None
/// };
///
/// // Uncorrelated effects: (x || group)
/// let uncorrelated = RandomEffect {
///     terms: vec![RandomTerm::Column("x".to_string())],
///     grouping: Grouping::Simple("group".to_string()),
///     correlation: CorrelationType::Uncorrelated,
///     correlation_id: None
/// };
/// ```
#[derive(Debug, Clone)]
pub struct RandomEffect {
    /// The terms that have random effects
    ///
    /// # Examples
    /// - `(1 | group)` → `[RandomTerm::SuppressIntercept]`
    /// - `(x | group)` → `[RandomTerm::Column("x")]`
    /// - `(x + z | group)` → `[RandomTerm::Column("x"), RandomTerm::Column("z")]`
    pub terms: Vec<RandomTerm>,

    /// The grouping structure for the random effects
    ///
    /// # Examples
    /// - `(1 | group)` → `Grouping::Simple("group")`
    /// - `(1 | gr(group, cor=FALSE))` → `Grouping::Gr{...}`
    /// - `(1 | group1/group2)` → `Grouping::Nested{...}`
    pub grouping: Grouping,

    /// The correlation structure between random effects
    ///
    /// # Examples
    /// - `(x | group)` → `CorrelationType::Correlated`
    /// - `(x || group)` → `CorrelationType::Uncorrelated`
    /// - `(x |ID| group)` → `CorrelationType::CrossParameter("ID")`
    pub correlation: CorrelationType,

    /// Optional correlation ID for cross-parameter correlations
    ///
    /// # Examples
    /// - `(x | group)` → `None`
    /// - `(x |ID| group)` → `Some("ID")`
    pub correlation_id: Option<String>,
}

/// Terms within random effects specifications
///
/// Random terms specify which variables or functions have random effects
/// within a grouping structure.
///
/// # Examples
///
/// ```rust
/// use fiasto::internal::ast::{RandomTerm, Argument};
///
/// // Simple variable with random effect
/// let var_term = RandomTerm::Column("x".to_string());
///
/// // Function with random effect
/// let func_term = RandomTerm::Function {
///     name: "poly".to_string(),
///     args: vec![Argument::Ident("x".to_string()), Argument::Integer(2)]
/// };
///
/// // Interaction with random effect
/// let interaction = RandomTerm::Interaction {
///     left: Box::new(RandomTerm::Column("x".to_string())),
///     right: Box::new(RandomTerm::Column("z".to_string()))
/// };
///
/// // Suppress intercept (0 + or -1 +)
/// let suppress = RandomTerm::SuppressIntercept;
/// ```
#[derive(Debug, Clone)]
pub enum RandomTerm {
    /// A simple variable with random effects
    ///
    /// # Examples
    /// - `x` → `RandomTerm::Column("x")`
    /// - `response` → `RandomTerm::Column("response")`
    Column(String),

    /// A function call with random effects
    ///
    /// # Examples
    /// - `poly(x, 2)` → `RandomTerm::Function { name: "poly", args: [...] }`
    /// - `log(y)` → `RandomTerm::Function { name: "log", args: [...] }`
    Function {
        /// The function name
        name: String,
        /// The function arguments
        args: Vec<Argument>,
    },

    /// An interaction between random terms
    ///
    /// # Examples
    /// - `x:z` → `RandomTerm::Interaction { left: Column("x"), right: Column("z") }`
    /// - `x*y` → `RandomTerm::Interaction { left: Column("x"), right: Column("y") }`
    Interaction {
        /// The left-hand side of the interaction
        left: Box<RandomTerm>,
        /// The right-hand side of the interaction
        right: Box<RandomTerm>,
    },

    /// Suppress the random intercept (0 + or -1 +)
    ///
    /// # Examples
    /// - `(0 + x | group)` → `[SuppressIntercept, Column("x")]`
    /// - `(-1 + x | group)` → `[SuppressIntercept, Column("x")]`
    SuppressIntercept,
}

/// Grouping structures for random effects
///
/// Grouping defines how observations are grouped for random effects.
/// Different grouping structures support various statistical modeling scenarios.
///
/// # Examples
///
/// ```rust
/// use fiasto::internal::ast::{Grouping, GrOption};
///
/// // Simple grouping: (1 | group)
/// let simple = Grouping::Simple("group".to_string());
///
/// // Enhanced grouping with options: (1 | gr(group, cor=FALSE))
/// let gr_grouping = Grouping::Gr {
///     group: "group".to_string(),
///     options: vec![GrOption::Cor(false)]
/// };
///
/// // Multi-membership: (1 | mm(group1, group2))
/// let mm_grouping = Grouping::Mm {
///     groups: vec!["group1".to_string(), "group2".to_string()]
/// };
///
/// // Interaction grouping: (1 | group1:group2)
/// let interaction = Grouping::Interaction {
///     left: "group1".to_string(),
///     right: "group2".to_string()
/// };
///
/// // Nested grouping: (1 | group1/group2)
/// let nested = Grouping::Nested {
///     outer: "group1".to_string(),
///     inner: "group2".to_string()
/// };
/// ```
#[derive(Debug, Clone)]
pub enum Grouping {
    /// Simple grouping by a single variable
    ///
    /// # Examples
    /// - `(1 | group)` → `Grouping::Simple("group")`
    /// - `(x | site)` → `Grouping::Simple("site")`
    Simple(String),

    /// Enhanced grouping with gr() function and options
    ///
    /// # Examples
    /// - `(1 | gr(group))` → `Grouping::Gr { group: "group", options: [] }`
    /// - `(1 | gr(group, cor=FALSE))` → `Grouping::Gr { group: "group", options: [Cor(false)] }`
    Gr {
        /// The grouping variable name
        group: String,
        /// Additional options for the grouping
        options: Vec<GrOption>,
    },

    /// Multi-membership grouping
    ///
    /// # Examples
    /// - `(1 | mm(group1, group2))` → `Grouping::Mm { groups: ["group1", "group2"] }`
    Mm {
        /// The multiple grouping variables
        groups: Vec<String>,
    },

    /// Interaction of grouping factors
    ///
    /// # Examples
    /// - `(1 | group1:group2)` → `Grouping::Interaction { left: "group1", right: "group2" }`
    Interaction {
        /// The left grouping factor
        left: String,
        /// The right grouping factor
        right: String,
    },

    /// Nested grouping structure
    ///
    /// # Examples
    /// - `(1 | group1/group2)` → `Grouping::Nested { outer: "group1", inner: "group2" }`
    Nested {
        /// The outer (higher-level) grouping factor
        outer: String,
        /// The inner (lower-level) grouping factor
        inner: String,
    },
}

/// Options for the gr() grouping function
///
/// The gr() function provides enhanced grouping capabilities with various
/// options to control correlation structures and grouping behavior.
///
/// # Examples
///
/// ```rust
/// use fiasto::internal::ast::GrOption;
///
/// // Control correlation: cor = FALSE
/// let cor_option = GrOption::Cor(false);
///
/// // Set grouping ID: id = "group_1"
/// let id_option = GrOption::Id("group_1".to_string());
///
/// // Set by variable: by = NULL
/// let by_option = GrOption::By(None);
///
/// // Control covariance: cov = TRUE
/// let cov_option = GrOption::Cov(true);
///
/// // Set distribution: dist = "student"
/// let dist_option = GrOption::Dist("student".to_string());
/// ```
#[derive(Debug, Clone)]
pub enum GrOption {
    /// Control correlation between random effects
    ///
    /// # Examples
    /// - `cor = TRUE` → `GrOption::Cor(true)`
    /// - `cor = FALSE` → `GrOption::Cor(false)`
    Cor(bool),

    /// Set a grouping ID for the random effects
    ///
    /// # Examples
    /// - `id = "group_1"` → `GrOption::Id("group_1")`
    /// - `id = "site_effects"` → `GrOption::Id("site_effects")`
    Id(String),

    /// Set a by variable (can be NULL)
    ///
    /// # Examples
    /// - `by = NULL` → `GrOption::By(None)`
    /// - `by = "treatment"` → `GrOption::By(Some("treatment"))`
    By(Option<String>), // Can be NULL

    /// Control covariance structure
    ///
    /// # Examples
    /// - `cov = TRUE` → `GrOption::Cov(true)`
    /// - `cov = FALSE` → `GrOption::Cov(false)`
    Cov(bool), // Can be TRUE/FALSE

    /// Set the distribution for random effects
    ///
    /// # Examples
    /// - `dist = "student"` → `GrOption::Dist("student")`
    /// - `dist = "normal"` → `GrOption::Dist("normal")`
    Dist(String),
}

/// Correlation types for random effects
///
/// Defines how random effects are correlated within and across grouping levels.
///
/// # Examples
///
/// ```rust
/// use fiasto::internal::ast::CorrelationType;
///
/// // Correlated random effects: (x | group)
/// let correlated = CorrelationType::Correlated;
///
/// // Uncorrelated random effects: (x || group)
/// let uncorrelated = CorrelationType::Uncorrelated;
///
/// // Cross-parameter correlation: (x |ID| group)
/// let cross_param = CorrelationType::CrossParameter("ID".to_string());
/// ```
#[derive(Debug, Clone)]
pub enum CorrelationType {
    /// Random effects are correlated (default)
    ///
    /// # Examples
    /// - `(x | group)` → `CorrelationType::Correlated`
    /// - `(1 | group)` → `CorrelationType::Correlated`
    Correlated,

    /// Random effects are uncorrelated
    ///
    /// # Examples
    /// - `(x || group)` → `CorrelationType::Uncorrelated`
    /// - `(1 || group)` → `CorrelationType::Uncorrelated`
    Uncorrelated,

    /// Cross-parameter correlation with specific ID
    ///
    /// # Examples
    /// - `(x |ID| group)` → `CorrelationType::CrossParameter("ID")`
    /// - `(x |CORR| group)` → `CorrelationType::CrossParameter("CORR")`
    CrossParameter(String),
}