コード例 #1
0
ファイル: generator.py プロジェクト: calzonelover/LimbCRs
def main():
    phi_lats = [i * 45.0 for i in range(8)]
    theta_lats = [i for i in range(int(settings.THETA_LAT_CUTOFF) + 1)]
    energy_mid_bins = getEnergyMidBins()

    pyIrfLoader.Loader_go()
    myFactory = pyIrfLoader.IrfsFactory_instance()
    irfs_f = myFactory.create("%s::FRONT" % settings.IRF_NAME)
    irfs_b = myFactory.create("%s::BACK" % settings.IRF_NAME)
    aeff_f = irfs_f.aeff()
    aeff_b = irfs_b.aeff()
    for energy_mid_bin in energy_mid_bins:
        f_eff = open(
            os.path.join(PATH_SAVE_EFF,
                         "eff_E%d.csv" % (int(math.floor(energy_mid_bin)))),
            "w")
        f_eff.write("theta_lat,eff_m2\n")
        for theta_lat in theta_lats:
            for phi_lat in phi_lats:
                eff = []
                eff_front = aeff_f.value(GEV_TO_MEV * energy_mid_bin,
                                         theta_lat, phi_lat) / CM2_TO_M2
                eff_back = aeff_b.value(GEV_TO_MEV * energy_mid_bin, theta_lat,
                                        phi_lat) / CM2_TO_M2
                eff.append(eff_front + eff_back)
            mean_eff = sum(eff) / len(eff)
            f_eff.write("%f,%f\n" % (theta_lat, mean_eff))
        f_eff.close()
コード例 #2
0
ファイル: psf_tests.py プロジェクト: Areustle/fermi-glast
class Psf(object):
    _factory = irf_loader.IrfsFactory_instance()

    def __init__(self, irfsName, energy=100., inc=0, phi=0):
        self._irfs = self._factory.create(irfsName)
        self._psf = self._irfs.psf()
        self._energy = energy
        self._inc = inc
        self._phi = phi

    def __call__(self, separation):
        psf, energy, inc, phi = self._psf, self._energy, self._inc, self._phi
        try:
            y = []
            for x in separation:
                y.append(psf.value(x, energy, inc, phi))
            return num.array(y)
        except TypeError:
            return psf.value(separation, energy, inc, phi)

    def app_dir(self):
        x = self._psf.app_dir(self._energy, self._inc)
        return x.first, x.second

    def __getattr__(self, attrname):
        return getattr(self._psf, attrname)
コード例 #3
0
class irf(object):
    _factory = pyIrfLoader.IrfsFactory_instance()

    def __init__(self, irfsName, inc=0, phi=0):
        self._irfs = self._factory.create(irfsName)
        self._inc = inc
        self._phi = phi
コード例 #4
0
def main():
    phi_lats = [i * 45.0 for i in range(8)]
    theta_lats = [i for i in range(int(settings.THETA_LAT_CUTOFF) + 1)]
    energy_mid_bins = np.logspace(
        -2, 4, 100, base=10.0)  # getEnergyMidBins(1e-2, 1e4, 100)
    print(energy_mid_bins)

    pyIrfLoader.Loader_go()
    myFactory = pyIrfLoader.IrfsFactory_instance()
    irfs_f = myFactory.create("%s::FRONT" % settings.IRF_NAME)
    irfs_b = myFactory.create("%s::BACK" % settings.IRF_NAME)
    aeff_f = irfs_f.aeff()
    aeff_b = irfs_b.aeff()
    for energy_mid_bin in energy_mid_bins:
        eff_front = aeff_f.value(GEV_TO_MEV * energy_mid_bin, FIX_THETA_LAT,
                                 FIX_PHI_LAT) / CM2_TO_M2
        eff_back = aeff_b.value(GEV_TO_MEV * energy_mid_bin, FIX_THETA_LAT,
                                FIX_PHI_LAT) / CM2_TO_M2
        eff = eff_front + eff_back
        LOG_EFF_FRONT.append(eff_front)
        LOG_EFF_BACK.append(eff_back)
        LOG_EFF.append(eff)
    # visualize
    plt.plot(energy_mid_bins, LOG_EFF_FRONT, 'ro-', label="FRONT")
    plt.plot(energy_mid_bins, LOG_EFF_BACK, 'bo-', label="BACK")
    plt.plot(energy_mid_bins, LOG_EFF, 'ko-', label="TOTAL")
    plt.legend()
    plt.title('%s eff area (THETA_LAT %d deg, PHI_LAT %d deg)' %
              (settings.IRF_NAME, FIX_THETA_LAT, FIX_PHI_LAT))
    plt.xlabel('E (GeV)')
    plt.xscale('log')
    plt.ylabel('Effective area ($m^2$)')
    plt.savefig('eff_energy_dist.png')
コード例 #5
0
def comp_exposure_phi_new(gta, energy=None, nevt_max=None):
    """
    Compute the approximate exposure 
    trying to speed things up on 09/21/2020

    Parameters
    ----------
    gta: `~fermipy.GTAnalysis`
        The analysis object

    {options}

    energy: float or None
        The energy at which the exposure is evaluated.
        If none, central energy from selection is used
    """
    from tqdm import tqdm

    # load the effective areas
    irf_loader.Loader_go()
    irfs = gta.config['gtlike']['irfs']
    factory = irf_loader.IrfsFactory_instance()
    fronta = factory.create(irfs + "::FRONT")
    backa = factory.create(irfs + "::BACK")
    aeff_fa = fronta.aeff()
    aeff_ba = backa.aeff()

    if type(energy) == type(None):
        energy = float(np.sqrt(gta.config['selection']['emin'] * \
                            gta.config['selection']['emax']))

    # load the FT1 and FT2 files
    ft1fits = fits.open(gta.config['data']['evfile'])
    ft2fits = fits.open(gta.config['data']['scfile'])
    TSTART = float(ft1fits['EVENTS'].header["TSTART"]) - 30.
    TSTOP = float(ft1fits['EVENTS'].header["TSTOP"]) + 30.
    nevt = int(ft2fits['SC_DATA'].header['NAXIS2']) if nevt_max is None else nevt_max
    src = gta.roi[gta.config['selection']['target']]
    c0 = SkyCoord(ra = src.radec[0],dec =  src.radec[1], unit = 'deg')

    # the GTIs from the FT1 file
    ft1_gti_start = ft1fits['GTI'].data.field('START')
    ft1_gti_stop = ft1fits['GTI'].data.field('STOP')

    # central times of GTI in SC file
    tcen = 0.5 * (ft2fits['SC_DATA'].data.field("START") + \
                    ft2fits['SC_DATA'].data.field("STOP"))
    mask = (tcen > TSTART) & (tcen < TSTOP)

    # Spacecraft coordinates
    cz = SkyCoord(ra = ft2fits['SC_DATA'].data.field('RA_SCZ'),
                    dec = ft2fits['SC_DATA'].data.field('DEC_SCZ'),
                    unit = 'deg')
    cx = SkyCoord(ra = ft2fits['SC_DATA'].data.field('RA_SCX'),
                    dec = ft2fits['SC_DATA'].data.field('DEC_SCX'),
                    unit = 'deg')
    czen = SkyCoord(ra = ft2fits['SC_DATA'].data.field('RA_ZENITH'),
                    dec = ft2fits['SC_DATA'].data.field('DEC_ZENITH'),
                    unit = 'deg')

    sep_z0 = c0.separation(cz)
    sep_zenith0 = c0.separation(czen)

    id = np.cos(np.radians(sep_z0))

    # compute phi direction to src in SC coordinates
    phi = get_phi(cz = cz, cx = cx, c0 = c0)

    # livetime
    livetime = ft2fits['SC_DATA'].data.field('LIVETIME')
    
    # loop over GTIs in SC file
    af, ab = np.zeros(nevt), np.zeros(nevt)
    logging.info("Calculating exposure for E = {0:.2f} MeV".format(energy))

    mask = mask & (sep_zenith0.value <= gta.config['selection']['zmax'])
    t1 = time.time()
    for i in tqdm(range(nevt)):
        if not mask[i]: continue

        #igti = 0

        # find the right GTI for the considered SC GTI 
        #while igti < ft1_gti_start.size and ft1_gti_start[igti] < tcen[i]:
            #igti += 1
            #if igti >= ft1_gti_start.size: 
                #break
        m1 = tcen[i] >= ft1_gti_start
        m2 = tcen[i] < ft1_gti_stop
        if not (m1 & m2).sum():
            continue

#        if tcen[i] > ft1_gti_start[igti - 1] and tcen[i] < ft1_gti_stop[igti - 1]:
#            af[i] = aeff_fa.value(energy,
#                            float(sep_z0[i].value),
#                            float(phi[i])) *livetime[i]
#            ab[i] = aeff_ba.value(energy,
#                            float(sep_z0[i].value),
#                            float(phi[i])) *livetime[i]
        af[i] = aeff_fa.value(energy,
                        float(sep_z0[i].value),
                        float(phi[i])) *livetime[i]
        ab[i] = aeff_ba.value(energy,
                        float(sep_z0[i].value),
                        float(phi[i])) *livetime[i]

    print ("it took {0:.2f}s".format(time.time() - t1))
    logging.info("Done")
    return tcen,af,ab
コード例 #6
0
def comp_exposure_phi_v2(gta, energy = None):
    """
    Compute the approximate exposure 

    Parameters
    ----------
    gta: `~fermipy.GTAnalysis`
        The analysis object

    {options}

    energy: float or None
        The energy at which the exposure is evaluated.
        If none, central energy from selection is used
    """

    # load the effective areas
    irf_loader.Loader_go()
    irfs = gta.config['gtlike']['irfs']
    factory = irf_loader.IrfsFactory_instance()
    fronta = factory.create(irfs + "::FRONT")
    backa = factory.create(irfs + "::BACK")
    aeff_fa = fronta.aeff()
    aeff_ba = backa.aeff()

    if type(energy) == type(None):
        energy = float(np.sqrt(gta.config['selection']['emin'] * \
                            gta.config['selection']['emax']))

    # load the FT1 and FT2 files
    ft1fits = fits.open(gta.config['data']['evfile'])
    ft2fits = fits.open(gta.config['data']['scfile'])
    TSTART = float(ft1fits['EVENTS'].header["TSTART"]) - 30.
    TSTOP = float(ft1fits['EVENTS'].header["TSTOP"]) + 30.
    nevt = int(ft2fits['SC_DATA'].header['NAXIS2'])
    src = gta.roi[gta.config['selection']['target']]
    c0 = SkyCoord(ra = src.radec[0],dec =  src.radec[1], unit = 'deg')

    # the GTIs from the FT1 file
    ft1_gti_start = ft1fits['GTI'].data.field('START')
    ft1_gti_stop = ft1fits['GTI'].data.field('STOP')

    # central times of GTI in SC file
    tcen = 0.5 * (ft2fits['SC_DATA'].data.field("START") + \
                    ft2fits['SC_DATA'].data.field("STOP"))
    mask = (tcen > TSTART) & (tcen < TSTOP)

    # Spacecraft coordinates
    cz = SkyCoord(ra = ft2fits['SC_DATA'].data.field('RA_SCZ'),
                    dec = ft2fits['SC_DATA'].data.field('DEC_SCZ'),
                    unit = 'deg')
    cx = SkyCoord(ra = ft2fits['SC_DATA'].data.field('RA_SCX'),
                    dec = ft2fits['SC_DATA'].data.field('DEC_SCX'),
                    unit = 'deg')
    czen = SkyCoord(ra = ft2fits['SC_DATA'].data.field('RA_ZENITH'),
                    dec = ft2fits['SC_DATA'].data.field('DEC_ZENITH'),
                    unit = 'deg')

    sep_z0 = c0.separation(cz)
    sep_zenith0 = c0.separation(czen)

    id = np.cos(np.radians(sep_z0))

    # compute phi direction to src in SC coordinates
    phi = get_phi(cz = cz, cx = cx, c0 = c0)

    # livetime
    livetime = ft2fits['SC_DATA'].data.field('LIVETIME')
    
    # loop over GTIs in SC file
    af, ab = np.zeros(nevt), np.zeros(nevt)
    logging.info("Calculating exposure for E = {0:.2f} MeV".format(energy))

    mask = mask & (sep_zenith0.value <= gta.config['selection']['zmax'])

    ft1_gti_bins = np.array([ft1_gti_start, ft1_gti_stop])

    igti = np.digitize(tcen, ft1_gti_start)

    # make 1d array with start0,stop0,start1,stop0,...
    ft1_gti_bins = ft1_gti_bins.T.reshape(-1)
    # check for all times of GTI file in which bin they are. 
    # if even, then inside a GTI if odd then outside 

    #igti = np.digitize(tcen, ft1_gti_bins)
    #mask = (igti > 0) & (igti < len(ft1_gti_bins)) & \
            #mask & np.invert((igti - 1 % 2).astype(np.bool))

    t1 = time.time()
    for i in range(nevt):
        if not mask[i]: continue

        if tcen[i] > ft1_gti_start[igti[i] - 1] and tcen[i] < ft1_gti_stop[igti[i] - 1]:
            af[i] = aeff_fa.value(energy,
                            float(sep_z0[i].value),
                            float(phi[i])) *livetime[i]
            ab[i] = aeff_ba.value(energy,
                            float(sep_z0[i].value),
                            float(phi[i])) *livetime[i]

    print ("it took {0:.2f}s".format(time.time() - t1))
    logging.info("Done")
    return tcen,af,ab
コード例 #7
0
        pylab.semilogy(x, y, marker, markersize=3, linewidth=linewidth)
    else:
        pylab.plot(x, y, marker, markersize=3, linewidth=linewidth)
    if not oplot:
        pylab.xlabel(xname)
        pylab.ylabel(yname)
    setAxis(xrange, yrange)
    return win


logspace = lambda xmin, xmax, nx: num.logspace(num.log10(xmin), num.log10(
    xmax), nx)

pyIrfLoader.Loader_go()

factory = pyIrfLoader.IrfsFactory_instance()

irfName = "P7SOURCE_V6MC"

front = factory.create(irfName + "::FRONT")
back = factory.create(irfName + "::BACK")

psf_f = front.psf()
psf_b = back.psf()

radii = logspace(1e-2, 30., 30)


@FunctionWrapper
def theta_68(energy, psf=None, inc=0, phi=0, frac=0.68):
    f = FunctionWrapper(lambda x: psf.angularIntegral(energy, inc, phi, x))