sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _compute_mean(map1, map2):
""" Make a map that is the mean of two maps
"""
data = (map1.data + map2.data) / 2.
return HpxMap(data, map1.hpx) | Make a map that is the mean of two maps | entailment |
def _compute_ratio(top, bot):
""" Make a map that is the ratio of two maps
"""
data = np.where(bot.data > 0, top.data / bot.data, 0.)
return HpxMap(data, top.hpx) | Make a map that is the ratio of two maps | entailment |
def _compute_diff(map1, map2):
""" Make a map that is the difference of two maps
"""
data = map1.data - map2.data
return HpxMap(data, map1.hpx) | Make a map that is the difference of two maps | entailment |
def _compute_product(map1, map2):
""" Make a map that is the product of two maps
"""
data = map1.data * map2.data
return HpxMap(data, map1.hpx) | Make a map that is the product of two maps | entailment |
def _compute_counts_from_intensity(intensity, bexpcube):
""" Make the counts map from the intensity
"""
data = intensity.data * np.sqrt(bexpcube.data[1:] * bexpcube.data[0:-1])
return HpxMap(data, intensity.hpx) | Make the counts map from the intensity | entailment |
def _compute_counts_from_model(model, bexpcube):
""" Make the counts maps from teh mdoe
"""
data = model.data * bexpcube.data
ebins = model.hpx.ebins
ratio = ebins[1:] / ebins[0:-1]
half_log_ratio = np.log(ratio) / 2.
int_map = ((data[0:-1].T * ebins[0:-1]) + (dat... | Make the counts maps from teh mdoe | entailment |
def _make_bright_pixel_mask(intensity_mean, mask_factor=5.0):
""" Make of mask of all the brightest pixels """
mask = np.zeros((intensity_mean.data.shape), bool)
nebins = len(intensity_mean.data)
sum_intensity = intensity_mean.data.sum(0)
mean_intensity = sum_intensity.mean()
... | Make of mask of all the brightest pixels | entailment |
def _get_aeff_corrections(intensity_ratio, mask):
""" Compute a correction for the effective area from the brighter pixesl
"""
nebins = len(intensity_ratio.data)
aeff_corrections = np.zeros((nebins))
for i in range(nebins):
bright_pixels_intensity = intensity_ratio.da... | Compute a correction for the effective area from the brighter pixesl | entailment |
def _apply_aeff_corrections(intensity_map, aeff_corrections):
""" Multipy a map by the effective area correction
"""
data = aeff_corrections * intensity_map.data.T
return HpxMap(data.T, intensity_map.hpx) | Multipy a map by the effective area correction | entailment |
def _fill_masked_intensity_resid(intensity_resid, bright_pixel_mask):
""" Fill the pixels used to compute the effective area correction with the mean intensity
"""
filled_intensity = np.zeros((intensity_resid.data.shape))
nebins = len(intensity_resid.data)
for i in range(nebins):... | Fill the pixels used to compute the effective area correction with the mean intensity | entailment |
def _smooth_hpx_map(hpx_map, sigma):
""" Smooth a healpix map using a Gaussian
"""
if hpx_map.hpx.ordering == "NESTED":
ring_map = hpx_map.swap_scheme()
else:
ring_map = hpx_map
ring_data = ring_map.data.copy()
nebins = len(hpx_map.data)
sm... | Smooth a healpix map using a Gaussian | entailment |
def _intergral_to_differential(hpx_map, gamma=-2.0):
""" Convert integral quantity to differential quantity
Here we are assuming the spectrum is a powerlaw with index gamma and we
are using log-log-quadrature to compute the integral quantities.
"""
nebins = len(hpx_map.data)
... | Convert integral quantity to differential quantity
Here we are assuming the spectrum is a powerlaw with index gamma and we
are using log-log-quadrature to compute the integral quantities. | entailment |
def _differential_to_integral(hpx_map):
""" Convert a differential map to an integral map
Here we are using log-log-quadrature to compute the integral quantities.
"""
ebins = hpx_map.hpx.ebins
ratio = ebins[1:] / ebins[0:-1]
half_log_ratio = np.log(ratio) / 2.
in... | Convert a differential map to an integral map
Here we are using log-log-quadrature to compute the integral quantities. | entailment |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
# Read the input maps
ccube_dirty = HpxMap.create_from_fits(args.ccube_dirty, hdu='SKYMAP')
bexpcube_dirty = HpxMap.create_from_fits(args.bexpcube_dirty, hdu='HPXEXPOSURES')
ccube_... | Run this analysis | entailment |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
components = Component.build_from_yamlfile(args['comp'])
NAME_FACTORY.update_base_dict(args['data'])
NAME_FACTORY_CLEAN.update_base_dict(args['data'])
NAME_FACTORY_DIRTY.u... | Hook to build job configurations | entailment |
def _map_arguments(self, args):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
config_yaml = args['config']
config_dict = load_yaml(config_yaml)
data = config_dict.get('data')
comp = config_dict.get('comp')
dry_run = ar... | Map from the top-level arguments to the arguments provided to
the indiviudal links | entailment |
def coadd_maps(geom, maps, preserve_counts=True):
"""Coadd a sequence of `~gammapy.maps.Map` objects."""
# FIXME: This functionality should be built into the Map.coadd method
map_out = gammapy.maps.Map.from_geom(geom)
for m in maps:
m_tmp = m
if isinstance(m, gammapy.maps.HpxNDMap):
... | Coadd a sequence of `~gammapy.maps.Map` objects. | entailment |
def sum_over_energy(self):
""" Reduce a 3D counts cube to a 2D counts map
"""
# Note that the array is using the opposite convention from WCS
# so we sum over axis 0 in the array, but drop axis 2 in the WCS object
return Map(np.sum(self.counts, axis=0), self.wcs.dropaxis(2)) | Reduce a 3D counts cube to a 2D counts map | entailment |
def xypix_to_ipix(self, xypix, colwise=False):
"""Return the flattened pixel indices from an array multi-dimensional
pixel indices.
Parameters
----------
xypix : list
List of pixel indices in the order (LON,LAT,ENERGY).
colwise : bool
Use column-... | Return the flattened pixel indices from an array multi-dimensional
pixel indices.
Parameters
----------
xypix : list
List of pixel indices in the order (LON,LAT,ENERGY).
colwise : bool
Use column-wise pixel indexing. | entailment |
def ipix_to_xypix(self, ipix, colwise=False):
"""Return array multi-dimensional pixel indices from flattened index.
Parameters
----------
colwise : bool
Use column-wise pixel indexing.
"""
return np.unravel_index(ipix, self.npix,
... | Return array multi-dimensional pixel indices from flattened index.
Parameters
----------
colwise : bool
Use column-wise pixel indexing. | entailment |
def ipix_swap_axes(self, ipix, colwise=False):
""" Return the transposed pixel index from the pixel xy coordinates
if colwise is True (False) this assumes the original index was
in column wise scheme
"""
xy = self.ipix_to_xypix(ipix, colwise)
return self.xypix_to_ipix(xy... | Return the transposed pixel index from the pixel xy coordinates
if colwise is True (False) this assumes the original index was
in column wise scheme | entailment |
def get_pixel_skydirs(self):
"""Get a list of sky coordinates for the centers of every pixel.
"""
xpix = np.linspace(0, self.npix[0] - 1., self.npix[0])
ypix = np.linspace(0, self.npix[1] - 1., self.npix[1])
xypix = np.meshgrid(xpix, ypix, indexing='ij')
return SkyCoord... | Get a list of sky coordinates for the centers of every pixel. | entailment |
def get_pixel_indices(self, lons, lats, ibin=None):
"""Return the indices in the flat array corresponding to a set of coordinates
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin... | Return the indices in the flat array corresponding to a set of coordinates
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : int or array-like
Extract data only for a given e... | entailment |
def get_map_values(self, lons, lats, ibin=None):
"""Return the map values corresponding to a set of coordinates.
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : int or array-l... | Return the map values corresponding to a set of coordinates.
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : int or array-like
Extract data only for a given energy bin. No... | entailment |
def create_from_hdu(cls, hdu, ebins):
""" Creates and returns an HpxMap object from a FITS HDU.
hdu : The FITS
ebins : Energy bin edges [optional]
"""
hpx = HPX.create_from_hdu(hdu, ebins)
colnames = hdu.columns.names
cnames = []
if hpx.conv.convname ... | Creates and returns an HpxMap object from a FITS HDU.
hdu : The FITS
ebins : Energy bin edges [optional] | entailment |
def create_from_hdulist(cls, hdulist, **kwargs):
""" Creates and returns an HpxMap object from a FITS HDUList
extname : The name of the HDU with the map data
ebounds : The name of the HDU with the energy bin data
"""
extname = kwargs.get('hdu', hdulist[1].name)
ebins = f... | Creates and returns an HpxMap object from a FITS HDUList
extname : The name of the HDU with the map data
ebounds : The name of the HDU with the energy bin data | entailment |
def make_wcs_from_hpx(self, sum_ebins=False, proj='CAR', oversample=2,
normalize=True):
"""Make a WCS object and convert HEALPix data into WCS projection
NOTE: this re-calculates the mapping, if you have already
calculated the mapping it is much faster to use
c... | Make a WCS object and convert HEALPix data into WCS projection
NOTE: this re-calculates the mapping, if you have already
calculated the mapping it is much faster to use
convert_to_cached_wcs() instead
Parameters
----------
sum_ebins : bool
sum energy bins ov... | entailment |
def convert_to_cached_wcs(self, hpx_in, sum_ebins=False, normalize=True):
""" Make a WCS object and convert HEALPix data into WCS projection
Parameters
----------
hpx_in : `~numpy.ndarray`
HEALPix input data
sum_ebins : bool
sum energy bins over energy... | Make a WCS object and convert HEALPix data into WCS projection
Parameters
----------
hpx_in : `~numpy.ndarray`
HEALPix input data
sum_ebins : bool
sum energy bins over energy bins before reprojecting
normalize : bool
True -> perserve integr... | entailment |
def get_pixel_skydirs(self):
"""Get a list of sky coordinates for the centers of every pixel. """
sky_coords = self._hpx.get_sky_coords()
if self.hpx.coordsys == 'GAL':
return SkyCoord(l=sky_coords.T[0], b=sky_coords.T[1], unit='deg', frame='galactic')
else:
retur... | Get a list of sky coordinates for the centers of every pixel. | entailment |
def sum_over_energy(self):
""" Reduce a counts cube to a counts map """
# We sum over axis 0 in the array, and drop the energy binning in the
# hpx object
return HpxMap(np.sum(self.counts, axis=0), self.hpx.copy_and_drop_energy()) | Reduce a counts cube to a counts map | entailment |
def get_map_values(self, lons, lats, ibin=None):
"""Return the indices in the flat array corresponding to a set of coordinates
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : ... | Return the indices in the flat array corresponding to a set of coordinates
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : int or array-like
Extract data only for a given e... | entailment |
def interpolate(self, lon, lat, egy=None, interp_log=True):
"""Interpolate map values.
Parameters
----------
interp_log : bool
Interpolate the z-coordinate in logspace.
"""
if self.data.ndim == 1:
theta = np.pi / 2. - np.radians(lat)
... | Interpolate map values.
Parameters
----------
interp_log : bool
Interpolate the z-coordinate in logspace. | entailment |
def _interpolate_cube(self, lon, lat, egy=None, interp_log=True):
"""Perform interpolation on a healpix cube. If egy is None
then interpolation will be performed on the existing energy
planes.
"""
shape = np.broadcast(lon, lat, egy).shape
lon = lon * np.ones(shape)
... | Perform interpolation on a healpix cube. If egy is None
then interpolation will be performed on the existing energy
planes. | entailment |
def expanded_counts_map(self):
""" return the full counts map """
if self.hpx._ipix is None:
return self.counts
output = np.zeros(
(self.counts.shape[0], self.hpx._maxpix), self.counts.dtype)
for i in range(self.counts.shape[0]):
output[i][self.hpx._i... | return the full counts map | entailment |
def explicit_counts_map(self, pixels=None):
""" return a counts map with explicit index scheme
Parameters
----------
pixels : `np.ndarray` or None
If set, grab only those pixels.
If none, grab only non-zero pixels
"""
# No pixel index, so build ... | return a counts map with explicit index scheme
Parameters
----------
pixels : `np.ndarray` or None
If set, grab only those pixels.
If none, grab only non-zero pixels | entailment |
def sparse_counts_map(self):
""" return a counts map with sparse index scheme
"""
if self.hpx._ipix is None:
flatarray = self.data.flattern()
else:
flatarray = self.expanded_counts_map()
nz = flatarray.nonzero()[0]
data_out = flatarray[nz]
... | return a counts map with sparse index scheme | entailment |
def compute_counts(self, skydir, fn, ebins=None):
"""Compute signal and background counts for a point source at
position ``skydir`` with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
ebins : `~numpy.ndarray`
Re... | Compute signal and background counts for a point source at
position ``skydir`` with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
ebins : `~numpy.ndarray`
Returns
-------
sig : `~numpy.ndarray`
... | entailment |
def diff_flux_threshold(self, skydir, fn, ts_thresh, min_counts):
"""Compute the differential flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinate... | Compute the differential flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinates at which the sensitivity will be evaluated.
fn : `~fermipy.spectru... | entailment |
def int_flux_threshold(self, skydir, fn, ts_thresh, min_counts):
"""Compute the integral flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
"""
ebins = 10**np.linspace(np.log10(self.ebins[0]),
np.log10(self.eb... | Compute the integral flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``. | entailment |
def coords_to_vec(lon, lat):
""" Converts longitute and latitude coordinates to a unit 3-vector
return array(3,n) with v_x[i],v_y[i],v_z[i] = directional cosines
"""
phi = np.radians(lon)
theta = (np.pi / 2) - np.radians(lat)
sin_t = np.sin(theta)
cos_t = np.cos(theta)
xVals = sin_t * ... | Converts longitute and latitude coordinates to a unit 3-vector
return array(3,n) with v_x[i],v_y[i],v_z[i] = directional cosines | entailment |
def get_pixel_size_from_nside(nside):
""" Returns an estimate of the pixel size from the HEALPix nside coordinate
This just uses a lookup table to provide a nice round number for each
HEALPix order.
"""
order = int(np.log2(nside))
if order < 0 or order > 13:
raise ValueError('HEALPix o... | Returns an estimate of the pixel size from the HEALPix nside coordinate
This just uses a lookup table to provide a nice round number for each
HEALPix order. | entailment |
def hpx_to_axes(h, npix):
""" Generate a sequence of bin edge vectors corresponding to the
axes of a HPX object."""
x = h.ebins
z = np.arange(npix[-1] + 1)
return x, z | Generate a sequence of bin edge vectors corresponding to the
axes of a HPX object. | entailment |
def hpx_to_coords(h, shape):
""" Generate an N x D list of pixel center coordinates where N is
the number of pixels and D is the dimensionality of the map."""
x, z = hpx_to_axes(h, shape)
x = np.sqrt(x[0:-1] * x[1:])
z = z[:-1] + 0.5
x = np.ravel(np.ones(shape) * x[:, np.newaxis])
z = np.... | Generate an N x D list of pixel center coordinates where N is
the number of pixels and D is the dimensionality of the map. | entailment |
def make_hpx_to_wcs_mapping_centers(hpx, wcs):
""" Make the mapping data needed to from from HPX pixelization to a
WCS-based array
Parameters
----------
hpx : `~fermipy.hpx_utils.HPX`
The healpix mapping (an HPX object)
wcs : `~astropy.wcs.WCS`
The wcs mapping (a pywcs.wc... | Make the mapping data needed to from from HPX pixelization to a
WCS-based array
Parameters
----------
hpx : `~fermipy.hpx_utils.HPX`
The healpix mapping (an HPX object)
wcs : `~astropy.wcs.WCS`
The wcs mapping (a pywcs.wcs object)
Returns
-------
ipixs : ar... | entailment |
def make_hpx_to_wcs_mapping(hpx, wcs):
"""Make the mapping data needed to from from HPX pixelization to a
WCS-based array
Parameters
----------
hpx : `~fermipy.hpx_utils.HPX`
The healpix mapping (an HPX object)
wcs : `~astropy.wcs.WCS`
The wcs mapping (a pywcs.wcs object)... | Make the mapping data needed to from from HPX pixelization to a
WCS-based array
Parameters
----------
hpx : `~fermipy.hpx_utils.HPX`
The healpix mapping (an HPX object)
wcs : `~astropy.wcs.WCS`
The wcs mapping (a pywcs.wcs object)
Returns
-------
ipixs : ar... | entailment |
def parse_hpxregion(region):
"""Parse the HPX_REG header keyword into a list of tokens."""
m = re.match(r'([A-Za-z\_]*?)\((.*?)\)', region)
if m is None:
raise Exception('Failed to parse hpx region string.')
if not m.group(1):
return re.split(',', m.group(2))
else:
return [... | Parse the HPX_REG header keyword into a list of tokens. | entailment |
def upix_to_pix(upix):
"""Get the nside from a unique pixel number."""
nside = np.power(2, np.floor(np.log2(upix / 4)) / 2).astype(int)
pix = upix - 4 * np.power(nside, 2)
return pix, nside | Get the nside from a unique pixel number. | entailment |
def create_hpx(cls, nside, nest, coordsys='CEL', order=-1, ebins=None,
region=None, conv=HPX_Conv('FGST_CCUBE'), pixels=None):
"""Create a HPX object.
Parameters
----------
nside : int
HEALPix nside paramter
nest : bool
True for H... | Create a HPX object.
Parameters
----------
nside : int
HEALPix nside paramter
nest : bool
True for HEALPix "NESTED" indexing scheme, False for "RING" scheme.
coordsys : str
"CEL" or "GAL"
order : int
nside = 2**ord... | entailment |
def identify_HPX_convention(header):
""" Identify the convention used to write this file """
# Hopefully the file contains the HPX_CONV keyword specifying
# the convention used
try:
return header['HPX_CONV']
except KeyError:
pass
indxschm = header... | Identify the convention used to write this file | entailment |
def create_from_header(cls, header, ebins=None, pixels=None):
""" Creates an HPX object from a FITS header.
header : The FITS header
ebins : Energy bin edges [optional]
"""
convname = HPX.identify_HPX_convention(header)
conv = HPX_FITS_CONVENTIONS[convname]
if ... | Creates an HPX object from a FITS header.
header : The FITS header
ebins : Energy bin edges [optional] | entailment |
def create_from_hdu(cls, hdu, ebins=None):
""" Creates an HPX object from a FITS header.
hdu : The FITS hdu
ebins : Energy bin edges [optional]
"""
convname = HPX.identify_HPX_convention(hdu.header)
conv = HPX_FITS_CONVENTIONS[convname]
try:
pixel... | Creates an HPX object from a FITS header.
hdu : The FITS hdu
ebins : Energy bin edges [optional] | entailment |
def make_header(self):
""" Builds and returns FITS header for this HEALPix map """
cards = [fits.Card("TELESCOP", "GLAST"),
fits.Card("INSTRUME", "LAT"),
fits.Card(self._conv.coordsys, self._coordsys),
fits.Card("PIXTYPE", "HEALPIX"),
f... | Builds and returns FITS header for this HEALPix map | entailment |
def make_hdu(self, data, **kwargs):
""" Builds and returns a FITs HDU with input data
data : The data begin stored
Keyword arguments
-------------------
extname : The HDU extension name
colbase : The prefix for column names
"""
shape = d... | Builds and returns a FITs HDU with input data
data : The data begin stored
Keyword arguments
-------------------
extname : The HDU extension name
colbase : The prefix for column names | entailment |
def make_energy_bounds_hdu(self, extname="EBOUNDS"):
""" Builds and returns a FITs HDU with the energy bin boundries
extname : The HDU extension name
"""
if self._ebins is None:
return None
cols = [fits.Column("CHANNEL", "I", array=np.arange(1, len(self... | Builds and returns a FITs HDU with the energy bin boundries
extname : The HDU extension name | entailment |
def make_energies_hdu(self, extname="ENERGIES"):
""" Builds and returns a FITs HDU with the energy bin boundries
extname : The HDU extension name
"""
if self._evals is None:
return None
cols = [fits.Column("ENERGY", "1E", unit='MeV',
... | Builds and returns a FITs HDU with the energy bin boundries
extname : The HDU extension name | entailment |
def write_fits(self, data, outfile, extname="SKYMAP", clobber=True):
""" Write input data to a FITS file
data : The data begin stored
outfile : The name of the output file
extname : The HDU extension name
clobber : True -> overwrite existing files
"""
... | Write input data to a FITS file
data : The data begin stored
outfile : The name of the output file
extname : The HDU extension name
clobber : True -> overwrite existing files | entailment |
def get_index_list(nside, nest, region):
""" Returns the list of pixels indices for all the pixels in a region
nside : HEALPix nside parameter
nest : True for 'NESTED', False = 'RING'
region : HEALPix region string
"""
tokens = parse_hpxregion(region)
i... | Returns the list of pixels indices for all the pixels in a region
nside : HEALPix nside parameter
nest : True for 'NESTED', False = 'RING'
region : HEALPix region string | entailment |
def get_ref_dir(region, coordsys):
""" Finds and returns the reference direction for a given
HEALPix region string.
region : a string describing a HEALPix region
coordsys : coordinate system, GAL | CEL
"""
if region is None:
if coordsys == "GAL":
... | Finds and returns the reference direction for a given
HEALPix region string.
region : a string describing a HEALPix region
coordsys : coordinate system, GAL | CEL | entailment |
def get_region_size(region):
""" Finds and returns the approximate size of region (in degrees)
from a HEALPix region string.
"""
if region is None:
return 180.
tokens = parse_hpxregion(region)
if tokens[0] in ['DISK', 'DISK_INC']:
return float... | Finds and returns the approximate size of region (in degrees)
from a HEALPix region string. | entailment |
def make_wcs(self, naxis=2, proj='CAR', energies=None, oversample=2):
""" Make a WCS projection appropirate for this HPX pixelization
"""
w = WCS(naxis=naxis)
skydir = self.get_ref_dir(self._region, self.coordsys)
if self.coordsys == 'CEL':
w.wcs.ctype[0] = 'RA---%s'... | Make a WCS projection appropirate for this HPX pixelization | entailment |
def get_sky_coords(self):
""" Get the sky coordinates of all the pixels in this pixelization """
if self._ipix is None:
theta, phi = hp.pix2ang(
self._nside, list(range(self._npix)), self._nest)
else:
theta, phi = hp.pix2ang(self._nside, self._ipix, self._... | Get the sky coordinates of all the pixels in this pixelization | entailment |
def get_pixel_indices(self, lats, lons):
""" "Return the indices in the flat array corresponding to a set of coordinates """
theta = np.radians(90. - lats)
phi = np.radians(lons)
return hp.ang2pix(self.nside, theta, phi, self.nest) | "Return the indices in the flat array corresponding to a set of coordinates | entailment |
def skydir_to_pixel(self, skydir):
"""Return the pixel index of a SkyCoord object."""
if self.coordsys in ['CEL', 'EQU']:
skydir = skydir.transform_to('icrs')
lon = skydir.ra.deg
lat = skydir.dec.deg
else:
skydir = skydir.transform_to('galactic')
... | Return the pixel index of a SkyCoord object. | entailment |
def write_to_fitsfile(self, fitsfile, clobber=True):
"""Write this mapping to a FITS file, to avoid having to recompute it
"""
from fermipy.skymap import Map
hpx_header = self._hpx.make_header()
index_map = Map(self.ipixs, self.wcs)
mult_map = Map(self.mult_val, self.wcs)... | Write this mapping to a FITS file, to avoid having to recompute it | entailment |
def create_from_fitsfile(cls, fitsfile):
""" Read a fits file and use it to make a mapping
"""
from fermipy.skymap import Map
index_map = Map.create_from_fits(fitsfile)
mult_map = Map.create_from_fits(fitsfile, hdu=1)
ff = fits.open(fitsfile)
hpx = HPX.create_from... | Read a fits file and use it to make a mapping | entailment |
def fill_wcs_map_from_hpx_data(self, hpx_data, wcs_data, normalize=True):
"""Fills the wcs map from the hpx data using the pre-calculated
mappings
hpx_data : the input HEALPix data
wcs_data : the data array being filled
normalize : True -> perserve integral by splitting HEALPi... | Fills the wcs map from the hpx data using the pre-calculated
mappings
hpx_data : the input HEALPix data
wcs_data : the data array being filled
normalize : True -> perserve integral by splitting HEALPix values between bins | entailment |
def make_wcs_data_from_hpx_data(self, hpx_data, wcs, normalize=True):
""" Creates and fills a wcs map from the hpx data using the pre-calculated
mappings
hpx_data : the input HEALPix data
wcs : the WCS object
normalize : True -> perserve integral by splitting HEALPix valu... | Creates and fills a wcs map from the hpx data using the pre-calculated
mappings
hpx_data : the input HEALPix data
wcs : the WCS object
normalize : True -> perserve integral by splitting HEALPix values between bins | entailment |
def _get_enum_bins(configfile):
"""Get the number of energy bin in the SED
Parameters
----------
configfile : str
Fermipy configuration file.
Returns
-------
nbins : int
The number of energy bins
"""
config = yaml.safe_load(open(configfile))
emin = config['s... | Get the number of energy bin in the SED
Parameters
----------
configfile : str
Fermipy configuration file.
Returns
-------
nbins : int
The number of energy bins | entailment |
def fill_output_table(filelist, hdu, collist, nbins):
"""Fill the arrays from the files in filelist
Parameters
----------
filelist : list
List of the files to get data from.
hdu : str
Name of the HDU containing the table with the input data.
colllist : list
List of th... | Fill the arrays from the files in filelist
Parameters
----------
filelist : list
List of the files to get data from.
hdu : str
Name of the HDU containing the table with the input data.
colllist : list
List of the column names
nbins : int
Number of bins in the... | entailment |
def vstack_tables(filelist, hdus):
"""vstack a set of HDUs from a set of files
Parameters
----------
filelist : list
List of the files to get data from.
hdus : list
Names of the HDU containing the table with the input data.
Returns
-------
out_tables : list
A... | vstack a set of HDUs from a set of files
Parameters
----------
filelist : list
List of the files to get data from.
hdus : list
Names of the HDU containing the table with the input data.
Returns
-------
out_tables : list
A list with the table with all the requeste... | entailment |
def collect_summary_stats(data):
"""Collect summary statisitics from an array
This creates a dictionry of output arrays of summary
statistics, with the input array dimension reducted by one.
Parameters
----------
data : `numpy.ndarray`
Array with the collected input data
Returns... | Collect summary statisitics from an array
This creates a dictionry of output arrays of summary
statistics, with the input array dimension reducted by one.
Parameters
----------
data : `numpy.ndarray`
Array with the collected input data
Returns
-------
output : dict
... | entailment |
def add_summary_stats_to_table(table_in, table_out, colnames):
"""Collect summary statisitics from an input table and add them to an output table
Parameters
----------
table_in : `astropy.table.Table`
Table with the input data.
table_out : `astropy.table.Table`
Table with the out... | Collect summary statisitics from an input table and add them to an output table
Parameters
----------
table_in : `astropy.table.Table`
Table with the input data.
table_out : `astropy.table.Table`
Table with the output data.
colnames : list
List of the column names to get... | entailment |
def summarize_sed_results(sed_table):
"""Build a stats summary table for a table that has all the SED results """
del_cols = ['dnde', 'dnde_err', 'dnde_errp', 'dnde_errn', 'dnde_ul',
'e2dnde', 'e2dnde_err', 'e2dnde_errp', 'e2dnde_errn', 'e2dnde_ul',
'norm', 'norm_err', 'norm_errp... | Build a stats summary table for a table that has all the SED results | entailment |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
sedfile = args.sed_file
if is_not_null(args.config):
configfile = os.path.join(os.path.dirname(sedfile), args.config)
else:
configfile = os.path.join(os.path.dirn... | Run this analysis | entailment |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
ttype = args['ttype']
(targets_yaml, sim) = NAME_FACTORY.resolve_targetfile(
args, require_sim_name=True)
if targets_yaml is None:
return job_configs
... | Hook to build job configurations | entailment |
def update_base_dict(self, yamlfile):
"""Update the values in baseline dictionary used to resolve names
"""
self.base_dict.update(**yaml.safe_load(open(yamlfile))) | Update the values in baseline dictionary used to resolve names | entailment |
def _format_from_dict(self, format_string, **kwargs):
"""Return a formatted file name dictionary components """
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
localpath = format_string.format(**kwargs_copy)
if kwargs.get('fullpath', False):
return se... | Return a formatted file name dictionary components | entailment |
def sim_sedfile(self, **kwargs):
"""Return the name for the simulated SED file for a particular target
"""
if 'seed' not in kwargs:
kwargs['seed'] = 'SEED'
return self._format_from_dict(NameFactory.sim_sedfile_format, **kwargs) | Return the name for the simulated SED file for a particular target | entailment |
def stamp(self, **kwargs):
"""Return the path for a stamp file for a scatter gather job"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
return NameFactory.stamp_format.format(**kwargs_copy) | Return the path for a stamp file for a scatter gather job | entailment |
def resolve_targetfile(self, args, require_sim_name=False): # x
"""Get the name of the targetfile based on the job arguments"""
ttype = args.get('ttype')
if is_null(ttype):
sys.stderr.write('Target type must be specified')
return (None, None)
sim = args.get('sim... | Get the name of the targetfile based on the job arguments | entailment |
def resolve_randconfig(self, args):
"""Get the name of the specturm file based on the job arguments"""
ttype = args.get('ttype')
if is_null(ttype):
sys.stderr.write('Target type must be specified')
return None
name_keys = dict(target_type=ttype,
... | Get the name of the specturm file based on the job arguments | entailment |
def main():
usage = "usage: %(prog)s [options] "
description = "Run gtselect and gtmktime on one or more FT1 files. "
"Note that gtmktime will be skipped if no FT2 file is provided."
parser = argparse.ArgumentParser(usage=usage, description=description)
add_lsf_args(parser)
parser.add_argumen... | Note that gtmktime will be skipped if no FT2 file is provided. | entailment |
def convert_sed_cols(tab):
"""Cast SED column names to lowercase."""
# Update Column names
for colname in list(tab.columns.keys()):
newname = colname.lower()
newname = newname.replace('dfde', 'dnde')
if tab.columns[colname].name == newname:
continue
tab.columns... | Cast SED column names to lowercase. | entailment |
def derivative(self, x, der=1):
""" return the derivative a an array of input values
x : the inputs
der : the order of derivative
"""
from scipy.interpolate import splev
return splev(x, self._sp, der=der) | return the derivative a an array of input values
x : the inputs
der : the order of derivative | entailment |
def _compute_mle(self):
"""Compute the maximum likelihood estimate.
Calls `scipy.optimize.brentq` to find the roots of the derivative.
"""
min_y = np.min(self._interp.y)
if self._interp.y[0] == min_y:
self._mle = self._interp.x[0]
elif self._interp.y[-1] == m... | Compute the maximum likelihood estimate.
Calls `scipy.optimize.brentq` to find the roots of the derivative. | entailment |
def getDeltaLogLike(self, dlnl, upper=True):
"""Find the point at which the log-likelihood changes by a
given value with respect to its value at the MLE."""
mle_val = self.mle()
# A little bit of paranoia to avoid zeros
if mle_val <= 0.:
mle_val = self._interp.xmin
... | Find the point at which the log-likelihood changes by a
given value with respect to its value at the MLE. | entailment |
def getLimit(self, alpha, upper=True):
""" Evaluate the limits corresponding to a C.L. of (1-alpha)%.
Parameters
----------
alpha : limit confidence level.
upper : upper or lower limits.
"""
dlnl = onesided_cl_to_dlnl(1.0 - alpha)
return self.getDeltaLo... | Evaluate the limits corresponding to a C.L. of (1-alpha)%.
Parameters
----------
alpha : limit confidence level.
upper : upper or lower limits. | entailment |
def getInterval(self, alpha):
""" Evaluate the interval corresponding to a C.L. of (1-alpha)%.
Parameters
----------
alpha : limit confidence level.
"""
dlnl = twosided_cl_to_dlnl(1.0 - alpha)
lo_lim = self.getDeltaLogLike(dlnl, upper=False)
hi_lim = self... | Evaluate the interval corresponding to a C.L. of (1-alpha)%.
Parameters
----------
alpha : limit confidence level. | entailment |
def create_from_table(cls, tab_e):
"""
Parameters
----------
tab_e : `~astropy.table.Table`
EBOUNDS table.
"""
convert_sed_cols(tab_e)
try:
emin = np.array(tab_e['e_min'].to(u.MeV))
emax = np.array(tab_e['e_max'].to(u.M... | Parameters
----------
tab_e : `~astropy.table.Table`
EBOUNDS table. | entailment |
def build_ebound_table(self):
""" Build and return an EBOUNDS table with the encapsulated data.
"""
cols = [
Column(name="E_MIN", dtype=float, data=self._emin, unit='MeV'),
Column(name="E_MAX", dtype=float, data=self._emax, unit='MeV'),
Column(name="E_REF", dt... | Build and return an EBOUNDS table with the encapsulated data. | entailment |
def derivative(self, x, der=1):
"""Return the derivate of the log-like summed over the energy
bins
Parameters
----------
x : `~numpy.ndarray`
Array of N x M values
der : int
Order of the derivate
Returns
-------
der_val :... | Return the derivate of the log-like summed over the energy
bins
Parameters
----------
x : `~numpy.ndarray`
Array of N x M values
der : int
Order of the derivate
Returns
-------
der_val : `~numpy.ndarray`
Array of negat... | entailment |
def mles(self):
""" return the maximum likelihood estimates for each of the energy bins
"""
mle_vals = np.ndarray((self._nx))
for i in range(self._nx):
mle_vals[i] = self._loglikes[i].mle()
return mle_vals | return the maximum likelihood estimates for each of the energy bins | entailment |
def ts_vals(self):
""" returns test statistic values for each energy bin
"""
ts_vals = np.ndarray((self._nx))
for i in range(self._nx):
ts_vals[i] = self._loglikes[i].TS()
return ts_vals | returns test statistic values for each energy bin | entailment |
def chi2_vals(self, x):
"""Compute the difference in the log-likelihood between the
MLE in each energy bin and the normalization predicted by a
global best-fit model. This array can be summed to get a
goodness-of-fit chi2 for the model.
Parameters
----------
x :... | Compute the difference in the log-likelihood between the
MLE in each energy bin and the normalization predicted by a
global best-fit model. This array can be summed to get a
goodness-of-fit chi2 for the model.
Parameters
----------
x : `~numpy.ndarray`
... | entailment |
def getLimits(self, alpha, upper=True):
""" Evaluate the limits corresponding to a C.L. of (1-alpha)%.
Parameters
----------
alpha : float
limit confidence level.
upper : bool
upper or lower limits.
returns an array of values, one for each energy... | Evaluate the limits corresponding to a C.L. of (1-alpha)%.
Parameters
----------
alpha : float
limit confidence level.
upper : bool
upper or lower limits.
returns an array of values, one for each energy bin | entailment |
def getIntervals(self, alpha):
""" Evaluate the two-sided intervals corresponding to a C.L. of
(1-alpha)%.
Parameters
----------
alpha : float
limit confidence level.
Returns
-------
limit_vals_hi : `~numpy.ndarray`
An array of lo... | Evaluate the two-sided intervals corresponding to a C.L. of
(1-alpha)%.
Parameters
----------
alpha : float
limit confidence level.
Returns
-------
limit_vals_hi : `~numpy.ndarray`
An array of lower limit values.
limit_vals_lo : ... | entailment |
def fitNormalization(self, specVals, xlims):
"""Fit the normalization given a set of spectral values that
define a spectral shape
This version is faster, and solves for the root of the derivatvie
Parameters
----------
specVals : an array of (nebin values that define a ... | Fit the normalization given a set of spectral values that
define a spectral shape
This version is faster, and solves for the root of the derivatvie
Parameters
----------
specVals : an array of (nebin values that define a spectral shape
xlims : fit limits
... | entailment |
def fitNorm_v2(self, specVals):
"""Fit the normalization given a set of spectral values
that define a spectral shape.
This version uses `scipy.optimize.fmin`.
Parameters
----------
specVals : an array of (nebin values that define a spectral shape
xlims : f... | Fit the normalization given a set of spectral values
that define a spectral shape.
This version uses `scipy.optimize.fmin`.
Parameters
----------
specVals : an array of (nebin values that define a spectral shape
xlims : fit limits
Returns
---... | entailment |
def fit_spectrum(self, specFunc, initPars, freePars=None):
""" Fit for the free parameters of a spectral function
Parameters
----------
specFunc : `~fermipy.spectrum.SpectralFunction`
The Spectral Function
initPars : `~numpy.ndarray`
The initial values o... | Fit for the free parameters of a spectral function
Parameters
----------
specFunc : `~fermipy.spectrum.SpectralFunction`
The Spectral Function
initPars : `~numpy.ndarray`
The initial values of the parameters
freePars : `~numpy.ndarray`
... | entailment |
def build_scandata_table(self):
"""Build an `astropy.table.Table` object from these data.
"""
shape = self._norm_vals.shape
col_norm = Column(name="norm", dtype=float)
col_normv = Column(name="norm_scan", dtype=float,
shape=shape)
col_dll = Colu... | Build an `astropy.table.Table` object from these data. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.