Flexible synthetic data for nested, longitudinal and relational multi-table data.
flexsynth generates utility-oriented synthetic data for supported flat, nested, longitudinal, and multi-table relational databases, working natively in long format — no pivoting nested or longitudinal data to wide. Version 0.3.0 adds general relational DAG schemas (Star N:1, Fan 1:N + 1:M, Snowflake chains, Associative M:N bridges, 3NF surrogate primary keys, and Coherent Diamond DAGs) alongside native zero-conversion temporal synthesis for Date, POSIXct, POSIXlt, difftime, and hms.
It ships two engines behind one interface:
-
Track A — high-utility (default). A sequential conditional-synthesis engine (CART,
rangerrandom forests, conditional-inference trees, parametric methods, PMM, logistic/multinomial/Poisson regression) that models within-unit longitudinal dependence and cross-table relationships. No formal privacy guarantee; ships empirical utility and disclosure-risk diagnostics to inform review of a proposed release. -
Track B — differentially private (opt-in).
synth(..., privacy = dp_control(...))andsynth_linked(..., privacy = dp_control(...))implement person-level (ε, δ) mechanisms with exact Laplace L1 / Gaussian zCDP accounting and fail closed on unrecognised or unbounded non-public domains. A governed release still requires independent review of the privacy unit, public-domain assumptions, contribution caps, and selected mechanism.
Synthetic data is not anonymisation, and Track A output must never be described as differentially private.
Features
-
Supported structures, native long format. Flat, nested / longitudinal (repeated visits), prefix-tree hierarchies (
~ id / visit / test), and general acyclic multi-table schemas declared withrel_schema(),rel_fk(),rule_sum(), andas_rel_schema()(StarN:1, Fan1:N+1:M+ sum conservation, Snowflake, AssociativeM:Nbridge, 3NF surrogate PKs, Diamond DAGs). -
Native temporal & chronological synthesis. Zero-conversion handling of
Date,POSIXct,POSIXlt,difftime, andhms(temporal_control()), preserving timezone/units/sub-second precision, cyclical calendar conditioning, cross-column offset ordering (e.g.discharge_date >= admit_date), and fail-closed Track B differential privacy bounds. - Longitudinal dependence. Learned rows-per-unit count model, initial-state model, and a lag-1 Markov transition model, so within-unit autocorrelation across visits is preserved. Subject-invariant baseline columns are synthesised once per unit and broadcast.
-
Linked & relational multi-table. Parent-first topological generation with foreign keys sampled cleanly from synthetic parents (referential integrity by construction), zero-inflated children-per-parent counts, multi-parent lookups, and cross-table predictors.
check_linkage()verifies key uniqueness and the absence of orphans. -
Extensible methods.
sample,cart,forest(ranger),ctree,norm,normrank,pmm,logreg,polyreg, andpoissonbuilt in; add your own withregister_method(). -
Constraints / temporal logic.
rule()enforces row-wise or per-unit constraints (e.g.dbp <= sbp, monotone dates) by unit-grain rejection sampling, whilerule_sum()reconciles grouped totals across relational tables. -
Pooled inference.
pool_synth()(single-table and multi-tablesynth_linked_result) /synth_glm()implement the published fully-synthetic variance rules (synthpop / Reiter) acrossmsynthetic datasets.compare_estimates()scores real-vs-synthetic analyses by confidence-interval overlap. -
Diagnostics.
diagnose()(marginal fit, correlation-matrix difference, categorical association via Cramer’s V, propensity pMSE) anddisclosure_risk()(replicated uniques, distance-to-closest-record, membership-inference AUC, and TCAP attribute-disclosure viatarget =). -
Performance. Optional
data.tablefast-path and parallel replicates (synth_control(parallel = TRUE)) with reproducible L’Ecuyer streams.
Installation
# install.packages("remotes")
remotes::install_github("lauyeehow1986-hub/Flexsynth")The package installs with base-R dependencies. The default method = "cart" requires the suggested rpart package; ranger / partykit unlock additional tree methods, and data.table unlocks the row-binding fast-path. Use method = "sample" when only base R is available.
Quick start
Multiple linked tables, synthesised jointly
patients <- data.frame(id = 1:50, sex = sample(c("F", "M"), 50, TRUE))
adm <- do.call(rbind, lapply(patients$id, function(pid) {
n <- 1 + rpois(1, 0.6)
data.frame(id = pid, admission_id = seq_len(n), los = 1L + rpois(n, 3))
}))
res <- synth_linked(
tables = list(patients = patients, admissions = adm),
structures = list(patients = ~ id,
admissions = ~ id / admission_id),
keys = list(patients = "id",
admissions = c("id", "admission_id")),
seed = 1
)
syn <- as.list(res)
check_linkage(syn, keys = list(patients = "id",
admissions = c("id", "admission_id")))Diagnostics and disclosure risk
syn <- as.data.frame(synth(df, structure = ~ id / visit, seed = 1))
analysis_vars <- c("age", "sbp") # exclude generated structure keys
d <- diagnose(real = df, syn = syn, vars = analysis_vars)
plot(d) # overlaid marginals
disclosure_risk(real = df, syn = syn, quasi = analysis_vars)Pooled inference from synthetic data
# Analyse all m synthetic sets with a published fully-synthetic pooling rule.
# A single set analysed naively generally under-states synthesis uncertainty.
res <- synth(df, structure = ~ id / visit, m = 10, seed = 1)
synth_glm(res, sbp ~ age) # pooled linear model
# any estimator works via pool_synth(res, function(d) <fit returning coef/vcov>)Opt into differential privacy (Track B)
dp <- dp_control(epsilon = 1, delta = 1e-6, mechanism = "gaussian",
bounds = list(visit = c(1, 2), age = c(18, 100), sbp = c(60, 240)))
dp_res <- synth(df, structure = ~ id, privacy = dp, seed = 1)
dp_res$privacy # the (ε, δ) accounting recordTrack B supports three release shapes:
- a flat table (
~ id); - a longitudinal table (
~ id / visit) using a bounded DP Markov model; and - a tree-linked hierarchy via
synth_linked(), using the root entity as the privacy unit.
dp_control() also exposes privately learned domains, cross-table conditioning, higher-order transitions, adaptive marginal selection, Private-PGM reconciliation, and AIM-style models. These controls trade statistical fidelity, cell sparsity, runtime, and privacy budget; they are not universally beneficial.
A governed DP release requires more than setting epsilon: define the privacy unit and public domain assumptions, justify contribution caps, retain the accounting record, review utility at the intended analysis grain, and obtain independent privacy review. See vignette("differential-privacy") for the supported combinations, accounting model, and limitations.
Learn more
- Package website: https://lauyeehow1986-hub.github.io/Flexsynth/
-
vignette("getting-started")— getting started -
vignette("valid-inference")— pooled inference and attribute-disclosure (TCAP) -
vignette("nested-longitudinal")— repeated-measures data -
vignette("linked-cardiac")— multi-table linked synthesis -
vignette("star-and-fan-schemas")— Star, Fan, Snowflake, Bridge & Diamond DAGs + native temporal synthesis -
vignette("differential-privacy")— Track B -
docs/roadmap.md— phased delivery and what’s next