Tracking a changing environment: optimal sampling, adaptive memory and overnight effects