def fringe_coherence(u, sinza):
    fringes = NP.exp(-1j * 2*NP.pi * u * sinza)
    fringe_cycle_coherence = NP.zeros(NP.ceil(u).astype(NP.int), dtype=NP.complex64)
    dsinza = 1/u
    eps = 1e-10
    sinza_intervals = NP.arange(0, 1, dsinza[0])
    sinza_intervals = NP.append(sinza_intervals, 1.0) - eps
    bincount, n_bin_edges, binnum, ri = OPS.binned_statistic(sinza, statistic='count', bins=sinza_intervals)
    for i in range(bincount.size):
        ind = ri[ri[i]:ri[i+1]]
        fringe_cycle_coherence[i] = NP.sum(fringes[ui,ind])
    return fringe_cycle_coherence
def fringe_coherence(u, sinza):
    fringes = NP.exp(-1j * 2 * NP.pi * u * sinza)
    fringe_cycle_coherence = NP.zeros(NP.ceil(u).astype(NP.int),
                                      dtype=NP.complex64)
    dsinza = 1 / u
    eps = 1e-10
    sinza_intervals = NP.arange(0, 1, dsinza[0])
    sinza_intervals = NP.append(sinza_intervals, 1.0) - eps
    bincount, n_bin_edges, binnum, ri = OPS.binned_statistic(
        sinza, statistic='count', bins=sinza_intervals)
    for i in range(bincount.size):
        ind = ri[ri[i]:ri[i + 1]]
        fringe_cycle_coherence[i] = NP.sum(fringes[ui, ind])
    return fringe_cycle_coherence
예제 #3
0
# progress.finish()

small_delays_ind = NP.abs(lags) <= 2.5e-6
lags = lags[small_delays_ind]
vis_lag = vis_lag[:,small_delays_ind,:]
skyvis_lag = skyvis_lag[:,small_delays_ind,:]

## Delay limits estimation

delay_matrix = DLY.delay_envelope(bl, pointings_dircos, units='mks')

## Binning baselines by orientation

blo = bl_orientation[:min(20*baseline_chunk_size, total_baselines)]
# blo[blo < -0.5*360.0/n_bins_baseline_orientation] = 360.0 - NP.abs(blo[blo < -0.5*360.0/n_bins_baseline_orientation])
bloh, bloe, blon, blori = OPS.binned_statistic(blo, statistic='count', bins=n_bins_baseline_orientation, range=[(-0.5*180.0/n_bins_baseline_orientation, 180.0-0.5*180.0/n_bins_baseline_orientation)])

# blo = bl_orientation[:min(20*baseline_chunk_size, total_baselines)]
# blo[blo < -0.5*360.0/n_bins_baseline_orientation] = 360.0 - NP.abs(blo[blo < -0.5*360.0/n_bins_baseline_orientation])
# bloh, bloe, blon, blori = OPS.binned_statistic(blo, statistic='count', bins=n_bins_baseline_orientation, range=[(-0.5*360.0/n_bins_baseline_orientation, 360.0-0.5*360.0/n_bins_baseline_orientation)])


# # ia.observing_run(pointing_init, skymod, t_snap, t_obs, chans, bpass, Tsys, lst_init, mode=obs_mode, freq_scale='GHz', brightness_units=flux_unit)
# # print 'Elapsed time = {0:.1f} minutes'.format((time.time()-ts)/60.0)
# # ia.delay_transform()

# for i in xrange(baseline_length.size):
#     ts = time.time()
#     ints[i].observing_run(pointing_init, skymod, t_snap, t_obs, chans, bpass, Tsys, lst_init, mode=obs_mode, freq_scale='GHz', brightness_units=flux_unit)
#     print 'Elapsed time = {0:.1f} minutes'.format((time.time()-ts)/60.0)
delaymat = DLY.delay_envelope(bl, pc_dircos, units='mks')
min_delay = -delaymat[0, :, 1] - delaymat[0, :, 0]
max_delay = delaymat[0, :, 0] - delaymat[0, :, 1]
clags = clean_lags.reshape(1, -1)
min_delay = min_delay.reshape(-1, 1)
max_delay = max_delay.reshape(-1, 1)
thermal_noise_window = NP.abs(clags) >= max_abs_delay * 1e-6
thermal_noise_window = NP.repeat(thermal_noise_window, bl.shape[0], axis=0)
EoR_window = NP.logical_or(clags > max_delay + 1 / bw,
                           clags < min_delay - 1 / bw)
wedge_window = NP.logical_and(clags <= max_delay, clags >= min_delay)
non_wedge_window = NP.logical_not(wedge_window)

bll_bin_count, bll_edges, bll_binnum, bll_ri = OPS.binned_statistic(
    bl_length,
    values=None,
    statistic='count',
    bins=NP.hstack((geor_bl_length - 1e-10, geor_bl_length.max() + 1e-10)))

snap_min = 0
snap_max = 39
fg_cc_skyvis_lag_tavg = NP.mean(fg_cc_skyvis_lag[:, :, snap_min:snap_max + 1],
                                axis=2)
fg_cc_skyvis_lag_res_tavg = NP.mean(
    fg_cc_skyvis_lag_res[:, :, snap_min:snap_max + 1], axis=2)

fg_cc_skyvis_lag_blavg = NP.zeros(
    (geor_bl_length.size, clags.size, snap_max - snap_min + 1),
    dtype=NP.complex64)
fg_cc_skyvis_lag_res_blavg = NP.zeros(
    (geor_bl_length.size, clags.size, snap_max - snap_min + 1),
    # ax.set_aspect('equal')
    # ax.set_xlabel('l', fontsize=18, weight='medium')
    # ax.set_ylabel('m', fontsize=18, weight='medium')    
    # cbax = fig.add_axes([0.9, 0.125, 0.02, 0.74])
    # cbar = fig.colorbar(ipsf, cax=cbax, orientation='vertical')
    # # PLT.tight_layout()
    # fig.subplots_adjust(right=0.85)
    # fig.subplots_adjust(top=0.88)
    # PLT.savefig('/data3/t_nithyanandan/project_MOFF/simulated/MWA/figures/quick_psf_via_FX_test_aperture.png'.format(max_n_timestamps), bbox_inches=0)
    
    psf_diff = NP.mean(beam_MOFF, axis=2) - NP.mean(vfimgobj.beam['P11'], axis=2)
    gridlmrad = NP.sqrt(vfimgobj.gridl**2 + vfimgobj.gridm**2)
    psfdiff_ds = psf_diff[::2,::2].ravel()
    gridlmrad = gridlmrad[::2,::2].ravel()
    lmradbins = NP.linspace(0.0, 1.0, 21, endpoint=True)
    psfdiffrms, psfdiffbe, psfdiffbn, psfdiffri = OPS.binned_statistic(gridlmrad, values=psfdiff_ds, statistic=NP.std, bins=lmradbins)
    psfref = NP.mean(beam_MOFF, axis=2)
    psfref = psfref[::2,::2].ravel()
    psfrms, psfbe, psfbn, psfri = OPS.binned_statistic(gridlmrad, values=psfref, statistic=NP.std, bins=lmradbins)
    pbmean = NP.mean(efimgobj.pbeam['P1'], axis=2)
    pbmean = pbmean[::2,::2].ravel()
    pbavg, pbbe, pbbn, pbri = OPS.binned_statistic(gridlmrad, values=pbmean, statistic=NP.mean, bins=lmradbins)

    fig, axs = PLT.subplots(ncols=2, figsize=(9,5))
    for j in range(2):
        if j == 0:
            dpsf = axs[j].imshow(psf_diff, origin='lower', extent=(vfimgobj.gridl.min(), vfimgobj.gridl.max(), vfimgobj.gridm.min(), vfimgobj.gridm.max()), interpolation='none', vmin=psf_diff.min(), vmax=psf_diff.max())            
            axs[j].plot(NP.cos(NP.linspace(0.0, 2*NP.pi, num=100)), NP.sin(NP.linspace(0.0, 2*NP.pi, num=100)), 'k-')    
            axs[j].set_xlim(-1,1)
            axs[j].set_ylim(-1,1)    
            axs[j].set_aspect('equal')
def main():

    # 01) Fringe pattern behaviour

    # 02) Fringe cycle coherence

    # 03) Fringe cycle coherence from 2D sky

    # 04) Delay bin coherence from 2D sky

    plot_01 = False
    plot_02 = False
    plot_03 = False
    plot_04 = True

    def za2sinza(za):
        sinza = NP.sin(NP.radians(za))
        return ['{0:.2f}'.format(l) for l in sinza]

    def sinza2za(sinza):
        za = NP.degrees(NP.arcsin(sinza))
        return ['{0:.1f}'.format(theta) for theta in za]

    if plot_01:

        # 01) Fringe pattern behaviour

        bll = 10.0  # Baseline length in m
        wl = 2.0  # Wavelength in m
        # freq = 150e6  # Frequency in Hz
        # wl = FCNST.c / freq
        freq = FCNST.c / wl
        n_theta = 10001
        theta = NP.pi * (NP.arange(n_theta) - n_theta / 2) / n_theta
        y_offset = 10.0 * NP.cos(theta)

        l = NP.sin(theta)  # Direction cosine

        fringe = NP.exp(-1j * 2 * NP.pi * bll * l / wl)
        fringe_l_interval = wl / bll
        l_intervals = NP.arange(-1, 1, fringe_l_interval)
        theta_intervals = NP.degrees(NP.arcsin(l_intervals))
        theta_intervals = NP.append(theta_intervals, 90.0)

        bincount, theta_bin_edges, binnum, ri = OPS.binned_statistic(
            NP.degrees(theta), statistic='count', bins=theta_intervals)
        fringe_sum = NP.zeros(bincount.size, dtype=NP.complex64)
        for i in range(bincount.size):
            ind = ri[ri[i]:ri[i + 1]]
            fringe_sum[i] = NP.sum(fringe[ind])

        fig = PLT.figure(figsize=(6, 6))
        axth = fig.add_subplot(111)
        fringe_theta = axth.plot(NP.degrees(theta), fringe.real, 'k.', ms=2)

        for theta_interval in theta_intervals:
            axth.axvline(x=theta_interval,
                         ymin=0,
                         ymax=0.75,
                         ls=':',
                         lw=0.5,
                         color='black')
        axth.set_xlim(-90, 90)
        axth.set_xlabel(r'$\theta$' + ' [degree]')
        axth.set_ylabel('Fringe [Arbitrary units]', fontsize=12)

        axdc = axth.twiny()
        fringe_dircos = axdc.plot(l, y_offset.max() + fringe.real, 'r.', ms=2)
        fringe_dircos_on_sky = axdc.plot(l,
                                         y_offset + fringe.real,
                                         color='orange',
                                         marker='.',
                                         ms=2)
        sky_curve = axdc.plot(l, y_offset, color='orange', ls='--', lw=1)
        axdc.set_xlim(-1.0, 1.0)
        axdc.set_xlabel(r'$\sin\,\theta$', fontsize=12, color='red')

        axr = axth.twinx()
        # axr.bar(theta_intervals[:-1], bincount/theta.size, width=theta_intervals[1:]-theta_intervals[:-1], color='white', fill=False)
        axr.errorbar(0.5 * (theta_intervals[1:] + theta_intervals[:-1]),
                     NP.abs(fringe_sum) / bincount,
                     yerr=1 / NP.sqrt(bincount),
                     color='b',
                     ecolor='b',
                     fmt='o-',
                     ms=10,
                     lw=2)
        axr.set_xlim(-90, 90)
        axr.set_ylim(-0.2, 0.4)
        axr.set_ylabel('Coherence Amplitude in Fringe Cycle',
                       fontsize=12,
                       color='blue')

        fig.subplots_adjust(right=0.85)

        PLT.savefig(
            '/data3/t_nithyanandan/project_global_EoR/figures/wide_field_effects_demo.png',
            bbox_inches=0)
        PLT.savefig(
            '/data3/t_nithyanandan/project_global_EoR/figures/wide_field_effects_demo.eps',
            bbox_inches=0)

        PLT.show()

    if plot_02:

        # 02) Fringe cycle coherence

        u = 2.0**NP.arange(13)
        u_max = u.max()
        dza = NP.degrees(1 / (512 * u_max))
        za = NP.arange(0.0, 90.0, dza)
        sinza = NP.sin(NP.radians(za))

        fringes = NP.exp(-1j * 2 * NP.pi * u.reshape(-1, 1) *
                         sinza.reshape(1, -1))
        fringe_cycle_coherence = NP.zeros((u.size, u_max), dtype=NP.complex64)
        sample_counts = NP.zeros((u.size, u_max))
        independent_sample_counts = NP.zeros((u.size, u_max))

        dsinza = 1 / u
        last_fringe_cycle_boundary_sinza = 1.0 - dsinza
        last_fringe_cycle_boundary = NP.degrees(
            NP.arcsin(last_fringe_cycle_boundary_sinza))

        eps = 1e-10
        sinza_intervals = NP.arange(0, 1, dsinza[-1])
        sinza_intervals = NP.append(sinza_intervals, 1.0) - eps
        za_intervals = NP.degrees(NP.arcsin(sinza_intervals))
        # za_intervals = NP.append(za_intervals, 90.0)
        bincount, za_bin_edges, binnum, ri = OPS.binned_statistic(
            sinza, statistic='count', bins=sinza_intervals)
        for ui in range(u.size):
            for i in range(u[ui].astype(NP.int)):
                begini = i * u_max / u[ui]
                endi = (i + 1) * u_max / u[ui]
                begini = begini.astype(NP.int)
                endi = endi.astype(NP.int)
                fine_fringe_cycle_ind = NP.arange(begini, endi)
                ind = ri[ri[begini]:ri[endi]]
                fringe_cycle_coherence[ui, fine_fringe_cycle_ind] = NP.sum(
                    fringes[ui, ind])
                sample_counts[ui, fine_fringe_cycle_ind] = float(ind.size)
                independent_sample_counts[
                    ui, fine_fringe_cycle_ind] = 2.0 / NP.sqrt(
                        1 - NP.mean(sinza[ind])**2)

                # ind = ri[ri[i]:ri[i+1]]
                # fringe_cycle_coherence[ui,ind] = NP.sum(fringes[ui,ind])
                # sample_counts[ui,ind] = bincount[i]
                # independent_sample_counts[ui,ind] = 2.0 / NP.sqrt(1-NP.mean(sinza[ind])**2)
        norm_fringe_cycle_coherence = fringe_cycle_coherence / sample_counts
        fringe_cycle_efficiency = fringe_cycle_coherence / za.size
        norm_fringe_cycle_coherence_SNR = norm_fringe_cycle_coherence * NP.sqrt(
            independent_sample_counts)

        fig = PLT.figure(figsize=(6, 6))
        ax = fig.add_subplot(111)
        fringe_matrix = ax.pcolormesh(
            sinza_intervals[:-1],
            u,
            NP.abs(norm_fringe_cycle_coherence),
            norm=PLTC.LogNorm(vmin=1e-6,
                              vmax=NP.abs(norm_fringe_cycle_coherence).max()))
        # fringe_matrix = ax.imshow(NP.abs(norm_fringe_cycle_coherence), origin='lower', extent=[za.min(), 90.0, u.min(), u.max()], norm=PLTC.LogNorm(vmin=1e-6, vmax=NP.abs(norm_fringe_cycle_coherence).max()))
        last_fringe_cycle_edge = ax.plot(last_fringe_cycle_boundary_sinza,
                                         u,
                                         ls='--',
                                         lw=2,
                                         color='white')
        ax.set_xlim(sinza.min(), 1.0)
        ax.set_ylim(u.min(), u.max())
        ax.set_yscale('log')
        ax.set_xlabel(r'$|\,\sin\,\theta\,|$ [degrees]', fontsize=14)
        ax.set_ylabel(r'$b/\lambda$', fontsize=14)
        ax.set_aspect('auto')

        axt = ax.twiny()
        axt.set_xticks(ax.get_xticks())
        axt.set_xbound(ax.get_xbound())
        axt.set_xticklabels(sinza2za(ax.get_xticks()))
        axt.set_xlabel(r'$|\,\theta\,|$', fontsize=14)

        fig.subplots_adjust(right=0.88, left=0.15, top=0.9)

        cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        cbar = fig.colorbar(fringe_matrix, cax=cbax, orientation='vertical')

        PLT.savefig(
            '/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_coherence.png',
            bbox_inches=0)
        PLT.savefig(
            '/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_coherence.eps',
            bbox_inches=0)

        fig = PLT.figure(figsize=(6, 6))
        ax = fig.add_subplot(111)
        fringe_matrix = ax.pcolormesh(
            sinza_intervals[:-1],
            u,
            NP.abs(fringe_cycle_efficiency),
            norm=PLTC.LogNorm(vmin=1e-8,
                              vmax=NP.abs(fringe_cycle_efficiency).max()))
        # fringe_matrix = ax.imshow(NP.abs(norm_fringe_cycle_efficiency), origin='lower', extent=[za.min(), 90.0, u.min(), u.max()], norm=PLTC.LogNorm(vmin=1e-6, vmax=NP.abs(norm_fringe_cycle_efficiency).max()))
        last_fringe_cycle_edge = ax.plot(last_fringe_cycle_boundary_sinza,
                                         u,
                                         ls='--',
                                         lw=2,
                                         color='white')
        ax.set_xlim(sinza.min(), 1.0)
        ax.set_ylim(u.min(), u.max())
        ax.set_yscale('log')
        ax.set_xlabel(r'$|\,\sin\,\theta\,|$ [degrees]', fontsize=14)
        ax.set_ylabel(r'$b/\lambda$', fontsize=14)
        ax.set_aspect('auto')

        axt = ax.twiny()
        axt.set_xticks(ax.get_xticks())
        axt.set_xbound(ax.get_xbound())
        axt.set_xticklabels(sinza2za(ax.get_xticks()))
        axt.set_xlabel(r'$|\,\theta\,|$', fontsize=14)

        fig.subplots_adjust(right=0.88, left=0.15, top=0.9)

        cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        cbar = fig.colorbar(fringe_matrix, cax=cbax, orientation='vertical')

        PLT.savefig(
            '/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_efficiency.png',
            bbox_inches=0)
        PLT.savefig(
            '/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_efficiency.eps',
            bbox_inches=0)

        # fig = PLT.figure(figsize=(6,6))
        # ax = fig.add_subplot(111)
        # fringe_matrix_SNR = ax.imshow(NP.abs(norm_fringe_cycle_coherence_SNR), origin='lower', extent=[za.min(), 90.0, u.min(), u.max()], norm=PLTC.LogNorm(vmin=NP.abs(norm_fringe_cycle_coherence_SNR).min(), vmax=NP.abs(norm_fringe_cycle_coherence_SNR).max()))
        # ax.set_xlim(za.min(), 90.0)
        # ax.set_ylim(u.min(), u.max())
        # ax.set_xlabel(r'$|\,\theta\,|$ [degrees]', fontsize=14)
        # ax.set_ylabel(r'$b/\lambda$', fontsize=14)
        # ax.set_aspect('auto')

        # axt = ax.twiny()
        # axt.set_xticks(ax.get_xticks())
        # axt.set_xbound(ax.get_xbound())
        # axt.set_xticklabels(za2sinza(ax.get_xticks()))
        # axt.set_xlabel(r'$|\,\sin\,\theta\,|$', fontsize=14)

        # fig.subplots_adjust(right=0.88, left=0.15, top=0.9)

        # cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        # cbar = fig.colorbar(fringe_matrix_SNR, cax=cbax, orientation='vertical')

        PLT.show()

    if plot_03:

        # 03) Fringe cycle coherence from 2D sky

        u = 2.0**NP.arange(10)
        u_max = u.max()

        dsa = 1 / (u_max**2)
        npix_orig = 4 * NP.pi / (dsa / 8)

        nside = HP.pixelfunc.get_min_valid_nside(npix_orig)
        npix = HP.nside2npix(nside)
        pixarea = HP.nside2pixarea(nside)
        nring = int(4 * nside - 1)
        isotheta = NP.pi / (nring + 1) * (1 + NP.arange(nring))
        ison = NP.sin(isotheta)

        theta, az = HP.pix2ang(nside, NP.arange(npix))
        n = NP.cos(theta)

        qrtr_sky_ind, = NP.where((theta <= NP.pi / 2) & (az <= NP.pi))
        theta = theta[qrtr_sky_ind]
        az = az[qrtr_sky_ind]
        n = n[qrtr_sky_ind]

        fringes = NP.exp(-1j * 2 * NP.pi * u.reshape(-1, 1) * n.reshape(1, -1))
        fringe_cycle_coherence = NP.zeros((u.size, u_max), dtype=NP.complex64)
        sample_counts = NP.zeros((u.size, u_max))

        dn = 1 / u
        last_fringe_cycle_boundary_n = 1.0 - dn
        last_fringe_cycle_boundary_za = NP.degrees(
            NP.arcsin(last_fringe_cycle_boundary_n))

        eps = 1e-10
        n_intervals = NP.arange(0, 1, dn[-1])
        n_intervals = NP.append(n_intervals, 1.0) - eps
        ang_intervals = NP.degrees(NP.arcsin(n_intervals))
        bincount, n_bin_edges, binnum, ri = OPS.binned_statistic(
            n, statistic='count', bins=n_intervals)
        for ui in range(u.size):
            for i in range(u[ui].astype(NP.int)):
                begini = i * u_max / u[ui]
                endi = (i + 1) * u_max / u[ui]
                begini = begini.astype(NP.int)
                endi = endi.astype(NP.int)
                fine_fringe_cycle_ind = NP.arange(begini, endi)
                ind = ri[ri[begini]:ri[endi]]
                fringe_cycle_coherence[ui, fine_fringe_cycle_ind] = NP.sum(
                    fringes[ui, ind])
                sample_counts[ui, fine_fringe_cycle_ind] = float(ind.size)

        norm_fringe_cycle_coherence = fringe_cycle_coherence / sample_counts
        fringe_cycle_efficiency = fringe_cycle_coherence / (npix / 4)
        fringe_cycle_solid_angle = sample_counts * pixarea

        fig = PLT.figure(figsize=(6, 6))
        ax = fig.add_subplot(111)
        fringe_matrix = ax.pcolormesh(
            n_intervals[:-1],
            u,
            NP.abs(fringe_cycle_efficiency),
            norm=PLTC.LogNorm(vmin=1e-8,
                              vmax=NP.abs(fringe_cycle_efficiency).max()))
        # fringe_matrix = ax.pcolormesh(n_intervals[:-1], u, NP.abs(norm_fringe_cycle_coherence), norm=PLTC.LogNorm(vmin=1e-6, vmax=NP.abs(norm_fringe_cycle_coherence).max()))
        last_fringe_cycle_edge = ax.plot(last_fringe_cycle_boundary_n,
                                         1.5 * u,
                                         ls='--',
                                         lw=2,
                                         color='black')
        ax.set_xlim(0.0, 1.0)
        ax.set_ylim(u.min(), u.max())
        ax.set_yscale('log')
        ax.set_xlabel(r'$|\,\sin\,\theta\,|$', fontsize=14)
        ax.set_ylabel(r'$b/\lambda$', fontsize=14)
        ax.set_aspect('auto')

        axt = ax.twiny()
        axt.set_xticks(ax.get_xticks())
        axt.set_xbound(ax.get_xbound())
        axt.set_xticklabels(sinza2za(ax.get_xticks()))
        axt.set_xlabel(r'$|\,\theta\,|$ [degrees]', fontsize=14)

        fig.subplots_adjust(right=0.88, left=0.15, top=0.9)

        cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        cbar = fig.colorbar(fringe_matrix, cax=cbax, orientation='vertical')

        PLT.savefig(
            '/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_efficiency_2D.png',
            bbox_inches=0)
        PLT.savefig(
            '/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_efficiency_2D.eps',
            bbox_inches=0)

        # fig = PLT.figure(figsize=(6,6))
        # ax = fig.add_subplot(111)
        # solid_angle_matrix = ax.pcolormesh(n_intervals[:-1], u, NP.abs(fringe_cycle_solid_angle), norm=PLTC.LogNorm(vmin=NP.abs(fringe_cycle_solid_angle).min(), vmax=NP.abs(fringe_cycle_solid_angle).max()))
        # last_fringe_cycle_edge = ax.plot(last_fringe_cycle_boundary_n, u, ls='--', lw=2, color='black')
        # ax.set_xlim(0.0, 1.0)
        # ax.set_ylim(u.min(), u.max())
        # ax.set_yscale('log')
        # ax.set_xlabel(r'$|\,\sin\,\theta\,|$', fontsize=14)
        # ax.set_ylabel(r'$b/\lambda$', fontsize=14)
        # ax.set_aspect('auto')

        # axt = ax.twiny()
        # axt.set_xticks(ax.get_xticks())
        # axt.set_xbound(ax.get_xbound())
        # axt.set_xticklabels(sinza2za(ax.get_xticks()))
        # axt.set_xlabel(r'$|\,\theta\,|$ [degrees]', fontsize=14)

        # fig.subplots_adjust(right=0.88, left=0.15, top=0.9)

        # cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        # cbar = fig.colorbar(solid_angle_matrix, cax=cbax, orientation='vertical')
        # cbax.set_xlabel(r'$\Omega$ [Sr]', fontsize=12, labelpad=10)
        # cbax.xaxis.set_label_position('top')

        # PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_solid_angle_2D.png', bbox_inches=0)
        # PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_solid_angle_2D.eps', bbox_inches=0)

    if plot_04:

        # 04) Delay bin coherence from 2D sky

        # f0 = 30e9    # Center frequency in Hz
        # bw = 1e9   # Bandwidth in Hz
        # nchan = 64  # number of frequency channels
        # l_delay_bins = 32
        # bl = 0.5 * l_delay_bins / bw * FCNST.c  # baseline length in m
        # wl0 = FCNST.c / f0
        # freq_resolution = bw / nchan
        # chans = (NP.arange(nchan) - nchan/2) * freq_resolution + f0
        # wl = FCNST.c / chans
        # l_binsize = 1.0 / (l_delay_bins/2)

        # u = bl / wl
        # u_max = u.max()

        # dl_coarse = 1.0 / u_max           # resolution in direction cosine
        # eps = 1e-10
        # # nl = NP.ceil(1.0 / dl_coarse).astype(NP.int)
        # # dl_coarse = 1.0 / nl
        # dl = dl_coarse / 4
        # dm = dl_coarse
        # lv = NP.arange(0.0, 1.0, dl)
        # # lv = NP.append(lv, 1.0-eps)
        # # mv = NP.arange(-1.0+eps, 1.0-eps, dm)
        # mv = NP.append(-lv[-1:0:-1], lv)
        # # mv = NP.append(mv, 1.0-eps)

        # lgrid, mgrid = NP.meshgrid(lv, mv)
        # lmrad = NP.sqrt(lgrid**2 + mgrid**2)
        # ngrid = NP.empty_like(lgrid)
        # sagrid = NP.empty_like(lgrid)
        # ngrid.fill(NP.nan)
        # sagrid.fill(NP.nan)
        # PDB.set_trace()
        # valid_ind = lmrad <= 1.0
        # ngrid[valid_ind] = NP.sqrt(1.0 - lmrad[valid_ind]**2)
        # sagrid[valid_ind] = dl * dm / ngrid[valid_ind]

        # lvect = lgrid[valid_ind]
        # mvect = mgrid[valid_ind]
        # nvect = ngrid[valid_ind]
        # savect = sagrid[valid_ind]

        # # fringes = NP.exp(-1j * 2*NP.pi * u.reshape(-1,1) * lvect.reshape(1,-1))
        # fringes = NP.empty((lgrid.shape[0], lgrid.shape[1], u.shape[0]), dtype=NP.complex64)
        # fringes.fill(NP.nan)
        # fringes[valid_ind] = NP.exp(-1j * 2*NP.pi * u.reshape(1,1,-1) * lgrid[:,:,NP.newaxis])
        # delay_bin_coherence = NP.zeros((u.size, l_delay_bins/2), dtype=NP.complex64)

        # l_intervals = NP.arange(0.0, 1.0, l_binsize)
        # l_intervals = NP.append(l_intervals, 1.0-eps)
        # delay_intervals = bl * l_intervals / FCNST.c
        # bincount, l_bin_edges, binnum, ri = OPS.binned_statistic(lvect, statistic='count', bins=l_intervals)
        # PDB.set_trace()

        # for di in range(l_delay_bins/2):
        #     ind = ri[ri[di]:ri[di+1]]
        #     delay_bin_coherence[:,di] = NP.sum(fringes[:,ind] * savect[ind], axis=1)

        # lgrid, mgrid = NP.meshgrid(lv, mv)
        # lgrid = lgrid.ravel()
        # mgrid = mgrid.ravel()
        # lmrad = NP.sqrt(lgrid**2 + mgrid**2)
        # ngrid = NP.empty_like(lgrid)
        # sagrid = NP.empty_like(lgrid)
        # ngrid.fill(NP.nan)
        # sagrid.fill(NP.nan)
        # valid_ind = lmrad <= 1.0
        # ngrid[valid_ind] = NP.sqrt(1.0 - lmrad[valid_ind]**2)
        # sagrid[valid_ind] = dl * dm / ngrid[valid_ind]

        # lvect = lgrid[valid_ind]
        # mvect = mgrid[valid_ind]
        # nvect = ngrid[valid_ind]
        # savect = sagrid[valid_ind]

        # fringes = NP.exp(-1j * 2*NP.pi * u.reshape(-1,1) * lvect.reshape(1,-1))
        # delay_bin_coherence = NP.zeros((u.size, l_delay_bins/2), dtype=NP.complex64)

        # l_intervals = NP.arange(0.0, 1.0, l_binsize)
        # l_intervals = NP.append(l_intervals, 1.0-eps)
        # delay_intervals = bl * l_intervals / FCNST.c
        # bincount, l_bin_edges, binnum, ri = OPS.binned_statistic(lvect, statistic='count', bins=l_intervals)
        # PDB.set_trace()

        # for di in range(l_delay_bins/2):
        #     ind = ri[ri[di]:ri[di+1]]
        #     delay_bin_coherence[:,di] = NP.sum(fringes[:,ind] * savect[ind], axis=1)

        # f0 = 30e9    # Center frequency in Hz
        # bw = 1e9   # Bandwidth in Hz
        # nchan = 64  # number of frequency channels
        # n_delay_bins = 32
        # bl = 0.5 * n_delay_bins / bw * FCNST.c  # baseline length in m
        # wl0 = FCNST.c / f0
        # freq_resolution = bw / nchan
        # chans = (NP.arange(nchan) - nchan/2) * freq_resolution + f0
        # wl = FCNST.c / chans
        # n_binsize = 1.0 / (n_delay_bins/2)

        # u = bl / wl
        # u_max = u.max()

        # dsa = 1/(u_max ** 2)   # solid angle resolution
        # npix_orig = 4 * NP.pi / (dsa/4)

        # nside = HP.pixelfunc.get_min_valid_nside(npix_orig)
        # npix = HP.nside2npix(nside)
        # pixarea = HP.nside2pixarea(nside)
        # # nring = int(4*nside - 1)
        # # isotheta = NP.pi/(nring+1) * (1 + NP.arange(nring))
        # # ison = NP.sin(isotheta)

        # theta, az = HP.pix2ang(nside, NP.arange(npix))
        # n = NP.cos(theta)

        # qrtr_sky_ind, = NP.where((theta <= NP.pi/2) & (az <= NP.pi))
        # theta = theta[qrtr_sky_ind]
        # az = az[qrtr_sky_ind]
        # n = n[qrtr_sky_ind]

        # fringes = NP.exp(-1j * 2*NP.pi * u.reshape(-1,1) * n.reshape(1,-1))
        # delay_bin_coherence = NP.zeros((u.size, n_delay_bins/2), dtype=NP.complex64)

        # PDB.set_trace()
        # eps = 1e-10
        # n_intervals = NP.arange(0.0, 1.0, n_binsize)
        # n_intervals = NP.append(n_intervals, 1.0) - eps
        # delay_intervals = bl * n_intervals / FCNST.c
        # bincount, n_bin_edges, binnum, ri = OPS.binned_statistic(n, statistic='count', bins=n_intervals)
        # for di in range(n_delay_bins/2):
        #     ind = ri[ri[di]:ri[di+1]]
        #     delay_bin_coherence[:,di] = NP.sum(fringes[:,ind], axis=1) * pixarea
        # #     # for ui in range(u.size):
        # #     #     delay_bin_coherence[ui,di] = NP.sum(fringes[ui,ind]) * pixarea

        # delay_spectrum_coherence = NP.fft.ifftshift(NP.fft.ifft2(delay_bin_coherence, axes=(0,)), axes=0) * bw

        # fig = PLT.figure(figsize=(6,6))
        # ax = fig.add_subplot(111)
        # dspec = ax.imshow(NP.abs(delay_bin_coherence), origin='lower', extent=[delay_intervals.min(), delay_intervals.max(), chans.min(), chans.max()])
        # ax.set_aspect('auto')

        # fig = PLT.figure(figsize=(6,6))
        # ax = fig.add_subplot(111)
        # dspec = ax.imshow(NP.abs(delay_spectrum_coherence), origin='lower', extent=[delay_intervals.min(), delay_intervals.max(), -0.5/freq_resolution, 0.5/freq_resolution])
        # ax.set_aspect('auto')
        # PLT.show()

        f0 = 30e9  # Center frequency in Hz
        bw = 1e9  # Bandwidth in Hz
        nchan = 40  # number of frequency channels
        n_delay_bins = 32
        bl = 0.5 * n_delay_bins / bw * FCNST.c  # baseline length in m
        wl0 = FCNST.c / f0
        freq_resolution = bw / nchan
        chans = (NP.arange(nchan) - nchan / 2) * freq_resolution + f0
        wl = FCNST.c / chans
        n_binsize = 1.0 / (n_delay_bins / 2)

        u = bl / wl
        u_max = u.max()

        dsa = 1 / (u_max**2)
        npix_orig = 4 * NP.pi / (dsa / 8)

        nside = HP.pixelfunc.get_min_valid_nside(npix_orig)
        npix = HP.nside2npix(nside)
        pixarea = HP.nside2pixarea(nside)
        nring = int(4 * nside - 1)
        isotheta = NP.pi / (nring + 1) * (1 + NP.arange(nring))
        ison = NP.sin(isotheta)

        theta, az = HP.pix2ang(nside, NP.arange(npix))
        n = NP.cos(theta)

        qrtr_sky_ind, = NP.where((theta <= NP.pi / 2) & (az <= NP.pi))
        theta = theta[qrtr_sky_ind]
        az = az[qrtr_sky_ind]
        n = n[qrtr_sky_ind]
        sortind = NP.argsort(n)
        nsorted = n[sortind]

        fringes = NP.exp(-1j * 2 * NP.pi * u.reshape(-1, 1) *
                         nsorted.reshape(1, -1))
        accumulated_fringes = accumulate_fringes(fringes) * pixarea
        fringe_cycle_coherence = accumulated_fringe_differencing(
            accumulated_fringes, nsorted, 1 / u_max)

        PDB.set_trace()
        nproc = max(MP.cpu_count() / 2 - 1, 1)
        # chunksize = int(ceil(u.size/float(nproc)))
        pool = MP.Pool(processes=nproc)
        fringe_cycle_coherences = pool.map(
            unwrap_fringe_coherence, IT.izip(u.tolist(), IT.repeat(nsorted)))
        PDB.set_trace()
clean_lags = DSP.downsampler(clean_lags, 1.0*clean_lags.size/ia.lags.size, axis=-1)
clean_lags = clean_lags.ravel()

delaymat = DLY.delay_envelope(bl, pc_dircos, units='mks')
min_delay = -delaymat[0,:,1]-delaymat[0,:,0]
max_delay = delaymat[0,:,0]-delaymat[0,:,1]
clags = clean_lags.reshape(1,-1)
min_delay = min_delay.reshape(-1,1)
max_delay = max_delay.reshape(-1,1)
thermal_noise_window = NP.abs(clags) >= max_abs_delay*1e-6
thermal_noise_window = NP.repeat(thermal_noise_window, bl.shape[0], axis=0)
EoR_window = NP.logical_or(clags > max_delay+1/bw, clags < min_delay-1/bw)
wedge_window = NP.logical_and(clags <= max_delay, clags >= min_delay)
non_wedge_window = NP.logical_not(wedge_window)

bll_bin_count, bll_edges, bll_binnum, bll_ri = OPS.binned_statistic(bl_length, values=None, statistic='count', bins=NP.hstack((geor_bl_length-1e-10, geor_bl_length.max()+1e-10)))

snap_min = 0
snap_max = 39
fg_cc_skyvis_lag_tavg = NP.mean(fg_cc_skyvis_lag[:,:,snap_min:snap_max+1], axis=2)
fg_cc_skyvis_lag_res_tavg = NP.mean(fg_cc_skyvis_lag_res[:,:,snap_min:snap_max+1], axis=2)

fg_cc_skyvis_lag_blavg = NP.zeros((geor_bl_length.size, clags.size, snap_max-snap_min+1), dtype=NP.complex64)
fg_cc_skyvis_lag_res_blavg = NP.zeros((geor_bl_length.size, clags.size, snap_max-snap_min+1), dtype=NP.complex64)
for i in xrange(geor_bl_length.size):
    blind = bll_ri[bll_ri[i]:bll_ri[i+1]]
    if blind.size != bll_bin_count[i]: PDB.set_trace()
    fg_cc_skyvis_lag_blavg[i,:,:] = NP.mean(fg_cc_skyvis_lag[blind,:,snap_min:snap_max+1], axis=0)
    fg_cc_skyvis_lag_res_blavg[i,:,:] = NP.mean(fg_cc_skyvis_lag_res[blind,:,snap_min:snap_max+1], axis=0)
fg_cc_skyvis_lag_avg = NP.mean(fg_cc_skyvis_lag_blavg, axis=2)
fg_cc_skyvis_lag_res_avg = NP.mean(fg_cc_skyvis_lag_res_blavg, axis=2)
    # ax.set_aspect('equal')
    # ax.set_xlabel('l', fontsize=18, weight='medium')
    # ax.set_ylabel('m', fontsize=18, weight='medium')    
    # cbax = fig.add_axes([0.9, 0.125, 0.02, 0.74])
    # cbar = fig.colorbar(ipsf, cax=cbax, orientation='vertical')
    # # PLT.tight_layout()
    # fig.subplots_adjust(right=0.85)
    # fig.subplots_adjust(top=0.88)
    # PLT.savefig('/data3/t_nithyanandan/project_MOFF/simulated/MWA/figures/quick_psf_via_FX.png'.format(max_n_timestamps), bbox_inches=0)
    
    psf_diff = NP.mean(beam_MOFF, axis=2) - NP.mean(vfimgobj.beam['P11'], axis=2)
    gridlmrad = NP.sqrt(vfimgobj.gridl**2 + vfimgobj.gridm**2)
    psfdiff_ds = psf_diff[::2,::2].ravel()
    gridlmrad = gridlmrad[::2,::2].ravel()
    lmradbins = NP.linspace(0.0, 1.0, 21, endpoint=True)
    psfdiffrms, psfdiffbe, psfdiffbn, psfdiffri = OPS.binned_statistic(gridlmrad, values=psfdiff_ds, statistic=NP.std, bins=lmradbins)
    psfref = NP.mean(beam_MOFF, axis=2)
    psfref = psfref[::2,::2].ravel()
    psfrms, psfbe, psfbn, psfri = OPS.binned_statistic(gridlmrad, values=psfref, statistic=NP.std, bins=lmradbins)

    fig, axs = PLT.subplots(nrows=2, ncols=1, figsize=(5,9))
    for j in range(2):
        if j == 0:
            dpsf = axs[j].imshow(psf_diff, origin='lower', extent=(vfimgobj.gridl.min(), vfimgobj.gridl.max(), vfimgobj.gridm.min(), vfimgobj.gridm.max()), interpolation='none', vmin=psf_diff.min(), vmax=psf_diff.max())            
            axs[j].plot(NP.cos(NP.linspace(0.0, 2*NP.pi, num=100)), NP.sin(NP.linspace(0.0, 2*NP.pi, num=100)), 'k-')    
            axs[j].set_xlim(-1,1)
            axs[j].set_ylim(-1,1)    
            axs[j].set_aspect('equal')
            axs[j].set_xlabel('l', fontsize=18, weight='medium')
            axs[j].set_ylabel('m', fontsize=18, weight='medium')                
            cbax = fig.add_axes([0.87, 0.53, 0.02, 0.37])
def main():

    # 01) Fringe pattern behaviour
    
    # 02) Fringe cycle coherence
    
    # 03) Fringe cycle coherence from 2D sky

    # 04) Delay bin coherence from 2D sky
    
    plot_01 = False
    plot_02 = False
    plot_03 = False
    plot_04 = True
    
    def za2sinza(za):
        sinza = NP.sin(NP.radians(za))
        return ['{0:.2f}'.format(l) for l in sinza]
    
    def sinza2za(sinza):
        za = NP.degrees(NP.arcsin(sinza))
        return ['{0:.1f}'.format(theta) for theta in za]
    
    if plot_01:
    
        # 01) Fringe pattern behaviour
        
        bll = 10.0 # Baseline length in m
        wl = 2.0  # Wavelength in m
        # freq = 150e6  # Frequency in Hz
        # wl = FCNST.c / freq
        freq = FCNST.c / wl
        n_theta = 10001
        theta = NP.pi * (NP.arange(n_theta) - n_theta/2)/n_theta
        y_offset = 10.0 * NP.cos(theta)
        
        l = NP.sin(theta) # Direction cosine
        
        fringe = NP.exp(-1j * 2 * NP.pi * bll * l / wl)
        fringe_l_interval = wl / bll
        l_intervals = NP.arange(-1, 1, fringe_l_interval)
        theta_intervals = NP.degrees(NP.arcsin(l_intervals))
        theta_intervals = NP.append(theta_intervals, 90.0)
        
        bincount, theta_bin_edges, binnum, ri = OPS.binned_statistic(NP.degrees(theta), statistic='count', bins=theta_intervals)
        fringe_sum = NP.zeros(bincount.size, dtype=NP.complex64)
        for i in range(bincount.size):
            ind = ri[ri[i]:ri[i+1]]
            fringe_sum[i] = NP.sum(fringe[ind])
        
        fig = PLT.figure(figsize=(6,6))
        axth = fig.add_subplot(111)
        fringe_theta = axth.plot(NP.degrees(theta), fringe.real, 'k.', ms=2)
        
        for theta_interval in theta_intervals:
            axth.axvline(x=theta_interval, ymin=0, ymax=0.75, ls=':', lw=0.5, color='black')
        axth.set_xlim(-90, 90)
        axth.set_xlabel(r'$\theta$'+' [degree]')
        axth.set_ylabel('Fringe [Arbitrary units]', fontsize=12)
        
        axdc = axth.twiny()
        fringe_dircos = axdc.plot(l, y_offset.max()+fringe.real, 'r.', ms=2)
        fringe_dircos_on_sky = axdc.plot(l, y_offset+fringe.real, color='orange', marker='.', ms=2)
        sky_curve = axdc.plot(l, y_offset, color='orange', ls='--', lw=1)
        axdc.set_xlim(-1.0, 1.0)
        axdc.set_xlabel(r'$\sin\,\theta$', fontsize=12, color='red')
        
        axr = axth.twinx()
        # axr.bar(theta_intervals[:-1], bincount/theta.size, width=theta_intervals[1:]-theta_intervals[:-1], color='white', fill=False)
        axr.errorbar(0.5*(theta_intervals[1:]+theta_intervals[:-1]), NP.abs(fringe_sum)/bincount, yerr=1/NP.sqrt(bincount), color='b', ecolor='b', fmt='o-', ms=10, lw=2)
        axr.set_xlim(-90,90)
        axr.set_ylim(-0.2, 0.4)
        axr.set_ylabel('Coherence Amplitude in Fringe Cycle', fontsize=12, color='blue')
        
        fig.subplots_adjust(right=0.85)
        
        PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/wide_field_effects_demo.png', bbox_inches=0)
        PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/wide_field_effects_demo.eps', bbox_inches=0)
        
        PLT.show()
        
    if plot_02:
    
        # 02) Fringe cycle coherence
        
        u = 2.0 ** NP.arange(13)
        u_max = u.max()
        dza = NP.degrees(1/(512*u_max))
        za = NP.arange(0.0, 90.0, dza)
        sinza = NP.sin(NP.radians(za))
    
        fringes = NP.exp(-1j*2*NP.pi*u.reshape(-1,1)*sinza.reshape(1,-1))
        fringe_cycle_coherence = NP.zeros((u.size, u_max), dtype=NP.complex64)
        sample_counts = NP.zeros((u.size, u_max))
        independent_sample_counts = NP.zeros((u.size, u_max))
    
        dsinza = 1/u
        last_fringe_cycle_boundary_sinza = 1.0-dsinza
        last_fringe_cycle_boundary = NP.degrees(NP.arcsin(last_fringe_cycle_boundary_sinza))

        eps = 1e-10
        sinza_intervals = NP.arange(0, 1, dsinza[-1])
        sinza_intervals = NP.append(sinza_intervals, 1.0) - eps
        za_intervals = NP.degrees(NP.arcsin(sinza_intervals))
        # za_intervals = NP.append(za_intervals, 90.0)
        bincount, za_bin_edges, binnum, ri = OPS.binned_statistic(sinza, statistic='count', bins=sinza_intervals)
        for ui in range(u.size):
            for i in range(u[ui].astype(NP.int)):
                begini = i*u_max/u[ui]
                endi = (i+1)*u_max/u[ui]
                begini = begini.astype(NP.int)
                endi = endi.astype(NP.int)                
                fine_fringe_cycle_ind = NP.arange(begini, endi)
                ind = ri[ri[begini]:ri[endi]]
                fringe_cycle_coherence[ui,fine_fringe_cycle_ind] = NP.sum(fringes[ui,ind])
                sample_counts[ui,fine_fringe_cycle_ind] = float(ind.size)
                independent_sample_counts[ui,fine_fringe_cycle_ind] = 2.0 / NP.sqrt(1-NP.mean(sinza[ind])**2)                

                # ind = ri[ri[i]:ri[i+1]]
                # fringe_cycle_coherence[ui,ind] = NP.sum(fringes[ui,ind])
                # sample_counts[ui,ind] = bincount[i]
                # independent_sample_counts[ui,ind] = 2.0 / NP.sqrt(1-NP.mean(sinza[ind])**2)
        norm_fringe_cycle_coherence = fringe_cycle_coherence / sample_counts
        fringe_cycle_efficiency = fringe_cycle_coherence / za.size
        norm_fringe_cycle_coherence_SNR = norm_fringe_cycle_coherence * NP.sqrt(independent_sample_counts)
    
        fig = PLT.figure(figsize=(6,6))
        ax = fig.add_subplot(111)
        fringe_matrix = ax.pcolormesh(sinza_intervals[:-1], u, NP.abs(norm_fringe_cycle_coherence), norm=PLTC.LogNorm(vmin=1e-6, vmax=NP.abs(norm_fringe_cycle_coherence).max()))
        # fringe_matrix = ax.imshow(NP.abs(norm_fringe_cycle_coherence), origin='lower', extent=[za.min(), 90.0, u.min(), u.max()], norm=PLTC.LogNorm(vmin=1e-6, vmax=NP.abs(norm_fringe_cycle_coherence).max()))
        last_fringe_cycle_edge = ax.plot(last_fringe_cycle_boundary_sinza, u, ls='--', lw=2, color='white')
        ax.set_xlim(sinza.min(), 1.0)
        ax.set_ylim(u.min(), u.max())
        ax.set_yscale('log')
        ax.set_xlabel(r'$|\,\sin\,\theta\,|$ [degrees]', fontsize=14)
        ax.set_ylabel(r'$b/\lambda$', fontsize=14)    
        ax.set_aspect('auto')
    
        axt = ax.twiny()
        axt.set_xticks(ax.get_xticks())
        axt.set_xbound(ax.get_xbound())
        axt.set_xticklabels(sinza2za(ax.get_xticks()))
        axt.set_xlabel(r'$|\,\theta\,|$', fontsize=14)
    
        fig.subplots_adjust(right=0.88, left=0.15, top=0.9)
    
        cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        cbar = fig.colorbar(fringe_matrix, cax=cbax, orientation='vertical')
    
        PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_coherence.png', bbox_inches=0)
        PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_coherence.eps', bbox_inches=0)    

        fig = PLT.figure(figsize=(6,6))
        ax = fig.add_subplot(111)
        fringe_matrix = ax.pcolormesh(sinza_intervals[:-1], u, NP.abs(fringe_cycle_efficiency), norm=PLTC.LogNorm(vmin=1e-8, vmax=NP.abs(fringe_cycle_efficiency).max()))
        # fringe_matrix = ax.imshow(NP.abs(norm_fringe_cycle_efficiency), origin='lower', extent=[za.min(), 90.0, u.min(), u.max()], norm=PLTC.LogNorm(vmin=1e-6, vmax=NP.abs(norm_fringe_cycle_efficiency).max()))
        last_fringe_cycle_edge = ax.plot(last_fringe_cycle_boundary_sinza, u, ls='--', lw=2, color='white')
        ax.set_xlim(sinza.min(), 1.0)
        ax.set_ylim(u.min(), u.max())
        ax.set_yscale('log')
        ax.set_xlabel(r'$|\,\sin\,\theta\,|$ [degrees]', fontsize=14)
        ax.set_ylabel(r'$b/\lambda$', fontsize=14)    
        ax.set_aspect('auto')
    
        axt = ax.twiny()
        axt.set_xticks(ax.get_xticks())
        axt.set_xbound(ax.get_xbound())
        axt.set_xticklabels(sinza2za(ax.get_xticks()))
        axt.set_xlabel(r'$|\,\theta\,|$', fontsize=14)
    
        fig.subplots_adjust(right=0.88, left=0.15, top=0.9)
    
        cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        cbar = fig.colorbar(fringe_matrix, cax=cbax, orientation='vertical')
    
        PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_efficiency.png', bbox_inches=0)
        PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_efficiency.eps', bbox_inches=0)    
        
        # fig = PLT.figure(figsize=(6,6))
        # ax = fig.add_subplot(111)
        # fringe_matrix_SNR = ax.imshow(NP.abs(norm_fringe_cycle_coherence_SNR), origin='lower', extent=[za.min(), 90.0, u.min(), u.max()], norm=PLTC.LogNorm(vmin=NP.abs(norm_fringe_cycle_coherence_SNR).min(), vmax=NP.abs(norm_fringe_cycle_coherence_SNR).max()))
        # ax.set_xlim(za.min(), 90.0)
        # ax.set_ylim(u.min(), u.max())
        # ax.set_xlabel(r'$|\,\theta\,|$ [degrees]', fontsize=14)
        # ax.set_ylabel(r'$b/\lambda$', fontsize=14)    
        # ax.set_aspect('auto')
    
        # axt = ax.twiny()
        # axt.set_xticks(ax.get_xticks())
        # axt.set_xbound(ax.get_xbound())
        # axt.set_xticklabels(za2sinza(ax.get_xticks()))
        # axt.set_xlabel(r'$|\,\sin\,\theta\,|$', fontsize=14)
    
        # fig.subplots_adjust(right=0.88, left=0.15, top=0.9)
    
        # cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        # cbar = fig.colorbar(fringe_matrix_SNR, cax=cbax, orientation='vertical')
        
        PLT.show()
        
    if plot_03:
    
        # 03) Fringe cycle coherence from 2D sky
        
        u = 2.0 ** NP.arange(10)
        u_max = u.max()
    
        dsa = 1/(u_max ** 2)
        npix_orig = 4 * NP.pi / (dsa/8)
    
        nside = HP.pixelfunc.get_min_valid_nside(npix_orig)
        npix = HP.nside2npix(nside)
        pixarea = HP.nside2pixarea(nside)
        nring = int(4*nside - 1)
        isotheta = NP.pi/(nring+1) * (1 + NP.arange(nring))
        ison = NP.sin(isotheta)
    
        theta, az = HP.pix2ang(nside, NP.arange(npix))
        n = NP.cos(theta)
    
        qrtr_sky_ind, = NP.where((theta <= NP.pi/2) & (az <= NP.pi))
        theta = theta[qrtr_sky_ind]
        az = az[qrtr_sky_ind]
        n = n[qrtr_sky_ind]
        
        fringes = NP.exp(-1j * 2*NP.pi * u.reshape(-1,1) * n.reshape(1,-1))
        fringe_cycle_coherence = NP.zeros((u.size, u_max), dtype=NP.complex64)
        sample_counts = NP.zeros((u.size, u_max))
        
        dn = 1/u
        last_fringe_cycle_boundary_n = 1.0-dn
        last_fringe_cycle_boundary_za = NP.degrees(NP.arcsin(last_fringe_cycle_boundary_n))
    
        eps = 1e-10
        n_intervals = NP.arange(0, 1, dn[-1])
        n_intervals = NP.append(n_intervals, 1.0) - eps
        ang_intervals = NP.degrees(NP.arcsin(n_intervals))
        bincount, n_bin_edges, binnum, ri = OPS.binned_statistic(n, statistic='count', bins=n_intervals)
        for ui in range(u.size):
            for i in range(u[ui].astype(NP.int)):
                begini = i*u_max/u[ui]
                endi = (i+1)*u_max/u[ui]
                begini = begini.astype(NP.int)
                endi = endi.astype(NP.int)                
                fine_fringe_cycle_ind = NP.arange(begini, endi)
                ind = ri[ri[begini]:ri[endi]]
                fringe_cycle_coherence[ui,fine_fringe_cycle_ind] = NP.sum(fringes[ui,ind])
                sample_counts[ui,fine_fringe_cycle_ind] = float(ind.size)
    
        norm_fringe_cycle_coherence = fringe_cycle_coherence / sample_counts
        fringe_cycle_efficiency = fringe_cycle_coherence / (npix/4)
        fringe_cycle_solid_angle = sample_counts * pixarea
    
        fig = PLT.figure(figsize=(6,6))
        ax = fig.add_subplot(111)
        fringe_matrix = ax.pcolormesh(n_intervals[:-1], u, NP.abs(fringe_cycle_efficiency), norm=PLTC.LogNorm(vmin=1e-8, vmax=NP.abs(fringe_cycle_efficiency).max()))
        # fringe_matrix = ax.pcolormesh(n_intervals[:-1], u, NP.abs(norm_fringe_cycle_coherence), norm=PLTC.LogNorm(vmin=1e-6, vmax=NP.abs(norm_fringe_cycle_coherence).max()))
        last_fringe_cycle_edge = ax.plot(last_fringe_cycle_boundary_n, 1.5*u, ls='--', lw=2, color='black')
        ax.set_xlim(0.0, 1.0)
        ax.set_ylim(u.min(), u.max())
        ax.set_yscale('log')
        ax.set_xlabel(r'$|\,\sin\,\theta\,|$', fontsize=14)
        ax.set_ylabel(r'$b/\lambda$', fontsize=14)    
        ax.set_aspect('auto')
    
        axt = ax.twiny()
        axt.set_xticks(ax.get_xticks())
        axt.set_xbound(ax.get_xbound())
        axt.set_xticklabels(sinza2za(ax.get_xticks()))
        axt.set_xlabel(r'$|\,\theta\,|$ [degrees]', fontsize=14)
    
        fig.subplots_adjust(right=0.88, left=0.15, top=0.9)
    
        cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        cbar = fig.colorbar(fringe_matrix, cax=cbax, orientation='vertical')
    
        PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_efficiency_2D.png', bbox_inches=0)
        PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_efficiency_2D.eps', bbox_inches=0)    

        # fig = PLT.figure(figsize=(6,6))
        # ax = fig.add_subplot(111)
        # solid_angle_matrix = ax.pcolormesh(n_intervals[:-1], u, NP.abs(fringe_cycle_solid_angle), norm=PLTC.LogNorm(vmin=NP.abs(fringe_cycle_solid_angle).min(), vmax=NP.abs(fringe_cycle_solid_angle).max()))
        # last_fringe_cycle_edge = ax.plot(last_fringe_cycle_boundary_n, u, ls='--', lw=2, color='black')
        # ax.set_xlim(0.0, 1.0)
        # ax.set_ylim(u.min(), u.max())
        # ax.set_yscale('log')
        # ax.set_xlabel(r'$|\,\sin\,\theta\,|$', fontsize=14)
        # ax.set_ylabel(r'$b/\lambda$', fontsize=14)    
        # ax.set_aspect('auto')
    
        # axt = ax.twiny()
        # axt.set_xticks(ax.get_xticks())
        # axt.set_xbound(ax.get_xbound())
        # axt.set_xticklabels(sinza2za(ax.get_xticks()))
        # axt.set_xlabel(r'$|\,\theta\,|$ [degrees]', fontsize=14)
    
        # fig.subplots_adjust(right=0.88, left=0.15, top=0.9)
    
        # cbax = fig.add_axes([0.9, 0.1, 0.02, 0.8])
        # cbar = fig.colorbar(solid_angle_matrix, cax=cbax, orientation='vertical')
        # cbax.set_xlabel(r'$\Omega$ [Sr]', fontsize=12, labelpad=10)
        # cbax.xaxis.set_label_position('top')
    
        # PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_solid_angle_2D.png', bbox_inches=0)
        # PLT.savefig('/data3/t_nithyanandan/project_global_EoR/figures/fringe_cycle_solid_angle_2D.eps', bbox_inches=0)    
        
    if plot_04:
    
        # 04) Delay bin coherence from 2D sky
        
        # f0 = 30e9    # Center frequency in Hz
        # bw = 1e9   # Bandwidth in Hz
        # nchan = 64  # number of frequency channels
        # l_delay_bins = 32
        # bl = 0.5 * l_delay_bins / bw * FCNST.c  # baseline length in m
        # wl0 = FCNST.c / f0
        # freq_resolution = bw / nchan
        # chans = (NP.arange(nchan) - nchan/2) * freq_resolution + f0
        # wl = FCNST.c / chans
        # l_binsize = 1.0 / (l_delay_bins/2)

        # u = bl / wl
        # u_max = u.max()

        # dl_coarse = 1.0 / u_max           # resolution in direction cosine
        # eps = 1e-10
        # # nl = NP.ceil(1.0 / dl_coarse).astype(NP.int)
        # # dl_coarse = 1.0 / nl
        # dl = dl_coarse / 4
        # dm = dl_coarse
        # lv = NP.arange(0.0, 1.0, dl)
        # # lv = NP.append(lv, 1.0-eps)
        # # mv = NP.arange(-1.0+eps, 1.0-eps, dm)
        # mv = NP.append(-lv[-1:0:-1], lv)
        # # mv = NP.append(mv, 1.0-eps) 

        # lgrid, mgrid = NP.meshgrid(lv, mv)
        # lmrad = NP.sqrt(lgrid**2 + mgrid**2)
        # ngrid = NP.empty_like(lgrid)
        # sagrid = NP.empty_like(lgrid)
        # ngrid.fill(NP.nan)
        # sagrid.fill(NP.nan)
        # PDB.set_trace()
        # valid_ind = lmrad <= 1.0
        # ngrid[valid_ind] = NP.sqrt(1.0 - lmrad[valid_ind]**2)
        # sagrid[valid_ind] = dl * dm / ngrid[valid_ind]

        # lvect = lgrid[valid_ind]
        # mvect = mgrid[valid_ind]
        # nvect = ngrid[valid_ind]
        # savect = sagrid[valid_ind]
        
        # # fringes = NP.exp(-1j * 2*NP.pi * u.reshape(-1,1) * lvect.reshape(1,-1))
        # fringes = NP.empty((lgrid.shape[0], lgrid.shape[1], u.shape[0]), dtype=NP.complex64)
        # fringes.fill(NP.nan)
        # fringes[valid_ind] = NP.exp(-1j * 2*NP.pi * u.reshape(1,1,-1) * lgrid[:,:,NP.newaxis])
        # delay_bin_coherence = NP.zeros((u.size, l_delay_bins/2), dtype=NP.complex64)
    
        # l_intervals = NP.arange(0.0, 1.0, l_binsize)
        # l_intervals = NP.append(l_intervals, 1.0-eps)
        # delay_intervals = bl * l_intervals / FCNST.c
        # bincount, l_bin_edges, binnum, ri = OPS.binned_statistic(lvect, statistic='count', bins=l_intervals)
        # PDB.set_trace()

        # for di in range(l_delay_bins/2):
        #     ind = ri[ri[di]:ri[di+1]]
        #     delay_bin_coherence[:,di] = NP.sum(fringes[:,ind] * savect[ind], axis=1)

        # lgrid, mgrid = NP.meshgrid(lv, mv)
        # lgrid = lgrid.ravel()
        # mgrid = mgrid.ravel()
        # lmrad = NP.sqrt(lgrid**2 + mgrid**2)
        # ngrid = NP.empty_like(lgrid)
        # sagrid = NP.empty_like(lgrid)
        # ngrid.fill(NP.nan)
        # sagrid.fill(NP.nan)
        # valid_ind = lmrad <= 1.0
        # ngrid[valid_ind] = NP.sqrt(1.0 - lmrad[valid_ind]**2)
        # sagrid[valid_ind] = dl * dm / ngrid[valid_ind]

        # lvect = lgrid[valid_ind]
        # mvect = mgrid[valid_ind]
        # nvect = ngrid[valid_ind]
        # savect = sagrid[valid_ind]
        
        # fringes = NP.exp(-1j * 2*NP.pi * u.reshape(-1,1) * lvect.reshape(1,-1))
        # delay_bin_coherence = NP.zeros((u.size, l_delay_bins/2), dtype=NP.complex64)
    
        # l_intervals = NP.arange(0.0, 1.0, l_binsize)
        # l_intervals = NP.append(l_intervals, 1.0-eps)
        # delay_intervals = bl * l_intervals / FCNST.c
        # bincount, l_bin_edges, binnum, ri = OPS.binned_statistic(lvect, statistic='count', bins=l_intervals)
        # PDB.set_trace()

        # for di in range(l_delay_bins/2):
        #     ind = ri[ri[di]:ri[di+1]]
        #     delay_bin_coherence[:,di] = NP.sum(fringes[:,ind] * savect[ind], axis=1)

            
        # f0 = 30e9    # Center frequency in Hz
        # bw = 1e9   # Bandwidth in Hz
        # nchan = 64  # number of frequency channels
        # n_delay_bins = 32
        # bl = 0.5 * n_delay_bins / bw * FCNST.c  # baseline length in m
        # wl0 = FCNST.c / f0
        # freq_resolution = bw / nchan
        # chans = (NP.arange(nchan) - nchan/2) * freq_resolution + f0
        # wl = FCNST.c / chans
        # n_binsize = 1.0 / (n_delay_bins/2)

        # u = bl / wl
        # u_max = u.max()

        # dsa = 1/(u_max ** 2)   # solid angle resolution
        # npix_orig = 4 * NP.pi / (dsa/4)
    
        # nside = HP.pixelfunc.get_min_valid_nside(npix_orig)
        # npix = HP.nside2npix(nside)
        # pixarea = HP.nside2pixarea(nside)
        # # nring = int(4*nside - 1)
        # # isotheta = NP.pi/(nring+1) * (1 + NP.arange(nring))
        # # ison = NP.sin(isotheta)
    
        # theta, az = HP.pix2ang(nside, NP.arange(npix))
        # n = NP.cos(theta)

        # qrtr_sky_ind, = NP.where((theta <= NP.pi/2) & (az <= NP.pi))
        # theta = theta[qrtr_sky_ind]
        # az = az[qrtr_sky_ind]
        # n = n[qrtr_sky_ind]
        
        # fringes = NP.exp(-1j * 2*NP.pi * u.reshape(-1,1) * n.reshape(1,-1))
        # delay_bin_coherence = NP.zeros((u.size, n_delay_bins/2), dtype=NP.complex64)

        # PDB.set_trace()
        # eps = 1e-10
        # n_intervals = NP.arange(0.0, 1.0, n_binsize)
        # n_intervals = NP.append(n_intervals, 1.0) - eps
        # delay_intervals = bl * n_intervals / FCNST.c
        # bincount, n_bin_edges, binnum, ri = OPS.binned_statistic(n, statistic='count', bins=n_intervals)
        # for di in range(n_delay_bins/2):
        #     ind = ri[ri[di]:ri[di+1]]
        #     delay_bin_coherence[:,di] = NP.sum(fringes[:,ind], axis=1) * pixarea
        # #     # for ui in range(u.size):
        # #     #     delay_bin_coherence[ui,di] = NP.sum(fringes[ui,ind]) * pixarea

        # delay_spectrum_coherence = NP.fft.ifftshift(NP.fft.ifft2(delay_bin_coherence, axes=(0,)), axes=0) * bw

        # fig = PLT.figure(figsize=(6,6))
        # ax = fig.add_subplot(111)
        # dspec = ax.imshow(NP.abs(delay_bin_coherence), origin='lower', extent=[delay_intervals.min(), delay_intervals.max(), chans.min(), chans.max()])
        # ax.set_aspect('auto')

        # fig = PLT.figure(figsize=(6,6))
        # ax = fig.add_subplot(111)
        # dspec = ax.imshow(NP.abs(delay_spectrum_coherence), origin='lower', extent=[delay_intervals.min(), delay_intervals.max(), -0.5/freq_resolution, 0.5/freq_resolution])
        # ax.set_aspect('auto')
        # PLT.show()

        f0 = 30e9    # Center frequency in Hz
        bw = 1e9   # Bandwidth in Hz
        nchan = 40  # number of frequency channels
        n_delay_bins = 32
        bl = 0.5 * n_delay_bins / bw * FCNST.c  # baseline length in m
        wl0 = FCNST.c / f0
        freq_resolution = bw / nchan
        chans = (NP.arange(nchan) - nchan/2) * freq_resolution + f0
        wl = FCNST.c / chans
        n_binsize = 1.0 / (n_delay_bins/2)

        u = bl / wl
        u_max = u.max()
                
        dsa = 1/(u_max ** 2)
        npix_orig = 4 * NP.pi / (dsa/8)
    
        nside = HP.pixelfunc.get_min_valid_nside(npix_orig)
        npix = HP.nside2npix(nside)
        pixarea = HP.nside2pixarea(nside)
        nring = int(4*nside - 1)
        isotheta = NP.pi/(nring+1) * (1 + NP.arange(nring))
        ison = NP.sin(isotheta)
    
        theta, az = HP.pix2ang(nside, NP.arange(npix))
        n = NP.cos(theta)
    
        qrtr_sky_ind, = NP.where((theta <= NP.pi/2) & (az <= NP.pi))
        theta = theta[qrtr_sky_ind]
        az = az[qrtr_sky_ind]
        n = n[qrtr_sky_ind]
        sortind = NP.argsort(n)
        nsorted = n[sortind]

        fringes = NP.exp(-1j * 2*NP.pi * u.reshape(-1,1) * nsorted.reshape(1,-1))
        accumulated_fringes = accumulate_fringes(fringes) * pixarea
        fringe_cycle_coherence = accumulated_fringe_differencing(accumulated_fringes, nsorted, 1/u_max)
        
        PDB.set_trace()
        nproc = max(MP.cpu_count()/2-1, 1)
        # chunksize = int(ceil(u.size/float(nproc)))
        pool = MP.Pool(processes=nproc)
        fringe_cycle_coherences = pool.map(unwrap_fringe_coherence, IT.izip(u.tolist(), IT.repeat(nsorted)))
        PDB.set_trace()
예제 #10
0
    def to_healpix(self, freq, nside, in_units='Jy', out_coords='equatorial',
                   out_units='K', outfile=None, outfmt='fits'):

        """
        -------------------------------------------------------------------------
        Convert catalog to a healpix format of given nside at specified 
        frequencies.

        Inputs:

        freq         [scalar or numpy array] Frequencies at which HEALPIX output
                     maps are to be generated

        nside        [integer] HEALPIX nside parameter for the output map(s)

        in_units     [string] Units of input map or catalog. Accepted values are
                     'K' for Temperature of 'Jy' for flux density. Default='Jy'

        out_coords   [string] Output coordinate system. Accepted values are 
                     'galactic' and 'equatorial' (default)

        out_units    [string] Units of output map. Accepted values are
                     'K' for Temperature of 'Jy' for flux density. Default='K'

        outfile      [string] Filename with full path to save the output HEALPIX
                     map(s) to. Default=None

        outfmt       [string] File format for output file. Accepted values are
                     'fits' (default) and 'ascii'

        Output(s):

        A dictionary with the following keys and values:

        'filename'   Pull path to the output file. Set only if input parameter 
                     outfile is set. Default=None.

        'spectrum'   A numpy array of size nsrc x nchan where nsrc is the number 
                     sky locations depending on input parameter out_nside and 
                     nchan is the number of frequencies in input parameter freq
        -------------------------------------------------------------------------
        """

        try:
            freq
        except NameError:
            freq = self.frequency.ravel()[self.frequency.size/2]
        else:
            if not isinstance(freq, (int,float,list,NP.ndarray)):
                raise TypeError('Input parameter freq must be a scalar or numpy array')
            else:
                freq = NP.asarray(freq).reshape(-1)

        try:
            nside
        except NameError:
            raise NameError('Input parameter nside not specified')
        else:
            if not isinstance(nside, int):
                raise TypeError('Input parameter nside must be an integer')

        if not isinstance(out_coords, str):
            raise TypeError('Input parameter out_coords must be a string')
        elif out_coords not in ['equatorial', 'galactic']:
            raise ValueError('Input parameter out_coords must be set to "equatorial" or "galactic"')

        if not isinstance(in_units, str):
            raise TypeError('in_units must be a string')
        elif in_units not in ['K', 'Jy']:
            raise ValueError('in_units must be "K" or "Jy"')

        if not isinstance(out_units, str):
            raise TypeError('out_units must be a string')
        elif out_units not in ['K', 'Jy']:
            raise ValueError('out_units must be "K" or "Jy"')

        if outfile is not None:
            if not isinstance(outfile, str):
                raise TypeError('outfile must be a string')

            if not isinstance(outfmt, str):
                raise TypeError('outfile format must be specified by a string')
            elif outfmt not in ['ascii', 'fits']:
                raise ValueError('outfile format must be "ascii" or "fits"')

        ec = SkyCoord(ra=self.location[:,0], dec=self.location[:,1], unit='deg', frame='icrs')
        gc = ec.transform_to('galactic')
        if out_coords == 'galactic':
            phi = gc.l.radian
            theta = NP.pi/2 - gc.b.radian
        else:
            phi = ec.ra.radian
            theta = NP.pi/2 - ec.dec.radian

        outmap = NP.zeros((HP.nside2npix(nside), freq.size))
        pixarea = HP.nside2pixarea(nside)
        pix = HP.ang2pix(nside, theta, phi)
        spectrum = self.generate_spectrum(frequency=freq)
        if in_units != out_units:
            if out_units == 'K':
                spectrum = (FCNST.c / freq.reshape(1,-1))**2 / (2*FCNST.k*pixarea) * spectrum * CNST.Jy # Convert into temperature
            else:
                spectrum = (freq.reshape(1,-1) / FCNST.c)**2 * (2*FCNST.k*pixarea) * spectrum / CNST.Jy # Convert into Jy

        uniq_pix, uniq_pix_ind, pix_invind = NP.unique(pix, return_index=True, return_inverse=True)
        counts, binedges, binnums, ri = OPS.binned_statistic(pix_invind, statistic='count', bins=NP.arange(uniq_pix.size+1))
        ind_count_gt1, = NP.where(counts > 1)
        ind_count_eq1, = NP.where(counts == 1)        
        upix_1count = []
        spec_ind = []
        for i in ind_count_eq1:
            ind = ri[ri[i]:ri[i+1]]
            upix_1count += [uniq_pix[i]]
            spec_ind += [ind]

        upix_1count = NP.asarray(upix_1count)
        spec_ind = NP.asarray(spec_ind).ravel()
        outmap[upix_1count,:] = spectrum[spec_ind,:]

        for i in ind_count_gt1:
            upix = uniq_pix[i]
            ind = ri[ri[i]:ri[i+1]]
            outmap[upix,:] = NP.sum(spectrum[ind,:], axis=0)

        # # Plot diagnostic begins
        # if out_coords == 'galactic':
        #     hpxgc = HP.cartview(outmap[:,0], coord='G', return_projected_map=True)
        #     hpxec = HP.cartview(outmap[:,0], coord=['G', 'C'], return_projected_map=True)
        # else:
        #     hpxec = HP.cartview(outmap[:,0], coord='C', return_projected_map=True)
        #     hpxgc = HP.cartview(outmap[:,0], coord=['C', 'G'], return_projected_map=True)
            
        # gcl = gc.l.degree
        # gcb = gc.b.degree
        # gcl[gcl > 180.0] -= 360.0
        # ecra = ec.ra.degree
        # ecdec = ec.dec.degree
        # ecra[ecra > 180.0] -= 360.0

        # fig, axs = PLT.subplots(nrows=2, sharex=True, sharey=True, figsize=(6,6))

        # gcimg = axs[0].imshow(hpxgc, origin='lower', extent=[180,-180,-90,90], norm=PLTC.LogNorm(vmin=hpxgc[hpxgc>0.0].min(), vmax=hpxgc.max()))
        # gcplt = axs[0].plot(gcl, gcb, 'o', mfc='none', mec='black')
        # axs[0].set_xlim(180, -180)
        # axs[0].set_ylim(-90, 90)

        # ecimg = axs[1].imshow(hpxec, origin='lower', extent=[180,-180,-90,90], norm=PLTC.LogNorm(vmin=hpxec[hpxec>0.0].min(), vmax=hpxec.max()))
        # ecplt = axs[1].plot(ecra, ecdec, 'o', mfc='none', mec='black')
        # axs[1].set_xlim(180, -180)
        # axs[1].set_ylim(-90, 90)
        
        # fig.subplots_adjust(hspace=0, wspace=0)
        # PLT.show()

        # # Plot diagnostic ends

        # Save the healpix spectrum to file
        if outfile is not None:
            if outfmt == 'fits':
                hdulist = []
    
                hdulist += [fits.PrimaryHDU()]
                hdulist[0].header['EXTNAME'] = 'PRIMARY'
                hdulist[0].header['NSIDE'] = nside
                hdulist[0].header['UNTIS'] = out_units
                hdulist[0].header['NFREQ'] = freq.size
        
                for chan, f in enumerate(freq):
                    hdulist += [fits.ImageHDU(outmap[:,chan], name='{0:.1f} MHz'.format(f/1e6))]
        
                hdu = fits.HDUList(hdulist)
                hdu.writeto(outfile+'.fits', clobber=True)

                return {'hlpxfile': outfile+outfmt, 'hlpxspec': outmap}
            else:
                out_dict = {}
                colnames = []
                colfrmts = {}
                for chan, f in enumerate(freq):
                    out_dict['{0:.1f}_MHz'.format(f/1e6)] = outmap[:,chan]
                    colnames += ['{0:.1f}_MHz'.format(f/1e6)]
                    colfrmts['{0:.1f}_MHz'.format(f/1e6)] = '%0.5f'

                tbdata = Table(out_dict, names=colnames)
                ascii.write(tbdata, output=outfile+'.txt', format='fixed_width_two_line', formats=colfrmts, bookend=False, delimiter='|', delimiter_pad=' ')

                return {'filename': outfile+outfmt, 'spectrum': outmap}
        else:
            return {'filename': outfile, 'spectrum': outmap}
예제 #11
0
    def generate_spectrum(self, frequency=None):

        """
        -------------------------------------------------------------------------
        Generate and return a spectrum from functional spectral parameters

        Inputs:

        frequency  [scalar or numpy array] Frequencies at which the spectrum at
                   all object locations is to be created. Must be in same units
                   as the attribute frequency and values under key 'freq-ref' 
                   of attribute spec_parms. If not provided (default=None), a 
                   spectrum is generated for all the frequencies specified in 
                   the attribute frequency and values under keys 'freq-ref' and
                   'z-width' of attribute spec_parms. 

        Outputs:

        spectrum   [numpy array] Spectrum of the sky model at the respective
                   sky locations. Has shape nobj x nfreq.

        Power law calculation uses the convention, 
        spectrum = flux_offset + flux_scale * (freq/freq0)**spindex

        Monotone places a delta function at the frequency channel closest to the
        reference frequency if it lies inside the frequency range, otherwise
        a zero spectrum is assigned. 
        Thus spectrum = flux_scale * delta(freq-freq0)

        Random (currently only gaussian) places random fluxes in the spectrum
        spectrum = flux_offset + flux_scale * random_normal(freq.size)

        tanh spectrum is defined as (Bowman & Rogers 2010):
        spectrum = flux_scale * sqrt((1+z)/10) * 0.5 * [tanh((z-zr)/dz) + 1]
        where, flux_scale is typically 0.027 K, zr = reionization redshift 
        when x_i = 0.5, and dz = redshift width (dz ~ 1)

        If the attribute spec_type is 'spectrum' the attribute spectrum is 
        returned without any modifications.
        -------------------------------------------------------------------------
        """

        if self.spec_type == 'func':
            if frequency is not None:
                if isinstance(frequency, (int,float,NP.ndarray)):
                    frequency = NP.asarray(frequency)
                else:
                    raise ValueError('Input parameter frequency must be a scalar or a numpy array')

                if NP.any(frequency <= 0.0):
                    raise ValueError('Input parameter frequency must contain positive values')
            else:
                frequency = NP.copy(self.frequency)

            spectrum = NP.empty((self.location.shape[0], frequency.size))
            spectrum.fill(NP.nan)

            uniq_names, invind = NP.unique(self.spec_parms['name'], return_inverse=True)
            if len(uniq_names) > 1:
                counts, edges, bnum, ri = OPS.binned_statistic(invind, statistic='count', bins=range(len(uniq_names)))
            else:
                counts = len(invind)
                ri = range(counts)

            for i, name in enumerate(uniq_names):
                if len(uniq_names) > 1:
                    indices = ri[ri[i]:ri[i+1]]
                else:
                    indices = ri

                if name == 'random':
                    spectrum[indices,:] = self.spec_parms['flux-offset'][indices].reshape(-1,1) + self.spec_parms['flux-scale'][indices].reshape(-1,1) * NP.random.randn(counts[i], frequency.size)
                if name == 'monotone':  # Needs serious testing
                    spectrum[indices,:] = 0.0
                    inpind, refind, dNN = LKP.find_1NN(frequency, self.spec_parms['freq-ref'][indices], distance=frequency[1]-frequency[0], remove_oob=True) 
                    ind = indices[inpind]
                    ind2d = zip(ind, refind)
                    spectrum[zip(*ind2d)] = self.spec_parms['flux-scale'][ind]
                if name == 'power-law':
                    spectrum[indices,:] = self.spec_parms['flux-offset'][indices].reshape(-1,1) + self.spec_parms['flux-scale'][indices].reshape(-1,1) * (frequency.reshape(1,-1)/self.spec_parms['freq-ref'][indices].reshape(-1,1))**self.spec_parms['power-law-index'][indices].reshape(-1,1)
                if name == 'tanh':
                    z = CNST.rest_freq_HI/frequency.reshape(1,-1) - 1
                    zr = CNST.rest_freq_HI/self.spec_parms['freq-ref'][indices].reshape(-1,1) - 1
                    dz = self.spec_parms['z-width'][indices].reshape(-1,1)

                    amp = self.spec_parms['flux-scale'][indices].reshape(-1,1) * NP.sqrt((1+z)/10)
                    xh = 0.5 * (NP.tanh((z-zr)/dz) + 1)
                    spectrum[indices,:] = amp * xh
                    
            return spectrum
        else:
            return self.spectrum