Remove outlier 'atoms' (aka bins) from a structure.

def trim_structure(struct, filtering="cube", n=2):
    """Remove outlier 'atoms' (aka bins) from a structure.
    """

    X, Y, Z = (struct[:, i] for i in range(3))

    if filtering == "sphere":
        R = (np.std(X)**2 + np.std(Y)**2 + np.std(Z)**2) * (n**2)
        f = (X - np.mean(X))**2 + (Y - np.mean(Y))**2 + (Z - np.mean(Z))**2 < R

    if filtering == "cube":
        R = min(np.std(X), np.std(Y), np.std(Z)) * n
        f = np.ones(len(X))
        for C in (X, Y, Z):
            f *= np.abs(C - np.mean(C)) < R

    if filtering == "percentile":
        f = np.ones(len(X))
        for C in (X, Y, Z):
            f *= np.abs(C - np.mean(C)
                        ) < np.percentile(np.abs(C - np.mean(C)), n)

    return np.array([X[f], Y[f], Z[f]])