Ejemplo n.º 1
0
 def test_fold_detection_level(self):
     """Test pulse phase calculation, frequency only."""
     np.testing.assert_almost_equal(fold_detection_level(16, 0.01),
                                    30.577914166892498)
     np.testing.assert_almost_equal(
         fold_detection_level(16, 0.01, ntrial=2),
         fold_detection_level(16, 0.01 / 2))
Ejemplo n.º 2
0
 def test_fold_detection_level(self):
     """Test pulse phase calculation, frequency only."""
     np.testing.assert_almost_equal(fold_detection_level(16, 0.01),
                                    30.577914166892498)
     np.testing.assert_almost_equal(
         fold_detection_level(16, 0.01, ntrial=2),
         fold_detection_level(16, 0.01 / 2))
Ejemplo n.º 3
0
 def test_fold_probability(self):
     detlev = fold_detection_level(16, 0.1, ntrial=3)
     np.testing.assert_almost_equal(fold_profile_probability(detlev, 16,
                                                             ntrial=3),
                                    0.1)
Ejemplo n.º 4
0
def plot_folding(fnames, figname=None, xlog=None, ylog=None,
                 output_data_file=None):
    from .fold import z2_n_detection_level
    from .io import find_file_in_allowed_paths
    from stingray.pulse.pulsar import fold_detection_level
    from matplotlib import gridspec
    import matplotlib.pyplot as plt

    if is_string(fnames):
        fnames = [fnames]

    for fname in fnames:
        ef = load_folding(fname)

        if not hasattr(ef, 'M') or ef.M is None:
            ef.M = 1

        if ef.kind == "Z2n":
            vmin = ef.N - 1
            vmax = z2_n_detection_level(0.001, n=ef.N,
                                        ntrial=max(ef.stat.shape),
                                        n_summed_spectra=ef.M)
            nbin = ef.N * 8
        else:
            vmin = ef.nbin
            vmax = fold_detection_level(ef.nbin, 0.001,
                                        ntrial=max(ef.stat.shape))
            nbin = ef.nbin

        if len(ef.stat.shape) > 1 and ef.stat.shape[0] > 1:
            idx = ef.stat.argmax()
            # ix, iy = np.unravel_index(np.argmax(ef.stat, axis=None),
            #                           ef.stat.shape)
            f, fdot = ef.freq.flatten()[idx], ef.fdots.flatten()[idx]
            df = np.min(np.diff(ef.freq[0]))
            dfdot = np.min(np.diff(ef.fdots[:, 0]))
        elif len(ef.stat.shape) == 1:
            f = ef.freq[ef.stat.argmax()]
            df = np.min(np.diff(ef.freq))

            fdot = 0
            dfdot = 1
        else:
            raise ValueError("Did not understand stats shape.")

        plt.figure(fname, figsize=(10, 10))

        if hasattr(ef, "filename") and ef.filename is not None and \
                os.path.exists(ef.filename):
            external_gs = gridspec.GridSpec(2, 1)
            search_gs_no = 1

            events = load_events(ef.filename)

            if hasattr(ef, "parfile") and ef.parfile is not None:
                root = os.path.split(fname)[0]
                parfile = find_file_in_allowed_paths(ef.parfile,
                                                     ['.', root])
                if not parfile:
                    warnings.warn("{} does not exist".format(ef.parfile))
                else:
                    ef.parfile = parfile

                if parfile and os.path.exists(ef.parfile):
                    events = deorbit_events(events, ef.parfile)

            phase, profile, profile_err = \
                fold_events(copy.deepcopy(events.time), f, fdot,
                            ref_time=events.gti[0, 0],
                            gtis=copy.deepcopy(events.gti),
                            expocorr=False, nbin=nbin)

            ax = plt.subplot(external_gs[0])

            ax.text(0.1, 0.9, "Profile for F0={} Hz, F1={} Hz/s".format(
                round(f, -np.int(np.floor(np.log10(np.abs(df))))),
                round(fdot, -np.int(np.floor(np.log10(np.abs(dfdot)))))),
                    horizontalalignment='left', verticalalignment = 'center',
                    transform = ax.transAxes)
            ax.plot(np.concatenate((phase, phase + 1)),
                    np.concatenate((profile, profile)), drawstyle='steps-mid')

            mean = np.mean(profile)

            low, high = \
                poisson_conf_interval(mean,
                                      interval='frequentist-confidence',
                                      sigma=1)

            ax.axhline(mean)
            ax.fill_between([0, 2], [low, low], [high, high],
                            label=r"1-$\sigma c.l.$", alpha=0.5)
            low, high = \
                poisson_conf_interval(mean,
                                      interval='frequentist-confidence',
                                      sigma=3)
            ax.fill_between([0, 2], [low, low], [high, high],
                            label=r"3-$\sigma c.l.$", alpha=0.5)
            ax.set_xlabel("Phase")
            ax.set_ylabel("Counts")
            ax.set_xlim([0, 2])
            ax.legend()
            phascommand = "HENphaseogram -f {} --fdot {} {}".format(f, fdot,
                                                                    ef.filename)
            if ef.parfile and os.path.exists(ef.parfile):
                phascommand += " --deorbit-par {}".format(parfile)

            print("To see the detailed phaseogram, "
                  "run {}".format(phascommand))

        elif not os.path.exists(ef.filename):
            warnings.warn(ef.filename + " does not exist")
            external_gs = gridspec.GridSpec(1, 1)
            search_gs_no = 0
        else:
            external_gs = gridspec.GridSpec(1, 1)
            search_gs_no = 0


        if len(ef.stat.shape) > 1 and ef.stat.shape[0] > 1:

            gs = gridspec.GridSpecFromSubplotSpec(
                2, 2, height_ratios=(1, 3), width_ratios=(3, 1),
                hspace=0, wspace=0, subplot_spec=external_gs[search_gs_no])

            axf = plt.subplot(gs[0, 0])
            axfdot = plt.subplot(gs[1, 1])
            if vmax is not None:
                axf.axhline(vmax, ls="--", label="99.9\% c.l.")
                axfdot.axvline(vmax)
            axffdot = plt.subplot(gs[1, 0], sharex=axf, sharey=axfdot)
            axffdot.pcolormesh(ef.freq, np.asarray(ef.fdots), ef.stat,
                               vmin=vmin, vmax=vmax)
            maximum_idx = 0
            maximum = 0
            for ix in range(ef.stat.shape[0]):
                axf.plot(ef.freq[ix, :], ef.stat[ix, :], alpha=0.5, lw=0.2,
                         color='k')
                if np.max(ef.stat[ix, :]) > maximum:
                    maximum = np.max(ef.stat[ix, :])
                    maximum_idx = ix
            if vmax is not None and maximum_idx > 0:
                axf.plot(ef.freq[maximum_idx, :], ef.stat[maximum_idx, :],
                         lw=1, color='k')
            maximum_idx = -1
            maximum = 0
            for iy in range(ef.stat.shape[1]):
                axfdot.plot(ef.stat[:, iy], np.asarray(ef.fdots)[:, iy],
                            alpha=0.5, lw=0.2, color='k')
                if np.max(ef.stat[:, iy]) > maximum:
                    maximum = np.max(ef.stat[:, iy])
                    maximum_idx = iy
            if vmax is not None and maximum_idx > 0:
                axfdot.plot(ef.stat[:, maximum_idx],
                            np.asarray(ef.fdots)[:, maximum_idx],
                            lw=1, color='k')
            axf.set_ylabel(r"Stat")
            axfdot.set_xlabel(r"Stat")

            # plt.colorbar()
            axffdot.set_xlabel('Frequency (Hz)')
            axffdot.set_ylabel('Fdot (Hz/s)')
            axffdot.set_xlim([np.min(ef.freq), np.max(ef.freq)])
            axffdot.set_ylim([np.min(ef.fdots), np.max(ef.fdots)])
            axf.legend()
        else:
            axf = plt.subplot(external_gs[search_gs_no])
            axf.plot(ef.freq, ef.stat, drawstyle='steps-mid', label=fname)
            axf.set_xlabel('Frequency (Hz)')
            axf.set_ylabel(ef.kind + ' stat')
            axf.legend()


        if hasattr(ef, 'best_fits') and ef.best_fits is not None and \
                not len(ef.stat.shape) > 1:

            for f in ef.best_fits:
                xs = np.linspace(np.min(ef.freq), np.max(ef.freq),
                                 len(ef.freq)*2)
                plt.plot(xs, f(xs))

        if output_data_file is not None:
            fdots = ef.fdots
            if not isinstance(fdots, collections.Iterable) or len(fdots) == 1:
                fdots = fdots + np.zeros_like(ef.freq.flatten())
            # print(fdots.shape, ef.freq.shape, ef.stat.shape)
            out = [ef.freq.flatten(), fdots.flatten(), ef.stat.flatten()]
            out_err = [None, None, None]

            if hasattr(ef, 'best_fits') and ef.best_fits is not None and \
                    not len(ef.stat.shape) > 1:
                for f in ef.best_fits:
                    out.append(f(ef.freq.flatten()))
                    out_err.append(None)

            save_as_qdp(out, out_err, filename=output_data_file, mode='a')

    ax = plt.gca()
    if xlog:
        ax.set_xscale('log', nonposx='clip')
    if ylog:
        ax.set_yscale('log', nonposy='clip')

    if figname is not None:
        plt.savefig(figname)