def test_theta_computed_boolean(self): theta_init = self.random_theta(2, 1) mcmc = KurslMCMC(theta_init, niter=2) self.assertFalse(mcmc._theta_computed(), "Without run should fail") mcmc.set_sampler(np.linspace(0, 1, 100), np.random.random(100)) mcmc.run() self.assertTrue(mcmc._theta_computed(), "After run should return true")
def test_run_start_from_solution(self): _cos = lambda l: l[2] * np.cos(l[0] * t + l[1]) theta = np.array([ [15, 0, 1, 0], [35, 2, 3, 0], ], dtype=np.float64) t = np.linspace(0, 1, 100) c1 = _cos(theta[0]) c2 = _cos(theta[1]) S = c1 + c2 # Initial guess is far off. Just for an example. theta_init = np.array(theta, dtype=np.float64) theta_init += np.random.random(theta_init.shape) * 3 mcmc = KurslMCMC(theta_init) mcmc.set_sampler(t, S) # However, execution starts close to solution. pos = np.tile(theta.flatten(), (mcmc.nwalkers, 1)) pos += np.random.random(pos.shape) * 0.3 mcmc.run(pos=pos) niter_executed = mcmc.get_lnprob().shape[0] self.assertTrue( niter_executed < mcmc.niter, "Starting close solution should allow for quick convergence " "and not all iterations would be executed.")
def test_run_default(self): _cos = lambda l: l[2] * np.cos(l[0] * t + l[1]) theta = [ [15, 0, 1, 0], [35, 2, 3, 0], ] theta_std = [ [1.0, 0.1, 0.8, 0.01], [1.5, 0.1, 1.5, 0.01], ] theta, theta_std = np.array(theta), np.array(theta_std) t = np.linspace(0, 1, 100) c1 = _cos(theta[0]) c2 = _cos(theta[1]) S = c1 + c2 theta_init = np.array(theta, dtype=np.float64) theta_init[:, 0] += 2 - np.random.random(2) * 0.5 theta_init[:, 2] += 1 - np.random.random(2) * 0.5 mcmc = KurslMCMC(theta_init, theta_std, nwalkers=40, niter=200) mcmc.set_threshold(0.001) mcmc.set_sampler(t, S) mcmc.run() # After simulation is finished check for correctness theta_computed = mcmc.get_theta() self.assertTrue( np.allclose(theta, theta_computed, atol=0.5), "Expected:\n{}\nReceived:\n{}".format(theta, theta_computed))
def test_run_with_incorrect_pos(self): t = np.linspace(0, 1, 100) S = np.random.random(t.size) mcmc = KurslMCMC(self.random_theta(3, 2)) mcmc.set_sampler(t, S) with self.assertRaises(ValueError) as error: mcmc.run(pos=self.random_theta(3, 2)) self.assertTrue("pos.shape" in str(error.exception))
def test_run_without_sampler(self): mcmc = KurslMCMC(self.random_theta(3, 2)) with self.assertRaises(AttributeError) as error: mcmc.run() self.assertTrue("Sampler not defined" in str(error.exception)) self.assertTrue("set_sampler" in str(error.exception))
def test_run_without_model(self): mcmc = KurslMCMC(self.random_theta(3, 2)) mcmc.model = None # This situation shouldn't even be possible with self.assertRaises(AttributeError) as error: mcmc.run() self.assertEqual("Model not selected", str(error.exception))