import torch


def from_rotation_matrix(mtr):
    """
    See
    http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
    """
    mtr = torch.from_numpy(mtr)
    def m(j, i):
        shape = mtr.shape
        begin = [0 for _ in range(len(shape))]
        begin[-2] = j
        begin[-1] = i
        size = [s for s in shape]
        size[-2] = 1
        size[-1] = 1
        v = mtr[:,j:j+1,i:i+1]
        v = v.squeeze()
        return v

    w = torch.sqrt(1.0 + m(0, 0) + m(1, 1) + m(2, 2)) / 2
    x = (m(2, 1) - m(1, 2)) / (4 * w)
    y = (m(0, 2) - m(2, 0)) / (4 * w)
    z = (m(1, 0) - m(0, 1)) / (4 * w)
    q = torch.stack([w, x, y, z], dim=-1)
    return q