The goal of frequency control is to balance power supply and demand to synchronize the frequency and maintain it to the nominal value. We reverse-engineer the swing dynamics with frequency control with general control functions, and show that it is a distributed algorithm to solve a well-defined global optimization problem. The optimization based model connects local controls with certain systemwide objective, and provides a unique perspective to understand the global properties that arise from interactions between local controls. By engineering the optimization model, we can design different frequency control schemes to achieve various objectives such as economic efficiency.