def test_sdtw(self):
        X, Y = _make_time_series(size_X=3, size_Y=4, num_dim=2)
        C = squared_euclidean_cost(X, Y)

        assert_almost_equal(sdtw_C(C), _sdtw_brute_force(C))
        assert_almost_equal(sdtw_C(C), sdtw_value_and_grad_C(C)[0])
        assert_almost_equal(sdtw_C(C), sdtw(X, Y))

        assert_almost_equal(sdtw_C(C, gamma=0.1),
                            _sdtw_brute_force(C, gamma=0.1))
        assert_almost_equal(sdtw_C(C, gamma=0.1),
                            sdtw_value_and_grad_C(C, gamma=0.1)[0])
    def test_sdtw_entropy(self):
        X, Y = _make_time_series(size_X=3, size_Y=4, num_dim=2)
        C = squared_euclidean_cost(X, Y)

        gamma = 1.0
        eps = 1e-6
        p = _probas(C, gamma=gamma)
        H1 = -np.dot(p, np.log(p))
        H2 = sdtw_entropy_C(C, gamma=gamma)
        H3 = -(sdtw_C(C, gamma + eps) - sdtw_C(C, gamma - eps)) / (2 * eps)
        H4 = sdtw_entropy(X, Y, gamma=gamma)
        assert_almost_equal(H1, H2)
        assert_almost_equal(H1, H3)
        assert_almost_equal(H1, H4)
    def test_sdtw_grad_C(self):
        X, Y = _make_time_series(size_X=3, size_Y=4, num_dim=2)
        C = squared_euclidean_cost(X, Y)

        V, P = sdtw_C(C, return_all=True)
        G = sdtw_grad_C(P)
        G_num = _num_gradient(sdtw_C, C)
        G_bf = _expectation_brute_force(C)
        assert_array_almost_equal(G, G_num)
        assert_array_almost_equal(G, G_bf)

        # Check value_and_grad.
        for gamma in (0.1, 1.0):
            G = sdtw_value_and_grad_C(C, gamma=gamma)[1]
            G_bf = _expectation_brute_force(C, gamma=gamma)
            assert_array_almost_equal(G, G_bf)
    def test_sdtw_hessian_product(self):
        def f(C, M):
            V, P = sdtw_C(C, return_all=True)
            return sdtw_directional_derivative_C(P, M)

        X, Y = _make_time_series(size_X=3, size_Y=4, num_dim=2)
        C = squared_euclidean_cost(X, Y)

        V, P = sdtw_C(C, return_all=True)
        E = sdtw_grad_C(P, return_all=True)
        V_dot = sdtw_directional_derivative_C(P, C, return_all=True)
        hvp = sdtw_hessian_product_C(P, E, V_dot)
        hvp_num = _num_gradient(functools.partial(f, M=C), C)
        # The Hessian product is equal to the gradient of the directional derivative.
        assert_array_almost_equal(hvp, hvp_num)

        # Check that wrong inputs raise an exception.
        assert_raises(ValueError, sdtw_hessian_product_C, P, E, X)
        assert_raises(ValueError, sdtw_hessian_product_C, P, X, V_dot)
 def f(X, Y):
     C = squared_euclidean_cost(X, Y, log=True)
     return sdtw_C(C)
 def f(C, M):
     V, P = sdtw_C(C, return_all=True)
     return sdtw_directional_derivative_C(P, M)