Principles of Dynamics and Inference, with Applications to the Brain