Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rlabbe
GitHub Repository: rlabbe/Kalman-and-Bayesian-Filters-in-Python
Path: blob/master/kf_book/DogSimulation.py
687 views
1
# -*- coding: utf-8 -*-
2
3
"""Copyright 2015 Roger R Labbe Jr.
4
5
6
Code supporting the book
7
8
Kalman and Bayesian Filters in Python
9
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
10
11
12
This is licensed under an MIT license. See the LICENSE.txt file
13
for more information.
14
"""
15
16
from __future__ import (absolute_import, division, print_function,
17
unicode_literals)
18
19
20
import copy
21
import math
22
import numpy as np
23
from numpy.random import randn
24
25
class DogSimulation(object):
26
27
def __init__(self, x0=0, velocity=1,
28
measurement_var=0.0, process_var=0.0):
29
""" x0 - initial position
30
velocity - (+=right, -=left)
31
measurement_variance - variance in measurement m^2
32
process_variance - variance in process (m/s)^2
33
"""
34
self.x = x0
35
self.velocity = velocity
36
self.measurement_noise = math.sqrt(measurement_var)
37
self.process_noise = math.sqrt(process_var)
38
39
40
def move(self, dt=1.0):
41
'''Compute new position of the dog assuming `dt` seconds have
42
passed since the last update.'''
43
# compute new position based on velocity. Add in some
44
# process noise
45
velocity = self.velocity + randn() * self.process_noise * dt
46
self.x += velocity * dt
47
48
49
def sense_position(self):
50
# simulate measuring the position with noise
51
return self.x + randn() * self.measurement_noise
52
53
54
def move_and_sense(self, dt=1.0):
55
self.move(dt)
56
x = copy.deepcopy(self.x)
57
return x, self.sense_position()
58
59
60
def run_simulation(self, dt=1, count=1):
61
""" simulate the dog moving over a period of time.
62
63
**Returns**
64
data : np.array[float, float]
65
2D array, first column contains actual position of dog,
66
second column contains the measurement of that position
67
"""
68
return np.array([self.move_and_sense(dt) for i in range(count)])
69
70
71
72
73
74
75