<jupyter_start><jupyter_text>Simulation<jupyter_code>def initialize_filter(x0, x0_v, dx0, dx0_v, dt, a, a_v, z_v):
    n, m, k = 2, 1, 1
    kf = KF(n, m, k)
    
    x = np.array([[x0, dx0]]).T
    f = np.array([[1, dt], [0, 1]])
    u = np.array([[a]]).T
    b = np.array([[(dt**2)/2.0, dt]]).T
    p = np.array([[x0_v, 0], [0, dx0_v]])
    q = np.array([[(dt**4)/4, (dt**3)/2], [(dt**3)/2, dt**2]]) * a_v
    h = np.array([[1, 0]])
    r = np.array([[z_v]])
    
    kf.initialize(_x=x, _F=f, _u=u, _B=b, _P=p, _Q=q, _H=h, _R=r)
    
    return kf
def propagate_in_time(x0, x0_v, dx0, dx0_v, dt, a, a_v, to):
    error = lambda var: np.random.randn() * np.sqrt(var)
    
    x0 = x0 + error(x0_v)
    pos, x, dx = [x0], x0, dx0 + error(dx0_v)
    
    for _ in range(to):
        x += dx * dt
        dx += (a + error(a_v)) * dt
        pos.append(x)
        
    return np.array(pos)

def make_observations(data, z_v):
    return data + np.random.randn(*data.shape) * np.sqrt(z_v)
def simple_simulation(x0, x0_std, dx0, dx0_std, dt, a, a_std, z_std, to=100):
    x0_v, dx0_v, a_v, z_v = map(lambda e: e**2, [x0_std, dx0_std, a_std, z_std])
    kf = initialize_filter(x0, x0_v, dx0, dx0_v, dt, a, a_v, z_v)
    data = propagate_in_time(x0, x0_v, dx0, dx0_v, dt, a, a_v, to)
    observations = make_observations(data, z_v)
    
    res = []
    for z in observations:
        kf.predict()
        kf.update(z)
        res.append(kf.get_state())
    res = np.array(res)
    
    plt.title('Kalman Filter')
    plt.plot(data, 'b-')
    plt.plot(observations, 'g^')
    plt.plot(res[:, 0], 'r-')
    plt.legend(['actual position', 'observations', 'filter result'])<jupyter_output><empty_output><jupyter_text>Dynamic Visualization<jupyter_code>interact(
    simple_simulation,
    x0 = fixed(0), x0_std=fixed(1), dt=fixed(1), to=fixed(100), a=fixed(0.01),
    dx0 = FloatSlider(min=0,max=1,step=0.01,value=0.1), dx0_std=fixed(0.01),
    a_std = FloatSlider(min=0,max=1,step=0.0001,value=0.01),
    z_std = IntSlider(min=0,max=40,step=1,value=4)
)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1991321118611379, 'fraction_numerical': 0.04725168756027001, 'mean_word_length': 3.1750503018108653, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '457493', 'license': 'MIT', 'n_tokens_mistral': 992, 'n_tokens_neox': 976, 'n_words': 184, 'path': 'examples/KF_simulation_simple.ipynb', 'repo_name': 'slanab/AttitudeDetermination', 'size': '2074'}