nuskybgd models

nuskybgd.model.addmodel_grxe(presets, refspec, model_num, model_name='grxe')[source]

Galactic ridge X-ray emission model, placeholder for now.

nuskybgd.model.addspec(specfiles, fresh=True)[source]

Add spectral data files in Xspec, each in their own data group. Afterward check the number of loaded spectra against length of input list. If not all spectra loaded, an Exception is raised.

Parameters
  • specfiles (list) – List of files to load into Xspec.

  • fresh (bool) – (Optional, default: True) All existing spectra are cleared before adding. If set to False, new spectra files are appended.

nuskybgd.model.applymodel_apbgd(presets, refspec, bgdapimwt, bgddetweights, model_num, src_number=None, model_name='apbgd')[source]

Xspec model component 2: apbgd (aperture image background)

The aperture background uses the cutoffpl model, with the first two parameters frozen (PhoIndex, HighCut).

Parameter 3 (norm) is calculated as

0.002353
--------  x  bgdapimwt
   32
bgdapimwt = np.sum(bgdapim * regmask) for each FPM and region.

This is calculated for the reference spectra for each FPM. The other spectra are scaled using the second part, sum(bgdapim * regmask).

Parameters
  • presets – Preset information from auxil/ratios.json.

  • refspec (dict) – A dictionary indicating the reference spectra index, e.g. {'A': 0, 'B': 1}.

  • bgdapimwt (list) – List of sum of the aperture image inside each background region.

  • model_num (int) – Model component number in Xspec, cannot be the same as another model or it will replace.

  • src_number (int) – (Optional, default None) Position of first spectrum to process, if not starting at 1. This is useful for rescaling background model parameters for a newly added spectrum.

  • model_name (str) – (Optional, default ‘apbgd’) Model component name in Xspec. Cannot be the same as another model.

nuskybgd.model.applymodel_fcxb(refspec, bgddetimsum, model_num, src_number=None, model_name='fcxb', apbgd_name='apbgd')[source]

Xspec model component 4: fcxb (focused CXB)

Note: the aperture image background model must have already been added.

The model uses a single component, ‘cutoffpl’, with first two parameters (PhoIndex, HighCut) tied to apbgd model source.

The normalization of cutoffpl is to be computed from:

0.002353 * 1.5 * (2.45810736/3600*1000)^2 * backscal
backscal = np.sum(regmask * bgddetim) / 1000^2
Parameters
  • refspec (dict) – A dictionary indicating the reference spectra index, e.g. {'A': 0, 'B': 1}.

  • bgddetimsum (list) – List of area (in px, summed from detector mask images) inside background region for each CCD.

  • model_num (int) – Model component number in Xspec. Cannot be the same as another model or it will replace.

  • model_name (str) – (Optional, default: 'fcxb') Model source name used in XSPEC.

  • src_number (int) – (Optional, default: None) Position of first spectrum to process, if not starting at 1. This is useful for rescaling background model parameters for a newly added spectrum.

  • apbgd_name (str) – Model component name of the aperture background model, which must have been already added.

nuskybgd.model.applymodel_intbgd(presets, refspec, bgddetimsum, model_num, src_number=None, model_name='intbgd', fix_line_ratios=False)[source]

Xspec model component 3: intbgd (instrument background)

This model consists of an APEC component followed by many lorentz lines. APEC has 4 parameters (kT, Abundanc, Redshift, norm). Each lorentz component has 3 parameters (LineE, Width, norm);

For the reference spectra (one from each telescope):

  • APEC params are loaded from preset.

  • Lines 1-3 (lorentz, lorentz_3, lorentz_4) are loaded from preset. The first two (3 and 6 keV) are probably solar related, and the third (10 keV) is poorly fit.

  • From Line 4 (19 keV, lorentz_5) onward, they are loaded from preset (detector area weighted sum of pre-determined values for each detector):

    norm = sum (ifactor * bgddetimsum)
           ---------------------------
                sum (bgddetimsum)
    
  • If the option fix_line_ratios=True, Line 5 onward are linked to Line 4 using:

    sum(ifactor * bgddetimsum)
    

For the other spectra:

  • All of the normalizations are linked to their reference spec counterparts using:

    sum(ifactor * bgddetimsum) of current spectrum
    ----------------------------------------------
    sum(ifactor * bgddetimsum) of reference
    

Note: due to perculiar model component numbering in XSPEC, as in the following:

Model intbgd:apec<1> + lorentz<2> + lorentz<3> + lorentz<4> + ...

In this case, the lorentz components have references lorentz, lorentz_3, lorentz_4, … etc. (skipping over lorentz_2). This numbering appears to be for all components, not just repeated ones, except the first occurrence omits the label.

Parameters
  • presets – Preset information from auxil/ratios.json.

  • refspec (dict) – A dictionary indicating the reference spectra index, e.g. {'A': 0, 'B': 1}.

  • bgddetimsum (list) – List of area (in px, summed from detector mask images) inside background region for each CCD.

  • model_num (int) – Model component number in Xspec, cannot be the same as another model or it will replace.

  • src_number (int) – (Optional, default None) Position of first spectrum to process, if not starting at 1. This is useful for rescaling background model parameters for a newly added spectrum.

  • model_name (str) – (Optional, default ‘intbgd’) Model component name in Xspec. Cannot be the same as another model.

  • fix_line_ratios (bool) – (Optional, default: False) Scale Gaussian line norms after the 19 keV line to the 19 keV norm. This affects only the reference spectra for the A and B modules, since parameters for the other spectra are tied to the reference spectra parameters rather than to its own parameters. E.g. when called by nuskybgd.cli.spec() with a src_number that is greater than the number of background data groups, this setting has no effect.

nuskybgd.model.applymodel_intn(presets, refspec, bgddetimsum, model_num, src_number=None, model_name='intn')[source]

Xspec model component 5: intn (bknpower)

The 3 parameters are read from preset and frozen (PhoIndx1, BreakE, PhoIndx2).

Normalization is calculated by multiplying the detector mask area (bgddetimsum) in arcmin^2 (1 px is 2.45 arcsec) and the preset for that detector, summed over all detectors.

Parameters
  • presets – Preset information from auxil/ratios.json.

  • refspec (dict) – A dictionary indicating the reference spectra index, e.g. {'A': 0, 'B': 1}.

  • bgddetimsum (list) – List of area (in px, summed from detector mask images) inside background region for each CCD.

  • model_num (int) – Model component number in Xspec, cannot be the same as another model or it will replace.

  • src_number (int) – (Optional, default None) Position of first spectrum to process, if not starting at 1. This is useful for rescaling background model parameters for a newly added spectrum.

  • model_name (str) – (Optional, default ‘intn’) Model component name in Xspec. Cannot be the same as another model.

nuskybgd.model.bgimg_apbgd(bgdinfo, model_norms, bgdapweights, refspec, model_name='apbgd', ignore='**-3. 20.-**', outprefix='')[source]

Create images of the aperture background model for each focal plane module.

The spectral models were constructed by summing the aperture images in the background regions, and using that as the weight to scale different background regions to the reference spectra (the first spectrum for each of A and B).

The image model of the background is created through the following steps:

  • 1. For each FPM reference region, sum the aperture images in the background regions;

  • 2. Ask XSPEC for the model predicted counts of the source apbgd (in user-specified energy band);

    1. Multiply the aperture image by model_count_rate / bgdap_region_sum.

The images will be written to files bgd_apbgd_A.fits and bgd_apbgd_B.fits by default.

Parameters
  • bgdinfo – Object returned by model.check_bgdinfofile().

  • model_norms – Object returned by read_xspec_model_norms().

  • bgdapweights – Object returned by model.calc_ap_weights() containing aperture image sums on each detector, for each background region.

  • refspec (dict) – A dictionary indicating the reference spectra index, e.g. {'A': 0, 'B': 1}.

  • model_name (str) – (Optional, default: 'apbgd') Model source name used in XSPEC.

  • ignore (str) – (Optional, default: '**-3. 20.-**') The XSPEC ‘ignore’ command to use before asking for the model predicted count rate.

  • outprefix (str) – (Optional, default: empty string) Prefix for the output file name.

nuskybgd.model.bgimg_fcxb(bgdinfo, model_norms, bgddetweights, bgddetim, regmask, model_name='fcxb', ignore='**-3. 20.-**', outprefix='')[source]

Create images of the FCXB background model.

All of the regions are allowed to have their own flux values. The image model of the background is created through the following steps:

  • 1. For each spectrum, ask XSPEC for the model count rate of fcxb (in user-specified energy band);

    1. Calculate the flux as model_count_rate / n_pixel.

  • 3. Fill the detector mask pixels in this spectral region with this flux value, output an image for this region;

  • 4. After all spectral regions have been processed, create an image for each module based on the fluxes in all of the background regions.

The last step above currently produces an image assuming a constant background over the field of view. Users may make use of the images of individual regions to create their own models of this.

The images will be written to files bgd_fcxb_A.fits and bgd_fcxb_B.fits by default. Images corresponding to the FCXB background in each region are written to bgd_fcxb_{num}.fits where {num} is the data group number in Xspec. (nuskybgd assigns every background spectrum to its own data group, so there is a one-to-one correspondence between data group and background region.)

Parameters
  • bgdinfo – Object returned by model.check_bgdinfofile().

  • model_norms – Object returned by read_xspec_model_norms().

  • bgddetweights – Object returned by model.calc_det_weights() containing detector image sums on each detector, for each spectrum.

  • bgddetim – Object containing seperate detector images returned by model.load_bgdimgs().

  • regmask (list of str) – Image masks for the spectral regions returned by util.mask_from_region().

  • model_name (str) – (Optional, default: 'fcxb') Model source name used in XSPEC.

  • ignore (str) – (Optional, default: '**-3. 20.-**') The XSPEC ‘ignore’ command to use before asking for the model predicted count rate.

  • outprefix (str) – (Optional, default: empty string) Prefix for the output file name.

nuskybgd.model.bgimg_intbgd(presets, refspec, bgdinfo, model_norms, bgddetweights, bgddetim, model_name='intbgd', ignore='**-3. 20.-**', outprefix='')[source]

Create images of the instrument background model for each focal plane module.

The model assigns constant background values for each detector (4 detectors x 2 modules). In the spectral model, there are optional parameter links among the spectral components, but the detector weighting (the ‘ifactors’ in the auxil file) are fixed. However, the different spectral components have different sets of ‘ifactors’ weights, so for any given region, the contributions from the detectors are different for each component.

The image model of the background is created through the following steps:

  1. For each module, go through each spectral model component separately (cache the model norms, then isolate the current component and zero the others);

  2. Ask XSPEC for the model count rate of intbgd (in user-specified energy band);

  3. Distribute the model count rate based on weights ifactor * det_area. Because the region may not cover all detectors (i.e. some det_area is zero), we shall calculate the flux on the detector that has the most counts and then scale it for the other detectors using their ifactor values:

    model_count_rate * ifactor_m / sum_i(ifactor_i * det_area_i)
    

    where ifactor_m * det_area_m is the largest weight, will be the pixel value of det_m. Calculate the pixel values of the other detectors using their relative ifactor values.

    1. Add the background image of the current component to the result.

The images will be written to files bgd_intbgd_A.fits and bgd_intbgd_B.fits by default.

Parameters
  • presets – Preset information from auxil/ratios.json.

  • refspec (dict) – A dictionary indicating the reference spectra index, e.g. {'A': 0, 'B': 1}.

  • bgdinfo – Object returned by model.check_bgdinfofile().

  • model_norms – Object returned by read_xspec_model_norms().

  • bgddetweights – Object returned by model.calc_det_weights() containing detector image sums on each detector, for each spectrum.

  • bgddetim – Object containing seperate detector images returned by model.load_bgdimgs().

  • model_name (str) – (Optional, default: 'intbgd') Model source name used in XSPEC.

  • ignore (str) – (Optional, default: '**-3. 20.-**') The XSPEC ‘ignore’ command to use before asking for the model predicted count rate.

  • outprefix (str) – (Optional, default: empty string) Prefix for the output file name.

nuskybgd.model.bgimg_intn(presets, refspec, bgdinfo, model_norms, bgddetweights, bgddetim, model_name='intn', ignore='**-3. 20.-**', outprefix='')[source]

Create images of the internal background model for each focal plane module.

The model uses a single component, a broken power law. There are only two free normalizations, one for each module. Relative weights of detectors are fixed by preset values of ifactors. The model image is created through an identical process to intbgd except we need only look at one model component.

The images will be written to files bgd_intn_A.fits and bgd_intn_B.fits by default.

Parameters
  • presets – Preset information from auxil/ratios.json.

  • refspec (dict) – A dictionary indicating the reference spectra index, e.g. {'A': 0, 'B': 1}.

  • bgdinfo – Object returned by model.check_bgdinfofile().

  • model_norms – Object returned by read_xspec_model_norms().

  • bgddetweights – Object returned by model.calc_det_weights() containing detector image sums on each detector, for each spectrum.

  • bgddetim – Object containing seperate detector images returned by model.load_bgdimgs().

  • model_name (str) – (Optional, default: 'intn') Model source name used in XSPEC.

  • ignore (str) – (Optional, default: '**-3. 20.-**') The XSPEC ‘ignore’ command to use before asking for the model predicted count rate.

  • outprefix (str) – (Optional, default: empty string) Prefix for the output file name.

nuskybgd.model.calc_ap_weights(apimgs, regmasks, fpmlist)[source]

Calculate sum of aperture image in the masks.

Parameters
  • apimgs (dict) – A dictionary {'A': np.ndarray, 'B': np.ndarray} containing aperture image of each module.

  • regmasks (list) – List of np.ndarray that are image masks of the background regions.

  • fpmlist (list) – List of A or B denoting the module corresponding to each region.

Returns

{'sum': []} containing a list of the sums of aperture image in each region.

Return type

dict

nuskybgd.model.calc_det_weights(detmasks, regmasks, fpmlist)[source]

Calculate detector area weights in specified region masks.

Parameters
  • detmasks (dict) – A dictionary {'A': [np.ndarray, ...], 'B': [np.ndarray, ...]} containing four detector mask images for each module.

  • regmasks (list) – List of np.ndarray that are image masks of the background regions.

  • fpmlist (list) – List of A or B denoting the module corresponding to each region.

Returns

{'sum': [], 'fraction': [[]]} containing a list of detector area in each region per detector; list of area fraction on each detector for every region.

Return type

dict

nuskybgd.model.check_bgdinfofile(bgdinfofile)[source]

Check that the background info file has the required items.

Parameters

bgdinfofile (str) –

Path to a JSON file containing information related to the background model. It must contain the following:

{
    "bgfiles": ["bgd1.pha", "bgd2.pha", ...],
    "regfiles": ["bgd1.reg", "bgd2.reg", ...],
    "bgdapfiles": {
        "A": "bgdapA.fits",
        "B": "bgdapB.fits"
    },
    "bgddetfiles": {
        "A": ["det1A.fits", "det2A.fits", ...],
        "B": ["det1B.fits", "det2B.fits", ...]
    },
    "refimgf": "bgdapA.fits"
}

bgfiles and regfiles list the background spectra and their corresponding region files; bgdapfiles list the two aperture image files; bgddetfiles list 4 detector mask images for each module; refimgf is an image that can be used for WCS reference, e.g. any of the aperture images or detector mask images generated by nuskybgd tasks.

Returns

  • dict – Containing information related to the background model.

  • False – If any problem was encountered.

nuskybgd.model.check_spec_order(bgdinfo)[source]

Check if the order of the loaded spectra files is the same as that in bgdinfo. Run this when loading an Xspec save file for the background model as a consistency check, because if the number or order of spectra files do not match, subsequent steps are invalid.

Parameters

bgdinfo – Object returned by model.check_bgdinfofile().

Returns

Whether the loaded spectra and entries in bgdinfo are the same.

Return type

bool

nuskybgd.model.fcxb_linkab(links, model_name='fcxb')[source]

Xspec model component 4: fcxb (focused CXB)

Tie normalizations between focal plane module A and B regions that cover the same region of sky.

Parameters
  • links (list) – A list of [ispec1, ispec2] to link Xspec spectrum number ispec2 to spectrum number ispec1.

  • model_name (str) – (Optional, default: 'fcxb') Model component name in Xspec. Cannot be the same as another model that is in use.

Example

Spectra 1 and 2 are from module A and B for the same background region; spectra 3 and 4 are from module A and B for another background region. They are each assigned to their own data groups.

>>> # Tie norm of data group 2 to 1, and 4 to 3.
>>> fcxb_linkab([[1, 2], [3, 4]])
nuskybgd.model.freeze_pars(groupnum)[source]

Look for any unfrozen model parameters that are not linked to another parameter, and freeze them. Return the list of parameters that were frozen, which can be used to thaw them.

Parameters

groupnum (int or list of ints) – The data group(s) to freeze model parameters for.

Returns

List of tuples (data group, model name, parameter number).

Return type

list

Example

>>> frozenpars = freeze_pars(range(1, nbgd+1))

All model parameters for data group 1 through nbgd are frozen.

nuskybgd.model.get_keyword_specfiles(specfiles, keyword, ext=0)[source]

Get values of specified keyword from a list of spectra files.

Parameters
  • specfiles (list) – List of spectra file names.

  • keyword (str) – Header keyword to check.

  • ext (int or str) – Extension index or name.

Returns

  • list – List of keyword values.

  • None – If either ext or keyword could not be found.

Raises

OSError – If an input spectrum file does not exist.

nuskybgd.model.get_keyword_xspecdata(keyword)[source]

Get values of specified keyword from currently loaded Xspec data files.

Parameters

keyword (str) – Header keyword to check.

Returns

  • list – List of keyword values.

  • None – If the keyword is not found in header.

nuskybgd.model.get_refspec(instlist)[source]

Determine the list indices of reference spectra files. The first entry of each module (inferred from the INSTRUME keyword) is designated the reference spectrum. If no spectrum from a module is encountered, it will have an entry None. Note that in xspec.AllData(i), the index i is 1-based.

Parameters

instlist (list) – List of INSTRUME keyword values. This can be retrieved from a list of spectra files using get_keyword_specfiles() or from the loaded xspec.AllData using get_keyword_xspecdata().

Returns

{'A': None, 'B': None} where None is replaced with the 0-based index of the first spectrum encountered for each module.

Return type

dict

Raises

Exception – An exception is raised if the focal plane module could not be determined for any of the entries in specfiles.

nuskybgd.model.load_bgdimgs(bgdinfo)[source]

Retrieve the aspect-projected background maps.

Parameters

bgdinfo – Object returned by model.check_bgdinfofile().

Returns

(bgdapim, bgddetim), both dictionaries:

bgdapim = {'A': numpy.ndarray, 'B': numpy.ndarray}
bgddetim = {'A': [numpy.ndarray], 'B': [numpy.ndarray]}

Return type

tuple

nuskybgd.model.read_xspec_model_norms(spec_nums=None)[source]

Make a record of the normalizations of the current XSPEC model. Only the values are saved, not parameter link information. (Note that if normalization value is set directly, the parameter link is overwritten.)

Parameters

spec_nums (list) – Spectrum numbers (numbering starts at 1). If not specified, all spectra are included.

Returns

A dictionary with the format:

{
    spec_num: {
        'source_name':{
            'component1': norm1,
            'component2': norm2,
            ...
        },
        ...
    },
    ...
}

Return type

dict

nuskybgd.model.remove_ispec(nspec)[source]

Remove a number of spectra from the front of Xspec’s loaded spectra.

Parameters

nspec (int) – The number of spectra to remove.

Example

>>> remove_ispec(2)

Removes the first 2 spectra.

nuskybgd.model.run_fit(statmethod='chi', method='leven 30000 1e-4', ignore='**-3. 150.-**')[source]

Change the fit settings in Xspec, and run fit.

Parameters
  • statmethod (str) – (Optional, default: 'chi') The statistical method to be used by Xspec. This is passed directly to Xspec via an analogous command to 'statistic'. By default this is 'chi', requiring spectra to be grouped into bins with typically 30 counts at least.

  • method (str) – (Optional, default: 'leven 30000 1e-4') Optimization method for the fit. Any valid argument for the Xspec command 'fit' is acceptable.

  • ignore (str) – (Optional, default: '**-3. 150.-**') Channels or energies to ignore. Any valid argument for the Xspec command 'ignore' will work here.

nuskybgd.model.run_fit_settings(statmethod='chi', method='leven 30000 1e-4', ignore='**-3. 150.-**')[source]

Change the fit settings in Xspec.

Parameters
  • statmethod (str) – (Optional, default: 'chi') The statistical method to be used by Xspec. This is passed directly to Xspec via an analogous command to ‘statistic’. By default this is ‘chi’, requiring spectra to be grouped into bins with typically 30 counts at least.

  • method (str) – (Optional, default: 'leven 30000 1e-4') Optimization method for the fit. Any valid argument for the Xspec command ‘fit’ is acceptable.

  • ignore (str) – (Optional, default: '**-3. 150.-**') Channels or energies to ignore. Any valid argument for the Xspec command ‘ignore’ will work here.

nuskybgd.model.save_xcm(prefix='bgdparams')[source]

Save current Xspec state to an xcm file.

Parameters

prefix (str) – (Optional, default: 'bgdparams') Specify file name prefix for the saved file. If a file with this name exists, will attempt bgdparams2.xcm through bgdparams100.xcm.

Returns

Whether a file was saved successfully.

Return type

bool

nuskybgd.model.thaw_pars(parlist)[source]

Thaw a list of parameters.

Parameters

parlist (list) – A list of tuples(3) containing (data group, model name, parameter number). Note: this parameter number starts at 1 for each data group, unlike the numbering in Xspec, which enumerates over all data groups.

Example

>>> # Thaw the 3rd parameter of apbgd for data groups 1 and 2
>>> frozenpars = [(1, 'apbgd', 3), (2, 'apbgd', 3)]
>>> thaw_pars(frozenpars)
nuskybgd.model.zero_xspec_model_norms(model_norms)[source]

Iterate through sources and model components in model_norms (obtained by read_xspec_model_norms) and set all of the normalizations to zero.

Note: setting the values to zero breaks any link it has to another parameter. The model thus modified should not be used for fitting.