Optimal Control of Epidemics in the Presence of Heterogeneity