Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for nested formulae (useful e.g. in IV contexts). #108

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions formulaic/parser/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,23 @@ def power(arg: OrderedSet[Term], power: OrderedSet[Term]) -> OrderedSet[Term]:
for term in itertools.product(*[arg] * int(power_term.factors[0].expr))
)

def sub_formula(lhs, rhs):
def get_terms(terms):
return [
Term(
factors=[Factor(str(t) + "_hat", eval_method="lookup")],
origin=t,
)
for t in terms
]

if isinstance(lhs, Structured):
lhs_hat = lhs._update(root=get_terms(lhs.root))
else:
lhs_hat = get_terms(lhs)

return Structured(lhs_hat, deps=(Structured(lhs=lhs, rhs=rhs),))

return [
Operator(
"~",
Expand All @@ -248,6 +265,15 @@ def power(arg: OrderedSet[Term], power: OrderedSet[Term]) -> OrderedSet[Term]:
accepts_context=lambda context: len(context) == 0,
structural=True,
),
Operator(
"~",
arity=2,
precedence=-100,
associativity=None,
to_terms=sub_formula,
accepts_context=lambda context: context and context[-1] == "[",
structural=True,
),
Operator(
"|",
arity=2,
Expand Down
7 changes: 5 additions & 2 deletions formulaic/parser/types/term.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import Any, Iterable, TYPE_CHECKING
from typing import Any, Iterable, Optional, TYPE_CHECKING

if TYPE_CHECKING:
from .factor import Factor # pragma: no cover
Expand All @@ -15,10 +15,13 @@ class Term:

Attributes:
factors: The set of factors to be multiplied to form the term.
origin: If this `Term` has been derived from another `Term`, for example
in subformulae, a reference to the original term.
"""

def __init__(self, factors: Iterable["Factor"]):
def __init__(self, factors: Iterable["Factor"], origin: Optional[Term] = None):
self.factors = tuple(dict.fromkeys(factors))
self.origin = origin
self._factor_key = tuple(factor.expr for factor in sorted(self.factors))
self._hash = hash(":".join(self._factor_key))

Expand Down
Loading