def test_run_hamiltonian(self): # Important to restrict the step in order to avoid the # discontinutiy at x=[0,0] of the hamiltonian for method in ['central', 'complex']: step = nd.MaxStepGenerator(base_step=1e-4) hessian = nd.Hessian(None, step=step, method=method) h, _error_estimate, true_h = run_hamiltonian(hessian, verbose=False) assert (np.abs((h - true_h) / true_h) < 1e-4).all()
def test_hessian_cos_x_y_at_0_0(): # cos(x-y), at (0,0) def fun(xy): return np.cos(xy[0] - xy[1]) htrue = [[-1., 1.], [1., -1.]] methods = [ 'multicomplex', 'complex', 'central', 'central2', 'forward', 'backward' ] for num_steps in [10, 1]: step = nd.MinStepGenerator(num_steps=num_steps) for method in methods: h_fun = nd.Hessian(fun, method=method, step=step, full_output=True) h_val, _info = h_fun([0, 0]) # print(method, (h_val-np.array(htrue))) assert_allclose(h_val, htrue)
def test_complex_hessian_issue_35(self): """ """ def foo(x): return 1j * np.inner(x, x) for method in [ 'multicomplex', 'complex', 'central', 'central2', 'forward', 'backward' ]: for offset in [0, 1j]: # testing real and complex argument print(method) x = np.random.randn(3) + offset hessn = nd.Hessian(foo, method=method) if method.endswith('complex'): self.assertRaises(ValueError, hessn, x) else: val = hessn(x) assert_allclose(val, [[2j, 0j, 0j], [0j, 2j, 0j], [0j, 0j, 2j]], atol=1e-13)
def test_hessian_cosIx_yI_at_I0_0I(): # cos(x-y), at (0,0) def fun(xy): return np.cos(xy[0] - xy[1]) htrue = [[-1., 1.], [1., -1.]] methods = [ 'multicomplex', 'complex', 'central', 'central2', 'forward', 'backward' ] for num_steps in [10, 1]: step = nd.MinStepGenerator(num_steps=num_steps) for method in methods: Hfun2 = nd.Hessian(fun, method=method, step=step, full_output=True) h2, _info = Hfun2([0, 0]) # print(method, (h2-np.array(htrue))) assert_array_almost_equal(h2, htrue)