def distmfld(q1, c1, q2, c2):
    """ Computes (batchwise) the distance between two batches of points in a
    manifold.

    Parameters
    ----------
    q1 : torch.tensor
        shape [nc, n] giving chart membership probabilities for the first batch
        of points.
    c1 : torch.tensor
        shape [nc, n, d] giving the coordinates for the first batch of points.
    q2 : torch.tensor
        shape [nc, n] giving chart membership probabilities for the second batch
        of points.
    c2 : torch.tensor
        shape [nc, n, d] giving the coordinates for the first batch of points.

    where nc is the number of coordinate charts, n is the number of points
    (e.g. batch size), and d is the dimension of the manifold.

    Returns
    -------
    torch.tensor
        has shape n. the ith component is the manifold distance between the point
        defined by q1[:, i], c1[:, i, :] and the point q2[:, i], c2[:, i, :]
    """
    q1q2_sum = (q1 * q2).sum(0)
    return ((q1 * q2 * ((c1 - c2) ** 2).mean(2)).sum(0) / q1q2_sum).masked_fill(
        q1q2_sum == 0, 1
    )