Esempio n. 1
0
    def get_point_sources(names, catalog):
        """ Input is a list of the name of 1FGL sources. What is
            return is a list of point source found from the names. """
        cat=FermiCatalog(catalog,free_radius=180) \
                if not isinstance(catalog,SourceCatalog) else catalog

        point_sources = []

        for name in names:

            index = np.where(cat.names == name)[0]
            if len(index) < 1:
                raise Exception("Cannot find source %s in the catalog %s" %
                                (name, catalog))
            if len(index) > 1:
                raise Exception(
                    "%s has too many counterpats in the catalog %s" %
                    (name, catalog))
            index = int(index)

            point_sources.append(
                PointSource(cat.dirs[index],
                            cat.names[index],
                            cat.models[index],
                            free_parameters=True))

        if len(names) == 1:
            return point_sources[0]

        return point_sources
Esempio n. 2
0
    def test_ps2(self):

        if PointlikeTest.VERBOSE:
            PointlikeTest.p('\nAnalyze a simulated point source\n')

        center = SkyDir(0, 0)

        model = PowerLawFlux(int_flux=1e-5, index=3, emin=1e2, emax=1e5)
        ps = PointSource(name='source', skydir=center, model=model)
        point_sources = [ps]
        diffuse_sources = None

        roi = PointlikeTest.get_roi('ps2',
                                    center,
                                    point_sources,
                                    diffuse_sources,
                                    emin=1e2,
                                    emax=1e5,
                                    binsperdec=4)
        global roi_pt
        roi_pt = roi  # helps with debugging

        if PointlikeTest.VERBOSE:
            print roi

        if PointlikeTest.VERBOSE:
            PointlikeTest.p('\nTesting if SED points are within errors\n')

        bf = roi.plot_sed(which='source', filename='sed.pdf', merge=False)

        elow = bf.rec.elow
        ehigh = bf.rec.ehigh
        e = np.sqrt(elow * ehigh)  # geometric mean

        flux = bf.rec.flux
        significant = bf.rec.flux > 0  # pointlike convention for upper limit
        uflux = bf.rec.uflux
        lflux = bf.rec.lflux
        true_flux = e**2 * model(e)
        pull = np.where(flux > true_flux, (flux - true_flux) / uflux,
                        (true_flux - flux) / lflux)

        self.assertTrue(
            np.all(pull[significant] < PointlikeTest.MAX_ALLOWED_PULL),
            'All SED points within errors of true value')
        if PointlikeTest.VERBOSE:
            PointlikeTest.p('\nPull for SED points is %s\n' %
                            pull[significant])

        # I am not sure this strictly has to always be true. Maybe there is a better test - J.L.
        self.assertTrue(np.all(uflux[~significant] > true_flux[~significant]),
                        'All SED upper limits must be above spectra')
Esempio n. 3
0
    def get_default_sources(self):

        point_sources, diffuse_sources = [], []

        model = PowerLaw(index=self.powerlaw_index,
                         e0=np.sqrt(self.emin * self.emax))
        model.set_flux(self.flux, emin=self.emin, emax=self.emax)
        ps = PointSource(name='source',
                         model=model.copy(),
                         skydir=self.roi_dir)
        point_sources.append(ps)

        if self.isotropic_bg:
            ds = get_sreekumar()
            diffuse_sources.append(ds)

        if self.nearby_source:
            ps = PointSource(name='nearby_source',
                             model=model.copy(),
                             skydir=SkyDir(self.roi_dir.ra(),
                                           self.roi_dir.dec() + 3))
            point_sources.append(ps)

        return point_sources, diffuse_sources
Esempio n. 4
0
    def test_ps1(self):

        if PointlikeTest.VERBOSE:
            print '\nAnalyze a simulated point source against the galactic + isotropic diffuse\n'

        center = SkyDir(0, 0)

        diffuse_sources = get_default_diffuse(
            diffdir='$GLAST_EXT/diffuseModels/v2r0p1/',
            gfile='ring_2year_P76_v0.fits',
            ifile='isotrop_2year_P76_source_v1.txt')

        model = PowerLaw(index=2)
        model.set_flux(1e-6)
        ps_mc = PointSource(name='source', skydir=center, model=model)
        ps_fit = ps_mc.copy()
        point_sources = [ps_fit]

        roi = PointlikeTest.get_roi('ps1', center, point_sources,
                                    diffuse_sources)
        global roi_pt
        roi_pt = roi  # helps with debugging

        if PointlikeTest.VERBOSE:
            print roi

        roi.fit(use_gradient=PointlikeTest.USE_GRADIENT)
        if PointlikeTest.VERBOSE: print roi
        roi.localize(update=True)
        roi.fit(use_gradient=PointlikeTest.USE_GRADIENT)
        if PointlikeTest.VERBOSE:
            roi.print_summary()
            print roi

        self.compare_model(ps_fit, ps_mc)
        self.compare_spatial_model(ps_fit, ps_mc, roi.lsigma)
Esempio n. 5
0
    def get_source(name,
                   position,
                   fit_emin,
                   fit_emax,
                   extended=False,
                   sigma=None):
        """ build a souce. """
        model = PowerLaw(index=2, e0=np.sqrt(fit_emin * fit_emax))
        PWNRegion.limit_powerlaw(model)
        flux = PowerLaw(norm=1e-11, index=2, e0=1e3).i_flux(fit_emin, fit_emax)
        model.set_flux(flux, emin=fit_emin, emax=fit_emax)

        if extended and sigma != 0:
            if not isnum(sigma): raise Exception("sigma must be set. " "")
            return ExtendedSource(name=name,
                                  model=model,
                                  spatial_model=Gaussian(sigma=sigma,
                                                         center=position))
        else:
            return PointSource(name=name, model=model, skydir=position)
Esempio n. 6
0
    def test_ff(self):
        """ Simulate from a filefunction object and test that the best
        fit flux
            is consistent with the simulated flux. """
        name = 'ff'

        model = PowerLaw(index=2)
        model.set_flux(1e-6)
        simdir = path.expand('$SIMDIR/%s' % name)
        if not os.path.exists(simdir):
            os.makedirs(simdir)

        filename = abspath(join(simdir, 'file_function.txt'))
        model.save_profile(filename, 10, 1e6)
        ff = FileFunction(file=filename)

        center = SkyDir(0, 0)
        ps = PointSource(name='source', skydir=center, model=ff)
        point_sources = [ps]
        diffuse_sources = None
        roi = PointlikeTest.get_roi(name,
                                    center,
                                    point_sources,
                                    diffuse_sources,
                                    emin=1e2,
                                    emax=1e5,
                                    binsperdec=4)

        if PointlikeTest.VERBOSE:
            roi.print_summary()
            print roi

        roi.fit(use_gradient=PointlikeTest.USE_GRADIENT)

        if PointlikeTest.VERBOSE:
            roi.print_summary()
            print roi

        fit, error = ff.i_flux(1e2, 1e5, error=True)
        true = model.i_flux(1e2, 1e5, error=False)
        self.assertPull(fit, true, error, 'flux')
Esempio n. 7
0
        type = args.type,
        mc = dict(
            extension=extension_mc,
            gal=[ skydir_mc.l(), skydir_mc.b() ],
            cel=[ skydir_mc.ra(), skydir_mc.dec() ],
            model=spectrum_to_dict(model_mc),
            flux=pointlike_model_to_flux(model_mc, emin, emax),
        )
    )

    tempdir = mkdtemp()

    point = 'point'
    ps = PointSource(
        name=point,
        model=model_mc.copy(),
        skydir = skydir_mc
    )

    extended = 'extended_%f' % extension_mc
    if extension_mc > 0:
        sm = Disk(sigma=extension_mc, center=skydir_mc)
        es = ExtendedSource(
            name=extended,
            model=model_mc,
            spatial_model=sm,
        )
        sim_es = es
    else:
        # If the source has no extension,
        # simulate the source as point-like
Esempio n. 8
0
def new_ps(
    roi,
    name,
    l,
    b,
    tsmap_kwargs=dict(size=10),
    fit_kwargs=dict(use_gradient=False),
    print_kwargs=dict(galactic=True, maxdist=15),
    localize=True,
    minuit_localizer=False,
):
    """ A 'throw away' convenience function to add a new source to
        the ROI, localize it, and then print out a string which can be
        used to modify an ROI to add a new source. """

    skydir = SkyDir(l, b, SkyDir.GALACTIC)

    roi.print_summary(**print_kwargs)

    emin, emax = roi.bin_edges[[0, -1]]

    model = PowerLaw(e0=np.sqrt(emin * emax))

    ps = PointSource(name=name, skydir=skydir, model=model)

    roi.add_source(ps)

    roi.print_summary(**print_kwargs)

    fit_prefactor(roi, name, **fit_kwargs)
    roi.fit(**fit_kwargs)

    roi.print_summary(**print_kwargs)

    if localize:
        if minuit_localizer:
            m = MinuitLocalizer(roi, which=name, fit_kwargs=fit_kwargs)
            m.localize()
        else:
            roi.localize(which=name, update=True)

    roi.fit(**fit_kwargs)

    roi.print_summary(**print_kwargs)

    print roi

    ts = roi.TS(which=name, quick=False, fit_kwargs=fit_kwargs)
    print 'TS for source %s is %.1f' % (name, ts)

    path = os.path.abspath(sys.argv[0])
    print """
Code to create point source:

    # Analysis came from %s
    ps=%s
    roi.add_source(ps)
""" % (path, pformat(ps))

    roi.save('roi.dat')

    roi.plot_tsmap(filename='residual_tsmap.pdf',
                   fitsfile='residual_tsmap.fits',
                   **tsmap_kwargs)
Esempio n. 9
0
    def build_roi(self, name, fast):


        if fast:
            roi_size=5
            binsperdec = 2
            max_free=2
            free_radius=2
        else:
            roi_size = 10
            binsperdec = 4
            max_free=5
            free_radius=5

        catalog = Catalog2FGL('$FERMI/catalogs/gll_psc_v05.fit', 
                              latextdir='$FERMI/extended_archives/gll_psc_v05_templates',
                              prune_radius=0,
                              max_free=max_free,
                              free_radius=free_radius,
                              limit_parameters=True)

        ft1 = self.radiopsr_loader.get_ft1(name)
        ft2 = self.radiopsr_loader.get_ft2(name)
        ltcube = self.radiopsr_loader.get_ltcube(name)
        binfile = self.radiopsr_loader.get_binfile(name, binsperdec)

        roi_dir = self.radiopsr_loader.get_skydir(name)

        ds = DataSpecification(
            ft1files = ft1,
            ft2files = ft2,
            ltcube   = ltcube,
            binfile  = binfile)

        sa = SpectralAnalysis(ds,
                              binsperdec = binsperdec,
                              emin       = 100,
                              emax       = 1000000,
                              irf        = "P7SOURCE_V6",
                              roi_dir    = roi_dir,
                              maxROI     = roi_size,
                              minROI     = roi_size,
                              event_class= 0)

        fit_emin = 1e2
        fit_emax = 10**5.5

        model=PowerLaw(index=2, e0=np.sqrt(fit_emin*fit_emax))
        model.set_limits('index',-5,5)

        ps = PointSource(name=name, model=model, skydir=roi_dir)
        point_sources = [ps]

        diffuse_sources = get_default_diffuse(diffdir="/afs/slac/g/glast/groups/diffuse/rings/2year",
                                   gfile="ring_2year_P76_v0.fits",
                                   ifile="isotrop_2year_P76_source_v0.txt",
                                   limit_parameters=True)

        roi=sa.roi(point_sources=point_sources,
                   diffuse_sources=diffuse_sources,
                   catalogs=catalog,
                   fit_emin=fit_emin, fit_emax=fit_emax)
        return roi