How to use the patsy.contrasts.ContrastMatrix function in patsy

To help you get started, we’ve selected a few patsy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github statsmodels / statsmodels / examples / python / contrasts.py View on Github external
def code_without_intercept(self, levels):
        contrast = self._simple_contrast(levels)
        return ContrastMatrix(contrast, _name_levels("Simp.", levels[:-1]))
github pydata / patsy / patsy / contrasts.py View on Github external
def code_without_intercept(self, levels):
        matrix = self._sum_contrast(levels)
        omit_i = self._omit_i(levels)
        included_levels = levels[:omit_i] + levels[omit_i + 1:]
        return ContrastMatrix(matrix, _name_levels("S.", included_levels))
github pydata / patsy / patsy / contrasts.py View on Github external
def test_ContrastMatrix():
    cm = ContrastMatrix([[1, 0], [0, 1]], ["a", "b"])
    assert np.array_equal(cm.matrix, np.eye(2))
    assert cm.column_suffixes == ["a", "b"]
    # smoke test
    repr(cm)

    from nose.tools import assert_raises
    assert_raises(PatsyError, ContrastMatrix, [[1], [0]], ["a", "b"])

    assert_no_pickling(cm)
github pydata / patsy / patsy / design_info.py View on Github external
["a[1]", "a[2]"],
                  factor_codings_a,
                  term_codings_a_bad_rows)

    # have a contrast matrix for a non-categorical factor
    t_ax = Term([f_a, f_x])
    factor_codings_ax = {f_a:
                           FactorInfo(f_a, "categorical", {},
                                      categories=["a1", "a2"]),
                         f_x:
                           FactorInfo(f_x, "numerical", {},
                                      num_columns=2)}
    term_codings_ax_extra_cm = OrderedDict([
        (t_ax,
         [SubtermInfo([f_a, f_x],
                      {f_a: ContrastMatrix(np.ones((2, 2)), ["[1]", "[2]"]),
                       f_x: ContrastMatrix(np.ones((2, 2)), ["[1]", "[2]"])},
                      4)])])
    assert_raises(ValueError, DesignInfo,
                  ["a[1]:x[1]", "a[2]:x[1]", "a[1]:x[2]", "a[2]:x[2]"],
                  factor_codings_ax,
                  term_codings_ax_extra_cm)

    # no contrast matrix for a categorical factor
    term_codings_ax_missing_cm = OrderedDict([
        (t_ax,
         [SubtermInfo([f_a, f_x],
                      {},
                      4)])])
    # This actually fails before it hits the relevant check with a KeyError,
    # but that's okay... the previous test still exercises the check.
    assert_raises((ValueError, KeyError), DesignInfo,
github pydata / patsy / patsy / contrasts.py View on Github external
def code_without_intercept(self, levels):
        contrast = self._helmert_contrast(levels)
        return ContrastMatrix(contrast,
                              _name_levels("H.", levels[1:]))
github pydata / patsy / patsy / contrasts.py View on Github external
scores -= scores.mean()
        raw_poly = scores.reshape((-1, 1)) ** np.arange(n).reshape((1, -1))
        q, r = np.linalg.qr(raw_poly)
        q *= np.sign(np.diag(r))
        q /= np.sqrt(np.sum(q ** 2, axis=1))
        # The constant term is always all 1's -- we don't normalize it.
        q[:, 0] = 1
        names = [".Constant", ".Linear", ".Quadratic", ".Cubic"]
        names += ["^%s" % (i,) for i in range(4, n)]
        names = names[:n]
        if intercept:
            return ContrastMatrix(q, names)
        else:
            # We always include the constant/intercept column as something to
            # orthogonalize against, but we don't always return it:
            return ContrastMatrix(q[:, 1:], names[1:])
github pydata / patsy / patsy / design_info.py View on Github external
def __init__(self, factors, contrast_matrices, num_columns):
        self.factors = tuple(factors)
        factor_set = frozenset(factors)
        if not isinstance(contrast_matrices, dict):
            raise ValueError("contrast_matrices must be dict")
        for factor, contrast_matrix in six.iteritems(contrast_matrices):
            if factor not in factor_set:
                raise ValueError("Unexpected factor in contrast_matrices dict")
            if not isinstance(contrast_matrix, ContrastMatrix):
                raise ValueError("Expected a ContrastMatrix, not %r"
                                 % (contrast_matrix,))
        self.contrast_matrices = contrast_matrices
        if not isinstance(num_columns, six.integer_types):
            raise ValueError("num_columns must be an integer")
        self.num_columns = num_columns