Understanding the valency of rare earths from first-principles theory