Skip to content

ENH: Add a formula interface to AbsorbingLS - #890

Merged
bashtage merged 2 commits into
bashtage:mainfrom
leninworld:enh-absorbing-formula
Dec 3, 2026
Merged

bashtage merged 2 commits into
bashtage:mainfrom
leninworld:enh-absorbing-formula

Conversation

@leninworld

@leninworld leninworld commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

This PR fixes issue #371.

Closes #371

As suggested in the issue, this adds a hybrid formula interface to AbsorbingLS: the formula gives the dependent variable and the non-absorbed regressors, and the effects are still passed to absorb (and interactions), so they stay sparse.

mod = AbsorbingLS.from_formula(
    "y ~ 1 + x + np.log(z) + C(industry)", data, absorb=data[["firm", "year"]]
)
res = mod.fit()
  • AbsorbingLS.from_formula(formula, data, *, absorb=None, interactions=None, weights=None, drop_absorbed=False) parses the formula with the parser the IV models use (IVFormulaParser), so the same transforms and C() terms work, and rows with a missing formula variable are dropped by the model as usual. A formula with an [endog ~ instruments] block raises ValueError, and so does one that writes effects after | (such as y ~ x | firm), with a message saying that effects go in absorb and interactions in interactions; | inside a term, as in I(a | b), still works.
  • AbsorbingLS.formula holds the formula ("" for models built from arrays, as in the IV models). Both are marked .. versionadded:: 7.2.
  • A release note in doc/source/changes/7.0.rst (7.2, New features) and a short example in the AbsorbingLS section of doc/source/iv/introduction.rst.

Tests (linearmodels/tests/iv/test_absorbing_formula.py): the formula model matches AbsorbingLS built from arrays, both from the parser output (absorb as a DataFrame and as an Interaction, with interactions, weights and drop_absorbed) and from a design matrix built by hand (constant, transforms, C() dummies), plus the intercept rule, y ~ 0, missing values (with the expected MissingValueWarnings), the IV-block error, the | error and I(a | b).

Not changed: a missing value in a categorical used through C() becomes a row of zero dummies in IVFormulaParser (with na_action="ignore"), so that row is kept in the base level. IV2SLS.from_formula behaves the same way today; I left the shared parser alone here.

Verification (macOS, Python 3.12):

  • the new tests fail on main and pass here; test_absorbing_formula.py passes with -W error::linearmodels.shared.exceptions.MissingValueWarning
  • pytest linearmodels/tests/iv: 9939 passed, 2400 skipped
  • flake8, black --check, isort --check and ruff check linearmodels pass; mypy reports the same errors as main; the new docstring example runs under --doctest-modules

Add AbsorbingLS.from_formula, which takes the dependent variable and
the non-absorbed regressors from a formula while the effects are still
passed to absorb. Store the formula in AbsorbingLS.formula.

Closes bashtage#371
@codecov

codecov Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.69%. Comparing base (04f080d) to head (d3f5925).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff            @@
##             main     #890    +/-   ##
========================================
  Coverage   99.69%   99.69%            
========================================
  Files         203      204     +1     
  Lines       38941    39054   +113     
  Branches     2503     2507     +4     
========================================
+ Hits        38822    38935   +113     
  Misses         51       51            
  Partials       68       68            
Flag Coverage Δ
adder 99.68% <100.00%> (+<0.01%) ⬆️
subtractor 99.68% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@bashtage bashtage left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is the hybrid I suggested in #371, and it is consistent with IV2SLS.from_formula. It agrees with OLS and WLS on the explicit design (with missing values, weights and transformed regressors) and with AbsorbingLS built by hand, to about 1e-14.

  1. Please add .. versionadded:: 7.2 to the docstrings of from_formula and formula.

  2. test_formula_missing_values leaks two MissingValueWarnings. Please wrap both constructions:

    from linearmodels.shared.exceptions import MissingValueWarning
    
    with pytest.warns(MissingValueWarning, match="missing values"):
        formula_res = AbsorbingLS.from_formula(formula, data, absorb=absorb).fit()
    with pytest.warns(MissingValueWarning, match="missing values"):
        direct_res = AbsorbingLS(parser.dependent, parser.exog, absorb=absorb).fit()
  3. Release note: please add the PR number and mention formula:

    - ``AbsorbingLS.from_formula`` creates a model from a formula for the dependent
      variable and the regressors that are not absorbed. The effects and interactions are
      passed to ``absorb`` and ``interactions``, not written in the formula, so that they
      stay sparse. ``AbsorbingLS.formula`` holds the formula (:issue:`371`, :issue:`890`).

Optional: "y ~ 1 + x1 | firm", the syntax mentioned in #371, fails with NumPy's "inhomogeneous shape" error (as IV2SLS.from_formula does). A ValueError saying that effects go in absorb would help users who try it.

Add versionadded 7.2 to from_formula and formula, expect the two
MissingValueWarnings in test_formula_missing_values, and use the
suggested release note. A formula that writes effects after '|' now
raises a ValueError that points to absorb and interactions; '|' inside
a term such as I(a | b) still works. Note in the guide that absorbed
effects must be categorical.
@leninworld

Copy link
Copy Markdown
Contributor Author

Thanks @bashtage. All three points and the optional one are in d3f59256 (review):

  1. versionadded: from_formula and the formula property now have .. versionadded:: 7.2.
  2. Leaked warnings: test_formula_missing_values wraps both constructions in pytest.warns(MissingValueWarning, match="missing values"), one per block as you suggested. test_absorbing_formula.py now passes with -W error::linearmodels.shared.exceptions.MissingValueWarning (it failed on the previous head).
  3. Release note: replaced with your text, which also cites this PR (:issue:`890` ).
  4. | syntax (optional): from_formula("y ~ 1 + x1 | firm", ...) now raises ValueError: Pass effects to absorb and interactions to interactions, not after '|' in the formula. instead of NumPy's shape error. It asks formulaic whether the dependent or regressor part is a multi-part formula, so | inside a term such as I(a | b) still works; there are tests for both. I also added one line to the guide example saying that the columns in absorb must be categorical to be absorbed as effects.

Checks: pytest linearmodels/tests/iv 9939 passed, 2400 skipped; ruff check linearmodels, black --check, isort --check and flake8 pass; the absorbing.py doctests pass. I updated the PR description to match.

@bashtage
bashtage merged commit 6855ff2 into bashtage:main Dec 3, 2026
27 checks passed
@bashtage

bashtage commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Thanks.

@leninworld

Copy link
Copy Markdown
Contributor Author

Thanks.

Thank you @bashtage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ENH: Add a formula API call for absorbing regression

2 participants