### Build Transform Example Source: https://sciminds.ucsd.edu/bossanova/api/maths/transforms Example of creating a stateful transform instance by name, such as 'center'. ```python >>> transform = build_transform("center") >>> transform.fit_transform(np.array([1.0, 2.0, 3.0])) array([-1., 0., 1.]) ``` -------------------------------- ### MathDisplay to_markdown Examples Source: https://sciminds.ucsd.edu/bossanova/api/containers/display Shows how to export equations as Quarto-compatible display math markdown, with and without explanations. The first example writes to a file, while the second returns the markdown string. ```python >>> m.show_math().to_markdown("equations/model_eq.md") ``` ```python >>> md = m.show_math().to_markdown(include_explanations=False) ``` -------------------------------- ### Install and Verify Project Dependencies Source: https://sciminds.ucsd.edu/bossanova/engineering/developer-guide Use pixi to install project dependencies, run linters, execute unit tests, and perform R parity tests. Ensure R and the lme4 package are installed for parity tests. ```bash # Clone and install git clone https://github.com/sciminds/bossanova.git cd bossanova pixi install # Verify everything works pixi run lint # ruff + ty check pixi run test # unit tests pixi run parity # R parity tests (requires R + lme4) ``` -------------------------------- ### MathDisplay Examples Source: https://sciminds.ucsd.edu/bossanova/api/containers/display Demonstrates how to obtain the raw LaTeX string and how the display object renders in a Jupyter environment. ```python >>> display = m.show_math() >>> display.to_latex() # raw LaTeX string >>> display # renders in Jupyter ``` -------------------------------- ### Example: Parsing with Conditioning Source: https://sciminds.ucsd.edu/bossanova/api/domain/marginal Illustrates parsing an explore formula that includes conditioning variables. ```python >>> parse_explore_formula("treatment ~ age@50") ExploreFormulaSpec( focal_var='treatment', contrast_type=None, conditions=(Condition(var='age', at_values=(50.0,))) ) ``` -------------------------------- ### Setup for Statistical Calculations Source: https://sciminds.ucsd.edu/bossanova/maths/inference Initializes numpy and scipy for numerical operations and sets print options for clarity. ```python import numpy as np from scipy import stats np.random.seed(42) np.set_printoptions(precision=4, suppress=True) ``` -------------------------------- ### Example: Contrast Function Parsing Source: https://sciminds.ucsd.edu/bossanova/api/domain/marginal Shows how to parse an explore formula that includes a contrast function. ```python >>> parse_explore_formula("pairwise(treatment)") ExploreFormulaSpec(focal_var='treatment', contrast_type='pairwise', conditions=()) ``` -------------------------------- ### Example: Build Gaussian Family Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Demonstrates creating a Gaussian family object using the build_family function with the default link. ```python >>> fam = build_family("gaussian") >>> fam.name 'gaussian' ``` -------------------------------- ### Install Bossanova with Sparse Support Source: https://sciminds.ucsd.edu/bossanova Install bossanova with optional sparse support for faster mixed-effects models. This requires additional system libraries on macOS and Ubuntu/Debian. ```bash # uv uv add "bossanova[sparse]" # pip pip install "bossanova[sparse]" ``` -------------------------------- ### Binomial Distribution Examples Source: https://sciminds.ucsd.edu/bossanova/api/distributions Create default Bernoulli and custom Binomial distributions, noting their mean. ```python dist = binomial() # Bernoulli(0.5) dist = binomial(n=10, p=0.3) # Binomial(10, 0.3), mean = 3 ``` -------------------------------- ### Example Distribution Class Implementing Protocol Source: https://sciminds.ucsd.edu/bossanova/api/containers/specs Demonstrates how to implement the Distribution protocol for generating random samples. Requires a sample method. ```python >>> class Normal: ... def __init__(self, mean: float = 0.0, sd: float = 1.0): ... self.mean = mean ... self.sd = sd ... def sample(self, n: int, rng: np.random.Generator) -> np.ndarray: ... return rng.normal(self.mean, self.sd, size=n) ... >>> dist = Normal(0, 1) >>> isinstance(dist, Distribution) True ``` -------------------------------- ### Setup for Mixed Model Analysis Source: https://sciminds.ucsd.edu/bossanova/maths/marginal-conditional Imports necessary libraries and sets random seed and print options for reproducible numerical analysis. ```python import numpy as np from scipy.special import expit np.random.seed(42) np.set_printoptions(precision=4, suppress=True) ``` -------------------------------- ### Example: Simple Term Parsing Source: https://sciminds.ucsd.edu/bossanova/api/domain/marginal Demonstrates parsing a basic explore formula with a single term. ```python >>> parse_explore_formula("treatment") ExploreFormulaSpec(focal_var='treatment', contrast_type=None, conditions=()) ``` -------------------------------- ### Build Ablated Formula Examples Source: https://sciminds.ucsd.edu/bossanova/api/domain/infer Examples demonstrating how to build a formula with one source term ablated. This utility function handles main effects and interactions, and can optionally include random effects. ```python >>> build_ablated_formula("y", ["x", "z", "x:z"], "x") 'y ~ z' ``` ```python >>> build_ablated_formula("y", ["x", "z", "x:z"], "x:z") 'y ~ x + z' ``` ```python >>> build_ablated_formula("y", ["x"], "x") 'y ~ 1' ``` ```python >>> build_ablated_formula("y", ["x", "z"], "x", ("(1|group)",)) 'y ~ z + (1|group)' ``` -------------------------------- ### Google-Style Docstring Example Source: https://sciminds.ucsd.edu/bossanova/engineering/developer-guide Implement Google-style docstrings for functions, including sections for arguments, returns, and other relevant information. ```python def compute_emm( spec: ModelSpec, bundle: DataBundle, fit: FitState, parsed: ExploreFormula, ) -> MeeState: """Compute estimated marginal means. Args: spec: Model configuration (family, link, formula). bundle: Validated model data (X, y, factor levels). fit: Fitted model state (coefficients, vcov). parsed: Parsed explore formula (focal variable, conditions). Returns: MeeState with grid, estimates, and metadata. """ ``` -------------------------------- ### Example: Build Gamma Family with Log Link Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Illustrates creating a Gamma family object and explicitly setting the 'log' link function. ```python >>> fam = build_family("gamma", "log") >>> fam.name 'gamma' ``` -------------------------------- ### Install R Packages Source: https://sciminds.ucsd.edu/bossanova/cheatsheet Installs necessary R packages for statistical modeling, including mixed models, marginal means, robust standard errors, and power analysis. ```r install.packages(c("lme4", "lmerTest", "emmeans", "sandwich", "lmtest", "car", "boot", "broom", "simr")) ``` -------------------------------- ### Example: Build Binomial Family with Probit Link Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Shows how to create a Binomial family object specifying a 'probit' link function. ```python >>> fam = build_family("binomial", "probit") >>> fam.link_name 'probit' ``` -------------------------------- ### Module Section Marker Example Source: https://sciminds.ucsd.edu/bossanova/engineering/developer-guide Use section markers for navigation in files over 300 lines to improve readability. ```python # ============================================================================= # Core Functions # ============================================================================= ``` -------------------------------- ### Distribution Algebra Examples Source: https://sciminds.ucsd.edu/bossanova/api/maths/distributions Demonstrates algebraic operations on distributions, including affine transforms, sums of random variables, and probability queries. ```python d = 2 * normal(5, 1) + 3 # Affine transform → Normal(13, 2) z = normal() + normal() # Sum of RVs → Normal(0, √2) p = normal() > 1.96 # Probability query → P(X > 1.96) = 0.025 ``` -------------------------------- ### Example: Gamma Family with Log Link Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Shows how to create a Gamma family object explicitly using the 'log' link function. ```python >>> # Gamma with log link >>> fam = gamma("log") >>> fam.link_name 'log' ``` -------------------------------- ### ModelSpec Initialization Example Source: https://sciminds.ucsd.edu/bossanova/api/containers/specs Shows how to create a ModelSpec instance with a formula and response variable. The family defaults to 'gaussian' if not specified. ```python >>> spec = ModelSpec( ... formula="y ~ x", ... response_var="y", ... fixed_terms=("Intercept", "x"), ... ) >>> spec.family 'gaussian' ``` -------------------------------- ### Example: Single Contrast Conversion Source: https://sciminds.ucsd.edu/bossanova/api/domain/design Demonstrates converting a single contrast vector (A vs average(B, C)) into a coding matrix. ```python >>> # Single contrast: A vs average(B, C) >>> array_to_coding_matrix([-1, 0.5, 0.5], n_levels=3) array([[-0.81649658, 0. ], [ 0.40824829, -0.70710678], [ 0.40824829, 0.70710678]]) ``` -------------------------------- ### Example Formula with Sum Coding and Custom Contrast Source: https://sciminds.ucsd.edu/bossanova/quickstart Demonstrates fitting models with different contrast coding schemes directly in the formula or via a contrasts dictionary. ```python model("y ~ sum(group) + x", data) # sum coding model("y ~ treatment(group, ref=B) + x", data) # treatment with ref="B" model("y ~ group + x", data, contrasts={\"group\": M}) # custom ndarray matrix ``` -------------------------------- ### Explore with Automatic Transforms Source: https://sciminds.ucsd.edu/bossanova/api/model This example demonstrates how `explore` automatically handles transformations like centering. Raw variable names in the formula are resolved. ```python m = model("y ~ center(x) + group", data).fit() m.explore("group ~ x@[50]") # auto-centers 50 ``` -------------------------------- ### Example: Gamma Family with Inverse Link Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Demonstrates creating a Gamma family object with its canonical 'inverse' link function. ```python >>> # Gamma with inverse link (canonical) >>> fam = gamma() >>> fam.name 'gamma' >>> fam.link_name 'inverse' ``` -------------------------------- ### Example Usage of solve_rtol Source: https://sciminds.ucsd.edu/bossanova/api/maths/tolerances Demonstrates how to use `solve_rtol` to obtain a relative tolerance and assert its correctness using `np.testing.assert_allclose`. ```python cond = 1e6 rtol = solve_rtol(cond) np.testing.assert_allclose(computed, expected, rtol=rtol) ``` -------------------------------- ### Example: Multiple Contrasts Conversion Source: https://sciminds.ucsd.edu/bossanova/api/domain/design Demonstrates converting multiple contrast vectors (A vs B, and (A,B) vs C) into a coding matrix. ```python >>> # Multiple contrasts: A vs B, and (A,B) vs C >>> array_to_coding_matrix([[-1, 1, 0], [-0.5, -0.5, 1]], n_levels=3) array([[-0.5 , -0.28867513], [ 0.5 , -0.28867513], [ 0. , 0.57735027]]) ``` -------------------------------- ### Example: Create Student-t Family Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Demonstrates how to instantiate a Student-t family with a specified degrees of freedom (df). The 'name' attribute confirms the family type. ```python >>> # Robust regression with df=10 >>> fam = tdist(df=10) >>> fam.name 'tdist' ``` -------------------------------- ### Load Data for One-Sample Tests Source: https://sciminds.ucsd.edu/bossanova/linear-models/one-sample Imports necessary libraries and loads the penguins dataset, dropping any rows with null values. This setup is common for both t-test and Wilcoxon signed-rank test examples. ```python import numpy as np import polars as pl from bossanova.model import model from bossanova import load_dataset np.random.seed(42) # Load penguins dataset penguins = load_dataset("penguins").drop_nulls() ``` -------------------------------- ### Unit Test Example Source: https://sciminds.ucsd.edu/bossanova/engineering An example of a unit test function name, indicating a test for the 'lmer' fit function returning parameters. Unit tests verify internal correctness. ```python test_lmer_fit_returns_params() ``` -------------------------------- ### get_varying_random_terms Source: https://sciminds.ucsd.edu/bossanova/api/containers/builders Get all random terms (Intercept + slope terms) for a VaryingSpec. ```APIDOC ## get_varying_random_terms ### Description Get all random terms (Intercept + slope terms) for a VaryingSpec. ### Method get_varying_random_terms ### Parameters #### Required Parameters - **spec** (VaryingSpec) - A VaryingSpec instance. ### Returns - **tuple[str, ...]** - Tuple of random term names, starting with “Intercept”. ``` -------------------------------- ### Instantiate Model with Different Contrast Codings Source: https://sciminds.ucsd.edu/bossanova/api/model Demonstrates how to instantiate the model using different contrast coding schemes directly within the formula or by providing custom contrast matrices. ```python model("y ~ sum(group) + x", data) # sum coding ``` ```python model("y ~ treatment(group, ref=B) + x", data) # treatment with ref="B" ``` ```python model("y ~ group + x", data, contrasts={"group": M}) # custom ndarray matrix ``` -------------------------------- ### Get Samples Source: https://sciminds.ucsd.edu/bossanova/api/maths/distributions Retrieves or generates cached Monte Carlo samples from the distribution. ```APIDOC ## get_samples ### Description Get or generate cached samples. ### Returns - Type: `ndarray` - Description: Sorted array of Monte Carlo samples from the distribution. ``` -------------------------------- ### Instantiate FitState Source: https://sciminds.ucsd.edu/bossanova/api/containers/fit Demonstrates how to create a FitState object with various fitting results. Ensure all required attributes are provided. ```python >>> import numpy as np >>> from fit import FitState >>> state = FitState( ... coef=np.array([1.0, 2.0]), ... vcov=np.eye(2), ... fitted=np.array([1.0, 2.0, 3.0]), ... residuals=np.array([0.1, -0.1, 0.0]), ... leverage=np.array([0.3, 0.3, 0.4]), ... df_resid=1.0, ... loglik=-10.0, ... ) ``` -------------------------------- ### Get True Parameter Value Source: https://sciminds.ucsd.edu/bossanova/api/domain/simulation Retrieves the true value for a specified parameter. ```python get_true_value(param: str | int) -> float ``` -------------------------------- ### Bossanova Full Workflow Example Source: https://sciminds.ucsd.edu/bossanova/cheatsheet Demonstrates a typical Bossanova workflow: fitting a model, inferring parameters with confidence intervals and p-values, exploring effects, and handling robust standard errors or bootstrapping. ```python # Full workflow — one chain m = model("y ~ x * group", data).fit().infer() m.params # estimates with CIs and p-values m.summary() # R-style summary table # Explore + infer m.explore("pairwise(group)").infer() m.effects # pairwise contrasts with CIs # Robust standard errors m.fit().infer(errors="HC3") # Bootstrap with parallel workers m.fit().infer(how="boot", n_boot=5000, n_jobs=4) # Mixed model with profile CIs on variance components m = model("y ~ x + (1 | subj)", data).fit().infer(how="profile") m.varying_spread # σ², τ² with profile CIs ``` -------------------------------- ### sum_coding_labels Source: https://sciminds.ucsd.edu/bossanova/api/domain/design Gets column labels for sum contrast. Labels correspond to the non-omitted levels. ```APIDOC ## sum_coding_labels ### Description Get column labels for sum contrast. This function returns labels for the non-omitted levels, which serve as column labels for the contrast matrix. ### Parameters - **levels** (list[str]) - Required - Ordered list of categorical level names. - **omit** (str | None) - Optional - Level to omit. Defaults to last level. ### Returns - **list[str]** - List of non-omitted level names (column labels). ``` -------------------------------- ### Set up random seed and print options Source: https://sciminds.ucsd.edu/bossanova/maths/diagnostics Initializes numpy for random number generation and sets print options for numerical precision. ```python import numpy as np np.random.seed(42) np.set_printoptions(precision=4, suppress=True) ``` -------------------------------- ### Match a string in formula Source: https://sciminds.ucsd.edu/bossanova/api/domain/formula Checks if the formula matches the expected string. No setup required. ```python match(expected: str) -> bool ``` -------------------------------- ### Get Samples Source: https://sciminds.ucsd.edu/bossanova/api/maths/distributions Retrieves cached random samples from the distribution or generates new ones if not available. ```APIDOC ## get_samples() ### Description Gets or generates cached samples from the distribution. ### Returns - **ndarray**: A sorted array of Monte Carlo samples from the distribution. ``` -------------------------------- ### Get Parameter Index Source: https://sciminds.ucsd.edu/bossanova/api/domain/simulation Retrieves the array index corresponding to a given parameter name or index. ```python get_idx(param: str | int) -> int ``` -------------------------------- ### tdist_initialize Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Initialize μ for Student-t family. Uses y directly as the starting value (like Gaussian). ```APIDOC ## tdist_initialize ### Description Initialize μ for Student-t family. Uses y directly as the starting value (like Gaussian). ### Parameters #### Path Parameters - **y** (ndarray) - Required - Response values (n,) - **weights** (ndarray | None) - Optional - Prior weights (n,). Unused for t-distribution. Defaults to None. ### Returns - **ndarray** - Initial mean values (n,) ``` -------------------------------- ### setup_ax Source: https://sciminds.ucsd.edu/bossanova/api/viz Sets up matplotlib axes, creating a new figure if necessary. ```APIDOC ## setup_ax ### Description Set up matplotlib axes, creating figure if needed. ### Parameters #### Path Parameters - **ax** (‘Axes | None’) - Required - Existing axes or None to create new figure. - **figsize** (tuple[float, float] | None) - Optional - Figure size if creating new figure. Default is None. ### Returns - **tuple[Figure, Axes]** - Tuple of (figure, axes). ``` -------------------------------- ### Get Previous Token Source: https://sciminds.ucsd.edu/bossanova/api/domain/formula Returns the last token that was consumed by the parser. Useful for context-dependent parsing rules. ```python previous() -> Token ``` -------------------------------- ### sequential_coding_labels Source: https://sciminds.ucsd.edu/bossanova/api/domain/design Gets column labels for sequential contrast. Labels represent successive differences between adjacent levels. ```APIDOC ## sequential_coding_labels ### Description Get column labels for sequential contrast. This function returns labels representing the successive differences between adjacent levels. ### Parameters - **levels** (list[str]) - Required - Ordered list of categorical level names. ### Returns - **list[str]** - List of successive difference labels like [‘B-A’, ‘C-B’, ...]. ### Examples ```python >>> sequential_coding_labels(['A', 'B', 'C']) ['B-A', 'C-B'] ``` ```python >>> sequential_coding_labels(['low', 'medium', 'high']) ['medium-low', 'high-medium'] ``` ``` -------------------------------- ### Get Display Digits Source: https://sciminds.ucsd.edu/bossanova/api/maths/config Retrieves the current number of significant figures for DataFrame display. Defaults to 4. ```python from bossanova import get_display_digits get_display_digits() # 4 ``` -------------------------------- ### Example: Fitting a Simple Linear Model Source: https://sciminds.ucsd.edu/bossanova/api/domain/fit Demonstrates fitting a simple linear model using `fit_model`. Requires `ModelSpec` and `DataBundle` to be constructed first. The output includes convergence status and coefficients. ```python >>> import numpy as np >>> from containers import build_model_spec, DataBundle >>> spec = build_model_spec( ... formula="y ~ x", ... response_var="y", ... fixed_terms=["Intercept", "x"], ... ) >>> bundle = DataBundle( ... X=np.array([[1.0, 1.0], [1.0, 2.0], [1.0, 3.0]]), ... y=np.array([2.0, 4.0, 6.0]), ... X_names=["Intercept", "x"], ... y_name="y", ... valid_mask=np.array([True, True, True]), ... n_total=3, ... ) >>> state = fit_model(spec, bundle) >>> state.converged True >>> state.coef # [Intercept, x] = [0, 2] array([0., 2.]) ``` -------------------------------- ### setup_ax Source: https://sciminds.ucsd.edu/bossanova/api/viz Sets up matplotlib axes, creating a figure if needed. This is useful for preparing a plotting area before rendering visualizations. ```APIDOC ## setup_ax ### Description Set up matplotlib axes, creating figure if needed. ### Parameters #### Path Parameters - **ax** (Axes | None) - Required - Existing axes or None to create new figure. - **figsize** (tuple[float, float] | None) - Optional - Figure size if creating new figure. Default: None ### Returns - **tuple[Figure, Axes]** - Tuple of (figure, axes). ``` -------------------------------- ### tdist_initialize Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Initializes the mean \(\mu\) for the Student-t family, using the response values directly as the starting point. ```APIDOC ## tdist_initialize ### Description Initialize \(\mu\) for Student-t family. Uses y directly as the starting value (like Gaussian). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **y** (ndarray) - Required - Response values (n,) - **weights** (ndarray | None) - Optional - Optional prior weights (n,). Unused for t-distribution. Default: None ### Request Example None ### Response #### Success Response (200) - **ndarray** - Initial mean values (n,) #### Response Example None ``` -------------------------------- ### Model Initialization and Usage Source: https://sciminds.ucsd.edu/bossanova/api/model Demonstrates how to initialize the BossaNova model with different formula structures and data inputs, including examples of sum coding and treatment coding with custom references. ```APIDOC ## model(formula, data, family, link, method, missing, contrasts) ### Description Initializes and fits a unified statistical model. The model type is inferred from the formula structure and family parameter. ### Parameters #### Path Parameters - **formula** (str) - R/Patsy-style formula (e.g., `"y ~ x"`, `"y ~ x + (1| group)"`). - **data** (DataFrame | str | None) - Input data. Accepts a Polars DataFrame, a file path (str to CSV/TSV/Parquet/JSON/NDJSON), or None for simulation-first workflows. - **family** (str) - Response distribution: `"gaussian"` (default), `"binomial"`, `"poisson"`, `"gamma"`, or `"tdist"`. - **link** (str | None) - Link function (`"identity"`, `"logit"`, `"log"`, etc.). None uses canonical link for family. - **method** (str | None) - Estimation method: `"ols"`, `"ml"`, or `"reml"`. None auto-selects. - **missing** (str) - Missing value handling: `"drop"` (default) or `"fail"`. - **contrasts** (dict | None) - Custom contrast matrices for categorical predictors. Dict mapping column names to ndarray matrices of shape `(n_levels, n_levels - 1)`. For named contrasts, use formula syntax instead: `sum(x)`, `treatment(x, ref=B)`, etc. ### Request Example ```python model("y ~ sum(group) + x", data) # sum coding model("y ~ treatment(group, ref=B) + x", data) # treatment with ref="B" model("y ~ group + x", data, contrasts={"group": M}) # custom ndarray matrix ``` ### Attributes - **contrasts** (dict | None) - Custom contrast matrices mapping column names to ndarray matrices. - **data** (DataFrame | str | None) - Input data as a Polars DataFrame, file path, or None for simulation. - **designmat** (DataFrame) - Fixed-effects design matrix as a named DataFrame. - **diagnostics** (DataFrame) - Model-level goodness-of-fit diagnostics. - **effects** (DataFrame) - Marginal effects or estimated marginal means (EMMs) table. - **family** (str) - Response distribution (`"gaussian"`, `"binomial"`, `"poisson"`, `"gamma"`, `"tdist"`). - **formula** (str) - R-style model formula string (e.g., `"y ~ x + (1 | group)"`). - **link** (str | None) - Link function (e.g., `"identity"`, `"logit"`, `"log"`). None uses canonical link. - **metadata** (DataFrame) - Model metadata: observation counts, parameter count, group counts. - **method** (str | None) - Estimation method (`"ols"`, `"ml"`, `"reml"`). None auto-selects. - **missing** (str) - Missing value handling: `"drop"` (default) or `"fail"`. - **params** (DataFrame) - Coefficient estimates table from the fitted model. - **power_results** (DataFrame) - Power analysis results from `simulate(power=...)`. - **predictions** (DataFrame) - Predictions table from the fitted model. - **resamples** (DataFrame | None) - Raw resampled values from bootstrap or permutation inference. - **simulations** (DataFrame) - Simulations table from data generation or response simulation. - **varying_corr** (DataFrame) - Random effect correlations for mixed models. ``` -------------------------------- ### Example: Sparse Cholesky factorization and solving Source: https://sciminds.ucsd.edu/bossanova/api/maths/linalg Demonstrates the usage of compute_sparse_cholesky to factor a sparse SPD matrix and then solve a linear system and compute the log-determinant using the resulting factorization object. ```python >>> import scipy.sparse as sp >>> A = sp.eye(100, format='csc') + sp.random(100, 100, density=0.1) >>> A = A @ A.T # Make SPD >>> factor = compute_sparse_cholesky(A) >>> x = factor.solve(b) >>> logdet = factor.logdet() ``` -------------------------------- ### tdist_loglik Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Placeholder function for tdist log-likelihood. Use tdist(df=...) factory to get the proper function. ```APIDOC ## tdist_loglik ### Description Placeholder - use tdist(df=...) factory to get proper function. ### Parameters #### Path Parameters - **y** (jnp.ndarray) - Required - **mu** (jnp.ndarray) - Required ### Returns - **jnp.ndarray** ``` -------------------------------- ### Fit Model with Dispatcher Source: https://sciminds.ucsd.edu/bossanova/api/domain/fit Use `fit_model` as the main entry point for fitting models. It automatically selects the appropriate solver (e.g., QR, IRLS, PLS, PIRLS) based on the `ModelSpec`. Handles rank-deficient design matrices by reducing and expanding coefficients. ```python fit_model(spec: ModelSpec, bundle: DataBundle, *, solver: str | None = None, max_iter: int | None = None, max_outer_iter: int = 10000, tol: float | None = None, verbose: bool = False, nAGQ: int = 1, use_hessian: bool = False) -> FitState ``` ```python >>> import numpy as np >>> from containers import build_model_spec, DataBundle >>> spec = build_model_spec( ... formula="y ~ x", ... response_var="y", ... fixed_terms=["Intercept", "x"], ... ) >>> bundle = DataBundle( ... X=np.array([[1.0, 1.0], [1.0, 2.0], [1.0, 3.0]]), ... y=np.array([2.0, 4.0, 6.0]), ... X_names=["Intercept", "x"], ... y_name="y", ... valid_mask=np.array([True, True, True]), ... n_total=3, ... ) >>> state = fit_model(spec, bundle) >>> state.converged True >>> state.coef # [Intercept, x] = [0, 2] array([0., 2.]) ``` -------------------------------- ### tdist_deviance Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Placeholder function for tdist deviance. Use tdist(df=...) factory to get the proper function. ```APIDOC ## tdist_deviance ### Description Placeholder - use tdist(df=...) factory to get proper function. ### Parameters #### Path Parameters - **y** (jnp.ndarray) - Required - **mu** (jnp.ndarray) - Required ### Returns - **jnp.ndarray** ``` -------------------------------- ### setup_ax Source: https://sciminds.ucsd.edu/bossanova/api/viz Set up matplotlib axes, creating the figure if needed. This function initializes axes for plotting. ```APIDOC ## setup_ax ### Description Set up matplotlib axes, creating figure if needed. ### Method setup_ax ### Parameters No parameters are explicitly documented for this function. ``` -------------------------------- ### Get Sum Coding Labels Source: https://sciminds.ucsd.edu/bossanova/api/domain/design Retrieves column labels for the sum contrast matrix, which correspond to the non-omitted levels. ```python sum_coding_labels(levels: list[str], omit: str | None = None) -> list[str] ``` -------------------------------- ### Get Singular Tolerance Source: https://sciminds.ucsd.edu/bossanova/api/maths/config Retrieves the current threshold for determining if a mixed model fit is singular. Defaults to 0.0001. ```python from bossanova import get_singular_tolerance get_singular_tolerance() # 0.0001 ``` -------------------------------- ### Create and Inspect DataBundle Source: https://sciminds.ucsd.edu/bossanova/api/containers/data Instantiate a DataBundle with observation data and inspect its properties like the number of observations (n) and parameters (p). ```python >>> import numpy as np >>> from data import DataBundle >>> bundle = DataBundle( ... X=np.array([[1, 0], [1, 1], [1, 2]]), ... y=np.array([1.0, 2.0, 3.0]), ... X_names=["Intercept", "x"], ... y_name="y", ... valid_mask=np.array([True, True, True]), ... n_total=3, ... ) >>> bundle.n 3 >>> bundle.p 2 ``` -------------------------------- ### arange Function Signature Source: https://sciminds.ucsd.edu/bossanova/api/maths/backend Creates an array with evenly spaced values. Accepts start, stop, and step parameters. ```python arange(start: int, stop: int | None = None, step: int = 1) -> Array ``` -------------------------------- ### Model Inference with CV Source: https://sciminds.ucsd.edu/bossanova/api/domain/infer Example of fitting a model and then inferring cross-validation diagnostics, including parameter importance and CV metrics. ```python m = model("y ~ x + z", data).fit().infer(how="cv") >>> m.params # Includes pre, pre_sd columns >>> m.diagnostics # Includes cv_rmse, cv_mae, cv_rsquared ``` -------------------------------- ### Initialize Linear Model (LM) in Python Source: https://sciminds.ucsd.edu/bossanova/cheatsheet Initializes a linear model using the bossanova library. Requires a formula string and a data source. ```python from bossanova import model m = model("y ~ x1 + x2", data) ``` -------------------------------- ### Create and Use Normal Distribution Source: https://sciminds.ucsd.edu/bossanova/api/maths/distributions Demonstrates creating a normal distribution using a factory function and calculating its CDF and PPF values. Ensure the 'distributions' module is imported. ```python from distributions import normal, t_dist d = normal(mean=0, sd=1) d.cdf(1.96) # 0.975 d.ppf(0.975) # 1.96 ``` -------------------------------- ### Get Distribution Samples Source: https://sciminds.ucsd.edu/bossanova/api/maths/distributions Retrieves or generates cached samples from the distribution. These samples can be used for various statistical analyses and simulations. ```python get_samples() -> np.ndarray ``` -------------------------------- ### Example: Asserting Algorithm Comparison with Absolute Tolerance Source: https://sciminds.ucsd.edu/bossanova/api/maths/tolerances Compares coefficients from QR and SVD solves using an absolute tolerance derived from `algorithm_comparison_atol`. This ensures that differences due to distinct rounding patterns are accounted for. ```python result_qr = qr_solve(X, y) result_svd = svd_solve(X, y) cond = np.linalg.cond(X) scale = max(np.abs(result_qr.coef).max(), 1.0) atol = algorithm_comparison_atol(scale, cond) np.testing.assert_allclose(result_qr.coef, result_svd.coef, atol=atol) ``` -------------------------------- ### tdist_robust_weights Source: https://sciminds.ucsd.edu/bossanova/api/maths/family Placeholder function for tdist robust weights. Use tdist(df=...) factory to get the proper function. ```APIDOC ## tdist_robust_weights ### Description Placeholder - use tdist(df=...) factory to get proper function. ### Parameters #### Path Parameters - **y** (jnp.ndarray) - Required - **mu** (jnp.ndarray) - Required - **scale** (float) - Required ### Returns - **jnp.ndarray** ``` -------------------------------- ### Get Sequential Coding Labels Source: https://sciminds.ucsd.edu/bossanova/api/domain/design Retrieves labels for sequential contrast matrix columns, representing successive differences between levels. ```python sequential_coding_labels(levels: list[str]) -> list[str] ``` ```python >>> sequential_coding_labels(['A', 'B', 'C']) ['B-A', 'C-B'] ``` ```python >>> sequential_coding_labels(['low', 'medium', 'high']) ['medium-low', 'high-medium'] ``` -------------------------------- ### Initialize ConvergenceMessage Source: https://sciminds.ucsd.edu/bossanova/api/maths/convergence Instantiate a ConvergenceMessage object with category, technical details, explanation, and an optional tip. ```python ConvergenceMessage(category: str, technical: str, explanation: str, tip: str | None = None) -> None ``` -------------------------------- ### Get Treatment Contrast Labels Source: https://sciminds.ucsd.edu/bossanova/api/domain/design Obtains the column labels for a treatment contrast matrix. These labels represent the non-reference levels. ```python >>> treatment_coding_labels(['A', 'B', 'C']) ['A', 'B'] ``` -------------------------------- ### ExploreParser Initialization Source: https://sciminds.ucsd.edu/bossanova/api/domain/marginal Initialize `ExploreParser` with a list of tokens and the original formula string for error reporting. This parser handles the recursive descent parsing of explore formula syntax. ```python ExploreParser(tokens: list[Token], formula: str) -> None ``` -------------------------------- ### Get Sum Contrast Labels Source: https://sciminds.ucsd.edu/bossanova/api/domain/design Retrieves the column labels for a sum contrast matrix. These labels correspond to the non-omitted levels. ```python >>> sum_coding_labels(['A', 'B', 'C']) ['A', 'B'] ``` -------------------------------- ### jit Source: https://sciminds.ucsd.edu/bossanova/api/maths/backend JIT-compile a function using JAX. For the NumPy backend, this is a no-op. ```APIDOC ## jit ### Description JIT-compile a function using JAX. For the NumPy backend, this is a no-op. ### Signature ```python jit(fn: Callable, *, donate_argnums: tuple[int, ...] | None = None) -> Callable ``` ``` -------------------------------- ### Get Model Type Source: https://sciminds.ucsd.edu/bossanova/api/domain/compare Retrieves the type string (e.g., 'lm', 'glm', 'lmer', 'glmer') for a fitted model instance. ```python get_model_type(model: Any) -> str ``` -------------------------------- ### Load Dataset and Initialize for Correlation Tests Source: https://sciminds.ucsd.edu/bossanova/linear-models/correlation This code block sets up the environment by importing necessary libraries and loading the 'penguins' dataset, dropping any rows with missing values, which is crucial for correlation analysis. ```python import numpy as np import polars as pl from bossanova.model import model from bossanova import load_dataset np.random.seed(42) # Load penguins dataset penguins = load_dataset("penguins").drop_nulls() ``` -------------------------------- ### Scanner Attributes Source: https://sciminds.ucsd.edu/bossanova/api/domain/formula Holds the input code, current scanning position, start of the current token, and the list of generated tokens. ```python code = code ``` ```python current = 0 ``` ```python start = 0 ``` ```python tokens: list[Token] = [] ```