  Quantum Entanglement is a fundamentally important resource in Quantum
Information Science; however, generating it in practice is plagued by noise and
decoherence, limiting its utility. Entanglement distillation and forward error
correction are the tools we employ to combat this noise, but designing the best
distillation and error correction circuits that function well, especially on
today's imperfect hardware, is still challenging. Here, we develop a simulation
algorithm for distillation circuits with gate-simulation complexity of
$\mathcal{O}(1)$ steps, providing for drastically faster modeling compared to
$\mathcal{O}(n)$ Clifford simulators or $\mathcal{O}(2^n)$ wavefunction
simulators over $n$ qubits.
  This new simulator made it possible to not only model but also optimize
practically interesting purification circuits. It enabled us to use a simple
discrete optimization algorithm to design purification circuits from $n$ raw
Bell pairs to $k$ purified pairs and study the use of these circuits in the
teleportation of logical qubits in second-generation quantum repeaters. The
resulting purification circuits are the best-known purification circuits for
finite-size noisy hardware and can be fine-tuned for specific hardware error
models. Furthermore, we design purification circuits that shape the
correlations of errors in the purified pairs such that the performance of the
error-correcting code used in teleportation or other higher-level protocols is
greatly improved. Our approach of optimizing multiple layers of the networking
stack, both the low-level entanglement purification, and the forward error
correction on top of it, are shown to be indispensable for the design of
high-performance second-generation quantum repeaters.
