Exemplo n.º 1
0
def test_individual():
    # This needs to be hidden
    orig_priors = priors.load_std_priors()
    config = getattr(frbs, 'FRB20180924'.lower())
    frbA = frbassociate.run_individual(config, orig_priors['adopted'])

    # Test
    assert isinstance(frbA.candidates, pandas.DataFrame)
    assert frbA.candidates.iloc[0].P_Ox > 0.98
Exemplo n.º 2
0
def fig_frb_excess(frb_list=None, outfile='fig_frb_excess.png', verbose=False):
    """

    Args:
        outfile:

    Returns:

    """
    sns.set_theme()
    sns.set_style('whitegrid')
    sns.set_context('paper')

    if frb_list is None:
        frb_list = associate_defs.frb_list

    # Plot
    plt.figure(figsize=(8, 8))
    ax = plt.gca()

    # Loop on FRBs
    all_seps = []
    for ss, frb_name in enumerate(frb_list):
        config = getattr(frbs, frb_name.lower())
        config['skip_bayesian'] = True
        # Go to 30''
        max = 60.
        config['max_radius'] = max
        config['cut_size'] = max
        config['cand_separation'] = max * units.arcsec
        #
        try:
            frbA = frbassociate.run_individual(config)
        except:
            embed(header='fail')
        # Save
        all_seps += frbA.candidates.separation.values.tolist()

    # Histogram
    _ = sns.histplot(x=all_seps, ax=ax)  #, log_scale=(False,True))

    ax.set_xlabel(r'Separation (arcsec)')
    ax.set_ylabel(r'Number')

    # Font size
    set_fontsize(ax, 15.)

    # End
    print('Writing {:s}'.format(outfile))
    kwargs = {}
    if 'png' in outfile:
        kwargs['dpi'] = 700
    plt.savefig(outfile, **kwargs)
    plt.close()
Exemplo n.º 3
0
def get_candidates():
    # Analyze without priors
    all_frbAs = []
    for ss, frb_name in enumerate(associate_defs.frb_list):
        config = getattr(frbs, frb_name.lower())
        config['skip_bayesian'] = True
        frbA = frbassociate.run_individual(config)
        all_frbAs.append(frbA)
    # df
    df = pandas.DataFrame(dict(frb=associate_defs.frb_list, frbA=all_frbAs))
    # Return
    return df
Exemplo n.º 4
0
def mktab_frb_results(outfile='tab_frb_results.tex', sub=False):

    priors = [associate_defs.conservative,
              associate_defs.adopted]  #, associate_defs.extreme]

    # Open
    tbfil = open(outfile, 'w')

    # Header
    #tbfil.write('\\clearpage\n')
    tbfil.write('\\startlongtable\n')
    tbfil.write('\\begin{deluxetable*}{cccccccccccccccc}\n')
    #tbfil.write('\\rotate\n')
    tbfil.write('\\tablewidth{0pc}\n')
    tbfil.write(
        '\\tablecaption{Results for FRB Associations\\label{tab:results}}\n')
    tbfil.write('\\tabletypesize{\\footnotesize}\n')
    tbfil.write('\\tablehead{\\colhead{FRB}  \n')
    tbfil.write(
        '& \\colhead{RA$_{\\rm cand}$} & \\colhead{Dec$_{\\rm cand}$} \n')
    #tbfil.write('& \\colhead{DM$_{\\rm FRB}$}
    tbfil.write('& \\colhead{$\\theta$} \n')
    tbfil.write('& \\colhead{\\halflight}  \n')
    tbfil.write('& \\colhead{\\gmag} \n')
    tbfil.write('& \\colhead{Filter} & \\colhead{\\pchance} \n')
    tbfil.write('& \\colhead{\\PO} & \\colhead{\\POx} \n')
    tbfil.write('& \\colhead{\\PU} & \\colhead{\\PUx} \n')
    tbfil.write('\\\\')
    #tbfil.write("& (deg) & (deg) & ($''$) & & (deg) & (deg) & ($''$) & ($''$) & ($''$) & ($''$) & (mag)\n")
    #tbfil.write("\\\\ (1) & (2) & (3) & (4) & (5) & (6) & (7) & (8) & (9) & (10) & (11) & (12) & (13) & (14) & (15)")
    tbfil.write('} \n')

    tbfil.write('\\startdata \n')

    # Loop on priors
    for pp, prior in enumerate(priors):
        tbfil.write('\\cutinhead{' + '{}'.format(prior['name']) + '} \n')
        # Loop on FRBs
        for ss, frb_name in enumerate(associate_defs.frb_list):
            # Config
            config = getattr(frbs, frb_name.lower())
            config['skip_bayesian'] = True
            # Could do this outside the prior loop
            frbA = frbassociate.run_individual(config)
            # Set priors
            frbA.calc_priors(prior['U'], method=prior['O'])
            prior['theta']['ang_size'] = frbA.candidates.half_light.values
            frbA.set_theta_prior(prior['theta'])

            # Calculate p(O_i|x)
            frbA.calc_POx()
            # Reverse Sort
            frbA.candidates = frbA.candidates.sort_values('P_Ox',
                                                          ascending=False)

            # Loop Galaxy
            first = True
            for cc, cand in frbA.candidates.iterrows():
                if first:
                    sline = frbA.frb.frb_name
                    first = False
                else:
                    sline = ""
                #
                sline += '& {:0.4f} & ${:0.4f}$'.format(cand.ra, cand.dec)
                sline += '& {:0.1f}'.format(cand.separation)
                sline += '& {:0.2f}'.format(cand.half_light)
                # m
                sline += '& {:0.2f}'.format(cand[frbA.filter])
                sline += '& {:s}'.format(frbA.filter.replace('_', '\_'))
                # Pchance
                sline += '& {:0.4f}'.format(cand.P_c)
                # P(M), P(M|x)
                sline += '& {:0.4f}'.format(cand.P_O)
                sline += '& {:0.4f}'.format(cand.P_Ox)
                # P(S), P(S|X)
                sline += '& {:0.4f}'.format(frbA.prior_U)
                sline += '& {:0.4f}'.format(frbA.P_Ux)

                tbfil.write(sline + '\\\\ \n')

    # End end
    tbfil.write('\\hline \n')

    tbfil.write('\\enddata \n')

    #tbfil.write('\\tablenotetext{a}{Spectroscopic redshifts are reported to 4 significant digits.  Photometric to 2.} \n')
    #tbfil.write('the gas below the line $\\rm DEC_{\\rm off} = \\aslope RA_{\\rm off} \\ayoff$}\n')
    #tbfil.write('\\tablecomments{Column 1: FRB source. Columns 2 and 3: R.A. and Decl. of the FRB (J2000). Column 4: FRB error ellipse. Column 5: FRB classication. Repeating = yes(y)/no(n). Column 6 and 7: R.A. and Dec. of the associated host galaxy (J2000). Column 8: projected angular offset of the FRB to the host galaxy center. Column 9: association radius $\delta x$ \citep{Tunnicliffe14}. Column 10: angular effective radius of the host measured from a sersic model using GALFIT \citep{galfit} on the $i$-band images (or equivalent). Column 11: effective search radius \citep{Bloom02}. Column 12: measured apparent magnitude of the host. Column 13: filter used for the magnitude measurement. Column 14: probability of chance coincidence using the \citet{Bloom02} formalism. Column 15: sample designations following the criteria outlined in $\S$~\\ref{ssec:associate}.}\n')
    # End
    tbfil.write('\\end{deluxetable*} \n')

    tbfil.close()
    print('Wrote {:s}'.format(outfile))
Exemplo n.º 5
0
def fig_vary_PU(frb_list=None, outfile='fig_vary_PU.png'):
    """

    Args:
        outfile:

    Returns:

    """
    sns.set_theme()
    sns.set_style('whitegrid')
    sns.set_context('paper')

    if frb_list is None:
        frb_list = associate_defs.frb_list
    # Priors
    aprior = associate_defs.adopted.copy()

    # Loop on PU
    #PUs = [0., 0.1, 0.5, 0.9]
    PUs = np.linspace(0., 0.1, 10)

    POx_frbs = np.zeros((len(frb_list), len(PUs)))
    for ss, frb_name in enumerate(frb_list):
        config = getattr(frbs, frb_name.lower())
        config['skip_bayesian'] = True
        for pp, PU in enumerate(PUs):
            frbA = frbassociate.run_individual(config)
            frbA.calc_priors(PU, method=aprior['O'])
            aprior['theta']['ang_size'] = frbA.candidates['half_light'].values
            frbA.set_theta_prior(aprior['theta'])

            # Calculate p(O_i|x)
            frbA.calc_POx()
            # Reverse sort
            frbA.candidates = frbA.candidates.sort_values('P_Ox',
                                                          ascending=False)

            # Save
            POx_frbs[ss, pp] = frbA.candidates.P_Ox.values[0]
            #if PU > 0.:
            #embed(header='613 of figs')
            #frbA.candidates[['ra', 'dec', 'P_O', 'P_Ox', 'p_xO']]

    # Plot
    set_mplrc()
    plt.figure(figsize=(15, 5))
    ax = plt.gca()

    # Colors
    cm = plt.get_cmap('jet')
    N = len(frb_list) + 1
    plt.rcParams["axes.prop_cycle"] = plt.cycler("color",
                                                 cm(np.linspace(0, 1, N)))

    # Plot
    for kk, frb_name in enumerate(frb_list):
        sns.lineplot(x=PUs, y=POx_frbs[kk, :], ax=ax, label=frb_name)

    # Label me
    ax.set_xlabel(r'$P(U)$')
    ax.set_ylabel(cPOxi)
    #ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
    #ax.xaxis.set_major_formatter(FormatStrFormatter(r'$%.3f$'))
    ax.set_ylim(0., 1.)

    # Legend
    legend = ax.legend(loc='upper right',
                       scatterpoints=1,
                       borderpad=0.2,
                       handletextpad=handletextpad,
                       fontsize='large')

    set_fontsize(ax, 13.)
    # End
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    print('Writing {:s}'.format(outfile))
    kwargs = {}
    if 'png' in outfile:
        kwargs['dpi'] = 700
    plt.savefig(outfile, **kwargs)
    plt.close()
Exemplo n.º 6
0
def fig_galaxy_priors(frb_name, outfile='fig_galaxy_priors.png'):
    """

    Args:
        frb_name:
        outfile:

    Returns:

    """
    if frb_name == 'FRB180924':
        config = frbs.frb180924
    elif frb_name == 'FRB190523':
        config = frbs.frb190523
    else:
        raise IOError("Bad FRB")
    config['skip_bayesian'] = True
    frbA = frbassociate.run_individual(config)  #, verbose=True, show=True)

    # Pchance
    frbA.calc_pchance()

    # Priors

    # Uniform
    P_U = 0
    frbA.calc_priors(P_U, method='identical')
    frbA.candidates['P_O_u'] = frbA.candidates['P_O'].values.copy()

    # Linear
    #frbA.calc_priors(P_U, method='linear')
    #frbA.candidates['P_O_l'] = frbA.candidates['P_O'].values.copy()

    # Inverse
    frbA.calc_priors(P_U, method='inverse')
    frbA.candidates['P_O_i'] = frbA.candidates['P_O'].values.copy()

    fsz = 9.
    lsz = fsz
    fig = plt.figure(figsize=(3, 6))

    # Image
    x0, y0 = 0.25, 0.5
    aximg = fig.add_axes([x0, y0, 0.95 - x0, 0.98 - y0], projection=frbA.wcs)

    blues = plt.get_cmap('Blues')
    vmnx = 200.
    d = aximg.imshow(frbA.hdu.data, cmap=blues, vmin=-vmnx, vmax=vmnx)

    # Mark candidates
    markers = ['o', 's', 'D', '^']

    ss = 0
    for _, cand in frbA.candidates.iterrows():
        aximg.plot(cand.ra,
                   cand.dec,
                   markers[ss],
                   color='pink',
                   transform=aximg.get_transform('icrs'),
                   ms=2,
                   alpha=0.5)
        ss += 1

    # FRB localization
    apermap = plot_frb_localization(frbA.frb, frbA.wcs)
    apermap.plot(color='red', lw=1, ls='dotted')

    plt.grid(color='gray', ls='dashed', lw=0.5)
    aximg.set_xlabel('Right Ascension (J2000)', fontsize=fsz)
    aximg.set_ylabel('Declination (J2000)', fontsize=fsz, labelpad=-2)
    aximg.tick_params(axis='both', labelsize=lsz)

    aximg.set_title(frbA.frb.frb_name)

    # ###############################################################
    # Priors
    #
    x0, y0 = 0.18, 0.08
    axp = fig.add_axes([x0, y0, 0.97 - x0, 0.47 - y0])

    clrs = ['g', 'k', 'b']
    #for lbl, postfix, clr in zip(['Identical', 'Linear', 'Inverse'],
    #                             ['_u', '_l', '_i'],
    #                             clrs):
    for lbl, postfix, clr in zip(['Identical', 'Inverse'], ['_u', '_i'], clrs):
        ss = 0
        for _, cand in frbA.candidates.iterrows():
            _lbl = lbl if ss == 0 else None
            axp.scatter(cand.separation,
                        cand['P_O' + postfix],
                        marker=markers[ss],
                        color=clr,
                        label=_lbl)
            ss += 1

    axp.set_xlabel(r'$\theta$ (arcsec)')
    axp.set_ylabel(cPOi)
    axp.set_xlim(0., 10.)
    axp.set_ylim(0., 1.)
    set_fontsize(axp, 9.)

    legend = axp.legend(loc='upper right',
                        scatterpoints=0,
                        borderpad=0.2,
                        handlelength=0,
                        handletextpad=0,
                        fontsize='small')
    # Color the text
    for ss, text in enumerate(legend.get_texts()):
        plt.setp(text, color=clrs[ss])
    # Turn off dots
    for item in legend.legendHandles:
        item.set_visible(False)

    # End
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    print('Writing {:s}'.format(outfile))
    kwargs = {}
    if 'png' in outfile:
        kwargs['dpi'] = 700
    plt.savefig(outfile, **kwargs)
    plt.close()
Exemplo n.º 7
0
def fig_pOx_frbs(frb_list=None,
                 outfile='fig_pOx_frbs.png',
                 tmax=None,
                 exp_offset=False,
                 verbose=False):
    """

    Args:
        outfile:

    Returns:

    """
    if frb_list is None:
        frb_list = associate_defs.frb_list
    # Priors
    #priors = [associate_defs.conservative, associate_defs.adopted, associate_defs.extreme]
    priors = [
        associate_defs.conservative.copy(),
        associate_defs.adopted.copy()
    ]
    # Adjust priors
    if tmax is not None:
        for prior in priors:
            prior['theta']['max'] = tmax
    if exp_offset:
        for prior in priors:
            prior['theta']['method'] = 'exp'
    #
    clrs = ['g', 'k', 'b']
    Npriors = len(priors)
    width = 0.9 / Npriors

    # Plot
    set_mplrc()
    plt.figure(figsize=(15, 5))
    ax = plt.gca()

    ind = np.arange(len(frb_list))
    plt.xticks(ind, frb_list)

    # Loop on FRBs
    for ss, frb_name in enumerate(frb_list):
        config = getattr(frbs, frb_name.lower())
        config['skip_bayesian'] = True
        for pp, prior in enumerate(priors):
            frbA = frbassociate.run_individual(config)
            frbA.calc_priors(prior['U'], method=prior['O'])
            prior['theta']['ang_size'] = frbA.candidates['half_light'].values
            frbA.set_theta_prior(prior['theta'])

            # Calculate p(O_i|x)
            frbA.calc_POx()
            # Reverse sort
            frbA.candidates = frbA.candidates.sort_values('P_Ox',
                                                          ascending=False)

            cum_POx = 0
            for cc, cand in frbA.candidates.iterrows():
                # Bar me!
                ax.bar(ss - 0.45 + (pp + 0.5) * width,
                       cand.P_Ox,
                       width,
                       color=clrs[pp],
                       bottom=cum_POx,
                       edgecolor=clrs[pp],
                       fill=(cum_POx == 0))
                cum_POx += cand.P_Ox
            # Print
            if verbose:
                print(
                    frb_name + '\n', frbA.candidates[[
                        'id', frbA.filter, 'half_light', 'separation', 'P_O',
                        'P_Ox'
                    ]])

    # Label me
    #ax.set_xlabel(r'$\theta/\theta_{1/2}$')
    ax.set_ylabel(cPOxi)
    #ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
    #ax.xaxis.set_major_formatter(FormatStrFormatter(r'$%.3f$'))
    ax.set_ylim(0., 1.)

    # Legend
    legend = ax.legend(loc='upper right',
                       scatterpoints=1,
                       borderpad=0.2,
                       handletextpad=handletextpad,
                       fontsize='large')

    set_fontsize(ax, 13.)
    # End
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    print('Writing {:s}'.format(outfile))
    kwargs = {}
    if 'png' in outfile:
        kwargs['dpi'] = 700
    plt.savefig(outfile, **kwargs)
    plt.close()
Exemplo n.º 8
0
def fig_pchance(frb_name='FRB180924', outfile='fig_pchance.png'):
    """

    Args:
        frb_name:
        outfile:
    """
    set_mplrc()
    mpl.rcParams['text.latex.preamble'] = [r'\boldmath']

    if frb_name == 'FRB180924':
        config = frbs.frb180924
    elif frb_name == 'FRB190614':
        config = frbs.frb190614
        config['cut_size'] = 20.
    else:
        raise IOError("Bad FRB")
    config['skip_bayesian'] = True
    frbA = frbassociate.run_individual(config)  #, verbose=True, show=True)

    fsz = 9.
    lsz = fsz
    fig = plt.figure(figsize=(5, 5))

    # Image
    x0, y0 = 0.25, 0.1
    aximg = fig.add_axes([x0, y0, 0.95 - x0, 0.98 - y0], projection=frbA.wcs)

    #blues = plt.get_cmap('Blues')
    greens = plt.get_cmap('Greens')
    vmnx = 200.
    d = aximg.imshow(frbA.hdu.data, cmap=greens, vmin=-vmnx, vmax=vmnx)

    # Label candidates
    for cc, cand in frbA.candidates.iterrows():
        roffset, doffset = 0, 0
        if frb_name == 'FRB180924':
            doffset = 0.9 / 3600. if cand.separation > 1.5 else -4. / 3600.
            if cand.separation < 1.5:
                roffset = 10 / 3600.
            elif np.abs(getattr(cand, frbA.filter) - 25.5) < 0.1:
                roffset = 3 / 3600.
            else:
                roffset = 1 / 3600.
        elif frb_name == 'FRB190614':
            doffset = -4. / 3600. if np.abs(cand.separation -
                                            2.18) < 0.1 else 0.9 / 3600.
            roffset = 3 / 3600  # if np.abs(cand.separation-2.18) < 0.1 else 0 / 3600.

        aximg.text(cand.ra + roffset,
                   cand.dec + doffset,
                   r"$m = {:0.1f}$".format(getattr(cand, frbA.filter)) + "\n" +
                   r"$" + cmhalf + "={:0.1f}''$".format(cand.half_light) +
                   "\n" + r"$\theta={:0.1f}''$".format(cand.separation) +
                   "\n" + r"$P^c={:0.2f}$".format(cand.P_c),
                   color='k',
                   transform=aximg.get_transform('icrs'),
                   size=fsz,
                   ha='left')
        #aximg.plot(row['ra'], row['dec'], markers[ss], color='pink',
        #           transform=aximg.get_transform('icrs'), ms=2,
        #           alpha=0.5)

    # FRB localization
    apermap = plot_frb_localization(frbA.frb, frbA.wcs, scale=5.)
    apermap.plot(color='red', lw=1, ls='dotted')

    plt.grid(color='gray', ls='dashed', lw=0.5)
    asz = 11.
    aximg.set_xlabel(r'\textbf{Right Ascension (J2000)}', fontsize=asz)
    aximg.set_ylabel(r'\textbf{Declination (J2000)}',
                     fontsize=asz,
                     labelpad=-1)
    aximg.tick_params(axis='both', labelsize=lsz)

    aximg.set_title(frbA.frb.frb_name)

    # End
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    print('Writing {:s}'.format(outfile))
    kwargs = {}
    if 'png' in outfile:
        kwargs['dpi'] = 700
    plt.savefig(outfile, **kwargs)
    plt.close()
Exemplo n.º 9
0
def fig_galaxy_posteriors(frb_name,
                          outfile='fig_galaxy_posteriors.png',
                          raoffsets=None,
                          decoffsets=None,
                          cmap=None,
                          frb_color='r',
                          vmnx=(None, None),
                          cut_low=False,
                          add_faint=None,
                          prior_mode='adopted',
                          min_POx=0.01):
    """

    Args:
        frb_name:
        outfile:
        add_faint (tuple, optional):
            separation, half-light, mag

    Returns:

    """
    if frb_name in ['FRB180301']:
        config = analysis.frb180301
    else:
        config = getattr(frbs, frb_name.lower())
    # Run
    config['skip_bayesian'] = True
    frbA = frbassociate.run_individual(config)  #, verbose=True, show=True)

    # Add fake?
    if add_faint:
        fake_coord = frbA.frb.coord.directional_offset_by(
            0. * units.deg, add_faint[0] * units.arcsec)
        fake_row = frbA.candidates.iloc[0]
        # Fill in
        fake_row.coords = fake_coord
        fake_row.ra = fake_coord.ra.value
        fake_row.dec = fake_coord.dec.value
        fake_row.separation = add_faint[0]
        fake_row.half_light = add_faint[1]
        fake_row[frbA.filter] = add_faint[2]
        fake_row.id = 99
        # Add it in
        frbA.candidates = frbA.candidates.append(fake_row, ignore_index=True)
        # Redo chance
        frbA.calc_pchance()

    # Prior
    prior = getattr(associate_defs, prior_mode).copy()

    # Set priors
    frbA.calc_priors(prior['U'], method=prior['O'])
    prior['theta']['ang_size'] = frbA.candidates['half_light'].values
    frbA.set_theta_prior(prior['theta'])

    # Calculate p(O_i|x)
    frbA.calc_POx()
    frbA.candidates = frbA.candidates.sort_values('P_Ox', ascending=False)

    # Plot
    fsz = 10.
    lsz = fsz
    fig = plt.figure(figsize=(5, 5))

    # Image
    x0, y0 = 0.25, 0.1
    aximg = fig.add_axes([x0, y0, 0.95 - x0, 0.98 - y0], projection=frbA.wcs)

    if cmap is None:
        cmap = plt.get_cmap('Blues')
    d = aximg.imshow(frbA.hdu.data, cmap=cmap, vmin=vmnx[0], vmax=vmnx[1])

    # Mark candidates
    markers = ['o', 's', 'D', '^']

    # Label candidates
    ss = 0
    for cc, cand in frbA.candidates.iterrows():
        if cut_low and cand.P_Ox < min_POx:
            continue
        # Offset
        roffset = 0. if raoffsets is None else raoffsets[ss] / 3600.
        doffset = 0. if decoffsets is None else decoffsets[ss] / 3600.
        #
        aximg.text(cand.ra + roffset,
                   cand.dec + doffset,
                   r"$P(O)" + "={:0.2f}$".format(cand.P_O) + "\n" +
                   r"$P(O_i|x) = {:0.2f}$".format(cand.P_Ox),
                   color='k',
                   transform=aximg.get_transform('icrs'),
                   size=fsz,
                   ha='left')
        #
        ss += 1

    # FRB localization
    apermap = plot_frb_localization(frbA.frb, frbA.wcs)
    apermap.plot(color=frb_color, lw=1, ls='dashed')

    plt.grid(color='gray', ls='dashed', lw=0.5)
    aximg.set_xlabel('Right Ascension (J2000)', fontsize=fsz)
    aximg.set_ylabel('Declination (J2000)', fontsize=fsz, labelpad=-1)
    aximg.tick_params(axis='both', labelsize=lsz)

    aximg.set_title(frbA.frb.frb_name)

    # End
    #plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    print('Writing {:s}'.format(outfile))
    kwargs = {}
    if 'png' in outfile:
        kwargs['dpi'] = 700
    plt.savefig(outfile, **kwargs)
    plt.close()
Exemplo n.º 10
0
def fig_segm(outfile='fig_segm.png'):
    """

    Args:
        outfile:

    Returns:

    """
    set_mplrc()

    # Plot
    plt.figure(figsize=(9, 5))
    gs = gridspec.GridSpec(1, 2)

    # FRB 180924
    ax0 = plt.subplot(gs[0])
    config0 = frbs.frb180924
    frbA_180924 = frbassociate.run_individual(config0)

    cmap = frbA_180924.segm.make_cmap()
    ax0.imshow(frbA_180924.segm,
               origin='lower',
               cmap=cmap,
               interpolation='nearest',
               extent=[
                   -config0['cut_size'] / 2, config0['cut_size'] / 2,
                   -config0['cut_size'] / 2, config0['cut_size'] / 2
               ])
    ax0.set_title('FRB 180924')

    # FRB localization
    apermap = plot_frb_localization(frbA_180924.frb, frbA_180924.wcs)
    apermap.plot(color='white', lw=1)

    # FRB 190523
    ax1 = plt.subplot(gs[1])
    config1 = frbs.frb190523
    frbA_190523 = frbassociate.run_individual(config1)

    cmap = frbA_190523.segm.make_cmap()
    ax1.imshow(frbA_190523.segm,
               origin='lower',
               cmap=cmap,
               interpolation='nearest',
               extent=[
                   -config1['cut_size'] / 2, config1['cut_size'] / 2,
                   -config1['cut_size'] / 2, config1['cut_size'] / 2
               ])
    ax1.set_title('FRB 190523')

    apermap = plot_frb_localization(frbA_190523.frb, frbA_190523.wcs)
    apermap.plot(color='white', lw=1)

    # Label me
    for ax in [ax0, ax1]:
        ax.set_xlabel('arcsec')
        ax.set_ylabel('arcsec')
    #ax.xaxis.set_major_locator(plt.MultipleLocator(1.))
    #ax.xaxis.set_major_formatter(FormatStrFormatter(r'$%.3f$'))

    # Font size
    for ax in [ax0, ax1]:
        set_fontsize(ax, 15.)

    # End
    plt.tight_layout(pad=0.2, h_pad=0., w_pad=0.1)
    print('Writing {:s}'.format(outfile))
    kwargs = {}
    if 'png' in outfile:
        kwargs['dpi'] = 700
    plt.savefig(outfile, **kwargs)
    plt.close()
Exemplo n.º 11
0
from frb.associate import frbassociate
from frb.associate import frbs

from IPython import embed
"""
RUN THIS
"""
#frb_name = 'FRB121102'
#frb_name = 'FRB180916'
frb_name = 'FRB180924'
#frb_name = 'FRB190611'
#frb_name = 'FRB190614'
#frb_name = 'FRB181112'
#frb_name = 'FRB190102'
#frb_name = 'FRB190711'
#frb_name = 'FRB190714'
#frb_name = 'FRB191001'
#frb_name = 'FRB200430'

config = getattr(frbs, frb_name.lower())
config['skip_bayesian'] = True

frbA = frbassociate.run_individual(config, show=True, verbose=True)

embed()
Exemplo n.º 12
0
def run(frb_list: list,
        host_coords: list,
        prior: dict,
        override: bool = False):
    """Main method for generating a Host JSON file

    Args:
        frb_list (list): List of FRB names from the database
        host_coords (list): List of host galaxy coords fom the database
        prior (dict):
            Prior for PATH
        override (bool, optional): Attempt to over-ride errors. 
            Mainly for time-outs of public data. Defaults to False.
        tol (float, optional):  Tolerance for a match to the expected host
            in arcsec.

    Raises:
        e: [description]
        ValueError: [description]

    Returns:
        pandas.DataFrame:  Table of PATH values and a bit more
    """
    good_frb, PATH_O, PATH_Ox, RAs, Decs = [], [], [], [], []
    ang_sizes, separations, sep_err = [], [], []
    skipped = []
    for frb, host_coord in zip(frb_list, host_coords):
        frb_name = utils.parse_frb_name(frb, prefix='frb')
        # Config
        if not hasattr(frbs, frb_name.upper()):
            print(f"PATH analysis not possible for {frb_name}")
            continue
        print(f"Performing PATH on {frb_name}")
        config = getattr(frbs, frb_name.upper())

        # Run me
        frbA = frbassociate.run_individual(config, prior=prior)

        if frbA is None:
            print(f"PATH analysis not possible for {frb_name}")
            skipped.append(frb_name)
            continue

        # Save for table
        good_frb.append(frb_name.upper())
        PATH_Ox.append(frbA.candidates.P_Ox.values[0])
        PATH_O.append(frbA.candidates.P_O.values[0])
        RAs.append(host_coord.ra.deg)
        Decs.append(host_coord.dec.deg)
        ang_sizes.append(frbA.candidates.ang_size.values[0])
        separations.append(frbA.candidates.separation.values[0])

    # Build the table
    df = pandas.DataFrame()
    df['FRB'] = good_frb
    df['RA'] = RAs
    df['Dec'] = Decs
    df['ang_size'] = ang_sizes
    df['P_O'] = PATH_O
    df['P_Ox'] = PATH_Ox
    df['separation'] = separations

    for frb_name in skipped:
        print(f"PATH analysis not possible for {frb_name}")

    #
    return df