def test_linear_constraint_repr(): r = np.eye(10) lc = LinearConstraint(r, require_pandas=False) assert hex(id(lc)) in lc.__repr__() assert '10 constraints' in lc.__repr__() assert isinstance(lc.q, pd.Series) assert np.all(lc.q == 0) assert lc.q.shape == (10,) assert isinstance(lc.r, pd.DataFrame) assert np.all(lc.r.values == np.eye(10))
def test_linear_constraint_errors(): r = np.zeros((2, 5)) r[0, 0] = r[1, 1] = 1 r_df = pd.DataFrame(r) q = np.zeros(2) with pytest.raises(TypeError): LinearConstraint(r) with pytest.raises(TypeError): LinearConstraint(r_df, q) with pytest.raises(TypeError): LinearConstraint([[0, 0, 1]]) with pytest.raises(ValueError): LinearConstraint(r[0], require_pandas=False) with pytest.raises(TypeError): LinearConstraint(r_df, q) with pytest.raises(TypeError): LinearConstraint(r_df, [0, 0]) with pytest.raises(TypeError, match="q must be a Series or"): LinearConstraint(r=np.eye(2), q=[0, 0], require_pandas=False) with pytest.raises(ValueError, match="r is incompatible"): LinearConstraint(r=np.eye(4), q=np.zeros(4), require_pandas=False, num_params=5) with pytest.raises(ValueError, match="Constraint inputs are"): LinearConstraint(r=np.eye(4), q=np.zeros(2), require_pandas=False)
def test_linear_constraint(): r = np.zeros((2, 5)) r[0, 0] = r[1, 1] = 1 lc = LinearConstraint(r, require_pandas=False) assert np.all(lc.t[:2] == 0) assert np.all(np.sum(lc.t, 1)[2:] == 1) assert np.all(lc.a == 0) x = np.random.randn(200, 5) y = np.random.randn(200, 1) xt = x @ lc.t bc = lstsq(xt, y)[0] ec = y - xt @ bc b = lstsq(x[:, 2:], y)[0] e = y - x[:, 2:] @ b assert_allclose(ec.T @ ec, e.T @ e) lc = LinearConstraint(r, require_pandas=False) assert np.all(lc.a == 0)
def add_constraints(self, r, q=None): r""" Parameters ---------- r : DataFrame Constraint matrix. nconstraints by nparameters q : Series, optional Constraint values (nconstraints). If not set, set to 0 Notes ----- Constraints are of the form .. math :: r \beta = q The property `param_names` can be used to determine the order of parameters. """ self._constraints = LinearConstraint(r, q=q, num_params=len(self._param_names), require_pandas=True)
def test_linear_constraint_errors(): r = np.zeros((2, 5)) r[0, 0] = r[1, 1] = 1 r_df = pd.DataFrame(r) q = np.zeros(2) with pytest.raises(TypeError): LinearConstraint(r) with pytest.raises(TypeError): LinearConstraint(r_df, q) with pytest.raises(TypeError): LinearConstraint([[0, 0, 1]]) with pytest.raises(ValueError): LinearConstraint(r[0], require_pandas=False) with pytest.raises(TypeError): LinearConstraint(r_df, q) with pytest.raises(TypeError): LinearConstraint(r_df, [0, 0])