PurposeThis study aims to optimize electrical systems represented by ordinary differential equations and events, using their frequency spectrum is an important purpose for designers, especially to calculate harmonics.Design/methodology/approachThis paper presents a methodology to achieve this, by using a gradient-based optimization algorithm. The paper proposes to use a time simulation of the electrical system, and then to compute its frequency spectrum in the optimization loop.FindingsThe paper shows how to proceed efficiently to compute the frequency spectrum of an electrical system to include it in an optimization loop. Derivatives of the frequency spectrum such as the optimization inputs can also be calculated. This is possible even if the sized system behavior cannot be defined a priori, e.g. when there are static converters or electrical devices with natural switching.Originality/valueUsing an efficient sequential quadratic programming optimizer, automatic differentiation is used to compute the model gradients. Frequency spectrum derivatives with respect to the optimization inputs are calculated by an analytical formula. The methodology uses a “white-box” approach so that automatic differentiation and the differential equations simulator can be used, unlike most state-of-the-art simulators.