Ejemplo n.º 1
0
    def run_analysis(self, argv):
        """Run this analysis"""
        args = self._parser.parse_args(argv)

        if not HAVE_ST:
            raise RuntimeError(
                "Trying to run fermipy analysis, but don't have ST")

        if is_not_null(args.roi_baseline):
            gta = GTAnalysis.create(args.roi_baseline, args.config)
        else:
            gta = GTAnalysis(args.config,
                             logging={'verbosity': 3},
                             fileio={'workdir_regex': '\.xml$|\.npy$'})
        gta.print_roi()
        
        test_source = args.target
        gta.sed(test_source, outfile='sed_%s.fits' % 'FL8Y', make_plots=True)
        gta.extension(test_source, make_plots=True)
        return gta
Ejemplo n.º 2
0
def run_analysis(config):
    print('Running analysis...')

    gta = GTAnalysis(config)
    gta.setup()
    gta.optimize()

    gta.print_roi()

    # Localize and generate SED for first source in ROI
    srcname = gta.roi.sources[0].name

    gta.free_source(srcname)
    gta.fit()

    gta.localize(srcname)
    gta.sed(srcname)

    gta.write_roi('roi', make_plots=True)
    gta.tsmap(make_plots=True)
    gta.residmap(make_plots=True)
Ejemplo n.º 3
0
    fit_res = gta.optimize()
    fit_res = gta.fit()
    gta.write_roi('fit_testsrc')
    print '# Test source fitted successfully... #'
        if gta.roi[srcname]._data['ts']>25:
            print '# ...and we have a significant detection! (TS='+str(gta.roi[srcname]._data['ts'])+') Localizing... #'
            loc=gta.localize(srcname, update=True)
            if loc['fit_success']==True:
                print '# Localization succeeded! #'
                print '#Final optimization run...#'
                fit_res = gta.optimize()
                gta.write_roi('fit_detected_localized_optimized')
            else:
                print '# Localization failed! #'
                print '# Running SED...#'
                sed = gta.sed(srcname,make_plots=True)
        else:
            print '# ...but the source is not significantly detected (TS='+str(gta.roi[srcname]._data['ts'])+') #'
            print '# Writing source properties to outfile.dat #'
            outfile=open('outfile.dat','w')
            outfile.write('ROI data for source close to target:\n')
            outfile.write(str(gta.roi.sources[0]))
            outfile.write('\nROI center offset\t:\t'+str(gta.roi.sources[0]._data['offset'])+' degrees')
            if gta.roi[srcname]._data['ts']<25:
                outfile.write('\n95% confidence flux upper limit\t:\t'+str(gta.roi.sources[0]._data['flux_ul95'])+' ph/cm**2/s')
                outfile.write('\n95% confidence energy flux upper limit\t:\t'+str(1.6021766e-6*gta.roi.sources[0]._data['eflux_ul95'])+' erg/cm**2/s')
            else:
                outfile.write('\nEnergy flux in cgs units\t:\t'+str(1.6021766e-6*gta.roi.sources[0]._data['eflux'])+' +\- '+str(1.6021766e-6*gta.roi.sources[0]._data['eflux_err'])+' erg/cm**2/s')
            outfile.close()
            gta.write_roi('fit_final', make_plots = True)
else:
Ejemplo n.º 4
0
Archivo: run.py Proyecto: cdeil/fermipy
# Fix sources w/ significance < 10
gta.free_sources(cuts=('Detection_Significance',0,10),free=False)

# Free sources within 3 degrees of ROI center
gta.free_sources(distance=3.0)

# Free sources by name
gta.free_source('mkn421')
gta.free_source('galdiff')
gta.free_source('isodiff')

# Free only the normalization of a specific source
gta.free_norm('3FGL J1129.0+3705')

gta.fit()

# Compute the SED for a source
gta.sed('mkn421')

# Write the current state of the ROI model -- this will generate XML
# model files for each component as well as an output analysis
# dictionary in numpy and yaml formats
gta.write_roi('fit1')






Ejemplo n.º 5
0
gta = GTAnalysis(args.config)

gta.setup()

# Iteratively optimize all components in the ROI
gta.optimize()

# Fix sources w/ TS < 10
gta.free_sources(minmax_ts=[None, 10], free=False)

# Free sources within 3 degrees of ROI center
gta.free_sources(distance=3.0)

# Free sources by name
gta.free_source('mkn421')
gta.free_source('galdiff')
gta.free_source('isodiff')

# Free only the normalization of a specific source
gta.free_norm('3FGL J1129.0+3705')

gta.fit()

# Compute the SED for a source
gta.sed('mkn421')

# Write the current state of the ROI model -- this will generate XML
# model files for each component as well as an output analysis
# dictionary in numpy and yaml formats
gta.write_roi('fit1')
Ejemplo n.º 6
0
    def run_analysis(self, argv):
        """Run this analysis"""
        args = self._parser.parse_args(argv)

        if not HAVE_ST:
            raise RuntimeError(
                "Trying to run fermipy analysis, but don't have ST")

        if is_null(args.skydirs):
            skydir_dict = None
        else:
            skydir_dict = load_yaml(args.skydirs)

        gta = GTAnalysis(args.config,
                         logging={'verbosity': 3},
                         fileio={'workdir_regex': '\.xml$|\.npy$'})
        #gta.setup(overwrite=False)
        gta.load_roi(args.roi_baseline)
        gta.print_roi()

        basedir = os.path.dirname(args.config)
        # This should be a no-op, b/c it was done in the baseline analysis

        for profile in args.profiles:
            if skydir_dict is None:
                skydir_keys = [None]
            else:
                skydir_keys = sorted(skydir_dict.keys())

            for skydir_key in skydir_keys:
                if skydir_key is None:
                    pkey, psrc_name, pdict = build_profile_dict(basedir, profile)
                else:
                    skydir_val = skydir_dict[skydir_key]
                    pkey, psrc_name, pdict = build_profile_dict(basedir, profile)
                    pdict['ra'] = skydir_val['ra']
                    pdict['dec'] = skydir_val['dec']
                    pkey += "_%06i" % skydir_key

                outfile = "sed_%s.fits" % pkey

                # Add the source and get the list of correlated soruces
                correl_dict, test_src_name = add_source_get_correlated(gta, psrc_name, 
                                                                       pdict, correl_thresh=0.25, 
                                                                       non_null_src=args.non_null_src)

                # Write the list of correlated sources
                correl_yaml = os.path.join(basedir, "correl_%s.yaml" % pkey)
                write_yaml(correl_dict, correl_yaml)

                gta.free_sources(False)
                for src_name in correl_dict.keys():
                    gta.free_source(src_name, pars='norm')

                # build the SED
                if args.non_null_src:
                    gta.update_source(test_src_name, reoptimize=True)
                    gta.write_roi("base_%s"% pkey, make_plots=False)
                gta.sed(test_src_name, prefix=pkey, outfile=outfile, make_plots=args.make_plots)

                # remove the source
                gta.delete_source(test_src_name)
                # put the ROI back to how it was
                gta.load_xml(args.roi_baseline)

        return gta
Ejemplo n.º 7
0
def FGES_BinnedAnalysis(prefix, ANALYSISDIR, numsources, xmlsources, spectrum,
                        spectrumpoints, spectrumpointsUL, spectrum_mev_or_erg,
                        spectrum_mev_or_tev, configfile):

    ANALYSISDIR = ANALYSISDIR + prefix + '/'
    i = numsources  #number of sources
    sources_names = ''
    for x in range(0, i):
        sources_names += str(xmlsources[x])

    #Run the likelihood analysis up to doing the fit
    gta = GTAnalysis(ANALYSISDIR + configfile, logging={'verbosity': 3})
    gta.setup()

    #Print the pre likelihood fit parameters
    gta.print_roi()
    for x in range(0, i):
        print(gta.roi[xmlsources[x]])

    #Do an initial optimization of parameters
    gta.optimize()

    gta.print_roi()

    #Prepare to get the likelihood
    #Free the normalizations of sources within 7 degrees of the center of the field of view
    gta.free_sources(distance=7.0, pars='norm')
    gta.free_source('galdiff')
    gta.free_source('isodiff')
    for x in range(0, i):
        gta.free_source(xmlsources[x])

    #LIKELIHOOD ANALYSIS
    fit_results = gta.fit()

    #print out and return the results
    print('Fit Quality: ', fit_results['fit_quality'])
    for x in range(0, i):
        print(gta.roi[xmlsources[x]])
    gta.write_roi(sources_names + 'fit')

    #RESIDUAL MAP
    model = {'Index': 2.0, 'SpatialModel': 'PointSource'}
    maps = gta.residmap('residual', model=model, make_plots=True)

    # Generate residual map with source of interest removed from the model
    model_nosource = {'Index': 2.0, 'SpatialModel': 'PointSource'}
    maps_nosource = gta.residmap('residual_wsource',
                                 model=model_nosource,
                                 exclude=xmlsources,
                                 make_plots=True)

    #TS Map
    tsmap = gta.tsmap('tsmap',
                      model={
                          'SpatialModel': 'PointSource',
                          'Index': 2.0
                      },
                      exclude=xmlsources,
                      make_plots=True)
    tsmap_wSNR = gta.tsmap('tsmap_wSNR',
                           model={
                               'SpatialModel': 'PointSource',
                               'Index': 2.0
                           },
                           make_plots=True)

    #PLOT SEDs
    for x in range(0, i):
        c = np.load('10to500gev/' + sources_names + 'fit.npy').flat[0]
        sorted(c['sources'].keys())
        c['sources'][xmlsources[x]]['flux']
        print(c['sources'][xmlsources[x]]['param_names'][:4])
        print(c['sources'][xmlsources[x]]['param_values'][:4])
        c['sources'][xmlsources[x]]['ts']

        E = np.array(c['sources'][xmlsources[x]]['model_flux']['energies'])
        dnde = np.array(c['sources'][xmlsources[x]]['model_flux']['dnde'])
        dnde_hi = np.array(
            c['sources'][xmlsources[x]]['model_flux']['dnde_hi'])
        dnde_lo = np.array(
            c['sources'][xmlsources[x]]['model_flux']['dnde_lo'])

        if spectrum_mev_or_erg == "erg":
            suffix = 'erg'
            mult = 0.00000160218
        elif spectrum_mev_or_erg == "mev":
            suffix = 'MeV'
            mult = 1

        if spectrum_mev_or_tev == "mev":
            xaxis = 'MeV'
            denominator = 1
        elif spectrum_mev_or_tev == "tev":
            xaxis = 'TeV'
            denominator = 1000000

        if spectrum:
            plt.loglog(E, (E**2) * dnde, 'k--')
            plt.loglog(E, (E**2) * dnde_hi, 'k')
            plt.loglog(E, (E**2) * dnde_lo, 'k')
            plt.xlabel('E [MeV]')
            plt.ylabel(r'E$^2$ dN/dE [MeV cm$^{-2}$ s$^{-1}$]')
            plt.savefig('spectrum_' + xmlsources[x] + '.png')

        #GET SED POINTS
        if spectrumpoints:
            sed = gta.sed(xmlsources[x], make_plots=True)
            #sed = gta.sed(xmlsource,prefix=xmlsource + 'spectrum',loge_bins=)
            src = gta.roi[xmlsources[x]]
            #Plot without upper limits
            plt.loglog(E, (E**2) * dnde, 'k--')
            plt.loglog(E, (E**2) * dnde_hi, 'k')
            plt.loglog(E, (E**2) * dnde_lo, 'k')
            plt.errorbar(np.array(sed['e_ctr']),
                         sed['e2dnde'],
                         yerr=sed['e2dnde_err'],
                         fmt='o')
            plt.xlabel('E [MeV]')
            plt.ylabel(r'E$^{2}$ dN/dE [MeV cm$^{-2}$ s$^{-1}$]')
            #plt.show()
            plt.savefig('spectrumpoints_' + xmlsources[x] + '.png')
            #Plot with upper limits, last 5 points
            plt.loglog(E, (E**2) * dnde, 'k--')
            plt.loglog(E, (E**2) * dnde_hi, 'k')
            plt.loglog(E, (E**2) * dnde_lo, 'k')
            plt.errorbar(sed['e_ctr'][:-5],
                         sed['e2dnde'][:-5],
                         yerr=sed['e2dnde_err'][:-5],
                         fmt='o')
            plt.errorbar(np.array(sed['e_ctr'][-5:]),
                         sed['e2dnde_ul95'][-5:],
                         yerr=0.2 * sed['e2dnde_ul95'][-5:],
                         fmt='o',
                         uplims=True)
            plt.xlabel('E [MeV]')
            plt.ylabel(r'E$^{2}$ dN/dE [MeV cm$^{-2}$ s$^{-1}$]')
            plt.savefig('spectrumpointsUL_' + xmlsources[x] + '.png')
        plt.clf()
Ejemplo n.º 8
0
def main():

    usage = "usage: %(prog)s [config file]"
    description = "Run fermipy analysis chain."
    parser = argparse.ArgumentParser(usage=usage, description=description)

    parser.add_argument('--config', default='sample_config.yaml')
    parser.add_argument('--source', default=None)

    args = parser.parse_args()
    gta = GTAnalysis(args.config,
                     logging={'verbosity': 3},
                     fileio={'workdir_regex': '\.xml$|\.npy$'})

    model0 = {'SpatialModel': 'PointSource', 'Index': 1.5}
    model1 = {'SpatialModel': 'PointSource', 'Index': 2.0}
    model2 = {'SpatialModel': 'PointSource', 'Index': 2.7}

    src_name = gta.config['selection']['target']

    gta.setup(overwrite=True)
    gta.free_sources(False)
    gta.print_roi()
    gta.optimize()
    gta.print_roi()

    exclude = []

    # Localize all point sources
    for s in sorted(gta.roi.sources, key=lambda t: t['ts'], reverse=True):
        #    for s in gta.roi.sources:

        if not s['SpatialModel'] == 'PointSource':
            continue
        if s['offset_roi_edge'] > -0.1:
            continue

        if s.name in exclude:
            continue
        if not '3FGL' in s.name:
            continue
        if s.name == src_name:
            continue

        gta.localize(s.name,
                     nstep=5,
                     dtheta_max=0.5,
                     update=True,
                     prefix='base',
                     make_plots=True)

    gta.optimize()
    gta.print_roi()

    gta.write_roi('base_roi', make_plots=True)

    exclude = [src_name]
    if not 'carina_2' in exclude:
        exclude += ['carina_2']
    if not 'carina_3' in exclude:
        exclude += ['carina_3']

    gta.tsmap('base', model=model0, make_plots=True, exclude=exclude)
    gta.residmap('base', model=model0, make_plots=True, exclude=exclude)
    gta.tsmap('base', model=model1, make_plots=True, exclude=exclude)
    gta.residmap('base', model=model1, make_plots=True, exclude=exclude)
    gta.tsmap('base', model=model2, make_plots=True, exclude=exclude)
    gta.residmap('base', model=model2, make_plots=True, exclude=exclude)

    gta.find_sources(sqrt_ts_threshold=5.0)
    gta.optimize()
    gta.print_roi()
    gta.print_params()

    gta.free_sources(skydir=gta.roi.skydir, distance=1.0, pars='norm')
    gta.fit()
    gta.print_roi()
    gta.print_params()

    gta.write_roi('fit0_roi', make_plots=True)

    m = gta.tsmap('fit0', model=model0, make_plots=True, exclude=exclude)
    gta.plotter.make_tsmap_plots(m, gta.roi, zoom=2, suffix='tsmap_zoom')
    gta.residmap('fit0', model=model0, make_plots=True, exclude=exclude)
    gta.tsmap('fit0', model=model1, make_plots=True, exclude=exclude)
    gta.plotter.make_tsmap_plots(m, gta.roi, zoom=2, suffix='tsmap_zoom')
    gta.residmap('fit0', model=model1, make_plots=True, exclude=exclude)
    gta.tsmap('fit0', model=model2, make_plots=True, exclude=exclude)
    gta.plotter.make_tsmap_plots(m, gta.roi, zoom=2, suffix='tsmap_zoom')
    gta.residmap('fit0', model=model2, make_plots=True, exclude=exclude)

    gta.sed(src_name, prefix='fit0', make_plots=True, free_radius=1.0)

    gta.free_source(src_name)
    gta.fit(reoptimize=True)
    gta.print_roi()
    gta.print_params()

    gta.write_roi('fit1_roi', make_plots=True)
Ejemplo n.º 9
0
    def run_analysis(self, argv):
        """Run this analysis"""
        args = self._parser.parse_args(argv)

        if not HAVE_ST:
            raise RuntimeError(
                "Trying to run fermipy analysis, but don't have ST")

        if is_null(args.skydirs):
            skydir_dict = None
        else:
            skydir_dict = load_yaml(args.skydirs)

        gta = GTAnalysis(args.config,
                         logging={'verbosity': 3},
                         fileio={'workdir_regex': '\.xml$|\.npy$'})
        #gta.setup(overwrite=False)
        gta.load_roi(args.roi_baseline)
        gta.print_roi()

        basedir = os.path.dirname(args.config)
        # This should be a no-op, b/c it was done in the baseline analysis

        for profile in args.profiles:
            if skydir_dict is None:
                skydir_keys = [None]
            else:
                skydir_keys = sorted(skydir_dict.keys())

            for skydir_key in skydir_keys:
                if skydir_key is None:
                    pkey, pdict = AnalyzeSED._build_profile_dict(
                        basedir, profile)
                else:
                    skydir_val = skydir_dict[skydir_key]
                    pkey, pdict = AnalyzeSED._build_profile_dict(
                        basedir, profile)
                    pdict['ra'] = skydir_val['ra']
                    pdict['dec'] = skydir_val['dec']
                    pkey += "_%06i" % skydir_key

                outfile = "sed_%s.fits" % pkey

                # Add the source and get the list of correlated soruces
                correl_list = add_source_get_correlated(gta,
                                                        pkey,
                                                        pdict,
                                                        correl_thresh=0.25)

                gta.free_sources(False)
                for src_name in correl_list:
                    gta.free_source(src_name, pars='norm')

                # build the SED
                gta.sed(pkey, outfile=outfile, make_plots=args.make_plots)

                # remove the source
                gta.delete_source(pkey)
                # put the ROI back to how it was
                gta.load_xml(args.roi_baseline)

        return gta