idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
36,200 | def xypix_to_ipix ( self , xypix , colwise = False ) : return np . ravel_multi_index ( xypix , self . npix , order = 'F' if colwise else 'C' , mode = 'raise' ) | Return the flattened pixel indices from an array multi - dimensional pixel indices . |
36,201 | def ipix_to_xypix ( self , ipix , colwise = False ) : return np . unravel_index ( ipix , self . npix , order = 'F' if colwise else 'C' ) | Return array multi - dimensional pixel indices from flattened index . |
36,202 | def ipix_swap_axes ( self , ipix , colwise = False ) : xy = self . ipix_to_xypix ( ipix , colwise ) return self . xypix_to_ipix ( xy , not colwise ) | Return the transposed pixel index from the pixel xy coordinates |
36,203 | def get_map_values ( self , lons , lats , ibin = None ) : pix_idxs = self . get_pixel_indices ( lons , lats , ibin ) idxs = copy . copy ( pix_idxs ) m = np . empty_like ( idxs [ 0 ] , dtype = bool ) m . fill ( True ) for i , p in enumerate ( pix_idxs ) : m &= ( pix_idxs [ i ] >= 0 ) & ( pix_idxs [ i ] < self . _npix [ ... | Return the map values corresponding to a set of coordinates . |
36,204 | def create_from_hdu ( cls , hdu , ebins ) : hpx = HPX . create_from_hdu ( hdu , ebins ) colnames = hdu . columns . names cnames = [ ] if hpx . conv . convname == 'FGST_SRCMAP_SPARSE' : pixs = hdu . data . field ( 'PIX' ) chans = hdu . data . field ( 'CHANNEL' ) keys = chans * hpx . npix + pixs vals = hdu . data . field... | Creates and returns an HpxMap object from a FITS HDU . |
36,205 | def create_from_hdulist ( cls , hdulist , ** kwargs ) : extname = kwargs . get ( 'hdu' , hdulist [ 1 ] . name ) ebins = fits_utils . find_and_read_ebins ( hdulist ) return cls . create_from_hdu ( hdulist [ extname ] , ebins ) | Creates and returns an HpxMap object from a FITS HDUList |
36,206 | def sum_over_energy ( self ) : return HpxMap ( np . sum ( self . counts , axis = 0 ) , self . hpx . copy_and_drop_energy ( ) ) | Reduce a counts cube to a counts map |
36,207 | def interpolate ( self , lon , lat , egy = None , interp_log = True ) : if self . data . ndim == 1 : theta = np . pi / 2. - np . radians ( lat ) phi = np . radians ( lon ) return hp . pixelfunc . get_interp_val ( self . counts , theta , phi , nest = self . hpx . nest ) else : return self . _interpolate_cube ( lon , lat... | Interpolate map values . |
36,208 | def _interpolate_cube ( self , lon , lat , egy = None , interp_log = True ) : shape = np . broadcast ( lon , lat , egy ) . shape lon = lon * np . ones ( shape ) lat = lat * np . ones ( shape ) theta = np . pi / 2. - np . radians ( lat ) phi = np . radians ( lon ) vals = [ ] for i , _ in enumerate ( self . hpx . evals )... | Perform interpolation on a healpix cube . If egy is None then interpolation will be performed on the existing energy planes . |
36,209 | def expanded_counts_map ( self ) : 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 . _ipix ] = self . counts [ i ] return output | return the full counts map |
36,210 | def explicit_counts_map ( self , pixels = None ) : if self . hpx . _ipix is None : if self . data . ndim == 2 : summed = self . counts . sum ( 0 ) if pixels is None : nz = summed . nonzero ( ) [ 0 ] else : nz = pixels data_out = np . vstack ( self . data [ i ] . flat [ nz ] for i in range ( self . data . shape [ 0 ] ) ... | return a counts map with explicit index scheme |
36,211 | def sparse_counts_map ( self ) : 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 ( nz , data_out ) | return a counts map with sparse index scheme |
36,212 | def diff_flux_threshold ( self , skydir , fn , ts_thresh , min_counts ) : sig , bkg , bkg_fit = self . compute_counts ( skydir , fn ) norms = irfs . compute_norm ( sig , bkg , ts_thresh , min_counts , sum_axes = [ 2 , 3 ] , rebin_axes = [ 10 , 1 ] , bkg_fit = bkg_fit ) npred = np . squeeze ( np . apply_over_axes ( np .... | Compute the differential flux threshold for a point source at position skydir with spectral parameterization fn . |
36,213 | def coords_to_vec ( lon , lat ) : phi = np . radians ( lon ) theta = ( np . pi / 2 ) - np . radians ( lat ) sin_t = np . sin ( theta ) cos_t = np . cos ( theta ) xVals = sin_t * np . cos ( phi ) yVals = sin_t * np . sin ( phi ) zVals = cos_t out = np . vstack ( ( xVals , yVals , zVals ) ) . swapaxes ( 0 , 1 ) return ou... | Converts longitute and latitude coordinates to a unit 3 - vector |
36,214 | def get_pixel_size_from_nside ( nside ) : order = int ( np . log2 ( nside ) ) if order < 0 or order > 13 : raise ValueError ( 'HEALPix order must be between 0 to 13 %i' % order ) return HPX_ORDER_TO_PIXSIZE [ order ] | Returns an estimate of the pixel size from the HEALPix nside coordinate |
36,215 | def hpx_to_axes ( h , npix ) : 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 . |
36,216 | def parse_hpxregion ( region ) : 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 [ m . group ( 1 ) ] + re . split ( ',' , m . group ( 2 ) ) | Parse the HPX_REG header keyword into a list of tokens . |
36,217 | def upix_to_pix ( upix ) : 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 . |
36,218 | def create_hpx ( cls , nside , nest , coordsys = 'CEL' , order = - 1 , ebins = None , region = None , conv = HPX_Conv ( 'FGST_CCUBE' ) , pixels = None ) : return cls ( nside , nest , coordsys , order , ebins , region = region , conv = conv , pixels = pixels ) | Create a HPX object . |
36,219 | def identify_HPX_convention ( header ) : try : return header [ 'HPX_CONV' ] except KeyError : pass indxschm = header . get ( 'INDXSCHM' , None ) extname = header . get ( 'EXTNAME' , None ) if extname == 'HPXEXPOSURES' : return 'FGST_BEXPCUBE' elif extname == 'SKYMAP2' : if 'COORDTYPE' in header . keys ( ) : return 'GAL... | Identify the convention used to write this file |
36,220 | def make_header ( self ) : cards = [ fits . Card ( "TELESCOP" , "GLAST" ) , fits . Card ( "INSTRUME" , "LAT" ) , fits . Card ( self . _conv . coordsys , self . _coordsys ) , fits . Card ( "PIXTYPE" , "HEALPIX" ) , fits . Card ( "ORDERING" , self . ordering ) , fits . Card ( "ORDER" , self . _order ) , fits . Card ( "NS... | Builds and returns FITS header for this HEALPix map |
36,221 | def make_hdu ( self , data , ** kwargs ) : shape = data . shape extname = kwargs . get ( 'extname' , self . conv . extname ) if shape [ - 1 ] != self . _npix : raise Exception ( "Size of data array does not match number of pixels" ) cols = [ ] if self . _ipix is not None : cols . append ( fits . Column ( self . conv . ... | Builds and returns a FITs HDU with input data |
36,222 | def write_fits ( self , data , outfile , extname = "SKYMAP" , clobber = True ) : hdu_prim = fits . PrimaryHDU ( ) hdu_hpx = self . make_hdu ( data , extname = extname ) hl = [ hdu_prim , hdu_hpx ] if self . conv . energy_hdu == 'EBOUNDS' : hdu_energy = self . make_energy_bounds_hdu ( ) elif self . conv . energy_hdu == ... | Write input data to a FITS file |
36,223 | def get_index_list ( nside , nest , region ) : tokens = parse_hpxregion ( region ) if tokens [ 0 ] == 'DISK' : vec = coords_to_vec ( float ( tokens [ 1 ] ) , float ( tokens [ 2 ] ) ) ilist = hp . query_disc ( nside , vec [ 0 ] , np . radians ( float ( tokens [ 3 ] ) ) , inclusive = False , nest = nest ) elif tokens [ 0... | Returns the list of pixels indices for all the pixels in a region |
36,224 | def get_ref_dir ( region , coordsys ) : if region is None : if coordsys == "GAL" : c = SkyCoord ( 0. , 0. , frame = Galactic , unit = "deg" ) elif coordsys == "CEL" : c = SkyCoord ( 0. , 0. , frame = ICRS , unit = "deg" ) return c tokens = parse_hpxregion ( region ) if tokens [ 0 ] in [ 'DISK' , 'DISK_INC' ] : if coord... | Finds and returns the reference direction for a given HEALPix region string . |
36,225 | def make_wcs ( self , naxis = 2 , proj = 'CAR' , energies = None , oversample = 2 ) : w = WCS ( naxis = naxis ) skydir = self . get_ref_dir ( self . _region , self . coordsys ) if self . coordsys == 'CEL' : w . wcs . ctype [ 0 ] = 'RA---%s' % ( proj ) w . wcs . ctype [ 1 ] = 'DEC--%s' % ( proj ) w . wcs . crval [ 0 ] =... | Make a WCS projection appropirate for this HPX pixelization |
36,226 | def get_sky_coords ( self ) : 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 . _nest ) lat = np . degrees ( ( np . pi / 2 ) - theta ) lon = np . degrees ( phi ) return np . vs... | Get the sky coordinates of all the pixels in this pixelization |
36,227 | def skydir_to_pixel ( self , skydir ) : 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' ) lon = skydir . l . deg lat = skydir . b . deg return self . get_pixel_indices ( lat , lon ) | Return the pixel index of a SkyCoord object . |
36,228 | def write_to_fitsfile ( self , fitsfile , clobber = True ) : 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 ) prim_hdu = index_map . create_primary_hdu ( ) mult_hdu = index_map . create_image_hdu ( )... | Write this mapping to a FITS file to avoid having to recompute it |
36,229 | def create_from_fitsfile ( cls , fitsfile ) : 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_hdu ( ff [ 0 ] ) mapping_data = dict ( ipixs = index_map . counts , mult_val = mul... | Read a fits file and use it to make a mapping |
36,230 | def fill_wcs_map_from_hpx_data ( self , hpx_data , wcs_data , normalize = True ) : hpx_naxis = len ( hpx_data . shape ) wcs_naxis = len ( wcs_data . shape ) if hpx_naxis + 1 != wcs_naxis : raise ValueError ( "HPX.fill_wcs_map_from_hpx_data: HPX naxis should be 1 less that WCS naxis: %i, %i" % ( hpx_naxis , wcs_naxis ) ... | Fills the wcs map from the hpx data using the pre - calculated mappings |
36,231 | def make_wcs_data_from_hpx_data ( self , hpx_data , wcs , normalize = True ) : wcs_data = np . zeros ( wcs . npix ) self . fill_wcs_map_from_hpx_data ( hpx_data , wcs_data , normalize ) return wcs_data | Creates and fills a wcs map from the hpx data using the pre - calculated mappings |
36,232 | def _get_enum_bins ( configfile ) : config = yaml . safe_load ( open ( configfile ) ) emin = config [ 'selection' ] [ 'emin' ] emax = config [ 'selection' ] [ 'emax' ] log_emin = np . log10 ( emin ) log_emax = np . log10 ( emax ) ndec = log_emax - log_emin binsperdec = config [ 'binning' ] [ 'binsperdec' ] nebins = int... | Get the number of energy bin in the SED |
36,233 | def fill_output_table ( filelist , hdu , collist , nbins ) : nfiles = len ( filelist ) shape = ( nbins , nfiles ) outdict = { } for c in collist : outdict [ c [ 'name' ] ] = np . ndarray ( shape ) sys . stdout . write ( 'Working on %i files: ' % nfiles ) sys . stdout . flush ( ) for i , f in enumerate ( filelist ) : sy... | Fill the arrays from the files in filelist |
36,234 | def vstack_tables ( filelist , hdus ) : nfiles = len ( filelist ) out_tables = [ ] out_names = [ ] for hdu in hdus : sys . stdout . write ( 'Working on %i files for %s: ' % ( nfiles , hdu ) ) sys . stdout . flush ( ) tlist = [ ] for f in filelist : try : tab = Table . read ( f , hdu ) tlist . append ( tab ) sys . stdou... | vstack a set of HDUs from a set of files |
36,235 | def collect_summary_stats ( data ) : mean = np . mean ( data , axis = 0 ) std = np . std ( data , axis = 0 ) median = np . median ( data , axis = 0 ) q02 , q16 , q84 , q97 = np . percentile ( data , [ 2.5 , 16 , 84 , 97.5 ] , axis = 0 ) o = dict ( mean = mean , std = std , median = median , q02 = q02 , q16 = q16 , q84 ... | Collect summary statisitics from an array |
36,236 | def add_summary_stats_to_table ( table_in , table_out , colnames ) : for col in colnames : col_in = table_in [ col ] stats = collect_summary_stats ( col_in . data ) for k , v in stats . items ( ) : out_name = "%s_%s" % ( col , k ) col_out = Column ( data = np . vstack ( [ v ] ) , name = out_name , dtype = col_in . dtyp... | Collect summary statisitics from an input table and add them to an output table |
36,237 | def summarize_sed_results ( sed_table ) : 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' , 'norm_errn' , 'norm_ul' , 'ts' ] stats_cols = [ 'dnde' , 'dnde_ul' , 'e2dnde' , 'e2dnde_ul' , '... | Build a stats summary table for a table that has all the SED results |
36,238 | def update_base_dict ( self , yamlfile ) : self . base_dict . update ( ** yaml . safe_load ( open ( yamlfile ) ) ) | Update the values in baseline dictionary used to resolve names |
36,239 | def _format_from_dict ( self , format_string , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) localpath = format_string . format ( ** kwargs_copy ) if kwargs . get ( 'fullpath' , False ) : return self . fullpath ( localpath = localpath ) return localpath | Return a formatted file name dictionary components |
36,240 | def sim_sedfile ( self , ** kwargs ) : 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 |
36,241 | def stamp ( self , ** kwargs ) : 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 |
36,242 | def resolve_targetfile ( self , args , require_sim_name = False ) : ttype = args . get ( 'ttype' ) if is_null ( ttype ) : sys . stderr . write ( 'Target type must be specified' ) return ( None , None ) sim = args . get ( 'sim' ) if is_null ( sim ) : if require_sim_name : sys . stderr . write ( 'Simulation scenario must... | Get the name of the targetfile based on the job arguments |
36,243 | def resolve_randconfig ( self , args ) : ttype = args . get ( 'ttype' ) if is_null ( ttype ) : sys . stderr . write ( 'Target type must be specified' ) return None name_keys = dict ( target_type = ttype , fullpath = True ) randconfig = self . randconfig ( ** name_keys ) rand_override = args . get ( 'rand_config' ) if i... | Get the name of the specturm file based on the job arguments |
36,244 | def convert_sed_cols ( tab ) : for colname in list ( tab . columns . keys ( ) ) : newname = colname . lower ( ) newname = newname . replace ( 'dfde' , 'dnde' ) if tab . columns [ colname ] . name == newname : continue tab . columns [ colname ] . name = newname return tab | Cast SED column names to lowercase . |
36,245 | def derivative ( self , x , der = 1 ) : from scipy . interpolate import splev return splev ( x , self . _sp , der = der ) | return the derivative a an array of input values |
36,246 | def _compute_mle ( self ) : 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 ] == min_y : self . _mle = self . _interp . x [ - 1 ] else : argmin_y = np . argmin ( self . _interp . y ) ix0 = max ( argmin_y - 4 , 0 ) ix1 = ... | Compute the maximum likelihood estimate . |
36,247 | def getDeltaLogLike ( self , dlnl , upper = True ) : mle_val = self . mle ( ) if mle_val <= 0. : mle_val = self . _interp . xmin if mle_val <= 0. : mle_val = self . _interp . x [ 1 ] log_mle = np . log10 ( mle_val ) lnl_max = self . fn_mle ( ) if upper : x = np . logspace ( log_mle , np . log10 ( self . _interp . xmax ... | Find the point at which the log - likelihood changes by a given value with respect to its value at the MLE . |
36,248 | def build_ebound_table ( self ) : 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" , dtype = float , data = self . _eref , unit = 'MeV' ) , Column ( name = "REF_DNDE" , dtype... | Build and return an EBOUNDS table with the encapsulated data . |
36,249 | def derivative ( self , x , der = 1 ) : if len ( x . shape ) == 1 : der_val = np . zeros ( ( 1 ) ) else : der_val = np . zeros ( ( x . shape [ 1 : ] ) ) for i , xv in enumerate ( x ) : der_val += self . _loglikes [ i ] . interp . derivative ( xv , der = der ) return der_val | Return the derivate of the log - like summed over the energy bins |
36,250 | def mles ( self ) : 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 |
36,251 | def ts_vals ( self ) : 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 |
36,252 | def chi2_vals ( self , x ) : chi2_vals = np . ndarray ( ( self . _nx ) ) for i in range ( self . _nx ) : mle = self . _loglikes [ i ] . mle ( ) nll0 = self . _loglikes [ i ] . interp ( mle ) nll1 = self . _loglikes [ i ] . interp ( x [ i ] ) chi2_vals [ i ] = 2.0 * np . abs ( nll0 - nll1 ) return chi2_vals | 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 . |
36,253 | def fitNormalization ( self , specVals , xlims ) : from scipy . optimize import brentq def fDeriv ( x ) : return self . norm_derivative ( specVals , x ) try : result = brentq ( fDeriv , xlims [ 0 ] , xlims [ 1 ] ) except : check_underflow = self . __call__ ( specVals * xlims [ 0 ] ) < self . __call__ ( specVals * xlims... | Fit the normalization given a set of spectral values that define a spectral shape |
36,254 | def fitNorm_v2 ( self , specVals ) : from scipy . optimize import fmin def fToMin ( x ) : return self . __call__ ( specVals * x ) result = fmin ( fToMin , 0. , disp = False , xtol = 1e-6 ) return result | Fit the normalization given a set of spectral values that define a spectral shape . |
36,255 | def fit_spectrum ( self , specFunc , initPars , freePars = None ) : if not isinstance ( specFunc , SEDFunctor ) : specFunc = self . create_functor ( specFunc , initPars , scale = specFunc . scale ) if freePars is None : freePars = np . empty ( len ( initPars ) , dtype = bool ) freePars . fill ( True ) initPars = np . a... | Fit for the free parameters of a spectral function |
36,256 | def build_scandata_table ( self ) : shape = self . _norm_vals . shape col_norm = Column ( name = "norm" , dtype = float ) col_normv = Column ( name = "norm_scan" , dtype = float , shape = shape ) col_dll = Column ( name = "dloglike_scan" , dtype = float , shape = shape ) tab = Table ( data = [ col_norm , col_normv , co... | Build an astropy . table . Table object from these data . |
36,257 | def create_from_yamlfile ( cls , yamlfile ) : data = load_yaml ( yamlfile ) nebins = len ( data ) emin = np . array ( [ data [ i ] [ 'emin' ] for i in range ( nebins ) ] ) emax = np . array ( [ data [ i ] [ 'emax' ] for i in range ( nebins ) ] ) ref_flux = np . array ( [ data [ i ] [ 'flux' ] [ 1 ] for i in range ( neb... | Create a Castro data object from a yaml file contains the likelihood data . |
36,258 | def create_from_flux_points ( cls , txtfile ) : tab = Table . read ( txtfile , format = 'ascii.ecsv' ) dnde_unit = u . ph / ( u . MeV * u . cm ** 2 * u . s ) loge = np . log10 ( np . array ( tab [ 'e_ref' ] . to ( u . MeV ) ) ) norm = np . array ( tab [ 'norm' ] . to ( dnde_unit ) ) norm_errp = np . array ( tab [ 'norm... | Create a Castro data object from a text file containing a sequence of differential flux points . |
36,259 | def create_from_tables ( cls , norm_type = 'eflux' , tab_s = "SCANDATA" , tab_e = "EBOUNDS" ) : if norm_type in [ 'flux' , 'eflux' , 'dnde' ] : norm_vals = np . array ( tab_s [ 'norm_scan' ] * tab_e [ 'ref_%s' % norm_type ] [ : , np . newaxis ] ) elif norm_type == "norm" : norm_vals = np . array ( tab_s [ 'norm_scan' ]... | Create a CastroData object from two tables |
36,260 | def create_from_fits ( cls , fitsfile , norm_type = 'eflux' , hdu_scan = "SCANDATA" , hdu_energies = "EBOUNDS" , irow = None ) : if irow is not None : tab_s = Table . read ( fitsfile , hdu = hdu_scan ) [ irow ] else : tab_s = Table . read ( fitsfile , hdu = hdu_scan ) tab_e = Table . read ( fitsfile , hdu = hdu_energie... | Create a CastroData object from a tscube FITS file . |
36,261 | def create_from_sedfile ( cls , fitsfile , norm_type = 'eflux' ) : tab_s = Table . read ( fitsfile , hdu = 1 ) tab_s = convert_sed_cols ( tab_s ) if norm_type in [ 'flux' , 'eflux' , 'dnde' ] : ref_colname = 'ref_%s' % norm_type norm_vals = np . array ( tab_s [ 'norm_scan' ] * tab_s [ ref_colname ] [ : , np . newaxis ]... | Create a CastroData object from an SED fits file |
36,262 | def spectrum_loglike ( self , specType , params , scale = 1E3 ) : sfn = self . create_functor ( specType , scale ) [ 0 ] return self . __call__ ( sfn ( params ) ) | return the log - likelihood for a particular spectrum |
36,263 | def create_functor ( self , specType , initPars = None , scale = 1E3 ) : emin = self . _refSpec . emin emax = self . _refSpec . emax fn = SpectralFunction . create_functor ( specType , self . norm_type , emin , emax , scale = scale ) if initPars is None : if specType == 'PowerLaw' : initPars = np . array ( [ 5e-13 , - ... | Create a functor object that computes normalizations in a sequence of energy bins for a given spectral model . |
36,264 | def find_and_refine_peaks ( self , threshold , min_separation = 1.0 , use_cumul = False ) : if use_cumul : theMap = self . _ts_cumul else : theMap = self . _tsmap peaks = find_peaks ( theMap , threshold , min_separation ) for peak in peaks : o , skydir = fit_error_ellipse ( theMap , ( peak [ 'ix' ] , peak [ 'iy' ] ) , ... | Run a simple peak - finding algorithm and fit the peaks to paraboloids to extract their positions and error ellipses . |
36,265 | def make_lat_lons ( cvects ) : lats = np . degrees ( np . arcsin ( cvects [ 2 ] ) ) lons = np . degrees ( np . arctan2 ( cvects [ 0 ] , cvects [ 1 ] ) ) return np . hstack ( [ lats , lons ] ) | Convert from directional cosines to latitidue and longitude |
36,266 | def fill_edge_matrix ( nsrcs , match_dict ) : e_matrix = np . zeros ( ( nsrcs , nsrcs ) ) for k , v in match_dict . items ( ) : e_matrix [ k [ 0 ] , k [ 1 ] ] = v return e_matrix | Create and fill a matrix with the graph edges between sources . |
36,267 | def make_rev_dict_unique ( cdict ) : rev_dict = { } for k , v in cdict . items ( ) : if k in rev_dict : rev_dict [ k ] [ k ] = True else : rev_dict [ k ] = { k : True } for vv in v . keys ( ) : if vv in rev_dict : rev_dict [ vv ] [ k ] = True else : rev_dict [ vv ] = { k : True } return rev_dict | Make a reverse dictionary |
36,268 | def make_clusters ( span_tree , cut_value ) : iv0 , iv1 = span_tree . nonzero ( ) match_dict = { } for i0 , i1 in zip ( iv0 , iv1 ) : d = span_tree [ i0 , i1 ] if d > cut_value : continue imin = int ( min ( i0 , i1 ) ) imax = int ( max ( i0 , i1 ) ) if imin in match_dict : match_dict [ imin ] [ imax ] = True else : mat... | Find clusters from the spanning tree |
36,269 | def select_from_cluster ( idx_key , idx_list , measure_vect ) : best_idx = idx_key best_measure = measure_vect [ idx_key ] out_list = [ idx_key ] + idx_list for idx , measure in zip ( idx_list , measure_vect [ idx_list ] ) : if measure < best_measure : best_idx = idx best_measure = measure out_list . remove ( best_idx ... | Select a single source from a cluster and make it the new cluster key |
36,270 | def count_sources_in_cluster ( n_src , cdict , rev_dict ) : ret_val = np . zeros ( ( n_src ) , int ) for i in range ( n_src ) : try : key = rev_dict [ i ] except KeyError : key = i try : n = len ( cdict [ key ] ) except : n = 0 ret_val [ i ] = n return ret_val | Make a vector of sources in each cluster |
36,271 | def find_dist_to_centroids ( cluster_dict , cvects , weights = None ) : distances = np . zeros ( ( cvects . shape [ 1 ] ) ) cent_dict = { } for k , v in cluster_dict . items ( ) : l = [ k ] + v distances [ l ] , centroid = find_dist_to_centroid ( cvects , l , weights ) cent_dict [ k ] = make_lat_lons ( centroid ) retur... | Find the centroids and the distances to the centroid for all sources in a set of clusters |
36,272 | def select_from_clusters ( cluster_dict , measure_vect ) : out_dict = { } for idx_key , idx_list in cluster_dict . items ( ) : out_idx , out_list = select_from_cluster ( idx_key , idx_list , measure_vect ) out_dict [ out_idx ] = out_list return out_dict | Select a single source from each cluster and make it the new cluster key |
36,273 | def make_reverse_dict ( in_dict , warn = True ) : out_dict = { } for k , v in in_dict . items ( ) : for vv in v : if vv in out_dict : if warn : print ( "Dictionary collision %i" % vv ) out_dict [ vv ] = k return out_dict | Build a reverse dictionary from a cluster dictionary |
36,274 | def make_dict_from_vector ( in_array ) : out_dict = { } for i , k in enumerate ( in_array ) : if k < 0 : continue try : out_dict [ k ] . append ( i ) except KeyError : out_dict [ k ] = [ i ] return out_dict | Converts the cluster membership array stored in a fits file back to a dictionary |
36,275 | def filter_and_copy_table ( tab , to_remove ) : nsrcs = len ( tab ) mask = np . zeros ( ( nsrcs ) , '?' ) mask [ to_remove ] = True inv_mask = np . invert ( mask ) out_tab = tab [ inv_mask ] return out_tab | Filter and copy a FITS table . |
36,276 | def baseline_roi_fit ( gta , make_plots = False , minmax_npred = [ 1e3 , np . inf ] ) : gta . free_sources ( False ) gta . write_roi ( 'base_roi' , make_plots = make_plots ) gta . free_sources ( True , minmax_npred = [ 1e3 , np . inf ] ) gta . optimize ( ) gta . free_sources ( False ) gta . print_roi ( ) | Do baseline fitting for a target Region of Interest |
36,277 | def localize_sources ( gta , ** kwargs ) : for src in sorted ( gta . roi . sources , key = lambda t : t [ 'ts' ] , reverse = True ) : if not src [ 'SpatialModel' ] == 'PointSource' : continue if src [ 'offset_roi_edge' ] > - 0.1 : continue gta . localize ( src . name , ** kwargs ) gta . optimize ( ) gta . print_roi ( ) | Relocalize sources in the region of interest |
36,278 | def add_source_get_correlated ( gta , name , src_dict , correl_thresh = 0.25 , non_null_src = False ) : if gta . roi . has_source ( name ) : gta . zero_source ( name ) gta . update_source ( name ) test_src_name = "%s_test" % name else : test_src_name = name gta . add_source ( test_src_name , src_dict ) gta . free_norm ... | Add a source and get the set of correlated sources |
36,279 | def copy_analysis_files ( cls , orig_dir , dest_dir , copyfiles ) : for pattern in copyfiles : glob_path = os . path . join ( orig_dir , pattern ) files = glob . glob ( glob_path ) for ff in files : f = os . path . basename ( ff ) orig_path = os . path . join ( orig_dir , f ) dest_path = os . path . join ( dest_dir , f... | Copy a list of files from orig_dir to dest_dir |
36,280 | def copy_target_dir ( cls , orig_dir , dest_dir , roi_baseline , extracopy ) : try : os . makedirs ( dest_dir ) except OSError : pass copyfiles = [ '%s.fits' % roi_baseline , '%s.npy' % roi_baseline , '%s_*.xml' % roi_baseline ] + cls . copyfiles if isinstance ( extracopy , list ) : copyfiles += extracopy cls . copy_an... | Create and populate directoris for target analysis |
36,281 | def _make_wcsgeom_from_config ( config ) : binning = config [ 'binning' ] binsz = binning [ 'binsz' ] coordsys = binning . get ( 'coordsys' , 'GAL' ) roiwidth = binning [ 'roiwidth' ] proj = binning . get ( 'proj' , 'AIT' ) ra = config [ 'selection' ] [ 'ra' ] dec = config [ 'selection' ] [ 'dec' ] npix = int ( np . ro... | Build a WCS . Geom object from a fermipy coniguration file |
36,282 | def _build_skydir_dict ( wcsgeom , rand_config ) : step_x = rand_config [ 'step_x' ] step_y = rand_config [ 'step_y' ] max_x = rand_config [ 'max_x' ] max_y = rand_config [ 'max_y' ] seed = rand_config [ 'seed' ] nsims = rand_config [ 'nsims' ] cdelt = wcsgeom . wcs . wcs . cdelt pixstep_x = step_x / cdelt [ 0 ] pixste... | Build a dictionary of random directions |
36,283 | def _clone_config_and_srcmaps ( config_path , seed ) : workdir = os . path . dirname ( config_path ) new_config_path = config_path . replace ( '.yaml' , '_%06i.yaml' % seed ) config = load_yaml ( config_path ) comps = config . get ( 'components' , [ config ] ) for i , comp in enumerate ( comps ) : comp_name = "%02i" % ... | Clone the configuration |
36,284 | def _run_simulation ( gta , roi_baseline , injected_name , test_sources , current_seed , seed , non_null_src ) : gta . load_roi ( 'sim_baseline_%06i.npy' % current_seed ) gta . set_random_seed ( seed ) gta . simulate_roi ( ) if injected_name : gta . zero_source ( injected_name ) gta . optimize ( ) gta . find_sources ( ... | Simulate a realization of this analysis |
36,285 | def get_branches ( aliases ) : ignore = [ 'pow' , 'log10' , 'sqrt' , 'max' ] branches = [ ] for k , v in aliases . items ( ) : tokens = re . sub ( '[\(\)\+\*\/\,\=\<\>\&\!\-\|]' , ' ' , v ) . split ( ) for t in tokens : if bool ( re . search ( r'^\d' , t ) ) or len ( t ) <= 3 : continue if bool ( re . search ( r'[a-zA-... | Get unique branch names from an alias dictionary . |
36,286 | def load_friend_chains ( chain , friend_chains , txt , nfiles = None ) : if re . search ( '.root?' , txt ) is not None : c = ROOT . TChain ( chain . GetName ( ) ) c . SetDirectory ( 0 ) c . Add ( txt ) friend_chains . append ( c ) chain . AddFriend ( c , rand_str ( ) ) return files = np . loadtxt ( txt , unpack = True ... | Load a list of trees from a file and add them as friends to the chain . |
36,287 | def find_and_read_ebins ( hdulist ) : from fermipy import utils ebins = None if 'ENERGIES' in hdulist : hdu = hdulist [ 'ENERGIES' ] ectr = hdu . data . field ( hdu . columns [ 0 ] . name ) ebins = np . exp ( utils . center_to_edge ( np . log ( ectr ) ) ) elif 'EBOUNDS' in hdulist : hdu = hdulist [ 'EBOUNDS' ] emin = h... | Reads and returns the energy bin edges . |
36,288 | def read_energy_bounds ( hdu ) : nebins = len ( hdu . data ) ebin_edges = np . ndarray ( ( nebins + 1 ) ) try : ebin_edges [ 0 : - 1 ] = np . log10 ( hdu . data . field ( "E_MIN" ) ) - 3. ebin_edges [ - 1 ] = np . log10 ( hdu . data . field ( "E_MAX" ) [ - 1 ] ) - 3. except KeyError : ebin_edges [ 0 : - 1 ] = np . log1... | Reads and returns the energy bin edges from a FITs HDU |
36,289 | def read_spectral_data ( hdu ) : ebins = read_energy_bounds ( hdu ) fluxes = np . ndarray ( ( len ( ebins ) ) ) try : fluxes [ 0 : - 1 ] = hdu . data . field ( "E_MIN_FL" ) fluxes [ - 1 ] = hdu . data . field ( "E_MAX_FL" ) [ - 1 ] npreds = hdu . data . field ( "NPRED" ) except : fluxes = np . ones ( ( len ( ebins ) ) ... | Reads and returns the energy bin edges fluxes and npreds from a FITs HDU |
36,290 | def make_energies_hdu ( energy_vals , extname = "ENERGIES" ) : cols = [ fits . Column ( "Energy" , "D" , unit = 'MeV' , array = energy_vals ) ] hdu = fits . BinTableHDU . from_columns ( cols , name = extname ) return hdu | Builds and returns a FITs HDU with the energy values |
36,291 | def read_projection_from_fits ( fitsfile , extname = None ) : f = fits . open ( fitsfile ) nhdu = len ( f ) try : ebins = find_and_read_ebins ( f ) except : ebins = None if extname is None : if f [ 0 ] . header [ 'NAXIS' ] != 0 : proj = WCS ( f [ 0 ] . header ) return proj , f , f [ 0 ] else : if f [ extname ] . header... | Load a WCS or HPX projection . |
36,292 | def write_tables_to_fits ( filepath , tablelist , clobber = False , namelist = None , cardslist = None , hdu_list = None ) : outhdulist = [ fits . PrimaryHDU ( ) ] rmlist = [ ] for i , table in enumerate ( tablelist ) : ft_name = "%s._%i" % ( filepath , i ) rmlist . append ( ft_name ) try : os . unlink ( ft_name ) exce... | Write some astropy . table . Table objects to a single fits file |
36,293 | def get_source_kernel ( gta , name , kernel = None ) : sm = [ ] zs = 0 for c in gta . components : z = c . model_counts_map ( name ) . data . astype ( 'float' ) if kernel is not None : shape = ( z . shape [ 0 ] , ) + kernel . shape z = np . apply_over_axes ( np . sum , z , axes = [ 1 , 2 ] ) * np . ones ( shape ) * ker... | Get the PDF for the given source . |
36,294 | def residmap ( self , prefix = '' , ** kwargs ) : timer = Timer . create ( start = True ) self . logger . info ( 'Generating residual maps' ) schema = ConfigSchema ( self . defaults [ 'residmap' ] ) config = schema . create_config ( self . config [ 'residmap' ] , ** kwargs ) config [ 'model' ] . setdefault ( 'Index' , ... | Generate 2 - D spatial residual maps using the current ROI model and the convolution kernel defined with the model argument . |
36,295 | def create ( appname , ** kwargs ) : if appname in LinkFactory . _class_dict : return LinkFactory . _class_dict [ appname ] . create ( ** kwargs ) else : raise KeyError ( "Could not create object associated to app %s" % appname ) | Create a Link of a particular class using the kwargs as options |
36,296 | def _replace_none ( self , aDict ) : for k , v in aDict . items ( ) : if v is None : aDict [ k ] = 'none' | Replace all None values in a dict with none |
36,297 | def irfs ( self , ** kwargs ) : dsval = kwargs . get ( 'dataset' , self . dataset ( ** kwargs ) ) tokens = dsval . split ( '_' ) irf_name = "%s_%s_%s" % ( DATASET_DICTIONARY [ '%s_%s' % ( tokens [ 0 ] , tokens [ 1 ] ) ] , EVCLASS_NAME_DICTIONARY [ tokens [ 3 ] ] , kwargs . get ( 'irf_ver' ) ) return irf_name | Get the name of IFRs associted with a particular dataset |
36,298 | def dataset ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) try : return NameFactory . dataset_format . format ( ** kwargs_copy ) except KeyError : return None | Return a key that specifies the data selection |
36,299 | def component ( self , ** kwargs ) : kwargs_copy = self . base_dict . copy ( ) kwargs_copy . update ( ** kwargs ) self . _replace_none ( kwargs_copy ) try : return NameFactory . component_format . format ( ** kwargs_copy ) except KeyError : return None | Return a key that specifies data the sub - selection |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.