How to use the geomstats.backend.to_ndarray function in geomstats

To help you get started, we’ve selected a few geomstats examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github geomstats / geomstats / geomstats / geometry / hyperbolic_space.py View on Github external
"""
        if self.point_type == 'ball':
            return self.belongs_to[self.point_type](point, tolerance=tolerance)
        else:
            point = gs.to_ndarray(point, to_ndim=2)
            _, point_dim = point.shape
            if point_dim is not self.dimension + 1:
                if point_dim is self.dimension:
                    logging.warning(
                        'Use the extrinsic coordinates to '
                        'represent points on the hyperbolic space.')
                    return gs.array([[False]])

            sq_norm = self.embedding_metric.squared_norm(point)
            euclidean_sq_norm = gs.linalg.norm(point, axis=-1) ** 2
            euclidean_sq_norm = gs.to_ndarray(euclidean_sq_norm,
                                              to_ndim=2, axis=1)
            diff = gs.abs(sq_norm + 1)
            belongs = diff < tolerance * euclidean_sq_norm
            return belongs
github geomstats / geomstats / geomstats / geometry / special_orthogonal3.py View on Github external
default: 'extrinsic'
        order : str, {'xyz', 'zyx'}, optional
            default: 'zyx'

        Returns
        -------
        rot_mat : array-like, shape=[n_samples, n, n]
        """
        assert self.n == 3, ('The Tait-Bryan angles representation'
                             ' does not exist'
                             ' for rotations in %d dimensions.' % self.n)

        assert extrinsic_or_intrinsic in ('extrinsic', 'intrinsic')
        assert order in ('xyz', 'zyx')

        tait_bryan_angles = gs.to_ndarray(tait_bryan_angles, to_ndim=2)

        extrinsic_zyx = (extrinsic_or_intrinsic == 'extrinsic'
                         and order == 'zyx')
        intrinsic_xyz = (extrinsic_or_intrinsic == 'intrinsic'
                         and order == 'xyz')

        extrinsic_xyz = (extrinsic_or_intrinsic == 'extrinsic'
                         and order == 'xyz')
        intrinsic_zyx = (extrinsic_or_intrinsic == 'intrinsic'
                         and order == 'zyx')

        if extrinsic_zyx:
            rot_mat = self.matrix_from_tait_bryan_angles_extrinsic_zyx(
                tait_bryan_angles)
        elif intrinsic_xyz:
            tait_bryan_angles_reversed = gs.flip(tait_bryan_angles, axis=1)
github geomstats / geomstats / geomstats / special_orthogonal_group.py View on Github external
assert mat_dim == self.n

        skew_mat = gs.zeros((n_vecs,) + (self.n,) * 2)
        if self.n == 3:
            for i in range(n_vecs):
                mask_i_float = get_mask_i_float(i, n_vecs)

                basis_vec_1 = gs.array([1., 0., 0.])
                basis_vec_2 = gs.array([0., 1., 0.])
                basis_vec_3 = gs.array([0., 0., 1.])

                cross_prod_1 = gs.cross(basis_vec_1, vec[i])
                cross_prod_2 = gs.cross(basis_vec_2, vec[i])
                cross_prod_3 = gs.cross(basis_vec_3, vec[i])

                cross_prod_1 = gs.to_ndarray(cross_prod_1, to_ndim=2)
                cross_prod_2 = gs.to_ndarray(cross_prod_2, to_ndim=2)
                cross_prod_3 = gs.to_ndarray(cross_prod_3, to_ndim=2)

                cross_prod_i = gs.concatenate(
                    [cross_prod_1, cross_prod_2, cross_prod_3], axis=0)

                #print(gs.shape(n_vecs))
                #n_vecs = gs.array([n_vecs])
                #print(gs.shape(n_vecs))
                #cross_prod_i = gs.to_ndarray(cross_prod_i, to_ndim=3)
                #cross_prod_i = gs.tile(cross_prod_i, (n_vecs, 1, 1))

                skew_mat += gs.einsum(
                    'n,ij->nij', mask_i_float, cross_prod_i)
        else:
            upper_triangle_indices = gs.triu_indices(mat_dim, k=1)
github geomstats / geomstats / geomstats / geometry / riemannian_metric.py View on Github external
base_point: array-like, shape=[..., dim]
            Base point.
            Optional, default: None.

        Returns
        -------
        inner_product : array-like, shape=[...,]
            Inner-product.
        """
        inner_prod_mat = self.inner_product_matrix(base_point)
        inner_prod_mat = gs.to_ndarray(inner_prod_mat, to_ndim=3)

        aux = gs.einsum('...j,...jk->...k', tangent_vec_a, inner_prod_mat)

        inner_prod = gs.einsum('...k,...k->...', aux, tangent_vec_b)
        inner_prod = gs.to_ndarray(inner_prod, to_ndim=1)
        inner_prod = gs.to_ndarray(inner_prod, to_ndim=2, axis=1)

        return inner_prod
github geomstats / geomstats / examples / gradient_descent_s2.py View on Github external
dpi=100,
                        out='out.mp4',
                        color='red'):
    """Render a set of geodesics and save it to an mpeg 4 file."""
    FFMpegWriter = animation.writers['ffmpeg']
    writer = FFMpegWriter(fps=fps)
    fig = plt.figure(figsize=(size, size))
    ax = fig.add_subplot(111, projection='3d')
    sphere = visualization.Sphere()
    sphere.plot_heatmap(ax, loss)
    points = gs.to_ndarray(geodesics[0], to_ndim=2)
    sphere.add_points(points)
    sphere.draw(ax, color=color, marker='.')
    with writer.saving(fig, out, dpi=dpi):
        for points in geodesics[1:]:
            points = gs.to_ndarray(points, to_ndim=2)
            sphere.draw_points(ax, points=points, color=color, marker='.')
            writer.grab_frame()
github geomstats / geomstats / geomstats / spd_matrices_space.py View on Github external
def sqrtm(sym_mat):
    sym_mat = gs.to_ndarray(sym_mat, to_ndim=3)

    [eigenvalues, vectors] = gs.linalg.eigh(sym_mat)

    sqrt_eigenvalues = gs.sqrt(eigenvalues)

    aux = gs.einsum('ijk,ik->ijk', vectors, sqrt_eigenvalues)
    sqrt_mat = gs.einsum('ijk,ilk->ijl', aux, vectors)

    sqrt_mat = gs.to_ndarray(sqrt_mat, to_ndim=3)
    return sqrt_mat
github geomstats / geomstats / geomstats / geometry / special_orthogonal3.py View on Github external
Returns
        -------
        regularized_tangent_vec : array-like,
            shape=[n_samples, 3]
        """
        if metric is None:
            metric = self.left_canonical_metric
        base_point = self.regularize(base_point)
        n_vecs = tangent_vec.shape[0]

        jacobian = self.jacobian_translation(
            point=base_point, left_or_right=metric.left_or_right)
        jacobian = gs.array([jacobian[0]] * n_vecs)
        inv_jacobian = gs.linalg.inv(jacobian)
        inv_jacobian = gs.to_ndarray(inv_jacobian, to_ndim=3)
        tangent_vec_at_id = gs.einsum(
            '...i,...ij->...j',
            tangent_vec,
            Matrices.transpose(inv_jacobian))

        tangent_vec_at_id = self.regularize_tangent_vec_at_identity(
            tangent_vec_at_id, metric)

        jacobian = gs.to_ndarray(jacobian, to_ndim=3)
        regularized_tangent_vec = gs.einsum(
            '...i,...ij->...j',
            tangent_vec_at_id,
            Matrices.transpose(jacobian))

        return regularized_tangent_vec
github geomstats / geomstats / geomstats / geometry / riemannian_metric.py View on Github external
print(n_points)

            if weights is None:
                weights = gs.ones((n_points, 1))

            weights = gs.array(weights)
            weights = gs.to_ndarray(weights, to_ndim=2, axis=1)

            sum_weights = gs.sum(weights)

            mean = points[0]
            if point_type == 'vector':
                mean = gs.to_ndarray(mean, to_ndim=2)
            if point_type == 'matrix':
                mean = gs.to_ndarray(mean, to_ndim=3)

            if n_points == 1:
                return mean

            sq_dists_between_iterates = []
            iteration = 0
            sq_dist = gs.array([[0.]])
            variance = gs.array([[0.]])

            last_iteration, mean, variance, sq_dist = gs.while_loop(
                lambda i, m, v, sq: while_loop_cond(i, m, v, sq),
                lambda i, m, v, sq: while_loop_body(i, m, v, sq),
                loop_vars=[iteration, mean, variance, sq_dist],
                maximum_iterations=n_max_iterations)

            if last_iteration == n_max_iterations:
github geomstats / geomstats / geomstats / spd_matrices_space.py View on Github external
def make_symmetric(mat):
    """Make a matrix fully symmetric to avoid numerical issues."""
    mat = gs.to_ndarray(mat, to_ndim=3)
    return (mat + gs.transpose(mat, axes=(0, 2, 1))) / 2
github geomstats / geomstats / geomstats / geometry / hyperbolic_space.py View on Github external
poincare ball coordinates
        """
        point_ball = \
            HyperbolicSpace._extrinsic_to_ball_coordinates(point)
        assert point_ball.shape[-1] == 2
        point_ball_x, point_ball_y = point_ball[:, 0], point_ball[:, 1]
        point_ball_x2 = point_ball_x**2
        denom = point_ball_x2 + (1-point_ball_y)**2

        point_ball_x = gs.to_ndarray(
            point_ball_x, to_ndim=2, axis=0)
        point_ball_y = gs.to_ndarray(
            point_ball_y, to_ndim=2, axis=0)
        point_ball_x2 = gs.to_ndarray(
            point_ball_x2, to_ndim=2, axis=0)
        denom = gs.to_ndarray(
            denom, to_ndim=2, axis=0)

        point_half_plane = gs.hstack((
            (2 * point_ball_x) / denom,
            (1 - point_ball_x2 - point_ball_y**2) / denom))
        return point_half_plane