  For a fixed graph $H$ and for arbitrarily large host graphs $G$, the number
of homomorphisms from $H$ to $G$ and the number of subgraphs isomorphic to $H$
contained in $G$ have been extensively studied in extremal graph theory and
graph limits theory when the host graphs are allowed to be dense. This paper
addresses the case when the host graphs are robustly sparse and proves a
general theorem that solves a number of open questions proposed since 1990s and
strengthens a number of results in the literature.
  We prove that for any graph $H$ and any set ${\mathcal H}$ of homomorphisms
from $H$ to members of a hereditary class ${\mathcal G}$ of graphs, if
${\mathcal H}$ satisfies a natural and mild condition, and contracting disjoint
subgraphs of radius $O(\lvert V(H) \rvert)$ in members of ${\mathcal G}$ cannot
create a graph with large edge-density, then an obvious lower bound for the
size of ${\mathcal H}$ gives a good estimation for the size of ${\mathcal H}$.
This result determines the maximum number of $H$-homomorphisms, the maximum
number of $H$-subgraphs, and the maximum number $H$-induced subgraphs in graphs
in any hereditary class with bounded expansion up to a constant factor; it also
determines the exact value of the asymptotic logarithmic density for
$H$-homomorphisms, $H$-subgraphs and $H$-induced subgraphs in graphs in any
hereditary nowhere dense class. Hereditary classes with bounded expansion
include (topological) minor-closed families and many classes of graphs with
certain geometric properties; nowhere dense classes are the most general sparse
classes in sparsity theory. Our machinery also allows us to determine the
maximum number of $H$-subgraphs in the class of all $d$-degenerate graphs with
any fixed $d$.
