Skip to content

ENH: Abstract formula engine - #9423

Merged
bashtage merged 46 commits into
statsmodels:mainfrom
bashtage:enable-formulaic-v2
Dec 11, 2024
Merged

bashtage merged 46 commits into
statsmodels:mainfrom
bashtage:enable-formulaic-v2

Conversation

@bashtage

Copy link
Copy Markdown
Member

Add patsy and formulaic aware formula engine abstraction

  • closes #xxxx
  • tests added / passed.
  • code/documentation is well formatted.
  • properly formatted commit message. See
    NumPy's guide.
Details

Notes:

  • It is essential that you add a test when making code changes. Tests are not
    needed for doc changes.
  • When adding a new function, test values should usually be verified in another package (e.g., R/SAS/Stata).
  • When fixing a bug, you must add a test that would produce the bug in main and
    then show that it is fixed with the new code.
  • New code additions must be well formatted. Changes should pass flake8. If on Linux or OSX, you can
    verify you changes are well formatted by running
    git diff upstream/main -u -- "*.py" | flake8 --diff --isolated
    
    assuming flake8 is installed. This command is also available on Windows
    using the Windows System for Linux once flake8 is installed in the
    local Linux environment. While passing this test is not required, it is good practice and it help
    improve code quality in statsmodels.
  • Docstring additions must render correctly, including escapes and LaTeX.

Comment thread statsmodels/formula/_manager.py Fixed
Comment thread statsmodels/formula/_manager.py Fixed
@matthewwardrop

Copy link
Copy Markdown

Nice! Thanks for working on this @bashtage ! A year or more ago I spent a couple of hours starting an abstraction like this, but never got around to finishing it. I'll take a closer look at this shortly, but from a quick pass it all looks great!

@pep8speaks

pep8speaks commented Nov 13, 2024 •

Copy link
Copy Markdown

Hello @bashtage! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

Line 5:1: F401 'statsmodels.tools.data as data_util' imported but unused

Comment last updated at 2024-11-13 10:53:05 UTC

@bashtage
bashtage force-pushed the enable-formulaic-v2 branch from 1a37dbc to eafc4a9 Compare November 13, 2024 10:03
Comment thread statsmodels/compat/patsy.py Fixed
"""
from statsmodels.discrete.diagnostic import (
PoissonDiagnostic)
from statsmodels.discrete.diagnostic import PoissonDiagnostic

Check notice

Code scanning / CodeQL

Cyclic import

Import of module [statsmodels.discrete.diagnostic](1) begins an import cycle.
Comment thread statsmodels/formula/_manager.py Fixed
import pandas as pd
from scipy import optimize

from statsmodels.base._penalized import PenalizedMixin

Check notice

Code scanning / CodeQL

Cyclic import

Import of module [statsmodels.base._penalized](1) begins an import cycle.
import warnings

import statsmodels.genmod.families.varfuncs as varfuncs
from statsmodels.genmod.generalized_linear_model import GLM, GLMResults

Check notice

Code scanning / CodeQL

Cyclic import

Import of module [statsmodels.genmod.generalized_linear_model](1) begins an import cycle.
_get_dummy_index, _get_count_index)
)
# used for wrapper:
import statsmodels.regression.linear_model as lm

Check notice

Code scanning / CodeQL

Cyclic import

Import of module [statsmodels.regression.linear_model](1) begins an import cycle.
LC = DesignInfo(names).linear_constraint(['a + b = 0', 'a + 2*c = 1', 'b-a', 'c-a', 'd-a'])
#LC = DesignInfo(self.model.exog_names).linear_constraint(r_matrix)
r_matrix, q_matrix = LC.coefs, LC.constants
lc = mgr.get_linear_constraints('a + b = 0', names)

Check warning

Code scanning / CodeQL

Variable defined multiple times

This assignment to 'lc' is unnecessary as it is [redefined](1) before this value is used.
r_matrix, q_matrix = LC.coefs, LC.constants
lc = mgr.get_linear_constraints('a + b = 0', names)
lc = mgr.get_linear_constraints(['a + b = 0', 'a + 2*c = 1', 'b-a', 'c-a', 'd-a'], names)
r_matrix, q_matrix = lc.constraint_matrix, lc.constraint_values

Check notice

Code scanning / CodeQL

Unused global variable

The global variable 'r_matrix' is not used.
r_matrix, q_matrix = LC.coefs, LC.constants
lc = mgr.get_linear_constraints('a + b = 0', names)
lc = mgr.get_linear_constraints(['a + b = 0', 'a + 2*c = 1', 'b-a', 'c-a', 'd-a'], names)
r_matrix, q_matrix = lc.constraint_matrix, lc.constraint_values

Check notice

Code scanning / CodeQL

Unused global variable

The global variable 'q_matrix' is not used.
Comment thread statsmodels/compat/patsy.py Fixed
Comment thread statsmodels/formula/__init__.py Fixed
@bashtage
bashtage force-pushed the enable-formulaic-v2 branch from b593018 to 8e2bd64 Compare November 15, 2024 16:01
Comment thread statsmodels/formula/_manager.py Fixed
@bashtage
bashtage force-pushed the enable-formulaic-v2 branch from a14c4c1 to 27b390d Compare November 15, 2024 16:42
Comment thread requirements.txt Outdated
scipy>=1.8,!=1.9.2 # released Feb 2022, 1.9.2 blocked due to bug
pandas>=1.4,!=2.1.0 # released Feb 2022, 2.1.0 blocked due to bug
patsy>=0.5.6 # released December 2023
formulaic>=1.0.2 # released June 2024

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

>=1.0.0 should be sufficient.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks. All comments and reviewed are appreciated. 👍

@matthewwardrop matthewwardrop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hi @bashtage ! Thanks so much for doing this work... it's definitely a heavier lift than I realised it would be, so I'm glad I don't have to do it!

Since this is an unsolicited review, I didn't go into too much depth, but I left a few (hopefully helpful) comments.

"""
return cls(lc.coefs, lc.constants, lc.variable_names)
try:
return cls(lc.constraint_matrix, lc.constraint_values, lc.variable_names)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Is it worth doing explicit type-checks here? If not, probably worth adding some comments as to why this works.

if _engine == "patsy" and not HAVE_PATSY:
raise ImportError(f"patsy {msg_base}.")
elif not HAVE_FORMULAIC:
raise ImportError(f"formulaic {msg_base}.")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Would tell you to install patsy when formulaic is not available. Is that the desired behaviour?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It should only do this if you request formulaic and it isn't installed. If you request it and have patsy then it should work. I need to write some separate tests for this.

Comment thread statsmodels/formula/_manager.py Outdated
_ordering = statsmodels.formula.options.ordering
_formula = formulaic.formula.Formula(formula, _ordering=_ordering)
output = formulaic.model_matrix(_formula, data, context=eval_env, **kwargs)
if isinstance(output, formulaic.ModelMatrices):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

There are other ways that ModelMatrices can be output; for example if multipart formulae are being used. Maybe check explicitly for lhs and rhs being present? And maybe raise an error if ModelMatrices is returned otherwise (until statmodels knows how to handle it)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Does Model matrices support len? Might be good to raise for len >2 if it did.

@matthewwardrop matthewwardrop Nov 16, 2024 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Yes, it does support len; but there are many ways that it can have length two that might be surprising. For example: x | y would also have length two.

I plan to add a way to restrict the kinds of formulae that can be created in the upcoming Formula 1.1, which may help here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Comment thread statsmodels/formula/_manager.py Outdated
"""
return self._spec

def get_arrays(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: This name feels a bit weird to me, since it implies (to me) that the output would be numpy arrays, when in fact the default output is a pandas dataframe. Perhaps get_matrices?

)
else: # self._engine == "formulaic"

# Handle list of constraints, which is not supported by formulaic

ghost Nov 16, 2024

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is an oversight. I'll add support for this in formulaic-next.

list[Term]
The terms with the intercept removed, if present.
"""
intercept = self.intercept_term

ghost Nov 16, 2024

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

question: removing the intercept term does not mean that generated matrices will not span the intercept; both patsy and formulaic will, in the absence of an intercept, expand categorical factors to span the intercept. How is that being handled?

ghost Nov 16, 2024

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

TBH I'm not that worried about this - it is mostly to deal with code that exists that someone else wrote a long time ago. It is only used in 1 place for anova, and then only to loop over columns that aren't the intercept. It isn't used to construct a model matrix.

ghost Dec 2, 2024

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@matthewwardrop

In models where we cannot have an intercept like OrderedModel, we require users when using formulas to use an explicit intercept that we remove internally.
That means that the remaining variables are by construction not spanning the intercept.
(patsy does not have an option to exclude explicit and implicit intercepts)

ghost Dec 3, 2024

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the context @josef-pkt .

ghost Dec 3, 2024

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

(fwiw, if it ever became sufficiently desirous to have this built into a formula parser, I'd be open to considering how best achieve it; but this seems like a reasonable approach for now)

if self._engine == "patsy":
return patsy.ModelDesc.from_formula(formula)
else:
return formulaic.Formula(formula)

ghost Nov 16, 2024

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

if you want to be able to set other parts of the spec, you can also do: ModelSpec(formula=formula).

ghost Nov 16, 2024

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I tried this initially but get the somewhat cryptic error

ValueError: Nominated `Formula` instance has structure, which is not permitted when attaching to a `ModelSpec` instance.

ghost Nov 17, 2024 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ah... whoops. To support nested formulae as well you'd want: ModelSpec.from_spec(formula); which then returns a ModelSpecs instance as necessary.

@josef-pkt

ghost commented Dec 2, 2024

Copy link
Copy Markdown
Member

ok, thanks

@josef-pkt

ghost commented Dec 2, 2024

Copy link
Copy Markdown
Member

I browsed through anova_lm and t_test_pairwise

looks great, get_contrast_matrix is much easier to use than the old code.

def missing_mask(self):
return self._missing_mask

def _legacy_orderer(

ghost Dec 3, 2024

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

  1. If this is trying to reproduce patsy's ordering, you should be able to just do: Formula(<formula>).get_model_matrix(data, cluster_by="numerical_factors")

ghost Dec 4, 2024

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

So far this exactly reproduced patsy's ordering in every specification I have tried. I'll run it through the test suite and see if I can match.

ghost Dec 4, 2024

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I gave this a go using

for order in ("none", "sort", "degree"):
    formulaic.Formula(formula, _ordering=order).get_model_matrix(data, cluster_by="numerical_factors")

and none were exactly able to match patsy's ordering.

I'm not too surprised given how many hoops I had to jump through to get it to work.

My plan is to move away from legacy order so that "legacy" it will be deprecated as soon as possible so that this code can eventually go away and only be left with the in-built options in formulaic.

Comment thread statsmodels/formula/_manager.py Resolved
Comment thread statsmodels/formula/_manager.py Resolved
df = getattr(output, key)
df.index = replacement_index
if isinstance(output, formulaic.ModelMatrices):
if (

ghost Dec 3, 2024

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

You can now just do: if not isinstance(SimpleFormula):

ghost Dec 4, 2024

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Do you mean isinstance(output.model_spec.formula, SimpleFormula)?

Comment thread statsmodels/formula/_manager.py Outdated
from formulaic.parser.types.factor import Factor
from formulaic.parser.types.term import Term

return Term((Factor("1"),))

ghost Dec 3, 2024

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Since you are only using this to check for equality, you can actually just return "1" here.

Comment thread statsmodels/formula/_manager.py Resolved
else:
cat = self.get_factor_categories(factor, model_spec)
reduced_rank = True
for ts in model_spec.structure:

ghost Dec 3, 2024 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This won't work in general; since a term may consist of the product of than one categorical variable.

In the past I toyed with the notion of adding a helper method for this, but looking at this code maybe I should have just done it. I could add a method model_spec.get_factor_contrasts_for_term(....); the final code could then be: model_spec.get_factor_contrasts_for_term(term)[factor].get_coding_matrix()... but there's a problem with this ...

Suppose you have a formula: 1 + A:B, with A and B being categorical variables. Under the hood (in both patsy and formulaic), this will be cast into: 1 + A- + A:B- (with the minus indicating reduced rankness). So the "term" A:B expands into two terms B- and A-:B, in which B is encoded differently. Therefore there is in general no single encoding of categorical factors per term. The algorithm used above for patsy is therefore "wrong", since it assumes reduced rank even where it is not universally true.

If you want to ignore this wrinkle, adding a method like that above is pretty trivial; since we store the scoping of factors in these expanded forms; e.g.:

import formulaic
import pandas
mm = formulaic.model_matrix("1 + A:B", pandas.DataFrame({"A": list("abc"), "B": list("def")}))
mm.model_spec.structure[1]

This outputs:

EncodedTermStructure(term=A:B, scoped_terms=[B-, A-:B], columns=['B[T.e]', 'B[T.f]', 'A[T.b]:B[d]', 'A[T.c]:B[d]', 'A[T.b]:B[e]', 'A[T.c]:B[e]', 'A[T.b]:B[f]', 'A[T.c]:B[f]'])

where term is the original term, scoped_terms describes how it is expanded, and columns indicates the set of columns resulting from these scoped terms.

I'm not exactly sure what to do with this. Perhaps @josef-pkt has thoughts?

ghost Dec 3, 2024 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The problem is that I don't know what to do with interaction terms.
I have several open issues to support both categorical-categorical and categorical-continuous interactions, e.g.

For t_test_pairwise, predict and marginal/predicitive effects, one requirement for categorical-categorical interaction would be to get all cell means, e.g. partial exog for the columns with possibly setting other columns to prespecified values.
One option I thought about is to automatically create artificial datasets, but I never tried to figure out how to do this with patsy, e.g. #8439 #7071 #8746 and more

There are several post-estimation results that need more information about the structure of terms in the design matrix. But those are currently not supported.
Currently only anova_lm and t_test_pairwise use term information, and t_test_pairwise is restricted to a single factor.

@matthewwardrop

ghost commented Dec 3, 2024

Copy link
Copy Markdown

@bashtage Once you've got this ready to your satisfaction, let me know... and I'll take a closer look (likely mainly at the FormulaManager part), but so far it is looking pretty good :).

@bashtage
bashtage force-pushed the enable-formulaic-v2 branch from 0aaed55 to 0525943 Compare December 4, 2024 12:14
Comment thread statsmodels/formula/_manager.py Fixed
Comment thread statsmodels/formula/_manager.py Fixed
@bashtage
bashtage force-pushed the enable-formulaic-v2 branch from 0525943 to 0094813 Compare December 4, 2024 12:40
Comment thread statsmodels/formula/_manager.py Fixed
"""
types = ["None", "NaN"] if types is _NoDefault else types
if self._using_patsy:
return NAAction(on_NA=action, NA_types=types)

Check failure

Code scanning / CodeQL

Wrong name for an argument in a class instantiation

Keyword argument 'on_NA' is not a supported parameter name of [NAAction.__init__](1). Keyword argument 'NA_types' is not a supported parameter name of [NAAction.__init__](1).
@bashtage
bashtage force-pushed the enable-formulaic-v2 branch from 3ae9a5e to 1af1160 Compare December 11, 2024 14:07
Comment on lines +412 to +436
f"""
Get the model matrices or design matrices from a formula and data.

Parameters
----------
formula : str, Formula
The formula to use.
data : DataFrame, dict, list, recarray
The data to use when evaluating the formula.
eval_env : {int, dict}
Additional context to use when evaluating the formula.
pandas : bool
Return a DataFrame if true, otherwise return a numpy array.
na_action : {NAAction, str}
The action to take on missing values.
prediction : bool
True if using the formula for prediction. In this case, only the
rhs is evaluated using data.

Returns
-------
tuple[DataFrame, ...], tuple[ndarray, ...], tuple[DesignMatrix, ...]
If pandas is True, returns one or more DataFrames. If False,
returns a NumPy ndarray (formulaic) or a DesignMatrix (patsy).
"""

Check notice

Code scanning / CodeQL

Statement has no effect

This statement has no effect.
Ensure statsmodels can run with only 1 of the engines available
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants