def test_mpi_eye(self): size = 128 part_eye = mpi_eye(size) test_eye = np.eye(size, dtype=np.float64) full_eye = np.vstack(comm.allgather(part_eye)) for i in range(full_eye.shape[0]): self.assertListEqual(list(test_eye[i]), list(full_eye[i]))
def peye(size): """ :py:func:`imagine.tools.mpi_helper.mpi_eye` or :py:func:`numpy.eye` depending on :py:data:`imagine.rc['distributed_arrays']`. """ if rc['distributed_arrays']: return m.mpi_eye(size) else: return np.eye(size)
def oas_mcov(data): """ Estimate covariance with the Oracle Approximating Shrinkage algorithm. See `imagine.tools.covariance_estimator.oas_cov` for details. This function aditionally returns the computed ensemble mean. Parameters ---------- data : numpy.ndarray distributed data in global shape (ensemble_size, data_size) Returns ------- mean : numpy.ndarray copied ensemble mean (on all nodes) cov : numpy.ndarray distributed covariance matrix in shape (data_size, data_size) """ log.debug('@ covariance_estimator::oas_mcov') assert isinstance(data, np.ndarray) assert (len(data.shape) == 2) # Finds ensemble size and data size data_size = data.shape[1] ensemble_size = np.array(0, dtype=np.uint) comm.Allreduce([np.array(data.shape[0], dtype=np.uint), MPI.LONG], [ensemble_size, MPI.LONG], op=MPI.SUM) # Calculates OAS covariance extimator from empirical covariance estimator mean = mpi_mean(data) u = data - mean s = mpi_mult(mpi_trans(u), u) / ensemble_size trs = mpi_trace(s) trs2 = mpi_trace(mpi_mult(s, s)) numerator = (1.0 - 2.0 / data_size) * trs2 + trs * trs denominator = (ensemble_size + 1.0 - 2.0 / data_size) * (trs2 - (trs * trs) / data_size) if denominator == 0: rho = 1 else: rho = np.min([1, numerator / denominator]) cov = (1. - rho) * s + mpi_eye(data_size) * rho * trs / data_size return mean, cov
def testfield(measure_size, simulation_size, make_plots=True, debug=False): if debug: log.basicConfig(filename='imagine_li_dynesty.log', level=log.DEBUG) else: log.basicConfig(filename='imagine_li_dynesty.log') """ :return: log.basicConfig(filename='imagine.log', level=log.INFO) """ """ # step 0, set 'a' and 'b', 'mea_std' TestField in LiSimulator is modeled as field = gaussian_random(mean=a,std=b)_x * cos(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) # data points in measurements np.random.seed(mea_seed) # seed for signal field signal_field = np.multiply( np.cos(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? """ # re-estimate according to measurement error mea_repeat = np.zeros((simulation_size, measure_size)) for i in range(simulation_size): # times of repeated measurements mea_repeat[i, :] = signal_field + np.random.normal( loc=0., scale=mea_std, size=measure_size) mea_cov = oas_mcov(mea_repeat)[1] print(mpirank, 're-estimated: \n', mea_cov, 'slogdet', mpi_slogdet(mea_cov)) # pre-defined according to measurement error mea_cov = (mea_std**2) * mpi_eye(measure_size) print(mpirank, 'pre-defined: \n', mea_cov, 'slogdet', mpi_slogdet(mea_cov)) """ # 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 mpirank == 0 and make_plots: plt.plot(x, mock_data[('test', 'nan', str(measure_size), 'nan')].data[0]) plt.savefig('testfield_mock_li.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 = LiSimulator(mock_data) """ # 2.5, pipeline """ pipe = DynestyPipeline(simer, factory_list, likelihood, prior, simulation_size) pipe.random_type = 'controllable' # 'fixed' random_type doesnt work for Dynesty pipeline, yet pipe.seed_tracer = int(23) pipe.sampling_controllers = {'nlive': 400} tmr = Timer() tmr.tick('test') results = pipe() tmr.tock('test') if mpirank == 0: print('\n elapse time ' + str(tmr.record['test']) + '\n') """ # step 3, visualize (with corner package) """ if mpirank == 0 and make_plots: 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": 15}, color='steelblue', truths=truths, truth_color='firebrick', plot_contours=True, hist_kwargs={'linewidth': 2}, label_kwargs={'fontsize': 20}) plt.savefig('testfield_posterior_li_dynesty.pdf')
def mock_errfix(_nside, _freq): """ return masked mock synchrotron Q, U error fixed """ # hammurabi parameter base file xmlpath = './params.xml' # active parameters true_b0 = 3.0 true_psi0 = 27.0 true_psi1 = 0.9 true_chi0 = 25. true_alpha = 3.0 true_r0 = 5.0 true_z0 = 1.0 true_rms = 6.0 true_rho = 0.8 true_a0 = 1.7 # _npix = 12*_nside**2 # x = np.zeros((1, _npix)) # only for triggering simulator trigger = Measurements() trigger.append(('sync', str(_freq), str(_nside), 'Q'), x) # Q map trigger.append(('sync', str(_freq), str(_nside), 'U'), x) # U map # initialize simulator error = 0.1 mocker = Hammurabi(measurements=trigger, xml_path=xmlpath) # start simulation # BregLSA field paramlist = {'b0': true_b0, 'psi0': true_psi0, 'psi1': true_psi1, 'chi0': true_chi0} breg_lsa = BregLSA(paramlist, 1) # CREAna field paramlist = {'alpha': true_alpha, 'beta': 0.0, 'theta': 0.0, 'r0': true_r0, 'z0': true_z0, 'E0': 20.6, 'j0': 0.0217} cre_ana = CREAna(paramlist, 1) # TEregYMW16 field paramlist = dict() fereg_ymw16 = TEregYMW16(paramlist, 1) # BrndES field paramlist = {'rms': true_rms, 'k0': 0.1, 'k1': 0.1, 'a1': 0.0, 'a0': true_a0, 'rho': true_rho, 'r0': 8.0, 'z0': 1.0} brnd_es = BrndES(paramlist, 1) # collect mock data and covariance outputs = mocker([breg_lsa, cre_ana, fereg_ymw16, brnd_es]) mock_raw_q = outputs[('sync', str(_freq), str(_nside), 'Q')].data mock_raw_u = outputs[('sync', str(_freq), str(_nside), 'U')].data # collect mean and cov from simulated results mock_data = Measurements() mock_cov = Covariances() mock_mask = Masks() mock_data.append(('sync', str(_freq), str(_nside), 'Q'), mock_raw_q) mock_data.append(('sync', str(_freq), str(_nside), 'U'), mock_raw_u) mask_map = mask_map_prod(_nside, 0, 90, 50) # not parameterizing this mock_mask.append(('sync', str(_freq), str(_nside), 'Q'), np.vstack([mask_map])) mock_mask.append(('sync', str(_freq), str(_nside), 'U'), np.vstack([mask_map])) mock_data.apply_mask(mock_mask) for key in mock_data.keys(): mock_cov.append(key, (error**2*(np.std(mock_raw_q))**2)*mpi_eye(int(key[2])), True) return mock_data, mock_cov
def lsa_errfix(): #log.basicConfig(filename='imagine.log', level=log.DEBUG) """ only LSA regular magnetic field model in test, @ 23GHz Faraday rotation provided by YMW16 thermal electron model full LSA parameter set {b0, psi0, psi1, chi0} """ # hammurabi parameter base file xmlpath = './params.xml' # we take three active parameters true_b0 = 6.0 true_psi0 = 27.0 true_psi1 = 0.9 true_chi0 = 25. true_alpha = 3.0 true_r0 = 5.0 true_z0 = 1.0 mea_nside = 2 # observable Nside mea_pix = 12 * mea_nside**2 # observable pixel number """ # step 1, prepare mock data """ x = np.zeros((1, mea_pix)) # only for triggering simulator trigger = Measurements() trigger.append(('sync', '23', str(mea_nside), 'I'), x) # only I map # initialize simulator error = 0.1 # theoretical raltive uncertainty for each (active) parameter mocker = Hammurabi(measurements=trigger, xml_path=xmlpath) # start simulation # BregLSA field paramlist = { 'b0': true_b0, 'psi0': true_psi0, 'psi1': true_psi1, 'chi0': true_chi0 } # inactive parameters at default breg_lsa = BregLSA(paramlist, 1) # CREAna field paramlist = { 'alpha': true_alpha, 'beta': 0.0, 'theta': 0.0, 'r0': true_r0, 'z0': true_z0, 'E0': 20.6, 'j0': 0.0217 } # inactive parameters at default cre_ana = CREAna(paramlist, 1) # TEregYMW16 field tereg_ymw16 = TEregYMW16(dict(), 1) # collect mock data and covariance outputs = mocker([breg_lsa, cre_ana, tereg_ymw16]) Imap = outputs[('sync', '23', str(mea_nside), 'I')].local_data # collect mean and cov from simulated results mock_data = Measurements() mock_cov = Covariances() mock_data.append(('sync', '23', str(mea_nside), 'I'), Imap) mock_cov.append(('sync', '23', str(mea_nside), 'I'), (error**2 * (mpi_mean(Imap))**2) * mpi_eye(mea_pix)) """ # step 2, prepare pipeline and execute analysis """ likelihood = EnsembleLikelihood(mock_data, mock_cov) breg_factory = BregLSAFactory(active_parameters=('b0', 'psi0', 'psi1', 'chi0')) breg_factory.parameter_ranges = { 'b0': (0., 10.), 'psi0': (0., 50.), 'psi1': (0., 2.), 'chi0': (0., 50.) } cre_factory = CREAnaFactory(active_parameters=('alpha', 'r0', 'z0')) cre_factory.parameter_ranges = { 'alpha': (1., 5.), 'r0': (1., 10.), 'z0': (0.1, 5.) } tereg_factory = TEregYMW16Factory() factory_list = [breg_factory, cre_factory, tereg_factory] prior = FlatPrior() simer = Hammurabi(measurements=mock_data, xml_path=xmlpath) ensemble_size = 10 pipe = DynestyPipeline(simer, factory_list, likelihood, prior, ensemble_size) pipe.random_type = 'free' pipe.sampling_controllers = {'nlive': 4000} results = pipe() """ # step 3, visualize (with corner package) """ if mpirank == 0: samples = results['samples'] np.savetxt('posterior_fullsky_regular_errfix.txt', samples) """