def gell_mann_basis(dim):
    """    
    Returns a :class:`~qinfer.tomography.TomographyBasis` on dim dimensions
    using the generalized Gell-Mann matrices.

    This implementation is based on a MATLAB-language implementation
    provided by Carlos Riofrío, Seth Merkel and Andrew Silberfarb.
    Used with permission.

    :param int dim: Dimension of the individual matrices making up
        the returned basis.
    :rtype: :class:`~qinfer.tomography.TomographyBasis`
    :return: A basis of ``dim * dim`` Gell-Mann matrices.
    """
    # Start by making an empty array of the right shape to
    # hold the matrices that we construct.
    basis = np.zeros((dim**2, dim, dim), dtype=complex)

    # The first matrix should be the identity.
    basis[0, :, :] = np.eye(dim) / np.sqrt(dim)

    # The next dim basis elements should be diagonal,
    # with all by one element nonnegative.
    for idx_basis in range(1, dim):
        basis[idx_basis, :, :] = np.diag(np.concatenate([
            np.ones((idx_basis, )),
            [-idx_basis],
            np.zeros((dim - idx_basis - 1, ))
        ])) / np.sqrt(idx_basis + idx_basis**2)

    # Finally, we get the off-diagonal matrices.
    # These rely on some index gymnastics I don't yet fully
    # understand.
    y_offset = dim * (dim - 1) // 2
    for idx_i in range(1, dim):
        for idx_j in range(idx_i):
            idx_basis = (idx_i - 1) * (idx_i) // 2 + idx_j + dim
            basis[idx_basis, [idx_i, idx_j], [idx_j, idx_i]] = 1 / np.sqrt(2)
            basis[idx_basis + y_offset, [idx_i, idx_j], [idx_j, idx_i]] = [1j / np.sqrt(2), -1j / np.sqrt(2)]

    return TomographyBasis(basis, [dim], r'\gamma', name='gell_mann_basis')
Returns a :class:`~qinfer.tomography.TomographyBasis` on dim dimensions
    using the generalized Gell-Mann matrices.

    This implementation is based on a MATLAB-language implementation
    provided by Carlos Riofrío, Seth Merkel and Andrew Silberfarb.
    Used with permission.

    :param int dim: Dimension of the individual matrices making up
        the returned basis.
    :rtype: :class:`~qinfer.tomography.TomographyBasis`
    :return: A basis of ``dim * dim`` Gell-Mann matrices.