Beispiel #1
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')
Beispiel #2
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 = 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()
def AeffPhiDepPlot(IRFs,
                   nph,
                   energy,
                   theta,
                   front=True,
                   back=False,
                   plot=True):
    #get phi points
    phis = [0 + i * (90. / (nph - 1.)) for i in range(nph)]
    #access available IRFs
    pyIrfLoader.Loader_go()
    if front and back:
        #get front and back IRFs, get effective area for phis for given energy and theta
        conv = 'FRONT + BACK'
        irfs_front = pyIrfLoader.IrfsFactory.instance().create(IRFs +
                                                               "::FRONT")
        irfs_back = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::BACK")
        Aeff_front = getAeff_phi(irfs_front.aeff(), energy, theta, phis)
        Aeff_back = getAeff_phi(irfs_back.aeff(), energy, theta, phis)
        Aeff = Aeff_front + Aeff_back
    else:
        #access the necessary IRFs, get effective area for phis for given energy and theta
        conv = ('FRONT' if front else "BACK")
        irfs = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::" + conv)
        Aeff = getAeff_phi(irfs.aeff(), energy, theta, phis)
    #expand the phi values out to 360 degrees, copy effective area values too
    phibins = array(phis + [p + 90.
                            for p in phis[1:]] + [p + 180. for p in phis[1:]] +
                    [p + 270. for p in phis[1:]])
    AeffValues = array([a for a in Aeff] + [a for a in Aeff[1:]] +
                       [a for a in Aeff[1:]] + [a for a in Aeff[1:]])
    #make and fill phi graph
    phigraph = TGraph(len(phibins), phibins, AeffValues)
    phigraph.SetMarkerStyle(20)
    phigraph.SetMarkerColor(1)
    phigraph.SetLineColor(1)
    if plot:
        #if plot set to True, draw and make some style choices
        phcan = TCanvas(
            'phcan',
            '%s %s Effective Area vs. phi for E = %.1f MeV and theta = %.1f deg'
            % (IRFs, conv, energy, theta), 1000, 800)
        phcan.SetTicks(1, 1)
        pdummy = TH1F('pdummy', '', 1000, 0, 360)
        pdummy.SetXTitle('#phi (#circ)')
        pdummy.GetXaxis().CenterTitle()
        pdummy.SetYTitle('A_{eff} (m^{2} )')
        pdummy.GetYaxis().CenterTitle()
        pdummy.GetYaxis().SetRangeUser(0., 1.)
        pdummy.Draw()
        phigraph.Draw('plsame')
        SetOwnership(phigraph, False)
        SetOwnership(phcan, False)
        SetOwnership(pdummy, False)
    return phigraph
Beispiel #4
0
    def createFromPyIRF(irf_name):
        """Create IRF object using pyIrf modules in Science Tools."""
        
        import pyIrfLoader
        if not IRFManager.load_irf:
            pyIrfLoader.Loader_go()
            IRFManager.load_irf = True

        irf_factory=pyIrfLoader.IrfsFactory.instance()
        irfs = irf_factory.create(irf_name)

        psf = PSFPyIRF(irfs.psf())
        aeff = AeffPyIRF(irfs.aeff())
        edisp = EDispPyIRF(irfs.edisp())

        return IRF(psf,aeff,edisp)
Beispiel #5
0
directions.

@author J. Chiang <*****@*****.**>

"""
# @file psf_tests.py
# $Header: /nfs/slac/g/glast/ground/cvs/ScienceTools-scons/irfs/pyIrfLoader/python/psf_tests.py,v 1.1.1.1 2006/10/24 19:42:15 jchiang Exp $
#
import os, sys, bisect
import numarray as num
import hippoplotter as plot
import pyIrfLoader as irf_loader
#from Interpolator import Interpolator
from ks import ks1, ks2

irf_loader.Loader_go()

SkyDir = irf_loader.SkyDir


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):
Beispiel #6
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function
import copy
from functools import wraps
import numpy as np
import pyLikelihood as pyLike
from SrcModel import SourceModel
from AnalysisBase import AnalysisBase
from LikelihoodState import LikelihoodState
import pyIrfLoader

pyIrfLoader.Loader_go()

_funcFactory = pyLike.SourceFactory_funcFactory()

import BinnedAnalysis as ba
import SummedLikelihood

from fermipy import utils
from fermipy import model_utils

evtype_string = {4: 'PSF0', 8: 'PSF1', 16: 'PSF2', 32: 'PSF3'}


def bitmask_to_bits(mask):

    bits = []
    for i in range(32):
        if mask & (2**i):
            bits += [2**i]
Beispiel #7
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
Beispiel #8
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
def EdispPlot(IRFs,
              perc,
              ptype,
              pmin,
              pmax,
              value,
              nbins,
              front=True,
              back=False,
              plot=True):
    #check ptype input value
    if ptype not in ['energy', 'theta']:
        print 'Error, ptype input must be either "energy" or "costheta".'
        return None
    #make bins accordingly
    if ptype == 'energy':
        bins = log10_array(nbins + 1, pmin, pmax)
        cents = [
            10**((log10(e) + log10(E)) / 2.)
            for e, E in zip(bins[:-1], bins[1:])
        ]
    else:
        bins = array([
            float(pmin + i * (pmax - pmin) / float(nbins))
            for i in range(nbins + 1)
        ])
        cents = [(c + C) / 2. for c, C in zip(bins[:-1], bins[1:])]
    #access the available IRFs
    pyIrfLoader.Loader_go()
    if front and back:
        #get front and back IRFs, get the energy resolution for both, then average them
        print "oops, can't do FRONT and BACK right now, sorry, try again"
        return None
        #conv='FRONT + BACK'
        #irfs_front=pyIrfLoader.IrfsFactory.instance().create(IRFs+"::FRONT")
        #irfs_back=pyIrfLoader.IrfsFactory.instance().create(IRFs+"::BACK")
        ##get for either one theta and range of energies or vice versa
        #if ptype=='energy':
        #res_front=[energyRes(irfs_front.edisp(),perc,e,value) for e in cents]
        #res_back=[energyRes(irfs_back.edisp(),perc,e,value) for e in cents]
        #res=[(f+b)/2. for f,b in zip(res_front,res_back)]
        #else:
        #res_front=[energyRes(irfs_front.edisp(),perc,value,th) for th in cents]
        #res_back=[energyRes(irfs_back.edisp(),perc,value,th) for th in cents]
        #res=[(f+b)/2. for f,b in zip(res_front,res_back)]
    else:
        #get the appropriate IRFs, get energy resolution based on ptype
        conv = ('FRONT' if front else "BACK")
        irfs = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::" + conv)
        if ptype == 'energy':
            res = [energyRes(irfs.edisp(), perc, e, value) for e in cents]
        else:
            res = [energyRes(irfs.edisp(), perc, value, th) for th in cents]
    #make histogram and fill
    edhist = TH1F('edhist', '', nbins, bins)
    for i, e in enumerate(res):
        edhist.SetBinContent(i + 1, e)
    #set axis titles and do other style stuff
    edhist.GetXaxis().CenterTitle()
    edhist.GetYaxis().CenterTitle()
    xtitle = ('Energy (MeV)' if ptype == 'energy' else '#theta (#circ)')
    ytitle = ('#frac{#Delta E}{E} (%.1f' % (perc * 100) + '%' +
              ' containtment for #theta = %.1f^{#circ} )' % value
              if ptype == 'energy' else '#frac{#Delta E}{E} (%.1f' %
              (perc * 100) + '%' + 'containment for E = %.1f MeV)' % value)
    edhist.SetYTitle(ytitle)
    edhist.SetLineColor(1)
    edhist.SetMarkerColor(1)
    edhist.SetMarkerStyle(20)
    if plot:
        can = TCanvas(
            'can', '%s %s %.1f' % (IRFs, conv, perc * 100) +
            '% Energy Resolution' + ' vs. %s' % ptype, 1000, 800)
        can.SetTicks(1, 1)
        if ptype == 'energy':
            can.SetLogx(1)
        edhist.Draw('pl')
        SetOwnership(can, False)
        SetOwnership(edhist, False)
    return edhist
def AeffPlot2D(IRFs,
               nebins=64,
               nctbins=32,
               emin=1.e2,
               emax=1.e5,
               ctmin=0.2,
               ctmax=1.0,
               front=True,
               back=False,
               plot=True,
               color=True):
    #should probably put some reasonability test on min and max values...
    ebins = log10_array(nebins + 1, emin, emax)
    #get the logarithmic midpoints for energy bins
    ecents = [
        10**((log10(e) + log10(E)) / 2.)
        for e, E in zip(ebins[:-1], ebins[1:])
    ]
    ctbins = [
        ctmin + i * (ctmax - ctmin) / nctbins for i in range(nctbins + 1)
    ]
    #get theta values in degrees of centers of cos(theta) bins
    thetas = [
        r2d * arccos((c + C) / 2.) for c, C in zip(ctbins[:-1], ctbins[1:])
    ]
    #get the available IRFs
    pyIrfLoader.Loader_go()
    if front and back:
        conv = 'FRONT + BACK'
        #get front and back IRFs
        irfs_front = pyIrfLoader.IrfsFactory.instance().create(IRFs +
                                                               "::FRONT")
        irfs_back = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::BACK")
        #get effective area for both sections and then add
        Aeff_front = getAeff_nophi(irfs_front.aeff(), ecents, thetas)
        Aeff_back = getAeff_nophi(irfs_back.aeff(), ecents, thetas)
        Aeff = Aeff_front + Aeff_back
    else:
        #get irfs for proper section and get effective area
        conv = ('FRONT' if front else 'BACK')
        irfs = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::" + conv)
        Aeff = getAeff_nophi(irfs.aeff(), ecents, thetas)
    #make and fill hist with some style options
    aehist = TH2F('aehist', '', nebins, array(ebins), nctbins, array(ctbins))
    for c in range(nctbins):
        for e in range(nebins):
            aehist.SetBinContent(e + 1, c + 1, Aeff[e][c])
    aehist.GetXaxis().CenterTitle()
    aehist.GetYaxis().CenterTitle()
    aehist.SetXTitle('Energy (MeV)')
    aehist.SetYTitle('cos(#theta)')
    aehist.SetContour(99)
    if plot:
        #if plotting, take care of some formatting issues
        if color:
            BPalette()
        else:
            GPalette()
        aeffcan = TCanvas('aeffcan', '%s %s Effective Area' % (IRFs, conv),
                          1000, 800)
        aeffcan.SetTicks(1, 1)
        aeffcan.SetLogx(1)
        aeffcan.SetFrameFillColor(1)
        aeffcan.SetFrameFillStyle(1001)
        aehist.GetXaxis().SetAxisColor(0)
        aehist.GetYaxis().SetAxisColor(0)
        aehist.Draw('cont4z')
        SetOwnership(aeffcan, False)
        SetOwnership(aehist, False)
    #return the 2D hist
    return aehist
def PSFPlot(IRFs,
            perc,
            ptype,
            pmin,
            pmax,
            value,
            nbins,
            perc2=None,
            front=True,
            back=False,
            plot=True):
    #check choice of ptype
    if ptype not in ['energy', 'theta']:
        print 'Error, ptype input must be either "energy" or "theta".'
        return None
    #make bins accordingly
    if ptype == 'energy':
        bins = log10_array(nbins + 1, pmin, pmax)
        cents = [
            10**((log10(e) + log10(E)) / 2.)
            for e, E in zip(bins[:-1], bins[1:])
        ]
    else:
        bins = [pmin + i * (pmax - pmin) / nctbins for i in range(nbins + 1)]
        cents = [(c + C) / 2. for c, C in zip(bins[:-1], bins[1:])]
    #access the available IRFs
    pyIrfLoader.Loader_go()
    if front and back:
        print "Calculating containment ratios for FRONT+BACK as the average"
        print "this is approximately correct near 685", "containment but underestimates for larger containment percentages"
        #get front and back IRFs
        conv = 'FRONT + BACK'
        irfs_front = pyIrfLoader.IrfsFactory.instance().create(IRFs +
                                                               "::FRONT")
        irfs_back = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::BACK")
        #get the front and back containment angles, either for one theta and range of energies or vice versa
        #then average the 2, makes the assumption that we'll have about the same number of events in both sections
        if ptype == 'energy':
            cont_front = [
                psfContAng(irfs_front.psf(), perc, e, value) for e in cents
            ]
            cont_back = [
                psfContAng(irfs_back.psf(), perc, e, value) for e in cents
            ]
            cont = array([(f + b) / 2. for f, b in zip(cont_front, cont_back)])
            #if we have a value for perc2, calculate those containment angles
            #average these values for front and back before calculating the ratio
            if perc2 != None:
                cont2_front = array([
                    psfContAng(irfs_front.psf(), perc2, e, value)
                    for e in cents
                ])
                cont2_back = array([
                    psfContAng(irfs_back.psf(), perc2, e, value) for e in cents
                ])
                cont2 = [(f + b) / 2. for f, b in zip(cont2_front, cont2_back)]
                cont = array([c / C for c, C in zip(cont2, cont)])
        else:
            cont_front = [
                psfContAng(irfs_front.psf(), perc, value, th) for th in cents
            ]
            cont_back = [
                psfContAng(irfs_back.psf(), perc, value, th) for th in cents
            ]
            cont = array([(f + b) / 2. for f, b in zip(cont_front, cont_back)])
            if perc2 != None:
                cont2_front = [
                    psfContAng(irfs_front.psf(), perc2, value, th)
                    for th in cents
                ]
                cont2_back = [
                    psfContAng(irfs_back.psf(), perc2, value, th)
                    for th in cents
                ]
                cont2 = [(f + b) / 2. for f, b in zip(cont2_front, cont2_back)]
                cont = array([c / C for c, C in zip(cont2, cont)])
    else:
        #get appropriate IRFs
        conv = ('FRONT' if front else "BACK")
        irfs = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::" + conv)
        #get containtment angles
        if ptype == 'energy':
            cont = array(
                [psfContAng(irfs.psf(), perc, e, value) for e in cents])
            if perc2 != None:
                #if we actually have a value for perc2, get second set of containment angles then calculate ratio
                cont2 = [
                    psfContAng(irfs.psf(), perc2, e, value) for e in cents
                ]
                cont = array([c / C for c, C in zip(cont2, cont)])
        else:
            cont = array(
                [psfContAng(irfs.psf(), perc, value, th) for th in cents])
            if perc2 != None:
                cont2 = [
                    psfContAng(irfs.psf(), perc2, value, th) for th in cents
                ]
                cont = array([c / C for c, C in zip(cont2, cont)])
    #make the histogram and fill
    psfhist = TH1F('psfhist', '', nbins, bins)
    for i, c in enumerate(cont):
        psfhist.SetBinContent(i + 1, c)
    #set axis titles and do other style stuff
    psfhist.GetXaxis().CenterTitle()
    psfhist.GetYaxis().CenterTitle()
    xtitle = ('Energy (MeV)' if ptype == 'energy' else '#theta (#circ)')
    psfhist.SetXTitle(xtitle)
    ytitle = ('%.1f' % (perc * 100) +
              '% Containment Angle (#circ)' if perc2 == None else '%.1f' %
              (perc2 * 100) + '%' + '/%.1f' % (perc * 100) + '%' +
              'Containment Angle Ratio')
    psfhist.SetYTitle(ytitle)
    psfhist.SetLineColor(1)
    psfhist.SetMarkerColor(1)
    psfhist.SetMarkerStyle(20)
    if plot:
        if perc2 == None:
            can = TCanvas(
                'can', '%s %s %.1f' % (IRFs, conv, perc * 100) +
                '% Containment Angle' + ' vs. %s' % ptype, 1000, 800)
            can.SetLogy(1)
        else:
            can = TCanvas(
                'can',
                '%s %s %.1f' % (IRFs, conv, perc2 * 100) + '%' + '/%.1f' %
                (perc * 100) + '% Containment Angle Ratio' + ' vs. %s' % ptype,
                1000, 800)
        can.SetTicks(1, 1)
        if ptype == 'energy':
            can.SetLogx(1)
        psfhist.Draw('pl')
        SetOwnership(can, False)
        SetOwnership(psfhist, False)
    return psfhist
def AeffPlot1D(IRFs,
               nbins,
               ptype,
               pmin,
               pmax,
               value,
               front=True,
               back=False,
               plot=True):
    #check pytpe input
    if ptype not in ['energy', 'theta']:
        print 'Error, ptype input must be either "energy" or "theta".'
        return None
    #bin accordingly depending on choice
    if ptype == 'energy':
        bins = log10_array(nbins + 1, pmin, pmax)
        cents = [
            10**((log10(e) + log10(E)) / 2.)
            for e, E in zip(bins[:-1], bins[1:])
        ]
    else:
        bins = [
            float(pmin + i * (pmax - pmin) / float(nbins))
            for i in range(nbins + 1)
        ]
        cents = [(c + C) / 2. for c, C in zip(bins[:-1], bins[1:])]
    #access the available IRFS
    pyIrfLoader.Loader_go()
    if front and back:
        #get FRONT and BACK IRFs
        conv = 'FRONT + BACK'
        irfs_front = pyIrfLoader.IrfsFactory.instance().create(IRFs +
                                                               "::FRONT")
        irfs_back = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::BACK")
        #get effective area in bins, either at one theta or at one energy
        if ptype == 'energy':
            Aeff_front = getAeff_nophi(irfs_front.aeff(), cents, [value])
            Aeff_back = getAeff_nophi(irfs_back.aeff(), cents, [value])
        else:
            Aeff_front = getAeff_nophi(irfs_front.aeff(), [value], cents)
            Aeff_back = getAeff_nophi(irfs_back.aeff(), [value], cents)
        #add effective areas
        Aeff = Aeff_front + Aeff_back
    else:
        #get appropriate IRFs
        conv = ('FRONT' if front else "BACK")
        irfs = pyIrfLoader.IrfsFactory.instance().create(IRFs + "::" + conv)
        #get effective area for either one theta or one energy
        if ptype == 'energy':
            Aeff = getAeff_nophi(irfs.aeff(), cents, [value])
        else:
            Aeff = getAeff_nophi(irfs.aeff(), [value], cents)
    #make histogram and fill
    aehist = TH1F('aehist', '', nbins, array(bins))
    for i, a in enumerate(Aeff):
        aehist.SetBinContent(i + 1, a)
    #set axis titles and do other style stuff
    aehist.GetXaxis().CenterTitle()
    aehist.GetYaxis().CenterTitle()
    xtitle = ('Energy (MeV)' if ptype == 'energy' else '#theta (#circ)')
    aehist.SetXTitle(xtitle)
    aehist.SetYTitle('A_{eff} (m^{2} )')
    aehist.SetLineColor(1)
    aehist.SetMarkerColor(1)
    aehist.SetMarkerStyle(20)
    if plot:
        can = TCanvas('can',
                      '%s %s Effective Area vs. %s' % (IRFs, conv, ptype),
                      1000, 800)
        can.SetTicks(1, 1)
        if ptype == 'energy':
            can.SetLogx(1)
        aehist.Draw('pl')
        SetOwnership(can, False)
        SetOwnership(aehist, False)
    return aehist