(self)
| 164 | assert_equal(str(p), " \n0") |
| 165 | |
| 166 | def test_polyfit(self): |
| 167 | c = np.array([3., 2., 1.]) |
| 168 | x = np.linspace(0, 2, 7) |
| 169 | y = np.polyval(c, x) |
| 170 | err = [1, -1, 1, -1, 1, -1, 1] |
| 171 | weights = np.arange(8, 1, -1)**2 / 7.0 |
| 172 | |
| 173 | # Check exception when too few points for variance estimate. Note that |
| 174 | # the estimate requires the number of data points to exceed |
| 175 | # degree + 1 |
| 176 | assert_raises(ValueError, np.polyfit, |
| 177 | [1], [1], deg=0, cov=True) |
| 178 | |
| 179 | # check 1D case |
| 180 | m, cov = np.polyfit(x, y + err, 2, cov=True) |
| 181 | est = [3.8571, 0.2857, 1.619] |
| 182 | assert_almost_equal(est, m, decimal=4) |
| 183 | val0 = [[ 1.4694, -2.9388, 0.8163], |
| 184 | [-2.9388, 6.3673, -2.1224], |
| 185 | [ 0.8163, -2.1224, 1.161 ]] # noqa: E202 |
| 186 | assert_almost_equal(val0, cov, decimal=4) |
| 187 | |
| 188 | m2, cov2 = np.polyfit(x, y + err, 2, w=weights, cov=True) |
| 189 | assert_almost_equal([4.8927, -1.0177, 1.7768], m2, decimal=4) |
| 190 | val = [[ 4.3964, -5.0052, 0.4878], |
| 191 | [-5.0052, 6.8067, -0.9089], |
| 192 | [ 0.4878, -0.9089, 0.3337]] |
| 193 | assert_almost_equal(val, cov2, decimal=4) |
| 194 | |
| 195 | m3, cov3 = np.polyfit(x, y + err, 2, w=weights, cov="unscaled") |
| 196 | assert_almost_equal([4.8927, -1.0177, 1.7768], m3, decimal=4) |
| 197 | val = [[ 0.1473, -0.1677, 0.0163], |
| 198 | [-0.1677, 0.228 , -0.0304], # noqa: E203 |
| 199 | [ 0.0163, -0.0304, 0.0112]] |
| 200 | assert_almost_equal(val, cov3, decimal=4) |
| 201 | |
| 202 | # check 2D (n,1) case |
| 203 | y = y[:, np.newaxis] |
| 204 | c = c[:, np.newaxis] |
| 205 | assert_almost_equal(c, np.polyfit(x, y, 2)) |
| 206 | # check 2D (n,2) case |
| 207 | yy = np.concatenate((y, y), axis=1) |
| 208 | cc = np.concatenate((c, c), axis=1) |
| 209 | assert_almost_equal(cc, np.polyfit(x, yy, 2)) |
| 210 | |
| 211 | m, cov = np.polyfit(x, yy + np.array(err)[:, np.newaxis], 2, cov=True) |
| 212 | assert_almost_equal(est, m[:, 0], decimal=4) |
| 213 | assert_almost_equal(est, m[:, 1], decimal=4) |
| 214 | assert_almost_equal(val0, cov[:, :, 0], decimal=4) |
| 215 | assert_almost_equal(val0, cov[:, :, 1], decimal=4) |
| 216 | |
| 217 | # check order 1 (deg=0) case, were the analytic results are simple |
| 218 | np.random.seed(123) |
| 219 | y = np.random.normal(size=(4, 10000)) |
| 220 | mean, cov = np.polyfit(np.zeros(y.shape[0]), y, deg=0, cov=True) |
| 221 | # Should get sigma_mean = sigma/sqrt(N) = 1./sqrt(4) = 0.5. |
| 222 | assert_allclose(mean.std(), 0.5, atol=0.01) |
| 223 | assert_allclose(np.sqrt(cov.mean()), 0.5, atol=0.01) |
nothing calls this directly
no test coverage detected