def test_substration_and_negation(): x = ad.Variable("x") y = ad.Exp(2 * x) - x yd1 = y.d_expr() assert np.isclose(yd1.eval({x: 0.0}), 1.0) y = -ad.Exp(3 * x) yd1 = y.d_expr() assert np.isclose(yd1.eval({x: 0.0}), -3.0)
def test_single_variable_trig_hyperbolic_2(): x = ad.Variable() # x^2 Cosh[Sin[x] + Tanh[Exp[3 * x] + Log[x]]] g = ad.Sin(x) + ad.Tanh(ad.Exp(3 * x) + ad.Log(x)) f = x * x * ad.Cosh(g) assert (equals(f.hessian({x: 1}), 11.464317742)) assert (equals(f.hessian({x: 2}), -13.704377252))
def test_logexp_multivar_hessian_2(): x, y, z = ad.Variable(), ad.Variable(), ad.Variable() f = ad.Sinh(ad.Exp(x - 3.0) * y) + ad.Log(y + x**2) * z * ad.Sin(x) h = f.hessian({x: 1, y: 3, z: 5}) assert (equals(h[x][x], -1.5705707143)) assert (equals(h[y][y], -0.2553174360)) assert (equals(h[z][z], 0)) assert (equals(h[x][y], 0.31902899408)) assert (equals(h[y][z], 0.2103677462)) assert (equals(h[x][z], 1.1697535323))
def test_exp_exceptions(): x = ad.Variable('x') y = ad.Exp(x) z = ad.Cos(x) a = ad.Log(x) b = ad.Sin(x) f1 = y*2 + y f2 = z*2 + z f3 = a*2 + a f4 = b*2 + b assert np.isclose(f1.d_n(1, 1), 8.154845485377136) assert np.isclose(f2.d_n(1, 1), -2.5244129544236893) assert np.isclose(f3.d_n(1, 1), 3.0) assert np.isclose(f4.d_n(1, 1), 1.6209069176044193)
def test_hyperbolic_expressions(): x = ad.Variable('x') y = ad.Variable('y') f1 = ad.Tan(x) f2 = ad.Sinh(x) f3 = ad.Cosh(x) f4 = ad.Tanh(x) f5 = ad.Exp(x) f6 = ad.Cos(x) assert f1._d_expr(y).eval({x:1}) == 0 assert np.isclose(f1._d_expr(x).eval({x:1}), f1.d({x: 1})) assert f2._d_expr(y).eval({x:1}) == 0 assert np.isclose(f2._d_expr(x).eval({x:1}), f2.d({x: 1})) assert f3._d_expr(y).eval({x:1}) == 0 assert np.isclose(f3._d_expr(x).eval({x:1}), f3.d({x: 1})) assert f4._d_expr(y).eval({x:1}) == 0 assert np.isclose(f4._d_expr(x).eval({x:1}), f4.d({x: 1})) assert f5._d_expr(y).eval({x:1}) == 0 assert np.isclose(f5._d_expr(x).eval({x:1}), f5.d({x: 1})) assert f6._d_expr(y).eval({x:1}) == 0 assert np.isclose(f6._d_expr(x).eval({x:1}), f6.d({x: 1}))
def test_unop(): x = ad.Variable("x") y = -x assert np.isclose(y.d_n(n=0, val=2.0), -2.0) assert np.isclose(y.d_n(n=1, val=2.0), -1.0) assert np.isclose(y.d_n(n=2, val=2.0), 0.0) y = ad.Sin(2 * x) assert np.isclose(y.d_n(n=0, val=0.0), 0.0) assert np.isclose(y.d_n(n=1, val=0.0), 2.0) assert np.isclose(y.d_n(n=3, val=0.0), -8.0) y = ad.Exp(3 * x) assert np.isclose(y.d_n(n=0, val=0.0), 1.0) assert np.isclose(y.d_n(n=1, val=0.0), 3.0) assert np.isclose(y.d_n(n=3, val=0.0), 27.0) y = ad.Log(2 * x) assert np.isclose(y.d_n(n=0, val=0.5), 0.0) assert np.isclose(y.d_n(n=1, val=0.5), 2.0) assert np.isclose(y.d_n(n=3, val=0.5), 2.0 / (0.5**3))
def test_exp_expression(): a = ad.Variable('a') b = ad.Exp(a) assert np.isclose(b.eval({a: 1}), 2.718281828459045) assert np.isclose(b.d({a: 1}), 2.718281828459045)