Пример #1
0
def testfield(measure_size, simulation_size):

    log.basicConfig(filename='imagine_bi_multinest.log', level=log.DEBUG)
    """
    # step 0, set 'a' and 'b', 'mea_std'
    
    TestField in BiSimulator is modeled as
        field = square( gaussian_rand(mean=a,std=b)_x * sin(x) )
        where x in (0,2pi)
    
    for generating mock data we need
    true values of a and b: true_a, true_b, mea_seed
    measurement uncertainty: mea_std
    measurement points, positioned in (0,2pi) evenly, due to TestField modelling
    """
    true_a = 3.
    true_b = 6.
    mea_std = 0.1  # std of gaussian measurement error
    mea_seed = 233
    truths = [true_a, true_b]  # will be used in visualizing posterior
    """
    # step 1, prepare mock data
    """
    """
    # 1.1, generate measurements
    mea_field = signal_field + noise_field
    """
    x = np.linspace(0, 2. * np.pi, measure_size)
    np.random.seed(mea_seed)  # seed for signal field
    signal_field = np.square(
        np.multiply(
            np.sin(x),
            np.random.normal(loc=true_a, scale=true_b, size=measure_size)))
    mea_field = np.vstack([
        signal_field +
        np.random.normal(loc=0., scale=mea_std, size=measure_size)
    ])
    """
    # 1.2, generate covariances
    what's the difference between pre-define dan re-estimated?
    """
    # pre-defined according to measurement error
    mea_cov = (mea_std**2) * mpi_eye(measure_size)
    """
    # 1.3 assemble in imagine convention
    """

    mock_data = Measurements()  # create empty Measrurements object
    mock_cov = Covariances()  # create empty Covariance object
    # pick up a measurement
    mock_data.append(('test', 'nan', str(measure_size), 'nan'), mea_field,
                     True)
    mock_cov.append(('test', 'nan', str(measure_size), 'nan'), mea_cov, True)
    """
    # 1.4, visualize mock data
    """
    if not mpirank:
        matplotlib.pyplot.plot(
            x, mock_data[('test', 'nan', str(measure_size), 'nan')].data[0])
        matplotlib.pyplot.savefig('testfield_mock_bi.pdf')
    """
    # step 2, prepare pipeline and execute analysis
    """
    """
    # 2.1, ensemble likelihood
    """
    likelihood = EnsembleLikelihood(
        mock_data, mock_cov)  # initialize likelihood with measured info
    """
    # 2.2, field factory list
    """
    factory = TestFieldFactory(
        active_parameters=('a', 'b'))  # factory with single active parameter
    factory.parameter_ranges = {
        'a': (0, 10),
        'b': (0, 10)
    }  # adjust parameter range for Bayesian analysis
    factory_list = [factory]  # likelihood requires a list/tuple of factories
    """
    # 2.3, flat prior
    """
    prior = FlatPrior()
    """
    # 2.4, simulator 
    """
    simer = BiSimulator(mock_data)
    """
    # 2.5, pipeline
    """
    pipe = MultinestPipeline(simer, factory_list, likelihood, prior,
                             simulation_size)
    pipe.random_type = 'controllable'
    pipe.seed_tracer = int(23)
    pipe.sampling_controllers = {
        'n_iter_before_update': 10,
        'n_live_points': 4000,
        'verbose': True,
        'resume': False
    }

    tmr = Timer()
    tmr.tick('test')
    results = pipe()  # run with pymultinest
    tmr.tock('test')
    if not mpirank:
        print('\n elapse time ' + str(tmr.record['test']) + '\n')
    """
    # step 3, visualize (with corner package)
    """
    if mpirank == 0:
        samples = results['samples']
        for i in range(len(
                pipe.active_parameters)):  # convert variables into parameters
            low, high = pipe.active_ranges[pipe.active_parameters[i]]
            for j in range(samples.shape[0]):
                samples[j, i] = unity_mapper(samples[j, i], low, high)
        # corner plot
        corner.corner(samples[:, :len(pipe.active_parameters)],
                      range=[0.99] * len(pipe.active_parameters),
                      quantiles=[0.02, 0.5, 0.98],
                      labels=pipe.active_parameters,
                      show_titles=True,
                      title_kwargs={"fontsize": 20},
                      color='steelblue',
                      truths=truths,
                      truth_color='firebrick',
                      plot_contours=True,
                      hist_kwargs={'linewidth': 2},
                      label_kwargs={'fontsize': 20})
        matplotlib.pyplot.savefig('testfield_posterior_bi_multinest.pdf')
Пример #2
0
    def test_multinest(self):
        # mock measures
        arr = np.random.rand(1, 3)
        measuredict = Measurements()
        measuredict.append(('test', 'nan', '3', 'nan'), arr, True)
        # simulator
        simer = LiSimulator(measuredict)
        # mock factory list
        tf = TestFieldFactory(active_parameters=tuple('a'))
        flist = (tf, )
        # mock likelihood
        lh = EnsembleLikelihood(measuredict)
        # mock prior
        pr = FlatPrior()
        # pipeline
        pipe = MultinestPipeline(simer, flist, lh, pr, 5)

        self.assertEqual(pipe.active_parameters, ('test_a', ))
        self.assertEqual(pipe.factory_list, (tf, ))
        self.assertEqual(pipe.simulator, simer)
        self.assertEqual(pipe.likelihood, lh)
        self.assertEqual(pipe.prior, pr)
        self.assertEqual(pipe.ensemble_size, 5)
        self.assertEqual(pipe.sampling_controllers, {})
        pipe.sampling_controllers = {'verbose': False}
        self.assertEqual(pipe.sampling_controllers, {'verbose': False})
        self.assertEqual(pipe.sample_callback, False)
        pipe.sample_callback = True
        self.assertEqual(pipe.sample_callback, True)
        self.assertEqual(pipe.likelihood_rescaler, 1.)
        pipe.likelihood_rescaler = 0.5
        self.assertEqual(pipe.likelihood_rescaler, 0.5)
        self.assertEqual(pipe.check_threshold, False)
        pipe.check_threshold = True
        self.assertEqual(pipe.check_threshold, True)
        self.assertEqual(pipe.likelihood_threshold, 0.)
        pipe.likelihood_threshold = -0.2
        self.assertEqual(pipe.likelihood_threshold, -0.2)
        self.assertEqual(pipe._ensemble_seeds, None)
        self.assertEqual(pipe.seed_tracer, int(0))
        self.assertEqual(pipe.random_type, 'free')

        # test free random seed, full randomness
        pipe._randomness()
        s1 = pipe._ensemble_seeds
        self.assertTrue(s1 is None)
        # test controllable random seed, with top level seed controllable
        pipe.random_type = 'controllable'
        pipe.seed_tracer = int(3)  # controlling seed at top level
        pipe._randomness(
        )  # core func in assigning ensemble seeds, before calling simulator
        s1 = pipe._ensemble_seeds
        pipe._randomness()  # 2nd call of sampeler
        s2 = pipe._ensemble_seeds
        pipe = MultinestPipeline(simer, flist, lh, pr, 5)  # init a new sampler
        pipe.random_type = 'controllable'
        pipe.seed_tracer = int(3)  # repeat the controlling seed
        pipe._randomness()
        s1re = pipe._ensemble_seeds
        pipe._randomness()
        s2re = pipe._ensemble_seeds
        self.assertListEqual(list(s1), list(s1re))  # should get the same seeds
        self.assertListEqual(list(s2), list(s2re))
        pipe = MultinestPipeline(simer, flist, lh, pr, 5)
        pipe.random_type = 'controllable'
        pipe.seed_tracer = int(4)  # different controlling seed
        pipe._randomness()
        s1new = pipe._ensemble_seeds
        for i in range(len(s1)):
            self.assertNotEqual(s1[i], s1new[i])  # should get different seeds
        # test fixed random seed
        pipe.random_type = 'fixed'
        pipe.seed_tracer = int(5)
        pipe._randomness()  # 1st time seed assignment
        s1 = pipe._ensemble_seeds
        pipe._randomness()  # 2nd time seed assignment
        s1re = pipe._ensemble_seeds
        self.assertListEqual(list(s1), list(s1re))  # should get the same seeds