Path: blob/master/kf_book/DogSimulation.py
687 views
# -*- coding: utf-8 -*-12"""Copyright 2015 Roger R Labbe Jr.345Code supporting the book67Kalman and Bayesian Filters in Python8https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python91011This is licensed under an MIT license. See the LICENSE.txt file12for more information.13"""1415from __future__ import (absolute_import, division, print_function,16unicode_literals)171819import copy20import math21import numpy as np22from numpy.random import randn2324class DogSimulation(object):2526def __init__(self, x0=0, velocity=1,27measurement_var=0.0, process_var=0.0):28""" x0 - initial position29velocity - (+=right, -=left)30measurement_variance - variance in measurement m^231process_variance - variance in process (m/s)^232"""33self.x = x034self.velocity = velocity35self.measurement_noise = math.sqrt(measurement_var)36self.process_noise = math.sqrt(process_var)373839def move(self, dt=1.0):40'''Compute new position of the dog assuming `dt` seconds have41passed since the last update.'''42# compute new position based on velocity. Add in some43# process noise44velocity = self.velocity + randn() * self.process_noise * dt45self.x += velocity * dt464748def sense_position(self):49# simulate measuring the position with noise50return self.x + randn() * self.measurement_noise515253def move_and_sense(self, dt=1.0):54self.move(dt)55x = copy.deepcopy(self.x)56return x, self.sense_position()575859def run_simulation(self, dt=1, count=1):60""" simulate the dog moving over a period of time.6162**Returns**63data : np.array[float, float]642D array, first column contains actual position of dog,65second column contains the measurement of that position66"""67return np.array([self.move_and_sense(dt) for i in range(count)])6869707172737475