A general scheme for ensemble purification