Gauge invariance, charge conservation, and variational principles