Beispiel #1
0
def test_simulate_bkgnd_spectrum():
    tmpdir = tempfile.mkdtemp()
    curdir = os.getcwd()
    os.chdir(tmpdir)

    prng = RandomState(29)

    hdxi_arf = AuxiliaryResponseFile("xrs_hdxi_3x10.arf")
    hdxi_rmf = RedistributionMatrixFile("xrs_hdxi.rmf")

    exp_time = 50000.0
    fov = 3600.0
    simulate_spectrum(None, "hdxi", exp_time, "test_bkgnd.pha",
                      instr_bkgnd=True, foreground=True, prng=prng,
                      overwrite=True, bkgnd_area=(fov, "arcsec**2"))
    ch_min = hdxi_rmf.e_to_ch(0.7)-hdxi_rmf.cmin
    ch_max = hdxi_rmf.e_to_ch(2.0)-hdxi_rmf.cmin
    f = pyfits.open("test_bkgnd.pha")
    ncts = f["SPECTRUM"].data["COUNTS"][ch_min:ch_max].sum()
    f.close()
    S = ncts/exp_time/fov
    dS = np.sqrt(ncts)/exp_time/fov
    foreground = ConvolvedBackgroundSpectrum(hm_astro_bkgnd, hdxi_arf)
    f_sum = foreground.get_flux_in_band(0.7, 2.0)[0]
    i_sum = acisi_particle_bkgnd.get_flux_in_band(0.7, 2.0)[0]
    b_sum = (f_sum+i_sum).to("ph/(arcsec**2*s)").value
    assert np.abs(S-b_sum) < 1.645*dS

    os.chdir(curdir)
    shutil.rmtree(tmpdir)
Beispiel #2
0
def test_uniform_bkgnd_scale():
    hdxi_arf = AuxiliaryResponseFile("xrs_hdxi_3x10.arf")
    events, event_params = make_background((50, "ks"), "hdxi", [30., 45.], 
                                           foreground=True, instr_bkgnd=True,
                                           ptsrc_bkgnd=False, prng=prng)
    ncts = np.logical_and(events["energy"] >= 0.7, events["energy"] <= 2.0).sum()
    t_exp = event_params["exposure_time"]
    fov = (event_params["fov"]*60.0)**2
    S = ncts/t_exp/fov
    dS = np.sqrt(ncts)/t_exp/fov
    foreground = ConvolvedBackgroundSpectrum(hm_astro_bkgnd, hdxi_arf)
    f_sum = foreground.get_flux_in_band(0.7, 2.0)[0]
    i_sum = acisi_particle_bkgnd.get_flux_in_band(0.7, 2.0)[0]
    b_sum = (f_sum+i_sum).to("ph/(arcsec**2*s)").value
    assert np.abs(S-b_sum) < 1.645*dS
Beispiel #3
0
def test_simulate_bkgnd_spectrum():
    tmpdir = tempfile.mkdtemp()
    curdir = os.getcwd()
    os.chdir(tmpdir)

    prng = RandomState(29)

    hdxi_arf = AuxiliaryResponseFile("xrs_hdxi_3x10.arf")
    hdxi_rmf = RedistributionMatrixFile("xrs_hdxi.rmf")

    exp_time = 50000.0
    fov = 3600.0
    simulate_spectrum(None, "lynx_hdxi", exp_time, "test_bkgnd.pha",
                      instr_bkgnd=True, foreground=True, prng=prng,
                      overwrite=True, bkgnd_area=(fov, "arcsec**2"))
    ch_min = hdxi_rmf.eb_to_ch(0.7)-hdxi_rmf.cmin
    ch_max = hdxi_rmf.eb_to_ch(2.0)-hdxi_rmf.cmin
    with pyfits.open("test_bkgnd.pha") as f:
        ncts = f["SPECTRUM"].data["COUNTS"][ch_min:ch_max].sum()
    S = ncts/exp_time/fov
    dS = np.sqrt(ncts)/exp_time/fov
    foreground = ConvolvedBackgroundSpectrum.convolve(hm_astro_bkgnd, hdxi_arf)
    f_sum = foreground.get_flux_in_band(0.7, 2.0)[0]
    i_sum = acisi_particle_bkgnd.get_flux_in_band(0.7, 2.0)[0]*(u.cm/u.arcmin)**2
    b_sum = (f_sum+i_sum).to_value("ph/(arcsec**2*s)")
    assert np.abs(S-b_sum) < 1.645*dS

    os.chdir(curdir)
    shutil.rmtree(tmpdir)
Beispiel #4
0
def make_foreground(event_params, arf, rmf, prng=None):
    import pyregion._region_filter as rfilter

    prng = parse_prng(prng)

    conv_frgnd_spec = ConvolvedBackgroundSpectrum(hm_astro_bkgnd, arf)

    energy = conv_frgnd_spec.generate_energies(event_params["exposure_time"],
                                               event_params["fov"], prng=prng, 
                                               quiet=True).value

    prng = parse_prng(prng)

    bkg_events = {}

    n_events = energy.size

    nx = event_params["num_pixels"]
    bkg_events["detx"] = prng.uniform(low=-0.5*nx, high=0.5*nx, size=n_events)
    bkg_events["dety"] = prng.uniform(low=-0.5*nx, high=0.5*nx, size=n_events)
    bkg_events["energy"] = energy

    if event_params["chips"] is None:
        bkg_events["chip_id"] = np.zeros(n_events, dtype='int')
    else:
        bkg_events["chip_id"] = -np.ones(n_events, dtype='int')
        for i, chip in enumerate(event_params["chips"]):
            thisc = np.ones(n_events, dtype='bool')
            rtype = chip[0]
            args = chip[1:]
            r = getattr(rfilter, rtype)(*args)
            inside = r.inside(bkg_events["detx"], bkg_events["dety"])
            thisc = np.logical_and(thisc, inside)
            bkg_events["chip_id"][thisc] = i

    keep = bkg_events["chip_id"] > -1

    if keep.sum() == 0:
        raise RuntimeError("No astrophysical foreground events were detected!!!")
    else:
        mylog.info("Making %d events from the astrophysical foreground." % keep.sum())

    for key in bkg_events:
        bkg_events[key] = bkg_events[key][keep]

    return make_diffuse_background(bkg_events, event_params, rmf, prng=prng)
Beispiel #5
0
def make_foreground(event_params, arf, rmf, prng=None):
    import pyregion._region_filter as rfilter

    prng = parse_prng(prng)

    conv_frgnd_spec = ConvolvedBackgroundSpectrum(hm_astro_bkgnd, arf)

    energy = conv_frgnd_spec.generate_energies(event_params["exposure_time"],
                                               event_params["fov"], prng=prng, 
                                               quiet=True).value

    prng = parse_prng(prng)

    bkg_events = {}

    n_events = energy.size

    nx = event_params["num_pixels"]
    bkg_events["detx"] = prng.uniform(low=-0.5*nx, high=0.5*nx, size=n_events)
    bkg_events["dety"] = prng.uniform(low=-0.5*nx, high=0.5*nx, size=n_events)
    bkg_events["energy"] = energy

    if event_params["chips"] is None:
        bkg_events["chip_id"] = np.zeros(n_events, dtype='int')
    else:
        bkg_events["chip_id"] = -np.ones(n_events, dtype='int')
        for i, chip in enumerate(event_params["chips"]):
            thisc = np.ones(n_events, dtype='bool')
            rtype = chip[0]
            args = chip[1:]
            r = getattr(rfilter, rtype)(*args)
            inside = r.inside(bkg_events["detx"], bkg_events["dety"])
            thisc = np.logical_and(thisc, inside)
            bkg_events["chip_id"][thisc] = i

    keep = bkg_events["chip_id"] > -1

    if keep.sum() == 0:
        raise RuntimeError("No astrophysical foreground events were detected!!!")
    else:
        mylog.info("Making %d events from the astrophysical foreground." % keep.sum())

    for key in bkg_events:
        bkg_events[key] = bkg_events[key][keep]

    return make_diffuse_background(bkg_events, event_params, rmf, prng=prng)
Beispiel #6
0
def make_foreground(event_params, arf, rmf, prng=None):
    prng = parse_prng(prng)

    conv_bkgnd_spec = ConvolvedBackgroundSpectrum(hm_astro_bkgnd, arf)

    energy = conv_bkgnd_spec.generate_energies(event_params["exposure_time"],
                                               event_params["fov"],
                                               prng=prng,
                                               quiet=True).value

    if energy.size == 0:
        raise RuntimeError(
            "No astrophysical foreground events were detected!!!")
    else:
        mylog.info("Making %d events from the astrophysical foreground." %
                   energy.size)

    return make_uniform_background(energy, event_params, rmf, prng=prng)
Beispiel #7
0
def test_uniform_bkgnd_scale():
    hdxi_arf = AuxiliaryResponseFile("xrs_hdxi_3x10.arf")
    events, event_params = make_background((50, "ks"),
                                           "hdxi", [30., 45.],
                                           foreground=True,
                                           instr_bkgnd=True,
                                           ptsrc_bkgnd=False,
                                           prng=prng)
    ncts = np.logical_and(events["energy"] >= 0.7,
                          events["energy"] <= 2.0).sum()
    t_exp = event_params["exposure_time"]
    fov = (event_params["fov"] * 60.0)**2
    S = ncts / t_exp / fov
    dS = np.sqrt(ncts) / t_exp / fov
    foreground = ConvolvedBackgroundSpectrum(hm_astro_bkgnd, hdxi_arf)
    f_sum = foreground.get_flux_in_band(0.7, 2.0)[0]
    i_sum = acisi_particle_bkgnd.get_flux_in_band(0.7, 2.0)[0]
    b_sum = (f_sum + i_sum).to("ph/(arcsec**2*s)").value
    assert np.abs(S - b_sum) < 1.645 * dS
Beispiel #8
0
def make_foreground(event_params, arf, rmf, prng=None):

    prng = parse_prng(prng)

    conv_frgnd_spec = ConvolvedBackgroundSpectrum.convolve(hm_astro_bkgnd, arf)

    bkg_events = {"energy": [], "detx": [], "dety": [], "chip_id": []}
    pixel_area = (event_params["plate_scale"]*60.0)**2
    for i, chip in enumerate(event_params["chips"]):
        rtype = chip[0]
        args = chip[1:]
        r, bounds = create_region(rtype, args, 0.0, 0.0)
        fov = np.sqrt((bounds[1]-bounds[0])*(bounds[3]-bounds[2])*pixel_area)
        e = conv_frgnd_spec.generate_energies(event_params["exposure_time"],
                                              fov, prng=prng, quiet=True).value
        n_events = e.size
        detx = prng.uniform(low=bounds[0], high=bounds[1], size=n_events)
        dety = prng.uniform(low=bounds[2], high=bounds[3], size=n_events)
        if rtype in ["Box", "Rectangle"]:
            thisc = slice(None, None, None)
            n_det = n_events
        else:
            thisc = r.contains(PixCoord(detx, dety))
            n_det = thisc.sum()
        bkg_events["energy"].append(e[thisc])
        bkg_events["detx"].append(detx[thisc])
        bkg_events["dety"].append(dety[thisc])
        bkg_events["chip_id"].append(i*np.ones(n_det))

    for key in bkg_events:
        bkg_events[key] = np.concatenate(bkg_events[key])

    if bkg_events["energy"].size == 0:
        raise RuntimeError("No astrophysical foreground events "
                           "were detected!!!")
    else:
        mylog.info(f"Making {bkg_events['energy'].size} events from the "
                   f"astrophysical foreground.")

    bkg_events = make_diffuse_background(bkg_events, 
                                         event_params, rmf, prng=prng)
    mylog.info(f"Scattering energies with "
               f"RMF {os.path.split(rmf.filename)[-1]}.")

    return rmf.scatter_energies(bkg_events, prng=prng)