File size: 15,530 Bytes
7f43ade |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 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 60 61 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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
import pytest
import numpy as np
from numpy.testing import assert_array_less, assert_allclose, assert_equal
import scipy._lib._elementwise_iterative_method as eim
from scipy import stats
from scipy.optimize._differentiate import (_differentiate as differentiate,
_EERRORINCREASE)
class TestDifferentiate:
def f(self, x):
return stats.norm().cdf(x)
@pytest.mark.parametrize('x', [0.6, np.linspace(-0.05, 1.05, 10)])
def test_basic(self, x):
# Invert distribution CDF and compare against distribution `ppf`
res = differentiate(self.f, x)
ref = stats.norm().pdf(x)
np.testing.assert_allclose(res.df, ref)
# This would be nice, but doesn't always work out. `error` is an
# estimate, not a bound.
assert_array_less(abs(res.df - ref), res.error)
assert res.x.shape == ref.shape
@pytest.mark.parametrize('case', stats._distr_params.distcont)
def test_accuracy(self, case):
distname, params = case
dist = getattr(stats, distname)(*params)
x = dist.median() + 0.1
res = differentiate(dist.cdf, x)
ref = dist.pdf(x)
assert_allclose(res.df, ref, atol=1e-10)
@pytest.mark.parametrize('order', [1, 6])
@pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
def test_vectorization(self, order, shape):
# Test for correct functionality, output shapes, and dtypes for various
# input shapes.
x = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6
n = np.size(x)
@np.vectorize
def _differentiate_single(x):
return differentiate(self.f, x, order=order)
def f(x, *args, **kwargs):
f.nit += 1
f.feval += 1 if (x.size == n or x.ndim <=1) else x.shape[-1]
return self.f(x, *args, **kwargs)
f.nit = -1
f.feval = 0
res = differentiate(f, x, order=order)
refs = _differentiate_single(x).ravel()
ref_x = [ref.x for ref in refs]
assert_allclose(res.x.ravel(), ref_x)
assert_equal(res.x.shape, shape)
ref_df = [ref.df for ref in refs]
assert_allclose(res.df.ravel(), ref_df)
assert_equal(res.df.shape, shape)
ref_error = [ref.error for ref in refs]
assert_allclose(res.error.ravel(), ref_error, atol=5e-15)
assert_equal(res.error.shape, shape)
ref_success = [ref.success for ref in refs]
assert_equal(res.success.ravel(), ref_success)
assert_equal(res.success.shape, shape)
assert np.issubdtype(res.success.dtype, np.bool_)
ref_flag = [ref.status for ref in refs]
assert_equal(res.status.ravel(), ref_flag)
assert_equal(res.status.shape, shape)
assert np.issubdtype(res.status.dtype, np.integer)
ref_nfev = [ref.nfev for ref in refs]
assert_equal(res.nfev.ravel(), ref_nfev)
assert_equal(np.max(res.nfev), f.feval)
assert_equal(res.nfev.shape, res.x.shape)
assert np.issubdtype(res.nfev.dtype, np.integer)
ref_nit = [ref.nit for ref in refs]
assert_equal(res.nit.ravel(), ref_nit)
assert_equal(np.max(res.nit), f.nit)
assert_equal(res.nit.shape, res.x.shape)
assert np.issubdtype(res.nit.dtype, np.integer)
def test_flags(self):
# Test cases that should produce different status flags; show that all
# can be produced simultaneously.
rng = np.random.default_rng(5651219684984213)
def f(xs, js):
f.nit += 1
funcs = [lambda x: x - 2.5, # converges
lambda x: np.exp(x)*rng.random(), # error increases
lambda x: np.exp(x), # reaches maxiter due to order=2
lambda x: np.full_like(x, np.nan)[()]] # stops due to NaN
res = [funcs[j](x) for x, j in zip(xs, js.ravel())]
return res
f.nit = 0
args = (np.arange(4, dtype=np.int64),)
res = differentiate(f, [1]*4, rtol=1e-14, order=2, args=args)
ref_flags = np.array([eim._ECONVERGED,
_EERRORINCREASE,
eim._ECONVERR,
eim._EVALUEERR])
assert_equal(res.status, ref_flags)
def test_flags_preserve_shape(self):
# Same test as above but using `preserve_shape` option to simplify.
rng = np.random.default_rng(5651219684984213)
def f(x):
return [x - 2.5, # converges
np.exp(x)*rng.random(), # error increases
np.exp(x), # reaches maxiter due to order=2
np.full_like(x, np.nan)[()]] # stops due to NaN
res = differentiate(f, 1, rtol=1e-14, order=2, preserve_shape=True)
ref_flags = np.array([eim._ECONVERGED,
_EERRORINCREASE,
eim._ECONVERR,
eim._EVALUEERR])
assert_equal(res.status, ref_flags)
def test_preserve_shape(self):
# Test `preserve_shape` option
def f(x):
return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]
x = 0
ref = [1, 3*np.cos(3*x), 1+10*np.cos(10*x),
20*np.cos(20*x)*(x-1)**2 + 2*np.sin(20*x)*(x-1)]
res = differentiate(f, x, preserve_shape=True)
assert_allclose(res.df, ref)
def test_convergence(self):
# Test that the convergence tolerances behave as expected
dist = stats.norm()
x = 1
f = dist.cdf
ref = dist.pdf(x)
kwargs0 = dict(atol=0, rtol=0, order=4)
kwargs = kwargs0.copy()
kwargs['atol'] = 1e-3
res1 = differentiate(f, x, **kwargs)
assert_array_less(abs(res1.df - ref), 1e-3)
kwargs['atol'] = 1e-6
res2 = differentiate(f, x, **kwargs)
assert_array_less(abs(res2.df - ref), 1e-6)
assert_array_less(abs(res2.df - ref), abs(res1.df - ref))
kwargs = kwargs0.copy()
kwargs['rtol'] = 1e-3
res1 = differentiate(f, x, **kwargs)
assert_array_less(abs(res1.df - ref), 1e-3 * np.abs(ref))
kwargs['rtol'] = 1e-6
res2 = differentiate(f, x, **kwargs)
assert_array_less(abs(res2.df - ref), 1e-6 * np.abs(ref))
assert_array_less(abs(res2.df - ref), abs(res1.df - ref))
def test_step_parameters(self):
# Test that step factors have the expected effect on accuracy
dist = stats.norm()
x = 1
f = dist.cdf
ref = dist.pdf(x)
res1 = differentiate(f, x, initial_step=0.5, maxiter=1)
res2 = differentiate(f, x, initial_step=0.05, maxiter=1)
assert abs(res2.df - ref) < abs(res1.df - ref)
res1 = differentiate(f, x, step_factor=2, maxiter=1)
res2 = differentiate(f, x, step_factor=20, maxiter=1)
assert abs(res2.df - ref) < abs(res1.df - ref)
# `step_factor` can be less than 1: `initial_step` is the minimum step
kwargs = dict(order=4, maxiter=1, step_direction=0)
res = differentiate(f, x, initial_step=0.5, step_factor=0.5, **kwargs)
ref = differentiate(f, x, initial_step=1, step_factor=2, **kwargs)
assert_allclose(res.df, ref.df, rtol=5e-15)
# This is a similar test for one-sided difference
kwargs = dict(order=2, maxiter=1, step_direction=1)
res = differentiate(f, x, initial_step=1, step_factor=2, **kwargs)
ref = differentiate(f, x, initial_step=1/np.sqrt(2), step_factor=0.5,
**kwargs)
assert_allclose(res.df, ref.df, rtol=5e-15)
kwargs['step_direction'] = -1
res = differentiate(f, x, initial_step=1, step_factor=2, **kwargs)
ref = differentiate(f, x, initial_step=1/np.sqrt(2), step_factor=0.5,
**kwargs)
assert_allclose(res.df, ref.df, rtol=5e-15)
def test_step_direction(self):
# test that `step_direction` works as expected
def f(x):
y = np.exp(x)
y[(x < 0) + (x > 2)] = np.nan
return y
x = np.linspace(0, 2, 10)
step_direction = np.zeros_like(x)
step_direction[x < 0.6], step_direction[x > 1.4] = 1, -1
res = differentiate(f, x, step_direction=step_direction)
assert_allclose(res.df, np.exp(x))
assert np.all(res.success)
def test_vectorized_step_direction_args(self):
# test that `step_direction` and `args` are vectorized properly
def f(x, p):
return x ** p
def df(x, p):
return p * x ** (p - 1)
x = np.array([1, 2, 3, 4]).reshape(-1, 1, 1)
hdir = np.array([-1, 0, 1]).reshape(1, -1, 1)
p = np.array([2, 3]).reshape(1, 1, -1)
res = differentiate(f, x, step_direction=hdir, args=(p,))
ref = np.broadcast_to(df(x, p), res.df.shape)
assert_allclose(res.df, ref)
def test_maxiter_callback(self):
# Test behavior of `maxiter` parameter and `callback` interface
x = 0.612814
dist = stats.norm()
maxiter = 3
def f(x):
res = dist.cdf(x)
return res
default_order = 8
res = differentiate(f, x, maxiter=maxiter, rtol=1e-15)
assert not np.any(res.success)
assert np.all(res.nfev == default_order + 1 + (maxiter - 1)*2)
assert np.all(res.nit == maxiter)
def callback(res):
callback.iter += 1
callback.res = res
assert hasattr(res, 'x')
assert res.df not in callback.dfs
callback.dfs.add(res.df)
assert res.status == eim._EINPROGRESS
if callback.iter == maxiter:
raise StopIteration
callback.iter = -1 # callback called once before first iteration
callback.res = None
callback.dfs = set()
res2 = differentiate(f, x, callback=callback, rtol=1e-15)
# terminating with callback is identical to terminating due to maxiter
# (except for `status`)
for key in res.keys():
if key == 'status':
assert res[key] == eim._ECONVERR
assert callback.res[key] == eim._EINPROGRESS
assert res2[key] == eim._ECALLBACK
else:
assert res2[key] == callback.res[key] == res[key]
@pytest.mark.parametrize("hdir", (-1, 0, 1))
@pytest.mark.parametrize("x", (0.65, [0.65, 0.7]))
@pytest.mark.parametrize("dtype", (np.float16, np.float32, np.float64))
def test_dtype(self, hdir, x, dtype):
# Test that dtypes are preserved
x = np.asarray(x, dtype=dtype)[()]
def f(x):
assert x.dtype == dtype
return np.exp(x)
def callback(res):
assert res.x.dtype == dtype
assert res.df.dtype == dtype
assert res.error.dtype == dtype
res = differentiate(f, x, order=4, step_direction=hdir,
callback=callback)
assert res.x.dtype == dtype
assert res.df.dtype == dtype
assert res.error.dtype == dtype
eps = np.finfo(dtype).eps
assert_allclose(res.df, np.exp(res.x), rtol=np.sqrt(eps))
def test_input_validation(self):
# Test input validation for appropriate error messages
message = '`func` must be callable.'
with pytest.raises(ValueError, match=message):
differentiate(None, 1)
message = 'Abscissae and function output must be real numbers.'
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, -4+1j)
message = "When `preserve_shape=False`, the shape of the array..."
with pytest.raises(ValueError, match=message):
differentiate(lambda x: [1, 2, 3], [-2, -3])
message = 'Tolerances and step parameters must be non-negative...'
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, atol=-1)
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, rtol='ekki')
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, initial_step=None)
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, step_factor=object())
message = '`maxiter` must be a positive integer.'
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, maxiter=1.5)
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, maxiter=0)
message = '`order` must be a positive integer'
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, order=1.5)
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, order=0)
message = '`preserve_shape` must be True or False.'
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, preserve_shape='herring')
message = '`callback` must be callable.'
with pytest.raises(ValueError, match=message):
differentiate(lambda x: x, 1, callback='shrubbery')
def test_special_cases(self):
# Test edge cases and other special cases
# Test that integers are not passed to `f`
# (otherwise this would overflow)
def f(x):
assert np.issubdtype(x.dtype, np.floating)
return x ** 99 - 1
res = differentiate(f, 7, rtol=1e-10)
assert res.success
assert_allclose(res.df, 99*7.**98)
# Test that if success is achieved in the correct number
# of iterations if function is a polynomial. Ideally, all polynomials
# of order 0-2 would get exact result with 0 refinement iterations,
# all polynomials of order 3-4 would be differentiated exactly after
# 1 iteration, etc. However, it seems that _differentiate needs an
# extra iteration to detect convergence based on the error estimate.
for n in range(6):
x = 1.5
def f(x):
return 2*x**n
ref = 2*n*x**(n-1)
res = differentiate(f, x, maxiter=1, order=max(1, n))
assert_allclose(res.df, ref, rtol=1e-15)
assert_equal(res.error, np.nan)
res = differentiate(f, x, order=max(1, n))
assert res.success
assert res.nit == 2
assert_allclose(res.df, ref, rtol=1e-15)
# Test scalar `args` (not in tuple)
def f(x, c):
return c*x - 1
res = differentiate(f, 2, args=3)
assert_allclose(res.df, 3)
@pytest.mark.xfail
@pytest.mark.parametrize("case", ( # function, evaluation point
(lambda x: (x - 1) ** 3, 1),
(lambda x: np.where(x > 1, (x - 1) ** 5, (x - 1) ** 3), 1)
))
def test_saddle_gh18811(self, case):
# With default settings, _differentiate will not always converge when
# the true derivative is exactly zero. This tests that specifying a
# (tight) `atol` alleviates the problem. See discussion in gh-18811.
atol = 1e-16
res = differentiate(*case, step_direction=[-1, 0, 1], atol=atol)
assert np.all(res.success)
assert_allclose(res.df, 0, atol=atol)
|