Skip to content

Instantly share code, notes, and snippets.

View albertbuchard's full-sized avatar

Albert Buchard albertbuchard

View GitHub Profile
@albertbuchard
albertbuchard / test_preweight_equivalence_full.py
Last active May 15, 2025 18:40
O3 Answers: Pre-weighting ≡ IPAW (in lmer)
"""
This example demonstrates that fitting a weighted linear mixed-effects model using lmer(weights = …)
is algebraically equivalent to pre-multiplying the outcome and all predictors (including intercepts)
by the square root of the weights and fitting an unweighted model on the transformed data.
The test validates that this "pre-weight and refit" strategy yields identical fitted values and
is especially useful when packages like clubSandwich prohibit prior weights in robust variance estimation.
Includes realistic longitudinal synthetic data with fixed and random effects, dropout, and continuous covariates.
"""
from typing import List
@albertbuchard
albertbuchard / entropy_balanced_ipaw.py
Created May 25, 2025 01:20
Entropy-Balanced IPAW: Efficient implementation of ridge-penalised entropy balancing applied to inverse probability of attrition weights (IPAW), ensuring finite, non-negative weights for longitudinal studies.
import numpy as np
import pandas as pd
import cvxpy as cp
from typing import Sequence, Union
def entropy_balance_ipaw(
df: pd.DataFrame,
*,
@albertbuchard
albertbuchard / PSM Bootstrap.py
Last active September 15, 2025 09:29
PSM Bootstrap
from typing import Optional
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
import statsmodels.formula.api as smf
from statsmodels.tools.sm_exceptions import (
ConvergenceWarning,