A continuous system of moment equations is introduced that models the transverse dynamics of a beam of charged particles as it passes through an arbitrary lattice of quadrupoles and solenoids in the presence of self-fields. Then, figures of merit are introduced specifying system characteristics to be optimized. The resulting model is used to optimize the parameters of the lattice elements of a flat to round transformer with self-fields, as could be applied in electron cooling. Results are shown for a case of no self-fields and two cases with self-fields. The optimization is based on a gradient descent algorithm in which the gradient is calculated using adjoint methods that prove to be very computationally efficient. Two figures of merit are studied and compared: one emphasizing radial force balance in the solenoid, the other emphasizing minimization of transverse beam energy in the solenoid.