pylimma.make_contrasts

pylimma.make_contrasts(*contrasts_args, contrasts=None, levels, **named_contrasts)[source]

Construct a contrast matrix from contrast expressions.

Parameters:
  • *contrasts_args (str) – Contrast expressions like “B-A”, “C-A”, “(B+C)/2-A”. Each expression becomes a column in the contrast matrix. The column name is the expression itself.

  • contrasts (list of str, optional) – Alternative way to pass contrasts as a list (R parity). Cannot be used together with positional contrasts.

  • levels (list of str, ndarray, or DataFrame) – Coefficient names. Can be: - List of coefficient names - Design matrix (column names extracted) - Factor (levels extracted)

  • **named_contrasts (str) – Named contrast expressions. The keyword becomes the column name, the value is the expression. E.g., TreatmentVsControl=”B-A”.

Returns:

Contrast matrix of shape (n_levels, n_contrasts). Row index contains level names, columns contain contrast names.

Return type:

DataFrame

Examples

>>> # Unnamed contrasts (expression becomes name)
>>> make_contrasts("B-A", "C-A", levels=['A', 'B', 'C'])
       B-A  C-A
A     -1.0 -1.0
B      1.0  0.0
C      0.0  1.0
>>> # Named contrasts
>>> make_contrasts(
...     TreatmentVsControl="B-A",
...     DrugVsDMSO="C-A",
...     levels=['A', 'B', 'C']
... )
       TreatmentVsControl  DrugVsDMSO
A                    -1.0        -1.0
B                     1.0         0.0
C                     0.0         1.0
>>> # Mixed: unnamed and named
>>> make_contrasts("C-B", AvsRest="A-(B+C)/2", levels=['A', 'B', 'C'])

Notes

The contrast expressions are evaluated in an environment where each level name is bound to an indicator vector. For example, with levels [‘A’, ‘B’, ‘C’], the expression “B-A” evaluates to [0, 1, 0] - [1, 0, 0] = [-1, 1, 0].