コード例 #1
0
ファイル: imrefspec.py プロジェクト: bwgref/nuskybgd-py
def imrefspec(fpmlist, idetlist, auxil,
              cxbp={'pl': 1.29, 'ecut': 41.13, 'norm': 0.002353},
              texp=1.0e9):

    queue = []

    # Check for RMF files
    for idet in idetlist:
        idet = int(idet)
        if idet not in (0, 1, 2, 3):
            continue
        for ab in fpmlist:
            if ab not in ('A', 'B'):
                continue
            rmffile = 'det%d%s.rmf' % (idet, ab)
            if os.path.exists(rmffile):
                queue.append((idet, ab))
                print('Queued FPM%s det%d: %s' %
                      (ab, idet, rmffile))
            else:
                print('Skipped FPM%s det%d: %s not found.' %
                      (ab, idet, rmffile))

    if len(queue) == 0:
        print('Nothing to be done.')
        return True

    m = xspec.Model('cutoffpl')
    m.cutoffpl.PhoIndex = cxbp['pl']
    m.cutoffpl.HighECut = cxbp['ecut']
    m.cutoffpl.norm = cxbp['norm']

    for idet, ab in queue:
        # If there is existing spectrum loaded, RMF and ARF in FakeSettings
        # will be ignored (the 'from existing spectra' flow). We need to do
        # the 'from scratch' flow.
        xspec.AllData.clear()

        fakesettings_ap = xspec.FakeitSettings(
            response='det%d%s.rmf' % (idet, ab),
            arf='%s/be.arf' % auxil,
            exposure=texp,
            correction=0.0,
            fileName='aperbgd%s_det%d.pha' % (ab, idet)
        )
        fakesettings_fcxb = xspec.FakeitSettings(
            response='det%d%s.rmf' % (idet, ab),
            arf='%s/fcxb%s.arf' % (auxil, ab),
            exposure=texp,
            correction=0.0,
            fileName='fcxbbgd%s_det%d.pha' % (ab, idet)
        )
        xspec.AllData.fakeit(
            nSpectra=2,
            settings=[fakesettings_ap, fakesettings_fcxb],
            applyStats=False,
            filePrefix='')

    return True
コード例 #2
0
ファイル: fakeit.py プロジェクト: mcrnogor/LLE-ALPs
def fake_data(**kwargs):
    bkg = kwargs['bkg'] + "{1}"
    rsp = kwargs['rsp']

    xs.AllData.clear()
    xs.AllModels.clear()
    m = xs.Model('ALP')

    for i in range(len(N)):
        m.ALP.norm.values = N[i]
        m.ALP.norm.frozen = True
        xs.AllData.clear()
        fs = xs.FakeitSettings(background=bkg,
                               response=rsp,
                               fileName='fake_spec_%s.fak' % i)
        sl = 2000 * [fs]  # making 2000 simulations
        xs.AllData.fakeit(2000, sl)

    if kwargs['show']:
        import matplotlib.pyplot as plt
        xs.AllData.clear()
        for i in range(1, 2001):
            xs.AllData += "fake_spec_20.fak{%i}" % i
        xs.AllModels.clear()
        m = xs.Model("ALP")
        xs.Fit.statMethod = "pgstat"

        xs.Plot.device = "/xs"
        xs.Plot.xAxis = "MeV"
        xs.Plot.add = True
        xs.Plot.background = True
        xs.Plot.xLog = True
        xs.Plot.yLog = True
        xs.Plot.show()
        xs.Plot("ufspec")

        xerr_uf = np.zeros((2001, len(E_LLE)))
        yerr_uf = np.zeros((2001, len(E_LLE)))
        spec_uf = np.zeros((2001, len(E_LLE)))

        for i in range(1, 2001):
            xerr_uf[i, :] = np.asarray(xs.Plot.xErr(i))
            yerr_uf[i, :] = np.asarray(xs.Plot.yErr(i))
            spec_uf[i, :] = np.asarray(xs.Plot.y(i))
        for i in range(1, 2001):
            plt.errorbar(E_LLE,
                         spec_uf[i, :],
                         xerr=xerr_uf[i, :],
                         yerr=yerr_uf[i, :])
        plt.plot(E_LLE,
                 SED * N[20],
                 'r',
                 zorder=2001,
                 label='Theoretical spectrum')
        plt.xlabel('Energy, [MeV]')
        plt.ylabel('[photons cm$^{-2}$ s$^{-1}$ MeV$^{-1}$] ')
        plt.xscale('log')
        plt.grid()
        plt.legend()
        plt.show()
コード例 #3
0
ファイル: xspec_module.py プロジェクト: lavanyanemani96/clumo
def xspec_flux(x):

    Temperature, z_, ind_file, El_, Eh_, Z_ = x

    L_factor, norm, abundance = 1e44, 1.0, Z_
    E_norm = [El_, Eh_]

    xspec.Model("apec")
    m1 = xspec.AllModels(1)
    m1.setPars(Temperature, abundance, z_, norm)

    filename = mydirectory+"/parameter_files/xspec/" + str(ind_file) + ".fak"
    fs1 = xspec.FakeitSettings(response, ancillary, fileName = filename,  \
                                exposure = 100000.0)
    xspec.AllData.fakeit(1,fs1,applyStats=False, noWrite = True)

    spec1 = xspec.AllData(1)
    xspec.AllModels.setEnergies(".01 100. 1000 log")

    xspec.AllModels.calcLumin("%f %f %f" %(E_norm[0],E_norm[1],z_))
    L = spec1.lumin[0]
    xspec.AllModels.calcFlux("%f %f" %(E_norm[0],E_norm[1]))
    F = spec1.flux[0]

    new_norm = L_factor / (L * 1e44)
    m1.setPars({4:new_norm})

    xspec.AllModels.calcLumin("%f %f %f" %(E_norm[0],E_norm[1],z_))
    L_new = spec1.lumin[0]
    xspec.AllModels.calcFlux("%f %f" %(E_norm[0],E_norm[1]))
    F_new = spec1.flux[0]

    spec1.ignore("**-%f %f-**" %(E_norm[0],E_norm[1]))
    rate = spec1.rate[3]

    xspec.AllData.clear()

    return [F_new, rate]
コード例 #4
0
def test_OGIP_response_against_xspec():

    # Test for various photon indexes
    for index in [-0.5, 0.0, 0.5, 1.5, 2.0, 3.0, 4.0]:

        print("Processing index %s" % index)

        # First reset xspec
        xspec.AllData.clear()

        # Create a model in XSpec

        mo = xspec.Model("po")

        # Change the default value for the photon index
        # (remember that in XSpec the definition of the powerlaw is norm * E^(-PhoIndex),
        # so PhoIndex is positive normally. This is the opposite of astromodels.
        mo.powerlaw.PhoIndex = index
        mo.powerlaw.norm = 12.2

        # Now repeat the same in 3ML

        # Generate the astromodels function and set it to the same values as the XSpec power law
        # (the pivot in XSpec is set to 1). Remember also that the definition in xspec has the
        # sign of the photon index opposite
        powerlaw = Powerlaw()
        powerlaw.piv = 1.0
        powerlaw.index = -mo.powerlaw.PhoIndex.values[0]
        powerlaw.K = mo.powerlaw.norm.values[0]

        # Exploit the fact that the power law integral is analytic
        powerlaw_integral = Powerlaw()
        # Remove transformation
        powerlaw_integral.K._transformation = None
        powerlaw_integral.K.bounds = (None, None)
        powerlaw_integral.index = powerlaw.index.value + 1
        powerlaw_integral.K = old_div(powerlaw.K.value, (powerlaw.index.value + 1))

        powerlaw_integral.display()

        integral_function = lambda e1, e2: powerlaw_integral(e2) - powerlaw_integral(e1)

        # Now check that the two convoluted model give the same number of counts in each channel

        # Fake a spectrum so we can actually compute the convoluted model

        # Get path of response file
        rsp_file = str(get_path_of_data_file("ogip_test_gbm_n6.rsp"))

        fs1 = xspec.FakeitSettings(
            rsp_file, exposure=1.0, fileName="_fake_spectrum.pha"
        )

        xspec.AllData.fakeit(noWrite=True, applyStats=False, settings=fs1)

        # Get the expected counts
        xspec_counts = mo.folded(1)

        # Now get the convolution from 3ML
        rsp = OGIPResponse(rsp_file)

        rsp.set_function(integral_function)

        threeML_counts = rsp.convolve()

        # Compare them
        assert np.allclose(xspec_counts, threeML_counts)

        # Now do the same with a matrix with a ARF

        # First reset xspec
        xspec.AllData.clear()

        # Then load rsp and arf in XSpec

        rsp_file = str(get_path_of_data_file("ogip_test_xmm_pn.rmf"))

        arf_file = str(get_path_of_data_file("ogip_test_xmm_pn.arf"))

        fs1 = xspec.FakeitSettings(
            rsp_file, arf_file, exposure=1.0, fileName="_fake_spectrum.pha"
        )

        xspec.AllData.fakeit(noWrite=True, applyStats=False, settings=fs1)

        # Get the expected counts
        xspec_counts = mo.folded(1)

        # Now get the convolution from 3ML
        rsp = OGIPResponse(rsp_file, arf_file=arf_file)

        rsp.set_function(integral_function)

        threeML_counts = rsp.convolve()

        # Compare them
        assert np.allclose(xspec_counts, threeML_counts)
コード例 #5
0
def test_response_against_xspec():

    # Make a response and write to a FITS OGIP file
    matrix, mc_energies, ebounds = get_matrix_elements()

    rsp = InstrumentResponse(matrix, ebounds, mc_energies)

    temp_file = "__test.rsp"

    rsp.to_fits(temp_file, "TEST", "TEST", overwrite=True)

    # Test for various photon indexes

    for index in np.linspace(-2.0, 2.0, 10):

        if index == 1.0:

            # This would make the integral of the power law different, so let's just
            # skip it

            continue

        # First reset xspec
        xspec.AllData.clear()

        # Create a model in XSpec

        mo = xspec.Model("po")

        # Change the default value for the photon index
        # (remember that in XSpec the definition of the powerlaw is norm * E^(-PhoIndex),
        # so PhoIndex is positive normally. This is the opposite of astromodels.
        mo.powerlaw.PhoIndex = index
        mo.powerlaw.norm = 12.2

        # Now repeat the same in 3ML

        # Generate the astromodels function and set it to the same values as the XSpec power law
        # (the pivot in XSpec is set to 1). Remember also that the definition in xspec has the
        # sign of the photon index opposite
        powerlaw = Powerlaw()
        powerlaw.piv = 1.0
        powerlaw.index = -mo.powerlaw.PhoIndex.values[0]
        powerlaw.K = mo.powerlaw.norm.values[0]

        # Exploit the fact that the power law integral is analytic
        powerlaw_integral = Powerlaw()
        powerlaw_integral.K._transformation = None
        powerlaw_integral.K.bounds = (None, None)
        powerlaw_integral.index = powerlaw.index.value + 1
        powerlaw_integral.K = old_div(powerlaw.K.value, (powerlaw.index.value + 1))

        integral_function = lambda e1, e2: powerlaw_integral(e2) - powerlaw_integral(e1)

        # Now check that the two convoluted model give the same number of counts in each channel

        # Fake a spectrum so we can actually compute the convoluted model

        # Get path of response file

        fs1 = xspec.FakeitSettings(
            temp_file, exposure=1.0, fileName="_fake_spectrum.pha"
        )

        xspec.AllData.fakeit(noWrite=True, applyStats=False, settings=fs1)

        # Get the expected counts
        xspec_counts = mo.folded(1)

        # Now get the convolution from 3ML

        rsp.set_function(integral_function)

        threeML_counts = rsp.convolve()

        # Compare them
        assert np.allclose(xspec_counts, threeML_counts)

    os.remove(temp_file)
コード例 #6
0
assert model.flux[0] > 0

# clean up

xspec.AllData.clear()
xspec.AllModels.clear()
try:
    # this will fail as expected: model does not exist anymore
    model.flux
    assert False
except Exception:
    pass

# second version:

# try again with fakeit to include response

model = xspec.Model('powerlaw')
ero_settings = xspec.FakeitSettings(
    arf='arf01_100nmAl_200nmPI_sdtq.fits',
    response='rmf01_sdtq.fits',
    exposure=10000,
    background='bkg1000000.fak',
    fileName='test.fak',
)
xspec.AllData.fakeit(1, settings=[ero_settings])
xspec.AllModels.calcFlux("2.3 6.0")
print(model.flux)
# we expect a model count rate > 0 as before, but this fails
assert model.flux[0] > 0