Theoretical analysis of the evolution of immune memory