`np.all(np.logical_and(contacts >= 0, contacts < traj.n_residues))` would be more robust.