idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
35,800 | def _get_parameters ( link , encoding ) : parameters = [ ] properties = { } required = [ ] for field in link . fields : parser = OpenApiFieldParser ( link , field ) if parser . location == 'form' : if encoding in ( 'multipart/form-data' , 'application/x-www-form-urlencoded' ) : parameters . append ( parser . as_paramet... | Generates Swagger Parameter Item object . |
35,801 | def auth_uri ( self , redirect_uri = None , scope = None , scope_delim = None , state = None , ** kwargs ) : kwargs . update ( { 'client_id' : self . client_id , 'response_type' : 'code' , } ) if scope is not None : kwargs [ 'scope' ] = scope if state is not None : kwargs [ 'state' ] = state if redirect_uri is not None... | Builds the auth URI for the authorization endpoint |
35,802 | def build_srcdict ( gta , prop ) : o = { } for s in gta . roi . sources : o [ s . name ] = s [ prop ] return o | Build a dictionary that maps from source name to the value of a source property |
35,803 | def get_src_names ( gta ) : o = [ ] for s in gta . roi . sources : o += [ s . name ] return sorted ( o ) | Build and return a list of source name |
35,804 | def set_wts_get_npred_wt ( gta , maskname ) : if is_null ( maskname ) : maskname = None gta . set_weights_map ( maskname ) for name in gta . like . sourceNames ( ) : gta . _init_source ( name ) gta . _update_roi ( ) return build_srcdict ( gta , 'npred_wt' ) | Set a weights file and get the weighted npred for all the sources |
35,805 | def snapshot ( gta , plotter , key , do_weighted = True , make_plots = True ) : gta . write_roi ( key , save_model_map = True , make_plots = make_plots , save_weight_map = do_weighted ) if make_plots : o = gta . residmap ( key ) plotter . make_residmap_plots ( o , gta . roi ) if do_weighted : gta . make_plots ( "%s_wt"... | Take a snapshot of the ROI |
35,806 | def get_unchanged ( src_list , npred_dict_new , npred_dict_old , npred_threshold = 1e4 , frac_threshold = 0.9 ) : o = [ ] for s in src_list : npred_new = npred_dict_new [ s ] if npred_new < npred_threshold : o += [ s ] continue if npred_dict_old is None : npred_old = 0. else : npred_old = npred_dict_old [ s ] frac = np... | Compare two dictionarys of npreds and get the list of sources than have changed less that set thresholds |
35,807 | def dispatch_job_hook ( self , link , key , job_config , logfile , stream = sys . stdout ) : full_sub_dict = job_config . copy ( ) full_command = "%s >& %s" % ( link . command_template ( ) . format ( ** full_sub_dict ) , logfile ) logdir = os . path . dirname ( logfile ) if self . _dry_run : sys . stdout . write ( "%s\... | Send a single job to be executed |
35,808 | def log_level ( level ) : levels_dict = { 0 : 50 , 1 : 40 , 2 : 30 , 3 : 20 , 4 : 10 } if not isinstance ( level , int ) : level = int ( level ) if level > 4 : level = 4 return levels_dict [ level ] | This is a function that returns a python like level from a HEASOFT like level . |
35,809 | def setup ( config = None , logfile = None ) : if config is None : configpath = os . path . join ( fermipy . PACKAGE_ROOT , 'config' , 'logging.yaml' ) with open ( configpath , 'r' ) as f : config = yaml . load ( f ) if logfile : for name , h in config [ 'handlers' ] . items ( ) : if 'file_handler' in name : config [ '... | This method sets up the default configuration of the logger . Once this method is called all subsequent instances Logger instances will inherit this configuration . |
35,810 | def configure ( name , logfile , loglevel = logging . DEBUG ) : logger = logging . getLogger ( name ) logger . propagate = False logger . setLevel ( logging . DEBUG ) datefmt = '%Y-%m-%d %H:%M:%S' format_stream = ( '%(asctime)s %(levelname)-8s' '%(name)s.%(funcName)s(): %(message)s' ) format_file = ( '%(asctime)s %(lev... | Create a python logger instance and configure it . |
35,811 | def extract_arguments ( args , defaults ) : out_dict = convert_option_dict_to_dict ( defaults ) for key in defaults . keys ( ) : mapped_val = args . get ( key , None ) if mapped_val is None : pass else : out_dict [ key ] = mapped_val return out_dict | Extract a set of arguments from a large dictionary |
35,812 | def check_files ( filelist , file_stage_manager = None , return_found = True , return_missing = True ) : found = [ ] missing = [ ] none_count = 0 for fname in filelist : if fname is None : none_count += 1 continue if fname [ 0 ] == '@' : fname = fname [ 1 : ] if os . path . exists ( fname ) : found . append ( fname ) c... | Check that all files in a list exist |
35,813 | def add_argument ( parser , dest , info ) : default , helpstr , typeinfo = info if dest == 'args' : parser . add_argument ( 'args' , nargs = '+' , default = None , help = helpstr ) elif typeinfo == list : parser . add_argument ( '--%s' % dest , action = 'append' , help = helpstr ) elif typeinfo == bool : parser . add_a... | Add an argument to an argparse . ArgumentParser object |
35,814 | def convert_dict_to_option_dict ( input_dict ) : ret_dict = { } for key , value in input_dict . items ( ) : ret_dict [ key ] = convert_value_to_option_tuple ( value ) return ret_dict | Convert a simple key - value dictionary to a dictionary of options tuples |
35,815 | def convert_option_dict_to_dict ( option_dict ) : ret_dict = { } for key , value in option_dict . items ( ) : if is_null ( value ) : ret_dict [ key ] = None elif isinstance ( value , tuple ) : ret_dict [ key ] = value [ 0 ] else : ret_dict [ key ] = value return ret_dict | Convert a dictionary of options tuples to a simple key - value dictionary |
35,816 | def reduce_by_keys ( orig_dict , keys , default = None ) : ret = { } for key in keys : ret [ key ] = orig_dict . get ( key , default ) return ret | Reduce a dictionary by selecting a set of keys |
35,817 | def construct_docstring ( options ) : s = "\nParameters\n" s += "----------\n\n" for key , opt in options . items ( ) : s += "%s : %s\n %s [%s]\n" % ( key , str ( opt [ 2 ] ) , str ( opt [ 1 ] ) , str ( opt [ 0 ] ) ) return s | Construct a docstring for a set of options |
35,818 | def register_class ( cls ) : if cls . appname in LinkFactory . _class_dict : return LinkFactory . register ( cls . appname , cls ) | Regsiter this class in the LinkFactory |
35,819 | def _fill_argparser ( self , parser ) : for key , val in self . _options . items ( ) : add_argument ( parser , key , val ) | Fill an argparser . ArgumentParser with the options from this chain |
35,820 | def _run_argparser ( self , argv ) : if self . _parser is None : raise ValueError ( 'Link was not given a parser on initialization' ) args = self . _parser . parse_args ( argv ) self . update_args ( args . __dict__ ) return args | Initialize a link with a set of arguments using an argparser . ArgumentParser |
35,821 | def _update_sub_file_dict ( self , sub_files ) : sub_files . file_dict . clear ( ) for job_details in self . jobs . values ( ) : if job_details . file_dict is not None : sub_files . update ( job_details . file_dict ) if job_details . sub_file_dict is not None : sub_files . update ( job_details . sub_file_dict ) | Update a file dict with information from self |
35,822 | def _pre_run_checks ( self , stream = sys . stdout , dry_run = False ) : input_missing = self . check_input_files ( return_found = False ) if input_missing : if dry_run : stream . write ( "Input files are missing: %s: %i\n" % ( self . linkname , len ( input_missing ) ) ) else : print ( self . args ) raise OSError ( "In... | Do some checks before running this link |
35,823 | def _create_job_details ( self , key , job_config , logfile , status ) : self . update_args ( job_config ) job_details = JobDetails ( jobname = self . full_linkname , jobkey = key , appname = self . appname , logfile = logfile , job_config = job_config , timestamp = get_timestamp ( ) , file_dict = copy . deepcopy ( sel... | Create a JobDetails for a single job |
35,824 | def _map_scratch_files ( self , file_dict ) : if self . _file_stage is None : return ( { } , { } ) input_files = file_dict . input_files_to_stage output_files = file_dict . output_files_to_stage input_file_mapping = self . _file_stage . map_files ( input_files ) output_file_mapping = self . _file_stage . map_files ( ou... | Build and return the mapping for copying files to and from scratch area |
35,825 | def _update_file_args ( self , file_mapping ) : for key , value in self . args . items ( ) : new_value = file_mapping . get ( value , value ) if new_value != value : self . args [ key ] = new_value | Adjust the arguments to deal with staging files to the scratch area |
35,826 | def _stage_input_files ( self , file_mapping , dry_run = True ) : if self . _file_stage is None : return self . _file_stage . copy_to_scratch ( file_mapping , dry_run ) | Stage the input files to the scratch area and adjust the arguments accordingly |
35,827 | def _stage_output_files ( self , file_mapping , dry_run = True ) : if self . _file_stage is None : return self . _file_stage . copy_from_scratch ( file_mapping , dry_run ) | Stage the output files to the scratch area and adjust the arguments accordingly |
35,828 | def _register_job ( self , key , job_config , logfile , status ) : job_details = self . _create_job_details ( key , job_config , logfile , status ) self . jobs [ job_details . fullkey ] = job_details return job_details | Create a JobDetails for this link and add it to the self . jobs dictionary . |
35,829 | def _register_self ( self , logfile , key = JobDetails . topkey , status = JobStatus . unknown ) : fullkey = JobDetails . make_fullkey ( self . full_linkname , key ) if fullkey in self . jobs : job_details = self . jobs [ fullkey ] job_details . status = status else : job_details = self . _register_job ( key , self . a... | Runs this link captures output to logfile and records the job in self . jobs |
35,830 | def _archive_self ( self , logfile , key = JobDetails . topkey , status = JobStatus . unknown ) : self . _register_self ( logfile , key , status ) if self . _job_archive is None : return self . _job_archive . register_jobs ( self . get_jobs ( ) ) | Write info about a job run by this Link to the job archive |
35,831 | def _set_status_self ( self , key = JobDetails . topkey , status = JobStatus . unknown ) : fullkey = JobDetails . make_fullkey ( self . full_linkname , key ) if fullkey in self . jobs : self . jobs [ fullkey ] . status = status if self . _job_archive : self . _job_archive . register_job ( self . jobs [ fullkey ] ) else... | Set the status of this job both in self . jobs and in the JobArchive if it is present . |
35,832 | def _write_status_to_log ( self , return_code , stream = sys . stdout ) : stream . write ( "Timestamp: %i\n" % get_timestamp ( ) ) if return_code == 0 : stream . write ( "%s\n" % self . _interface . string_successful ) else : stream . write ( "%s %i\n" % ( self . _interface . string_exited , return_code ) ) | Write the status of this job to a log stream . This is used to check on job completion . |
35,833 | def get_failed_jobs ( self , fail_running = False , fail_pending = False ) : failed_jobs = { } for job_key , job_details in self . jobs . items ( ) : if job_details . status == JobStatus . failed : failed_jobs [ job_key ] = job_details elif job_details . status == JobStatus . partial_failed : failed_jobs [ job_key ] = ... | Return a dictionary with the subset of jobs that are marked as failed |
35,834 | def check_job_status ( self , key = JobDetails . topkey , fail_running = False , fail_pending = False , force_check = False ) : if key in self . jobs : status = self . jobs [ key ] . status if status in [ JobStatus . unknown , JobStatus . ready , JobStatus . pending , JobStatus . running ] or force_check : status = sel... | Check the status of a particular job |
35,835 | def check_jobs_status ( self , fail_running = False , fail_pending = False ) : n_failed = 0 n_partial = 0 n_passed = 0 n_total = 0 for job_details in self . jobs . values ( ) : n_total += 1 if job_details . status in [ JobStatus . failed , JobStatus . partial_failed ] : n_failed += 1 elif fail_running and job_details .... | Check the status of all the jobs run from this link and return a status flag that summarizes that . |
35,836 | def check_input_files ( self , return_found = True , return_missing = True ) : all_input_files = self . files . chain_input_files + self . sub_files . chain_input_files return check_files ( all_input_files , self . _file_stage , return_found , return_missing ) | Check if input files exist . |
35,837 | def check_output_files ( self , return_found = True , return_missing = True ) : all_output_files = self . files . chain_output_files + self . sub_files . chain_output_files return check_files ( all_output_files , self . _file_stage , return_found , return_missing ) | Check if output files exist . |
35,838 | def missing_output_files ( self ) : missing = self . check_output_files ( return_found = False ) ret_dict = { } for miss_file in missing : ret_dict [ miss_file ] = [ self . linkname ] return ret_dict | Make and return a dictionary of the missing output files . |
35,839 | def formatted_command ( self ) : command_template = self . command_template ( ) format_dict = self . args . copy ( ) for key , value in format_dict . items ( ) : if isinstance ( value , list ) : outstr = "" if key == 'args' : outkey = "" else : outkey = "--%s " for lval in value : outstr += ' ' outstr += outkey outstr ... | Build and return the formatted command for this Link . |
35,840 | def run_with_log ( self , dry_run = False , stage_files = True , resubmit_failed = False ) : fullkey = JobDetails . make_fullkey ( self . full_linkname ) job_details = self . jobs [ fullkey ] odir = os . path . dirname ( job_details . logfile ) try : os . makedirs ( odir ) except OSError : pass ostream = open ( job_det... | Runs this link with output sent to a pre - defined logfile |
35,841 | def create_wcs ( skydir , coordsys = 'CEL' , projection = 'AIT' , cdelt = 1.0 , crpix = 1. , naxis = 2 , energies = None ) : w = WCS ( naxis = naxis ) if coordsys == 'CEL' : w . wcs . ctype [ 0 ] = 'RA---%s' % ( projection ) w . wcs . ctype [ 1 ] = 'DEC--%s' % ( projection ) w . wcs . crval [ 0 ] = skydir . icrs . ra .... | Create a WCS object . |
35,842 | def wcs_add_energy_axis ( wcs , energies ) : if wcs . naxis != 2 : raise Exception ( 'wcs_add_energy_axis, input WCS naxis != 2 %i' % wcs . naxis ) w = WCS ( naxis = 3 ) w . wcs . crpix [ 0 ] = wcs . wcs . crpix [ 0 ] w . wcs . crpix [ 1 ] = wcs . wcs . crpix [ 1 ] w . wcs . ctype [ 0 ] = wcs . wcs . ctype [ 0 ] w . wc... | Copy a WCS object and add on the energy axis . |
35,843 | def sky_to_offset ( skydir , lon , lat , coordsys = 'CEL' , projection = 'AIT' ) : w = create_wcs ( skydir , coordsys , projection ) skycrd = np . vstack ( ( lon , lat ) ) . T if len ( skycrd ) == 0 : return skycrd return w . wcs_world2pix ( skycrd , 0 ) | Convert sky coordinates to a projected offset . This function is the inverse of offset_to_sky . |
35,844 | def skydir_to_pix ( skydir , wcs ) : if len ( skydir . shape ) > 0 and len ( skydir ) == 0 : return [ np . empty ( 0 ) , np . empty ( 0 ) ] return skydir . to_pixel ( wcs , origin = 0 ) | Convert skydir object to pixel coordinates . |
35,845 | def pix_to_skydir ( xpix , ypix , wcs ) : xpix = np . array ( xpix ) ypix = np . array ( ypix ) if xpix . ndim > 0 and len ( xpix ) == 0 : return SkyCoord ( np . empty ( 0 ) , np . empty ( 0 ) , unit = 'deg' , frame = 'icrs' ) return SkyCoord . from_pixel ( xpix , ypix , wcs , origin = 0 ) . transform_to ( 'icrs' ) | Convert pixel coordinates to a skydir object . |
35,846 | def wcs_to_axes ( w , npix ) : npix = npix [ : : - 1 ] x = np . linspace ( - ( npix [ 0 ] ) / 2. , ( npix [ 0 ] ) / 2. , npix [ 0 ] + 1 ) * np . abs ( w . wcs . cdelt [ 0 ] ) y = np . linspace ( - ( npix [ 1 ] ) / 2. , ( npix [ 1 ] ) / 2. , npix [ 1 ] + 1 ) * np . abs ( w . wcs . cdelt [ 1 ] ) if w . wcs . naxis == 2 :... | Generate a sequence of bin edge vectors corresponding to the axes of a WCS object . |
35,847 | def get_cel_to_gal_angle ( skydir ) : wcs0 = create_wcs ( skydir , coordsys = 'CEL' ) wcs1 = create_wcs ( skydir , coordsys = 'GAL' ) x , y = SkyCoord . to_pixel ( SkyCoord . from_pixel ( 1.0 , 0.0 , wcs0 ) , wcs1 ) return np . arctan2 ( y , x ) | Calculate the rotation angle in radians between the longitude axes of a local projection in celestial and galactic coordinates . |
35,848 | def extract_mapcube_region ( infile , skydir , outfile , maphdu = 0 ) : h = fits . open ( os . path . expandvars ( infile ) ) npix = 200 shape = list ( h [ maphdu ] . data . shape ) shape [ 1 ] = 200 shape [ 2 ] = 200 wcs = WCS ( h [ maphdu ] . header ) skywcs = WCS ( h [ maphdu ] . header , naxis = [ 1 , 2 ] ) coordsy... | Extract a region out of an all - sky mapcube file . |
35,849 | def readlines ( arg ) : fin = open ( arg ) lines_in = fin . readlines ( ) fin . close ( ) lines_out = [ ] for line in lines_in : line = line . strip ( ) if not line or line [ 0 ] == '#' : continue lines_out . append ( line ) return lines_out | Read lines from a file into a list . |
35,850 | def create_inputlist ( arglist ) : lines = [ ] if isinstance ( arglist , list ) : for arg in arglist : if os . path . splitext ( arg ) [ 1 ] == '.lst' : lines += readlines ( arg ) else : lines . append ( arg ) elif is_null ( arglist ) : pass else : if os . path . splitext ( arglist ) [ 1 ] == '.lst' : lines += readline... | Read lines from a file and makes a list of file names . |
35,851 | def init ( self ) : evclass_shape = [ 16 , 40 , 10 ] evtype_shape = [ 16 , 16 , 40 , 10 ] evclass_psf_shape = [ 16 , 40 , 10 , 100 ] evtype_psf_shape = [ 16 , 16 , 40 , 10 , 100 ] self . _hists_eff = dict ( ) self . _hists = dict ( evclass_on = np . zeros ( evclass_shape ) , evclass_off = np . zeros ( evclass_shape ) ,... | Initialize histograms . |
35,852 | def create_hist ( self , evclass , evtype , xsep , energy , ctheta , fill_sep = False , fill_evtype = False ) : nevt = len ( evclass ) ebin = utils . val_to_bin ( self . _energy_bins , energy ) scale = self . _psf_scale [ ebin ] vals = [ energy , ctheta ] bins = [ self . _energy_bins , self . _ctheta_bins ] if fill_sep... | Load into a histogram . |
35,853 | def calc_eff ( self ) : hists = self . hists hists_out = self . _hists_eff cth_axis_idx = dict ( evclass = 2 , evtype = 3 ) for k in [ 'evclass' , 'evtype' ] : if k == 'evclass' : ns0 = hists [ 'evclass_on' ] [ 4 ] [ None , ... ] nb0 = hists [ 'evclass_off' ] [ 4 ] [ None , ... ] else : ns0 = hists [ 'evclass_on' ] [ 4... | Calculate the efficiency . |
35,854 | def calc_containment ( self ) : hists = self . hists hists_out = self . _hists_eff quantiles = [ 0.34 , 0.68 , 0.90 , 0.95 ] cth_axis_idx = dict ( evclass = 2 , evtype = 3 ) for k in [ 'evclass' ] : print ( k ) non = hists [ '%s_psf_on' % k ] noff = hists [ '%s_psf_off' % k ] alpha = hists [ '%s_alpha' % k ] [ ... , No... | Calculate PSF containment . |
35,855 | def update_from_schema ( cfg , cfgin , schema ) : cfgout = copy . deepcopy ( cfg ) for k , v in schema . items ( ) : if k not in cfgin : continue if isinstance ( v , dict ) : cfgout . setdefault ( k , { } ) cfgout [ k ] = update_from_schema ( cfg [ k ] , cfgin [ k ] , v ) elif v [ 2 ] is dict : cfgout [ k ] = utils . m... | Update configuration dictionary cfg with the contents of cfgin using the schema dictionary to determine the valid input keys . |
35,856 | def write_config ( self , outfile ) : utils . write_yaml ( self . config , outfile , default_flow_style = False ) | Write the configuration dictionary to an output file . |
35,857 | def create ( cls , configfile ) : config = { } if config [ 'fileio' ] [ 'outdir' ] is None : config [ 'fileio' ] [ 'outdir' ] = os . path . abspath ( os . path . dirname ( configfile ) ) user_config = cls . load ( configfile ) config = utils . merge_dict ( config , user_config , True ) config [ 'fileio' ] [ 'outdir' ] ... | Create a configuration dictionary from a yaml config file . This function will first populate the dictionary with defaults taken from pre - defined configuration files . The configuration dictionary is then updated with the user - defined configuration file . Any settings defined by the user will take precedence over t... |
35,858 | def update_null_primary ( hdu_in , hdu = None ) : if hdu is None : hdu = fits . PrimaryHDU ( header = hdu_in . header ) else : hdu = hdu_in hdu . header . remove ( 'FILENAME' ) return hdu | Update a null primary HDU |
35,859 | def update_primary ( hdu_in , hdu = None ) : if hdu is None : hdu = fits . PrimaryHDU ( data = hdu_in . data , header = hdu_in . header ) else : hdu . data += hdu_in . data return hdu | Update a primary HDU |
35,860 | def update_image ( hdu_in , hdu = None ) : if hdu is None : hdu = fits . ImageHDU ( data = hdu_in . data , header = hdu_in . header , name = hdu_in . name ) else : hdu . data += hdu_in . data return hdu | Update an image HDU |
35,861 | def update_ebounds ( hdu_in , hdu = None ) : if hdu is None : hdu = fits . BinTableHDU ( data = hdu_in . data , header = hdu_in . header , name = hdu_in . name ) else : for col in [ 'CHANNEL' , 'E_MIN' , 'E_MAX' ] : if ( hdu . data [ col ] != hdu_in . data [ col ] ) . any ( ) : raise ValueError ( "Energy bounds do not ... | Update the EBOUNDS HDU |
35,862 | def merge_all_gti_data ( datalist_in , nrows , first ) : max_row = nrows . cumsum ( ) min_row = max_row - nrows out_hdu = fits . BinTableHDU . from_columns ( first . columns , header = first . header , nrows = nrows . sum ( ) ) for ( imin , imax , data_in ) in zip ( min_row , max_row , datalist_in ) : for col in first ... | Merge together all the GTI data |
35,863 | def extract_gti_data ( hdu_in ) : data = hdu_in . data exposure = hdu_in . header [ 'EXPOSURE' ] tstop = hdu_in . header [ 'TSTOP' ] return ( data , exposure , tstop ) | Extract some GTI related data |
35,864 | def update_hpx_skymap_allsky ( map_in , map_out ) : if map_out is None : in_hpx = map_in . hpx out_hpx = HPX . create_hpx ( in_hpx . nside , in_hpx . nest , in_hpx . coordsys , None , in_hpx . ebins , None , in_hpx . conv , None ) data_out = map_in . expanded_counts_map ( ) print ( data_out . shape , data_out . sum ( )... | Update a HEALPix skymap |
35,865 | def merge_wcs_counts_cubes ( filelist ) : out_prim = None out_ebounds = None datalist_gti = [ ] exposure_sum = 0. nfiles = len ( filelist ) ngti = np . zeros ( nfiles , int ) for i , filename in enumerate ( filelist ) : fin = fits . open ( filename ) sys . stdout . write ( '.' ) sys . stdout . flush ( ) if i == 0 : out... | Merge all the files in filelist assuming that they WCS counts cubes |
35,866 | def merge_hpx_counts_cubes ( filelist ) : out_prim = None out_skymap = None out_ebounds = None datalist_gti = [ ] exposure_sum = 0. nfiles = len ( filelist ) ngti = np . zeros ( nfiles , int ) out_name = None for i , filename in enumerate ( filelist ) : fin = fits . open ( filename ) sys . stdout . write ( '.' ) sys . ... | Merge all the files in filelist assuming that they HEALPix counts cubes |
35,867 | def _write_xml ( xmlfile , srcs ) : root = ElementTree . Element ( 'source_library' ) root . set ( 'title' , 'source_library' ) for src in srcs : src . write_xml ( root ) output_file = open ( xmlfile , 'w' ) output_file . write ( utils . prettify_xml ( root ) ) | Save the ROI model as an XML |
35,868 | def _handle_component ( sourcekey , comp_dict ) : if comp_dict . comp_key is None : fullkey = sourcekey else : fullkey = "%s_%s" % ( sourcekey , comp_dict . comp_key ) srcdict = make_sources ( fullkey , comp_dict ) if comp_dict . model_type == 'IsoSource' : print ( "Writing xml for %s to %s: %s %s" % ( fullkey , comp_d... | Make the source objects and write the xml for a component |
35,869 | def find_peaks ( input_map , threshold , min_separation = 0.5 ) : data = input_map . data cdelt = max ( input_map . geom . wcs . wcs . cdelt ) min_separation = max ( min_separation , 2 * cdelt ) region_size_pix = int ( min_separation / cdelt ) region_size_pix = max ( 3 , region_size_pix ) deltaxy = utils . make_pixel_d... | Find peaks in a 2 - D map object that have amplitude larger than threshold and lie a distance at least min_separation from another peak of larger amplitude . The implementation of this method uses ~scipy . ndimage . filters . maximum_filter . |
35,870 | def estimate_pos_and_err_parabolic ( tsvals ) : a = tsvals [ 2 ] - tsvals [ 0 ] bc = 2. * tsvals [ 1 ] - tsvals [ 0 ] - tsvals [ 2 ] s = a / ( 2 * bc ) err = np . sqrt ( 2 / bc ) return s , err | Solve for the position and uncertainty of source in one dimension assuming that you are near the maximum and the errors are parabolic |
35,871 | def refine_peak ( tsmap , pix ) : nx = tsmap . shape [ 1 ] ny = tsmap . shape [ 0 ] if pix [ 0 ] == 0 or pix [ 0 ] == ( nx - 1 ) : xval = float ( pix [ 0 ] ) xerr = - 1 else : x_arr = tsmap [ pix [ 1 ] , pix [ 0 ] - 1 : pix [ 0 ] + 2 ] xval , xerr = estimate_pos_and_err_parabolic ( x_arr ) xval += float ( pix [ 0 ] ) i... | Solve for the position and uncertainty of source assuming that you are near the maximum and the errors are parabolic |
35,872 | def spectral_pars_from_catalog ( cat ) : spectrum_type = cat [ 'SpectrumType' ] pars = get_function_defaults ( cat [ 'SpectrumType' ] ) par_idxs = { k : i for i , k in enumerate ( get_function_par_names ( cat [ 'SpectrumType' ] ) ) } for k in pars : pars [ k ] [ 'value' ] = cat [ 'param_values' ] [ par_idxs [ k ] ] if ... | Create spectral parameters from 3FGL catalog columns . |
35,873 | def is_free ( self ) : return bool ( np . array ( [ int ( value . get ( "free" , False ) ) for key , value in self . spectral_pars . items ( ) ] ) . sum ( ) ) | returns True if any of the spectral model parameters is set to free else False |
35,874 | def set_position ( self , skydir ) : if not isinstance ( skydir , SkyCoord ) : skydir = SkyCoord ( ra = skydir [ 0 ] , dec = skydir [ 1 ] , unit = u . deg ) if not skydir . isscalar : skydir = np . ravel ( skydir ) [ 0 ] radec = np . array ( [ skydir . icrs . ra . deg , skydir . icrs . dec . deg ] ) self . _set_radec (... | Set the position of the source . |
35,875 | def skydir ( self ) : return SkyCoord ( self . radec [ 0 ] * u . deg , self . radec [ 1 ] * u . deg ) | Return a SkyCoord representation of the source position . |
35,876 | def create_from_dict ( cls , src_dict , roi_skydir = None , rescale = False ) : src_dict = copy . deepcopy ( src_dict ) src_dict . setdefault ( 'SpatialModel' , 'PointSource' ) src_dict . setdefault ( 'Spectrum_Filename' , None ) src_dict . setdefault ( 'SpectrumType' , 'PowerLaw' ) src_dict [ 'SpatialType' ] = get_spa... | Create a source object from a python dictionary . |
35,877 | def create_from_xmlfile ( cls , xmlfile , extdir = None ) : root = ElementTree . ElementTree ( file = xmlfile ) . getroot ( ) srcs = root . findall ( 'source' ) if len ( srcs ) == 0 : raise Exception ( 'No sources found.' ) return cls . create_from_xml ( srcs [ 0 ] , extdir = extdir ) | Create a Source object from an XML file . |
35,878 | def write_xml ( self , root ) : if not self . extended : try : source_element = utils . create_xml_element ( root , 'source' , dict ( name = self [ 'Source_Name' ] , type = 'PointSource' ) ) except TypeError as msg : print ( self [ 'Source_Name' ] , self ) raise TypeError ( msg ) spat_el = ElementTree . SubElement ( so... | Write this source to an XML node . |
35,879 | def clear ( self ) : self . _srcs = [ ] self . _diffuse_srcs = [ ] self . _src_dict = collections . defaultdict ( list ) self . _src_radius = [ ] | Clear the contents of the ROI . |
35,880 | def create_source ( self , name , src_dict , build_index = True , merge_sources = True , rescale = True ) : src_dict = copy . deepcopy ( src_dict ) if isinstance ( src_dict , dict ) : src_dict [ 'name' ] = name src = Model . create_from_dict ( src_dict , self . skydir , rescale = rescale ) else : src = src_dict src . s... | Add a new source to the ROI model from a dictionary or an existing source object . |
35,881 | def load_sources ( self , sources ) : self . clear ( ) for s in sources : if isinstance ( s , dict ) : s = Model . create_from_dict ( s ) self . load_source ( s , build_index = False ) self . _build_src_index ( ) | Delete all sources in the ROI and load the input source list . |
35,882 | def load_source ( self , src , build_index = True , merge_sources = True , ** kwargs ) : src = copy . deepcopy ( src ) name = src . name . replace ( ' ' , '' ) . lower ( ) min_sep = kwargs . get ( 'min_separation' , None ) if min_sep is not None : sep = src . skydir . separation ( self . _src_skydir ) . deg if len ( se... | Load a single source . |
35,883 | def match_source ( self , src ) : srcs = [ ] names = [ src . name ] for col in self . config [ 'assoc_xmatch_columns' ] : if col in src . assoc and src . assoc [ col ] : names += [ src . assoc [ col ] ] for name in names : name = name . replace ( ' ' , '' ) . lower ( ) if name not in self . _src_dict : continue srcs +=... | Look for source or sources in the model that match the given source . Sources are matched by name and any association columns defined in the assoc_xmatch_columns parameter . |
35,884 | def load ( self , ** kwargs ) : coordsys = kwargs . get ( 'coordsys' , 'CEL' ) extdir = kwargs . get ( 'extdir' , self . extdir ) srcname = kwargs . get ( 'srcname' , None ) self . clear ( ) self . load_diffuse_srcs ( ) for c in self . config [ 'catalogs' ] : if isinstance ( c , catalog . Catalog ) : self . load_existi... | Load both point source and diffuse components . |
35,885 | def create_from_roi_data ( cls , datafile ) : data = np . load ( datafile ) . flat [ 0 ] roi = cls ( ) roi . load_sources ( data [ 'sources' ] . values ( ) ) return roi | Create an ROI model . |
35,886 | def create ( cls , selection , config , ** kwargs ) : if selection [ 'target' ] is not None : return cls . create_from_source ( selection [ 'target' ] , config , ** kwargs ) else : target_skydir = wcs_utils . get_target_skydir ( selection ) return cls . create_from_position ( target_skydir , config , ** kwargs ) | Create an ROIModel instance . |
35,887 | def create_from_position ( cls , skydir , config , ** kwargs ) : coordsys = kwargs . pop ( 'coordsys' , 'CEL' ) roi = cls ( config , skydir = skydir , coordsys = coordsys , ** kwargs ) return roi | Create an ROIModel instance centered on a sky direction . |
35,888 | def create_from_source ( cls , name , config , ** kwargs ) : coordsys = kwargs . pop ( 'coordsys' , 'CEL' ) roi = cls ( config , src_radius = None , src_roiwidth = None , srcname = name , ** kwargs ) src = roi . get_source_by_name ( name ) return cls . create_from_position ( src . skydir , config , coordsys = coordsys ... | Create an ROI centered on the given source . |
35,889 | def get_source_by_name ( self , name ) : srcs = self . get_sources_by_name ( name ) if len ( srcs ) == 1 : return srcs [ 0 ] elif len ( srcs ) == 0 : raise Exception ( 'No source matching name: ' + name ) elif len ( srcs ) > 1 : raise Exception ( 'Multiple sources matching name: ' + name ) | Return a single source in the ROI with the given name . The input name string can match any of the strings in the names property of the source object . Case and whitespace are ignored when matching name strings . If no sources are found or multiple sources then an exception is thrown . |
35,890 | def get_sources_by_name ( self , name ) : index_name = name . replace ( ' ' , '' ) . lower ( ) if index_name in self . _src_dict : return list ( self . _src_dict [ index_name ] ) else : raise Exception ( 'No source matching name: ' + name ) | Return a list of sources in the ROI matching the given name . The input name string can match any of the strings in the names property of the source object . Case and whitespace are ignored when matching name strings . |
35,891 | def load_fits_catalog ( self , name , ** kwargs ) : cat = catalog . Catalog . create ( name ) self . load_existing_catalog ( cat , ** kwargs ) | Load sources from a FITS catalog file . |
35,892 | def _build_src_index ( self ) : self . _srcs = sorted ( self . _srcs , key = lambda t : t [ 'offset' ] ) nsrc = len ( self . _srcs ) radec = np . zeros ( ( 2 , nsrc ) ) for i , src in enumerate ( self . _srcs ) : radec [ : , i ] = src . radec self . _src_skydir = SkyCoord ( ra = radec [ 0 ] , dec = radec [ 1 ] , unit =... | Build an indices for fast lookup of a source given its name or coordinates . |
35,893 | def write_xml ( self , xmlfile , config = None ) : root = ElementTree . Element ( 'source_library' ) root . set ( 'title' , 'source_library' ) for s in self . _srcs : s . write_xml ( root ) if config is not None : srcs = self . create_diffuse_srcs ( config ) diffuse_srcs = { s . name : s for s in srcs } for s in self .... | Save the ROI model as an XML file . |
35,894 | def create_table ( self , names = None ) : scan_shape = ( 1 , ) for src in self . _srcs : scan_shape = max ( scan_shape , src [ 'dloglike_scan' ] . shape ) tab = create_source_table ( scan_shape ) for s in self . _srcs : if names is not None and s . name not in names : continue s . add_to_table ( tab ) return tab | Create an astropy Table object with the contents of the ROI model . |
35,895 | def write_fits ( self , fitsfile ) : tab = self . create_table ( ) hdu_data = fits . table_to_hdu ( tab ) hdus = [ fits . PrimaryHDU ( ) , hdu_data ] fits_utils . write_hdus ( hdus , fitsfile ) | Write the ROI model to a FITS file . |
35,896 | def write_ds9region ( self , region , * args , ** kwargs ) : lines = self . to_ds9 ( * args , ** kwargs ) with open ( region , 'w' ) as fo : fo . write ( "\n" . join ( lines ) ) | Create a ds9 compatible region file from the ROI . |
35,897 | def select_extended ( cat_table ) : try : l = [ len ( row . strip ( ) ) > 0 for row in cat_table [ 'Extended_Source_Name' ] . data ] return np . array ( l , bool ) except KeyError : return cat_table [ 'Extended' ] | Select only rows representing extended sources from a catalog table |
35,898 | def make_mask ( cat_table , cut ) : cut_var = cut [ 'cut_var' ] min_val = cut . get ( 'min_val' , None ) max_val = cut . get ( 'max_val' , None ) nsrc = len ( cat_table ) if min_val is None : min_mask = np . ones ( ( nsrc ) , bool ) else : min_mask = cat_table [ cut_var ] >= min_val if max_val is None : max_mask = np .... | Mask a bit mask selecting the rows that pass a selection |
35,899 | def select_sources ( cat_table , cuts ) : nsrc = len ( cat_table ) full_mask = np . ones ( ( nsrc ) , bool ) for cut in cuts : if cut == 'mask_extended' : full_mask *= mask_extended ( cat_table ) elif cut == 'select_extended' : full_mask *= select_extended ( cat_table ) else : full_mask *= make_mask ( cat_table , cut )... | Select only rows passing a set of cuts from catalog table |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.