def setUp(self): # synthetic parameters. May be completely mathematically invalid self.setup_1 = { # n = 2, k = 3, j = 4 "A": np.array([[1, 2], [3, 4]]), # n*n "B": np.array([[1, 2, 3], [4, 5, 6]]), # n*k "C": np.array([[1, 2], [3, 4], [5, 6], [7, 8]]), # j*n "D": np.array([[1, 2, 3], [5, 6, 7], [9, 1, 2], [2, 3, 4]]), # j*k "Q": np.array([[2, 3], [4, 5]]), # n*n "R": np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 1, 2, 3], [2, 3, 4, 5]]), # j*j "state_pdf": pb.GaussPdf(np.array([1, 2]), np.array([[1, 0], [0, 2]])) # n } self.setup_2 = { # n = 2, k = 1, j = 1 "A": np.array([[1.0, -0.5], [1.0, 0.0]]), "B": np.array([[1.0], [0.1]]), "C": np.array([[1.0, 0.0]]), "D": np.array([[0.1]]), "Q": np.array([[0.2, 0.0], [0.0, 0.2]]), "R": np.array([[0.01]]), "state_pdf": pb.GaussPdf(np.array([0.0, 0.0]), np.array([[200.0, 0.0], [0.0, 200.0]])) }
def setUp(self): gausses = np.array([ pb.GaussPdf(np.array([1., 2.]), np.array([[1., 0.], [0., 2.]])), pb.GaussPdf(np.array([-2., -1.]), np.array([[9., 0.], [0., 3.]])), pb.GaussPdf(np.array([-8., 5.]), np.array([[1., 0.5], [0.5, 1.]])), ], dtype=pb.GaussPdf) particles = np.array([ [1., 2.], [2., 4.], [3., 6.], ]) self.emp = pb.MarginalizedEmpPdf(gausses, particles)
def test_eval_log(self): x = np.array([0.]) norm = pb.GaussPdf(np.array([0.]), np.array([[1.]])) expected = np.array([ 1.48671951473e-06, 0.000133830225765, 0.00443184841194, 0.0539909665132, 0.241970724519, 0.398942280401, 0.241970724519, 0.0539909665132, 0.00443184841194, 0.000133830225765, 1.48671951473e-06, ]) for i in xrange(0, 11): x[0] = i - 5. res = exp(norm.eval_log(x)) self.assertApproxEqual(res, expected[i]) # same variance, non-zero mean: norm = pb.GaussPdf(np.array([17.9]), np.array([[1.]])) for i in xrange(0, 11): x[0] = i - 5. + 17.9 res = exp(norm.eval_log(x)) self.assertApproxEqual(res, expected[i]) # non-unit variance: norm = pb.GaussPdf(np.array([0.]), np.array([[15.0]])) expected = np.array([ 0.044766420317807747, 0.060428346749642113, 0.076309057876818423, 0.090148500118746672, 0.099629500639377908, 0.10300645387285032, 0.099629500639377908, 0.090148500118746672, 0.076309057876818423, 0.060428346749642113, 0.044766420317807747, ]) for i in xrange(0, 11): x[0] = (i - 5.) res = exp(norm.eval_log(x)) self.assertApproxEqual(res, expected[i])
def setUp(self): # constructor parameters: self.mean = np.array([1., 3., 9.]) self.covariance = np.array([[1., 0., 0.], [0., 2., 0.], [0., 0., 3.]]) # expected values: self.variance = np.array([1., 2., 3.]) # diagonal elements of covariance self.shape = 3 # shape of random variable (and mean) self.gauss = pb.GaussPdf(self.mean, self.covariance)
def test_eval_log(self): # for this test, we assume that GaussPdf is already well tested and correct for i in range(self.test_conds.shape[0]): cond = self.test_conds[i] mean = self.cond_means[i] var = self.cond_vars[i].reshape((1, 1)) gauss = pb.GaussPdf(mean, var) for j in range(-5, 6): x = mean + j * var[0] / 2. ret = self.gauss.eval_log(x, cond) self.assertApproxEqual(ret, gauss.eval_log(x))
def test_sample_multi(self): """Test GaussPdf.sample() mean and variance (multivariate case).""" N = 500 mean = np.array([124.6, -1.5]) cov = np.array([[0.7953, 0.], [0., 1.7]]) samples = pb.GaussPdf(mean, cov).samples(N) emp = pb.EmpPdf(samples) self.assertAlmostEqual(np.max(abs(emp.mean() - mean)), 0., delta=0.2) self.assertAlmostEqual(np.max(abs(emp.variance() - cov.diagonal())), 0., delta=0.3)
def test_rvs(self): self.assertEqual(self.gauss.rv.dimension, 3) self.assertEqual(self.gauss.cond_rv.dimension, 0) a, b = pb.RVComp(2, "a"), pb.RVComp(1, "b") gauss_rv = pb.GaussPdf(self.mean, self.covariance, pb.RV(a, b)) self.assertTrue(gauss_rv.rv.contains(a)) self.assertTrue(gauss_rv.rv.contains(b)) # invalid total rv dimension: c = pb.RVComp(2) self.assertRaises(ValueError, pb.GaussPdf, self.mean, self.covariance, pb.RV(a, c))
def test_sample_uni(self): """Test GaussPdf.sample() mean and variance (univariate case).""" N = 500 mean = np.array([124.6]) cov = np.array([[0.7953]]) samples = pb.GaussPdf(mean, cov).samples(N) emp = pb.EmpPdf(samples) fuzz = 0.2 self.assertTrue(np.all(abs(emp.mean() - mean) <= fuzz)) var, fuzz = cov.diagonal(), 0.2 self.assertTrue(np.all(abs(emp.variance() - var) <= fuzz))
def run_kalman_on_mat_data(input_file, output_file, timer): # this should be here so that only this stress fails when scipy is not installed loadmat = scipy.io.loadmat savemat = scipy.io.savemat d = loadmat(input_file, struct_as_record=True, mat_dtype=True) mu0 = np.reshape(d.pop('mu0'), (-1, )) # otherwise we would get 2D array of shape (1xN) P0 = d.pop('P0') y = d.pop('y').T u = d.pop('u').T #x = d.pop('x').T x = None gauss = pb.GaussPdf(mu0, P0) kalman = pb.KalmanFilter(d['A'], d['B'], d['C'], d['D'], d['Q'], d['R'], gauss) N = y.shape[0] n = mu0.shape[0] mean = np.zeros((N, n)) var = np.zeros((N, n)) timer.start() for t in range(1, N): # the 1 start offset is intentional kalman.bayes(y[t], u[t]) mean[t] = kalman.posterior().mean() #var[t] = kalman.posterior().variance() timer.stop() var = np.sqrt(var) # to get standard deviation plt = None # turn off plotting for now if plt: axis = np.arange(N) plt.plot(axis, x[:, 0], 'k-', label='x_1') plt.plot(axis, x[:, 1], 'k--', label='x_2') plt.errorbar(axis, mean[:, 0], fmt='s', label='mu_1') # yerror=var[:,0] plt.errorbar(axis, mean[:, 1], fmt='D', label='mu_2') # yerror=var[:,1] plt.legend() plt.show() savemat(output_file, { "Mu_py": mean.T, "exec_time_pybayes": timer.spent[0] }, oned_as='row')
def setUp(self): def f(x): return -x self.f = f def g(x): return np.diag(-x) self.g = g self.cgauss = pb.GaussCPdf(2, 2, f, g) self.gauss = pb.GaussPdf(np.array([1., 2.]), np.array([[1., 0.], [0., 2.]])) self.cond = np.array([-1., -2. ]) # condition that makes cgauss behave as gauss
def test_invalid_init(self): args = ["A", "B", "C", "D", "Q", "R", "state_pdf"] # invalid type: for arg in args: setup = self.setup_1.copy() setup[arg] = 125.65 self.assertRaises(TypeError, pb.KalmanFilter, **setup) # invalid dimension del args[6] # remove state_pdf for arg in args: setup = self.setup_1.copy() setup[arg] = np.array([[1],[2]]) self.assertRaises(ValueError, pb.KalmanFilter, **setup) gauss = pb.GaussPdf(np.array([1]), np.array([[1]])) setup = self.setup_1.copy() setup['state_pdf'] = gauss self.assertRaises(ValueError, pb.KalmanFilter, **setup)
def test_rvs(self): self.assertEqual(self.prod.rv.dimension, 3) # test that child rv components are copied into parent ProdPdf a, b, c = pb.RVComp(1, "a"), pb.RVComp(1, "b"), pb.RVComp(1, "c") uni = pb.UniPdf(np.array([0., 0.]), np.array([1., 2.]), pb.RV(a, b)) gauss = pb.GaussPdf(np.array([0.]), np.array([[1.]]), pb.RV(c)) prod = pb.ProdPdf((uni, gauss)) self.assertEquals(prod.rv.name, "[a, b, c]") for rv_comp in a, b, c: self.assertTrue(prod.rv.contains(rv_comp)) # that that custom rv passed to constructor is accepted d = pb.RVComp(3, "d") prod_custom = pb.ProdPdf((uni, gauss), pb.RV(d)) self.assertEquals(prod_custom.rv.name, "[d]") self.assertTrue(prod_custom.rv.contains(d)) self.assertFalse(prod_custom.rv.contains(a)) self.assertFalse(prod_custom.rv.contains(b)) self.assertFalse(prod_custom.rv.contains(c))
def setUp(self): self.uni = pb.UniPdf(np.array([0., 0.]), np.array([1., 2.])) self.gauss = pb.GaussPdf(np.array([0.]), np.array([[1.]])) self.prod = pb.ProdPdf((self.uni, self.gauss))
# this should be here so that only this stress fails when scipy is not installed try: from scipy.io import loadmat, savemat except ImportError, e: raise StopIteration("Kalman filter stress needs scipy installed: " + str(e)) d = loadmat(input_file, struct_as_record=True, mat_dtype=True) mu0 = np.reshape(d.pop('mu0'), (-1,)) # otherwise we would get 2D array of shape (1xN) P0 = d.pop('P0') y = d.pop('y').T u = d.pop('u').T #x = d.pop('x').T x = None gauss = pb.GaussPdf(mu0, P0) kalman = pb.KalmanFilter(d['A'], d['B'], d['C'], d['D'], d['Q'], d['R'], gauss) N = y.shape[0] n = mu0.shape[0] mean = np.zeros((N, n)) var = np.zeros((N, n)) timer.start() for t in xrange(1, N): # the 1 start offset is intentional kalman.bayes(y[t], u[t]) mean[t] = kalman.posterior().mean() #var[t] = kalman.posterior().variance() timer.stop() var = np.sqrt(var) # to get standard deviation