gta = GTAnalysis(args.config, logging={"verbosity": 3})

    gta.setup()
    gta.simulate_roi(restore=True)

    ext_fit_data = []
    halo_fit_data = []

    gta.write_roi("base_model", save_model_map=False, make_plots=False)

    for i in range(1):

        gta.load_xml("base_model")

        gta.simulate_roi(randomize=False)

        gta.free_source("testsource")
        gta.update_source("testsource")
        #        gta.fit()
        gta.free_sources(free=False)

        gta.extension("testsource", width=np.logspace(-2.5, -0.5, 9))

        ext_fit_data += [copy.deepcopy(gta.roi["testsource"])]

        gta.write_roi("fit%04i" % i, save_model_map=False, make_plots=False, format="npy")

        fit_halo(gta, "fit%04i" % i, "testsource", halo_width, halo_index)

    np.save(os.path.join(gta._savedir, "ext_fit_data.npy"), ext_fit_data)
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$'})

    gta.setup()

    names = [s.name for s in gta.roi.sources if not s.diffuse]
    gta.reload_sources(names)
    
    sqrt_ts_threshold=3
    
    model0 = { 'SpatialModel' : 'PointSource', 'Index' : 1.5 }
    model1 = { 'SpatialModel' : 'PointSource', 'Index' : 2.0 }
    model2 = { 'SpatialModel' : 'PointSource', 'Index' : 2.5 }
    #src_name = gta.roi.sources[0].name
    if args.source is None:
        src_name = gta.config['selection']['target']
    else:
        src_name = args.source
        
    # -----------------------------------
    # Fit the Baseline Model
    # -----------------------------------

    # Get a reasonable starting point for the spectral model
    gta.free_source(src_name)
    gta.fit()
    gta.free_source(src_name,False)

    gta.optimize()
    
    # Localize 3FGL sources
    for s in gta.roi.sources:

        if not s['SpatialModel'] == 'PointSource':
            continue

        if s['offset'] < 0.5 or s['ts'] < 25.:
            continue

        if s['offset_roi_edge'] > -0.1:
            continue
        
        gta.localize(s.name,nstep=5,dtheta_max=0.5,update=True,
                     prefix='base')

        gta.free_source(s.name,False)

    gta.tsmap('base',model=model1)

    # Look for new point sources outside the inner 1.0 deg

    gta.find_sources('base',model=model1,
                     search_skydir=gta.roi.skydir,
                     max_iter=5,min_separation=0.5,
                     sqrt_ts_threshold=sqrt_ts_threshold,
                     search_minmax_radius=[1.0,None])
    gta.optimize()

    gta.print_roi()

    gta.write_roi('base')

    # -----------------------------------
    # Pass 0 - Source at Nominal Position
    # -----------------------------------

    fit_region(gta,'fit0',src_name)

    # -------------------------------------
    # Pass 1 - Source at Localized Position
    # -------------------------------------

    gta.localize(src_name,nstep=5,dtheta_max=0.5,update=True,
                 prefix='fit1')

    fit_region(gta,'fit1',src_name)
    fit_halo(gta,'fit1',src_name)
    gta.load_roi('fit1')

    # -------------------------------------
    # Pass 2 - 2+ Point Sources
    # -------------------------------------

    srcs = []

    # Fit up to 4 sources
    for i in range(2,6):

        srcs_fit = gta.find_sources('fit%i'%i,
                                    search_skydir=gta.roi.skydir,
                                    max_iter=1,
                                    sources_per_iter=1,
                                    sqrt_ts_threshold=3,
                                    min_separation=0.5,
                                    search_minmax_radius=[None,1.0])

        if len(srcs_fit['sources']) == 0:
            break

        srcs += srcs_fit['sources']
        best_fit_idx = i
        
        gta.localize(src_name,nstep=5,dtheta_max=0.4,
                     update=True,prefix='fit%i'%i)

        # Relocalize new sources
        for s in sorted(srcs, key=lambda t: t['ts'],reverse=True):        
            gta.localize(s.name,nstep=5,dtheta_max=0.4,
                         update=True,prefix='fit%i'%i)

        fit_region(gta,'fit%i'%i,src_name)
        fit_halo(gta,'fit%i'%i,src_name)

        gta.load_roi('fit%i'%i)
        
    new_source_data = []
    for s in srcs:
        src_data = gta.roi[s.name].data
        new_source_data.append(copy.deepcopy(src_data))

    np.save(os.path.join(gta.workdir,'new_source_data.npy'),
            new_source_data)
    ext_fit_data = []
    halo_fit_data = []

    gta.write_roi('base_model',save_model_map=False,make_plots=False)

    for i in range(10):

        gta.load_xml('base_model')

        gta.simulate_roi()

        gta.free_source('testsource')
        gta.free_source('galdiff',pars='norm')
        gta.free_source('isodiff',pars='norm')

        gta.fit()
        gta.update_source('testsource',reoptimize=True,npts=9)
        gta.free_sources(free=False)

        gta.extension('testsource',width=np.logspace(-2.5,-0.5,9))

        ext_fit_data += [copy.deepcopy(gta.roi['testsource'])]

        gta.write_roi('fit%04i'%i,save_model_map=False,make_plots=False,
                      format='npy')

        fit_halo(gta,'fit%04i'%i,'testsource',halo_width,halo_index)
        
    np.save(os.path.join(gta._savedir,'ext_fit_data.npy'),ext_fit_data)

    # -----------------------------------

    fit_region(gta,'fit0',src_name)
    #fit_region(gta,'fit0_emin40',src_name,erange=[4.0,5.5])

    gta.load_roi('fit0')

    # -------------------------------------
    # Pass 1 - Source at Localized Position
    # -------------------------------------

    gta.localize(src_name,nstep=5,dtheta_max=0.5,update=True,
                 prefix='fit1')

    fit_region(gta,'fit1',src_name)
    fit_halo(gta,'fit1',src_name,halo_width,halo_index)

    #fit_region(gta,'fit1_emin40',src_name,erange=[4.0,5.5])
    #fit_halo(gta,'fit1_emin40',src_name,halo_width,halo_index,erange=[4.0,5.5])

    gta.load_roi('fit1')

    # -------------------------------------
    # Pass 2 - 2+ Point Sources
    # -------------------------------------

    srcs = []
    best_fit_idx = 1

    # Fit up to 4 sources
    for i in range(2,5):
    gta.load_roi("fit0", reload_sources=True)

    # fit_region(gta,'fit0',src_name)
    fit_region(gta, "fit0_emin40", src_name, erange=[4.0, 5.5])

    # -------------------------------------
    # Pass 1 - Source at Localized Position
    # -------------------------------------

    gta.load_roi("fit1", reload_sources=True)

    # fit_region(gta,'fit1',src_name)
    # fit_halo(gta,'fit1',src_name,halo_width,halo_index)

    fit_region(gta, "fit1_emin40", src_name, erange=[4.0, 5.5])
    fit_halo(gta, "fit1_emin40", src_name, halo_width, halo_index, erange=[4.0, 5.5])

    # -------------------------------------
    # Pass 2 - 2+ Point Sources
    # -------------------------------------

    best_fit_idx = 1

    # Fit up to 4 sources
    for i in range(2, 5):

        roi_file = "fit%i.npy" % i

        if not os.path.isfile(os.path.join(gta.workdir, roi_file)):
            continue