Dynamic optimization of energy systems with thermal energy storage