  We develop a general optimization strategy for performing a chosen unitary or
non-unitary task on an open quantum system. The goal is to design a controlled
time-dependent system Hamiltonian by variationally minimizing or maximizing a
chosen function of the system state, which quantifies the task success (score),
such as fidelity, purity, or entanglement. If the time-dependence of the system
Hamiltonian is fast enough to be comparable or shorter than the response-time
of the bath, then the resulting non-Markovian dynamics is shown to optimize the
chosen task score to second order in the coupling to the bath. This strategy
can protect a desired unitary system evolution from bath-induced decoherence,
but ca also take advantage of the system-bath coupling so as to realize a
desired non-unitary effect on the system.
