Skip to content

formula

closing_paren(text)

Index of the bracket closing the one at text[0], or -1.

Source code in scdesigner/src/scdesigner/data/formula.py
116
117
118
119
120
121
122
123
124
125
126
def closing_paren(text: str) -> int:
    """Index of the bracket closing the one at ``text[0]``, or -1."""
    depth = 0
    for i, char in enumerate(text):
        if char in "([{":
            depth += 1
        elif char in ")]}":
            depth -= 1
            if depth == 0:
                return i
    return -1

partition_formula(formula)

Modify a formula to partition observations.

We remove the intercept unless the formula has no other terms, so that "~ cell_type" is a proper indicator across cell types (and there is no intercept-like column equal to 1 across all cells).

Parameters:

Name Type Description Default
formula str

A copula group formula.

required

Returns:

Type Description
str

The normalized formula.

Examples:

>>> partition_formula("~ cell_type")
'~ -1 + cell_type'
Source code in scdesigner/src/scdesigner/data/formula.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def partition_formula(formula: str) -> str:
    """Modify a formula to partition observations.

    We remove the intercept unless the formula has no other terms, so that ``"~
    cell_type"`` is a proper indicator across cell types (and there is no
    intercept-like column equal to 1 across all cells).

    Parameters
    ----------
    formula : str
        A copula group formula.

    Returns
    -------
    str
        The normalized formula.

    Examples
    --------
    >>> partition_formula("~ cell_type")
    '~ -1 + cell_type'
    """
    rhs = formula.split("~", 1)[-1]
    terms = []
    for raw_term in rhs.split("+"):

        # strip out irrelevant whitespaces
        term = re.sub(r"-\s*[01]\b", "", raw_term).strip()
        if term and term not in {"0", "1"}:
            terms.append(term)
    if not terms:
        return "~ 1"
    return "~ -1 + " + " + ".join(terms)

split_random_terms(formula)

Separate lme4-style random-effect terms from a formula.

We parse random-effect terms formatted like (1 | donor), since they aren't supported natively in formulaic.

Parameters:

Name Type Description Default
formula str

A formula whose right-hand side may include random-effect terms.

required

Returns:

Name Type Description
fixed str

The formula without random-effect terms, or "~ 1" if the formula only included random effects.

random list of tuple of str

(lhs, group) pairs in order of appearance, e.g. ("1", "donor").

Examples:

>>> split_random_terms("~ genotype * cell_type + (1 | donor)")
('~ genotype * cell_type', [('1', 'donor')])
Source code in scdesigner/src/scdesigner/data/formula.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def split_random_terms(formula: str) -> tuple[str, list[tuple[str, str]]]:
    """Separate lme4-style random-effect terms from a formula.

    We parse random-effect terms formatted like ``(1 | donor)``, since they
    aren't supported natively in formulaic.

    Parameters
    ----------
    formula : str
        A formula whose right-hand side may include random-effect terms.

    Returns
    -------
    fixed : str
        The formula without random-effect terms, or ``"~ 1"`` if the formula
        only included random effects.
    random : list of tuple of str
        ``(lhs, group)`` pairs in order of appearance, e.g. ``("1", "donor")``.

    Examples
    --------
    >>> split_random_terms("~ genotype * cell_type + (1 | donor)")
    ('~ genotype * cell_type', [('1', 'donor')])
    """
    rhs = formula.split("~", 1)[-1]
    fixed, random = [], []
    for summand in split_top_level(rhs, "+"):
        is_group = summand.startswith("(") and closing_paren(summand) == len(summand) - 1
        sides = split_top_level(summand[1:-1], "|") if is_group else [summand]
        if len(sides) > 1:
            random.append((sides[0], sides[1]))
        elif summand:
            fixed.append(summand)
    return "~ " + (" + ".join(fixed) or "1"), random

split_top_level(text, separator)

Split on separator outside of brackets

This also removes surrounding whitespace.

Source code in scdesigner/src/scdesigner/data/formula.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def split_top_level(text: str, separator: str) -> list[str]:
    """Split on ``separator`` outside of brackets

   This also removes surrounding whitespace.
    """
    parts, depth, start = [], 0, 0
    for i, char in enumerate(text):
        if char in "([{":
            depth += 1
        elif char in ")]}":
            depth -= 1
        elif char == separator and depth == 0:
            parts.append(text[start:i].strip())
            start = i + 1
    parts.append(text[start:].strip())
    return parts