Utilities¶
Reporting¶
- hdfe_stream.etable(models, **kwargs)[source]¶
pf.etablefor streaming results: a regression table ofHDFEResultandHDFEMultimodels, mixed freely with ordinary pyfixest models.A multi-model result expands into one column per model. The spacing of the fixed-effect side is normalized, so
"a + b"and"a+b"share a row (pf.etableitself matches rows on the literal text). Withtype="tex", labels are escaped for LaTeX.- Parameters:
models (HDFEResult, HDFEMulti, or a list of them and pyfixest models) – The models, one column each.
**kwargs – Passed to
pf.etable:type,model_stats,labels,felabels,file_name, …
- Returns:
object – What
pf.etablereturns for thetypeasked for.
Examples
>>> etable([fit1, fit2], type="df", model_stats=["N", "se_type", "r2"])
Multiple testing¶
- hdfe_stream.bonferroni(models, param)[source]¶
Bonferroni-adjusted p-values for
param = 0across models.Each p-value, from
HDFEResult.tidy, is multiplied by the number of hypotheses (models times parameters), capped at 1. As pyfixest’sbonferroni, which takes one parameter.- Parameters:
models (HDFEResult, HDFEMulti, or a list of them) – The models.
param (str or list of str) – The coefficient(s) tested in every model; each must be in every model.
- Returns:
polars.DataFrame – One row per model and parameter:
model(its position),fml, thetidycolumns, andBonferroni Pr(>|t|).
- hdfe_stream.holm(models, param)[source]¶
Holm’s step-down adjusted p-values for
param = 0across models.The p-values are sorted from smallest to largest, the j-th of m is multiplied by m - j + 1, and each adjusted p-value is the running maximum of those, capped at 1. Like Bonferroni’s, the adjustment controls the familywise error rate under any dependence between the tests, and no adjusted p-value is larger than Bonferroni’s, so it rejects at least as often (Holm, 1979).
- Parameters:
models – As in
bonferroni.param – As in
bonferroni.
- Returns:
polars.DataFrame – As in
bonferroni, withHolm Pr(>|t|).
- hdfe_stream.rwolf(models, param, reps=9999, seed=None, weights_type='rademacher')[source]¶
Romano-Wolf adjusted p-values for
param = 0across models, from the wild cluster bootstrap.Every model is bootstrapped on the same draws (each cluster gets the same weight in every model), and the hypotheses are stepped down from the largest absolute t statistic: each one’s p-value is the share of draws whose largest absolute bootstrap t statistic, over the hypotheses not yet stepped past, reaches its t statistic, with one added to the count and to the draws, and the p-values are then made monotone (Romano and Wolf 2005; Clarke, Romano and Wolf 2020). This controls the familywise error rate while using the dependence between the tests, so it rejects more than Bonferroni or Holm when they are correlated. As pyfixest’s
rwolf, with the same draws for the same seed.- Parameters:
models (HDFEResult, HDFEMulti, or a list of them) – Fit with the same
bootcluster=.param (str or list of str) – The coefficient(s) tested in every model.
reps (int, default 9999) – Bootstrap draws.
seed (int, optional) – Seed for the draws.
weights_type ({"rademacher", "mammen", "webb", "norm"}, default "rademacher") – The distribution of the cluster weights.
- Returns:
polars.DataFrame – As in
bonferroni, withRW Pr(>|t|).
- hdfe_stream.wyoung(models, param, reps=9999, seed=None, weights_type='rademacher')[source]¶
Westfall-Young adjusted p-values for
param = 0across models, from the wild cluster bootstrap.The free step-down resampling method (Westfall and Young 1993): each test’s t statistic, and each draw’s, is turned into a p-value from the t distribution with G - 1 degrees of freedom; in each draw, the p-values are replaced by their running minimum over the tests with larger original p-values; and a test’s adjusted p-value is the share of draws in which that minimum is at most its own p-value, made monotone. As pyfixest’s
wyoung, with the same draws for the same seed.
Run directories¶
- hdfe_stream.cleanup(workdir=None, older_than_hours=None, force=False, dry_run=False)[source]¶
Remove leftover run directories, e.g. from killed processes.
Only directories created by hdfe_stream (they carry a marker file) are touched, and empty ones named like them (whose files were deleted but which could not be removed while a file in them was still open, as on NFS); every new fit removes those too.
Runs of this process are removed unless a fit is still running in them (this includes result files of finished fits; their
resid()andfixef()stop working). Skipped unlessforce=True: runs of other processes still alive on this host, runs from other hosts (their liveness can’t be checked), and runs younger thanolder_than_hoursif given.- Parameters:
workdir (str or Path, optional) – The directory to sweep. Default: the
HDFE_STREAM_WORKDIRenvironment variable if set, else the system temporary directory.older_than_hours (float, optional) – Skip runs younger than this.
force (bool, default False) – Remove runs of live processes and of other hosts too.
dry_run (bool, default False) – List what would be removed, and remove nothing.
- Returns:
list of (str, int) –
(path, bytes)for each run that was (or, withdry_run, would be) removed.
Warnings¶
ExperimentalWarning marks a method that goes beyond what its authors developed.
Packages built on hdfe_stream.core raise subclasses of it for their own experimental
features. To silence all of them:
import warnings
import hdfe_stream
warnings.filterwarnings("ignore", category=hdfe_stream.ExperimentalWarning)
- class hdfe_stream.ExperimentalWarning[source]¶
A fit uses a method that goes beyond what its authors developed or validated.
Packages built on
hdfe_stream.coresubclass it for their own experimental features, so a user can silence one package’s warnings or, with this class, all of them:warnings.filterwarnings("ignore", category=hdfe_stream.ExperimentalWarning)- __init__(*args, **kwargs)¶
- classmethod __new__(*args, **kwargs)¶
Simulated data¶
Simulated matched employer-employee panels with AKM structure.
Used by the test suite and the examples, and useful for trying the library out before pointing it at real data:
from hdfe_stream import feols_stream
from hdfe_stream.simulate import simulate_akm
simulate_akm(n_workers=50_000).write_parquet("sim.parquet")
feols_stream("log_earn ~ age_squared | worker_id + firm_id + year",
"sim.parquet").summary()
simulate_akm is the base panel: workers move between firms over a run of
years, and log earnings are a worker effect plus a firm effect plus an age
profile plus noise. Because the worker and firm effects are drawn explicitly,
the true variance decomposition is known, and there is enough worker mobility
to connect the firms into one component.
simulate_rich adds the columns the wider feature set needs – categoricals,
coarser cluster variables, weights, instruments, a second outcome, a column
with missing values – and simulate_trends adds worker-specific time trends
for varying-slopes (FEIS) models. simulate_bottleneck builds a panel whose
variance components are weakly identified, for leave-out estimation. All of
them take a seed and are deterministic.
Only numpy and Polars are used, so nothing here needs the optional dependencies.
- hdfe_stream.simulate.simulate_akm(n_workers=50000, n_firms=None, years=range(2005, 2015), p_move=0.08, p_obs=0.85, sd_worker=0.4, sd_firm=0.25, sd_noise=0.3, seed=0, keep_effects=False)[source]¶
An AKM panel: one row per worker-year actually observed.
Worker and firm effects are positively assorted – better workers tend to be at better firms – so the firm effect is not orthogonal to the worker effect and the fixed effects genuinely have to be estimated jointly.
- Parameters:
n_workers (int, default 50_000) – The number of workers.
n_firms (int, optional) – The number of firms. Default: n_workers / 15 (at least 50), which keeps firms large enough to be identified.
years (iterable of int) – The years observed (default 2005-2014).
p_move (float, default 0.08) – Probability a worker changes firm between consecutive years. Mobility is what connects firms, so lowering it a lot will split the data into several components.
p_obs (float, default 0.85) – Probability a worker is observed in a given year, so the panel is unbalanced.
sd_worker (float) – Standard deviations of the worker effect (0.4), the firm effect (0.25) and the residual (0.3).
sd_firm (float) – Standard deviations of the worker effect (0.4), the firm effect (0.25) and the residual (0.3).
sd_noise (float) – Standard deviations of the worker effect (0.4), the firm effect (0.25) and the residual (0.3).
seed (int or anything
numpy.random.default_rngaccepts, default 0) – The seed; the panel is deterministic given it.keep_effects (bool, default False) – Also return the worker and firm effects that generated the data, as
true_worker_effectandtrue_firm_effect. Off by default so they cannot be used as regressors by accident. Useful for checking an estimator against a known answer – in particular for bias corrections to variance components, where the quantity being estimated is a moment of exactly these columns.
- Returns:
polars.DataFrame – Shuffled so it is not sorted on disk, with columns
worker_id(int64, deliberately not dense),firm_id(string),year(int32),age(float),age_squared,age_cubed(age polynomials scaled into a sane range) andlog_earn(the outcome).
Examples
>>> simulate_akm(n_workers=1_000_000).write_parquet("sim.parquet")
- hdfe_stream.simulate.simulate_rich(n_workers=50000, n_firms=None, seed=0, extra_seed=9, **kwargs)[source]¶
simulate_akmplus the columns that exercise the wider feature set.On top of the base panel, it adds:
state,region: coarse firm-level groupings, for clustering on something that is not a fixed effect (regionis coarser still);cohort: year-of-birth decade, another non-fixed-effect cluster variable;treat,occ,cat: a binary, an integer-coded and a string categorical, forC(),i()and interaction terms;y2: a second outcome, for multiple-estimation formulas;x_na: a covariate that is null in about 5% of rows;wa,wf: analytic and frequency weights;z1,z2,x2: two instruments and the endogenous regressor they predict;y_iv: an outcome that depends onx2, for 2SLS.
log_earnalso picks up an occupation effect and a post-2010 treatment effect, soi(year, treat)event-study terms have something to find.- Parameters:
n_workers – As in
simulate_akm.n_firms – As in
simulate_akm.seed – As in
simulate_akm.extra_seed (default 9) – The seed of the added columns.
**kwargs – Passed to
simulate_akm.
- Returns:
polars.DataFrame
- hdfe_stream.simulate.simulate_trends(n_workers=600, n_firms=60, seed=3, **kwargs)[source]¶
simulate_akmplus worker-specific time trends, for FEIS models.Each worker gets their own linear and quadratic trend in
t(the year as a float), soy ~ x | worker_id[t] + firm_idis the correctly specified model and a plain worker intercept is not. It adds:t,t2: the year, and its centered square;x,v: an exogenous covariate and an unobservable;xe,z: an endogenous regressor and its instrument;wa: analytic weights;y: the outcome, generated with the worker trends in it.
Defaults are small because the brute-force comparison for varying slopes needs one dummy per worker per slope.
- Parameters:
n_workers – As in
simulate_akm, with smaller defaults (600, 60 and 3).n_firms – As in
simulate_akm, with smaller defaults (600, 60 and 3).seed – As in
simulate_akm, with smaller defaults (600, 60 and 3).**kwargs – Passed to
simulate_akm.
- Returns:
polars.DataFrame
- hdfe_stream.simulate.simulate_bottleneck(n_bridge=6, firms_per_block=8, movers_per_block=150, stayers_per_firm=8, block_gap=0.5, sd_worker=0.4, sd_firm=0.3, sd_noise=0.15, seed=0, keep_effects=False)[source]¶
A panel whose AKM variance components are weakly identified.
Two blocks of firms with plenty of mobility inside each and only
n_bridgeworkers moving between them: a bottleneck in the mobility network. The difference between the blocks’ average firm effects is then one linear combination of the effects that is estimated far worse than the rest, so one eigenvalue dominates the estimator’s variance – KSS’s weakly identified case, where the normal interval undercovers and the q = 1 interval is the one to use.leave_out_kss(..., se=True)reports both.- Parameters:
n_bridge (int, default 6) – Workers moving between the blocks. Fewer is weaker; with only one or two, the leading direction rests on so few rows that even the q = 1 theory’s conditions fail, and six is a comfortable middle.
firms_per_block (int) – The size of each block (8, 150 and 8). Movers are observed four years across two firms of their block, stayers three years at one.
movers_per_block (int) – The size of each block (8, 150 and 8). Movers are observed four years across two firms of their block, stayers three years at one.
stayers_per_firm (int) – The size of each block (8, 150 and 8). Movers are observed four years across two firms of their block, stayers three years at one.
block_gap (float, default 0.5) – Added to every firm effect in the second block. It sets how far the badly estimated direction’s true value is from zero, which is what decides whether the ordinary interval merely widens or badly undercovers.
sd_worker (float) – Standard deviations of the effects (0.4 and 0.3) and the residual (0.15).
sd_firm (float) – Standard deviations of the effects (0.4 and 0.3) and the residual (0.15).
sd_noise (float) – Standard deviations of the effects (0.4 and 0.3) and the residual (0.15).
seed (int or anything
numpy.random.default_rngaccepts, default 0) – The seed.keep_effects (bool, default False) – Also return the effects that generated the data, as in
simulate_akm.
- Returns:
polars.DataFrame – With
worker_id,firm_idandlog_earn(and, withkeep_effects,true_worker_effectandtrue_firm_effect).
IV diagnostics from sums¶
The algebra behind HDFEResult.iv_diag, for estimators built on
hdfe_stream.core (it works on cross-products and score covariances, never
on data).
Instrumental-variable diagnostics from sums: identification and overidentification tests for any linear IV or GMM estimator whose moments are sums over rows or clusters.
Everything here works on small matrices – cross-products of the instruments and regressors, and the (cluster-)robust covariances of their scores – never on data, so an estimator that streams its rows computes those sums in a pass it makes anyway and hands them over. feols_stream’s IV fits use it, and so does dpd-stream for GMM.
The statistics, with ivreg2’s conventions (Baum, Schaffer and Stillman):
Underidentification: Kleibergen and Paap’s (2006) rk LM test (Anderson’s canonical-correlation LM under iid errors).
Weak identification: the Kleibergen-Paap rk Wald F (Cragg-Donald’s F under iid errors), and per endogenous regressor Sanderson and Windmeijer’s (2016) conditional F. The F statistics take ivreg2’s small-sample factor, (N - L)/N, times (G - 1)/G with G clusters (with N/(N - 1) in place of the first factor’s N), so that with one endogenous regressor the SW F is the first-stage F.
Overidentification: Hansen’s J at the two-step efficient GMM estimate, weighted by the moments’ covariance at the given residuals (ivreg2’s J after robust 2SLS), or Sargan’s statistic under iid errors.
With
identification, also each endogenous regressor’s first-stage partial R^2 and Shea’s (1997) partial R^2 (Godfrey’s 1999 formula), and, with one endogenous regressor, Montiel Olea and Pflueger’s (2013) effective F with its simplified critical value for 2SLS.Weak-instrument-robust inference: the Anderson-Rubin (1949) test of the endogenous regressors’ coefficients (robust as the variance is), and with one endogenous regressor its confidence set (
anderson_rubin).Endogeneity: the C statistic (difference-in-Sargan/Hansen) for treating the endogenous regressors as exogenous, as ivreg2’s
endog()(c_statistic).
kp_rk follows ranktest’s SVD algebra (Kleibergen and Paap 2006, section 3).
- hdfe_stream.core.ivtests.identification(ZZ, ZY, YY, OU, OV, *, n_obs, n_inst, n_clusters=None, dof_extra=0, endog=None, exog=None, sw='2sls')[source]¶
The identification tests from the partialled moments.
ZZ = Z1’Z1 (L1 x L1), ZY = Z1’Y (L1 x Ke), YY = Y’Y: the excluded instruments Z1 and the endogenous regressors Y, both net of the included exogenous regressors (and of anything absorbed); OU, OV the covariances of vec(Z1’Y) and vec(Z1’V), V = Y - Z1 Pi (from
iid_omegasfor iid errors).n_obs,n_inst(all instruments),n_clustersanddof_extragive the F statistics’ factor (weak_f).swpicks the Sanderson-Windmeijer statistic:“2sls” (ivreg2’s): for each endogenous regressor, its 2SLS regression on the others; the Wald test, with OV, that the excluded instruments do not explain the residuals, chi2(L1 - Ke + 1), and its F.
“gmm” (Windmeijer’s robust test, as Stata’s underid): the J statistic of that auxiliary regression estimated by two-step efficient GMM with the moments’ covariance from OU, chi2(L1 - Ke + 1).
Collinear excluded instruments are dropped first, as ranktest does. Returns a dict with
kp_lm,kp_wald(withF) andsanderson_windmeijer(one entry per endogenous regressor).
- hdfe_stream.core.ivtests.kp_rk(Qzz, Pi, Qyy, Omega)[source]¶
Kleibergen and Paap’s rk statistic for rank(Pi) = K - 1.
Qzz = Z’Z (L x L) and Qyy = Y’Y (K x K), both net of the included exogenous regressors; Pi = Qzz^-1 Z’Y, the first-stage coefficients; Omega the covariance of vec(Z’u) (columns stacked, one per regressor), unnormalized, with u = Y for the LM form and the first-stage residuals for the Wald form. Returns (statistic, degrees of freedom).
- hdfe_stream.core.ivtests.weak_f(wald, df1, n_obs, n_inst, n_clusters=None, dof_extra=0)[source]¶
ivreg2’s F form of a Wald statistic of
df1restrictions on the first stage: wald/N (N - L - dof_extra)/df1, or with G clusters wald/(N - 1) (N - L - dof_extra) (G - 1)/G / df1. L counts all the instruments (excluded and included exogenous, the constant among them);dof_extrathe parameters partialled out besides them, such as absorbed fixed effects. Returns (F, df2).
- hdfe_stream.core.ivtests.iid_omegas(ZZ, ZY, YY, n_obs)[source]¶
The covariances of vec(Z’Y) and vec(Z’V) under iid errors, V the first-stage residuals: kron(Y’Y/N, Z’Z) and kron(V’V/N, Z’Z), for Anderson’s LM and Cragg and Donald’s Wald statistic.
- hdfe_stream.core.ivtests.hansen_j(ZX, ZY, S)[source]¶
Hansen’s J: the minimized two-step GMM criterion with weight S^-1 (S the moments’ covariance, unnormalized, at the residuals of a first estimate). ZX = Z’X, ZY = Z’y. Returns (J, df, p); df = rank(S) - K.
- hdfe_stream.core.ivtests.sargan(ZZ, Ze, ee, n_obs, k)[source]¶
Sargan’s statistic, N e’P_Z e / e’e, from Z’Z, Z’e and e’e at the 2SLS residuals; chi2(L - k). Returns (statistic, df, p).
- hdfe_stream.core.ivtests.partial_r2(ZZ, ZY, YY, endog=None)[source]¶
Each endogenous regressor’s first-stage partial R^2 (of the excluded instruments, net of the included exogenous regressors) and Shea’s (1997) partial R^2, by Godfrey’s (1999) formula: [(Y’Y)^-1]_kk / [(Y^’Y^)^-1]_kk, Y^ the first-stage fitted values (all net of the exogenous regressors, which leaves those diagonal elements as they are with them). With one endogenous regressor the two are equal. Returns {name: {“partial”: …, “shea”: …}}.
- hdfe_stream.core.ivtests.effective_f(ZZ, ZY, OV, *, n_obs, n_inst, n_clusters=None, dof_extra=0, tau=0.1, alpha=0.05)[source]¶
Montiel Olea and Pflueger’s (2013) effective F for one endogenous regressor: pi’(Z’Z) pi / tr(Sigma (Z’Z)), with pi its first-stage coefficients on the excluded instruments (net of the exogenous regressors) and Sigma their robust variance, from OV (the covariance of Z’v), with ivreg2’s small-sample factor (
weak_f): under iid errors it is the first-stage F. Also the simplified critical value for 2SLS (Patnaik’s approximation, worst-case biastaurelative to OLS’s, sizealpha), with its effective degrees of freedom. Returns a dict.
- hdfe_stream.core.ivtests.anderson_rubin(ZZ, ZYa, OVa, *, n_obs, n_inst, n_clusters=None, dof_extra=0, beta0=None, level=0.95, center=None, scale=None)[source]¶
The Anderson-Rubin test of H0: the endogenous regressors’ coefficients are
beta0(default 0): the Wald test that the excluded instruments do not explain y - Y beta0 (net of the exogenous regressors), with the variance of the first-stage residuals’ moments, so as robust as that is. Valid however weak the instruments.ZZ = Z1’Z1; ZYa = Z1’[Y y] (L1 x (Ke + 1)), y last; OVa the covariance of vec(Z1’[V v]), V and v their first-stage (reduced-form) residuals. Returns the chi2(L1) statistic, its F (
weak_f) and p-values, and with one endogenous regressor the confidence set atlevel: the beta0 the test does not reject, as a list of intervals (they can be unbounded, or two rays, or everything).centerandscale(an estimate and its standard error) place the search’s grid.
- hdfe_stream.core.ivtests.c_statistic(ZX, Zy, S, tested)[source]¶
The C (difference-in-Sargan/Hansen) statistic for the moments
tested(indices): Hansen’s J with every moment less J without them, both weighted by (submatrices of) the full set’s covariance S, so it is never negative (Hayashi 2000). As ivreg2’sendog(), with the endogenous regressors added to the instruments as the tested moments, and S at the residuals of the model that treats them as exogenous (OLS). Returns (C, df, p); df = the tested moments’ rank.
Refit bootstrap¶
The machinery of a bootstrap that resamples whole units, or whole clusters of
units, with replacement and refits an estimator on each draw, for estimators
built on hdfe_stream.core (diff-stream’s refit_bootstrap uses it). The
resamples are written to disk in bounded memory, one per worker at a time;
refits run in the parent process or in worker processes, each with its share of
the job’s threads and memory. Workers start once and fit one draw after another. The consumer supplies the fit and decides what a draw must satisfy.
- hdfe_stream.core.refit.refit_draws(snapshot, scratch, *, fit, task, width, reps, budget, preprocess_mb, key, sort_columns, seed=None, workers=1, threads=None, memory_gb=None, select=None, within=None, time_column=None, expected_groups=None, expected_rows=None, worker_minimum_gb=0.5, preload=(), persistent_workers=True, worker_draws=200)[source]¶
Draw
repsresamples of the groups ofsnapshotand refit each withfit.snapshotis a Parquet file of the analysis sample’s source rows andscratchan existing directory for the run.fitis an importable function (it is pickled by reference for the workers) called with a dict:taskplusdraw,path(the resample),unit_column(each copy’s unit ID),workdir,dates(the values oftime_columnit covers),rows, and thethreadsandmemory_gbthe refit may use. It returns thewidthcoefficients, or raisesValueError(orFloatingPointError,LinAlgError) for a draw that cannot be estimated.Groups are
key(withwithin: clusters ofwithinunits), sorted bysort_columnsand filtered byselect(frame);expected_groupsandexpected_rowscheck the staging against the original fit.seedfixes the draws for a given group order.workers> 1 runs refits in worker processes, which first import the modules inpreload(a package’s scheduler defaults) and needworker_minimum_gbeach. They are started once and given one draw after another, each restarted afterworker_drawsdraws (so that memory a runtime keeps cannot accumulate); withpersistent_workers=Falseeach draw has a fresh process instead. Either way the draws are the same, and only one resample per worker is on disk at a time.
- hdfe_stream.core.refit.refit_workers(reps, workers, threads)[source]¶
Validate the run’s options; return (workers used, job threads, threads per worker).
- class hdfe_stream.core.refit.RefitDraws[source]¶
What
refit_drawsreturns: the draws (reps by coefficients, NaN rows for failed draws), the failures, the warnings the refits raised, and diagnostics of how the draws were made (seed, group order and draw-plan hashes, workers).- __init__(draws, failures, warnings, diagnostics)¶
- classmethod __new__(*args, **kwargs)¶
- class hdfe_stream.core.refit.RefitBootstrapResult[source]¶
Point estimates, refit draws and pointwise bootstrap inference.
No source or fit scratch survives. Failed attempts remain in the ledger and are never redrawn. Inference on successful draws requires allow_incomplete when any attempt failed; such inference is conditional on successful fits.
- confint(alpha=0.05, *, method='percentile', allow_incomplete=False)[source]¶
Pointwise percentile/type-7, basic, or uncorrected normal intervals.
Normal intervals are point estimate +/- normal critical value times bootstrap SD, without boot.ci’s normal bias correction. No simultaneous, studentized or BCa intervals are supplied.
- __init__(*, fml, estimator, coefnames, beta, diagnostics, _draws, _failures, _warnings)¶
- classmethod __new__(*args, **kwargs)¶
- class hdfe_stream.core.refit.BootstrapFailureWarning[source]¶
Some refits of a bootstrap failed; inference on the rest needs explicit acknowledgment.
- __init__(*args, **kwargs)¶
- classmethod __new__(*args, **kwargs)¶
- class hdfe_stream.core.resample.DiskGroupResampler[source]¶
Stage
snapshotbykeyand draw whole-group resamples from it.The source is partitioned in bounded memory (
budget,preprocess_mb, scratch inroot); each piece is sorted bysort_columns, filtered byselect(frame)(the consumer’s sample rules, applied a piece at a time), and its groups are numbered inindex_column.n_unitsis the number of groups andn_rowsof rows;identityhashes the group order, which with a seed fixes the draws.With
within(a unit column nested in thekeyclusters), clusters are drawn, and in each copy every unit gets an ID of its own:draw_columnis then the copy times the largest number of units in a cluster plus the unit’s rank within its cluster, so that it can serve as the unit ID of a refit.n_withincounts the units.- __init__(snapshot, root, budget, preprocess_mb, *, key, sort_columns, select, index_column, draw_column, within=None)[source]¶
- materialize(rng, root, *, time_column, chunk_rows=32768)[source]¶
Write one exact N-group resample. Return path, dates, rows, plan hash.
Integer plans are routed to leaf-specific binary files, never collected into an N-row in-memory manifest. Output buffers and join multiplicity are bounded separately from the number of groups in the population.
time_column(or None) names the column whose distinct values are returned as the dates the resample covers.
- classmethod __new__(*args, **kwargs)¶
- class hdfe_stream.core.partition.GroupPartitions[source]¶
Recursive whole-group hash partitioning under a memory budget.
rootis the scratch directory,budgetaMemoryBudget,preprocess_mbthe working memory for a piece (a quarter of it is the largest decoded piece), andkeythe group column. Subclasses implement_leaf(part), called once per piece that fits, and may override_oversized_group(part)(a single group larger than the allowance; an error by default)._prepare(part, 0)starts the partitioning;_guardchecks an allocation against the budget, and_namegives a fresh scratch path.extra_row_bytesadds the per-row bytes of columns the leaves will add, so that pieces stay within the allowance after projection.- classmethod __new__(*args, **kwargs)¶
- hdfe_stream.core.partition.whole_group_batches(path, key, max_groups, read_rows=32768)[source]¶
Read sorted Parquet without splitting a group across yielded frames.
Memory is bounded by one reader batch, one unfinished group, and the consumer’s batch. Keys need only be unique within this file.
- hdfe_stream.core.partition.preprocess_budget_mb(preprocess_mb, budget)[source]¶
The working memory for partitioning and sorting, in decimal MB.
An explicit value is validated and used as given. None (the default) uses a quarter of the job’s current memory headroom, between 16 MB and 32 GB, so a panel that fits in memory is sorted in one piece instead of being hash-partitioned through disk, and a smaller
max_memory_gbgives smaller partitions automatically. A quarter, not more: headroom shrinks while the data are staged, and each leaf is checked against it again.
- class hdfe_stream.core.process.ProcessBatch[source]¶
Run commands in up to
workerschild processes at once.Use as a context manager:
submit(command, log)startscommand(an argument list) with its output inlogand returns a future of its exit code. Leaving the block stops any children still running, so an error or an interrupt in the parent never leaves workers behind.- classmethod __new__(*args, **kwargs)¶